[렛츠기릿 자바스크립트] 끝말잇기 만들기

EOH·2023년 5월 21일
0
post-thumbnail

💻 실습환경

vscode로 코드를 작성하고 chrome 웹 브라우저와 개발자도구를 이용해 코드를 실행해보았다.

💬 끝말잇기 만들기

이 강의는 프로그램을 만들면서 코드를 익히는 방식으로 진행된다. 이번 강의에서는 입력창에서 입력을 받고, 틀리면 경고창을 띄우는 끝말잇기를 만들것이다.


🔎 순서도

순서도는 간단하게 작성해보았다.

1️⃣ 인원수 입력받기

인원수를 입력받으려면 입력받는 매서드를 알아야한다.
입력창을 띄우는 방법에는 3가지가 있다.

prompt('');
//입력창(대화상자)를 띄워 사용자에게 입력을 받는다.

alert('');
//경고창을 띄운다.

confirm('');
//예, 아니오 버튼이 있는 확인창을 띄운다.

이 방법외에 화면에서 바로 입력받는 방법도 있으나 이번 과제에서는 prompt매서드를 이용해 입력받을 것이다.

const number = Number(prompt("몇 명이 참가하나요?"));

prompt메서드로 받은 문자열을 숫자로 형변환하여 number라는 변수 안에 담아둔다. 다음 참가자로 넘기는 과정에서 이 변수가 필요할 것이다.

2️⃣ 첫 번째로 받은 입력인지 판단하기

여기서 제시어는 word라는 변수 안에 저장되고, 새로 입력받은 단어는 newWord라는 변수에 저장되도록 짜놓았다.
게임을 시작하고 첫 번째로 받은 입력인지 판단하려면 이 제시어가 비어있는지 아닌지 보고 판단할 수 있다.

const $word = document.querySelector('#word'); //제시어자리의 span 태그를 가져옴
let word;
let newWord;

conts onClickButton = () => { //콜백함수를 정의하는 중
	if (!word) {
    	word = newWord; //데이터값을 넣어줌
        $word.textContent = word; //span태그의 textContent에 변수 word의 값을 넣어줌   
    } else {
    }
};
const onInput = (event) => {
	newWord = event.target.value;
};

$button.addEventListner('click', onClickButton);
$input.addEventListner('input', onInput);

3️⃣ 이어지는 단어인지 판단하기

이어지는 단어인지 판단하는것은 if 문에 조건만 추가하면된다.
이어지는 단어인지 어떻게 판단할 것인지 생각해보면 제시어(word)의 마지막 글자와 새로 입력받은 단어(newWord)의 첫글자가 같은지 판단하면 된다.

if (!word || word[length.word - 1] === newWord[0])

위 코드처럼 if문에 조건에 추가하면 된다.

4️⃣ 맞을 경우 제시어 바꿔서 띄우기, 다음 참가자로 넘기기

제시어 바꿔서 띄우는 것은
1️⃣의 $word.textContent = word;로 가능하다.
다음 참가자로 넘기는 방법도 크게 다르지 않지만 조건을 잘 생각해야한다.
처음에 참가자의 명 수를 입력받음으로 1번째 참가자->2번째 참가자-> ... -> 마지막 참가자 다음엔 다시 1번째 참가자로 돌아와야한다.

<div><span id="order">1</span>번째 참가자</div>
  
const $order = document.querySelector('#order');
if (!word || word[word.length - 1] === newWord[0]) {
	word = newWord;
	$word.textContent = word;
	const order = Number($order.textContent);
	if (order + 1 > number) {
		$order.textContent = 1;
	}
	else {
    	$order.textContent = order + 1;     
    }
}

이중 if 문을 이용해 n번째 참가자에 해당하는 n을 order라는 변수에 넣어서 마지막 참가자 전까지는 order을 ++해주고 마지막 참가자 순서가 지난 후에는 다시 1번째 참가자로 표시되게 만들어주었다.

5️⃣ 틀릴 경우 경고창 띄우기

경고창 띄우는 것은 간단하다.

else {
	alert("틀렸습니다!");
}

6️⃣ 입력창 비우고 focus가도록 처리하기

단어를 입력받고 나면 입력창을 비우고 커서를 깜빡거리게(focus가 가게)만들어 주면 사용자가 더 편리할 것이다.

$input.value = ''; //input태그의 값을 ''로 만든다. 값이 null인 상태
$input.focus(); // input태그에 focus함수를 실행

이 두 코드를 if문 안에 작성하면 처리가능하다.

📝 전체 코드

<!DOCTYPE html>
<html lang="ko">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>끝말잇기</title>
</head>

<body>
<div><span id="order">1</span>번째 참가자</div>
<div>제시어: <span id="word"></span></div>
<input type="text">
<button>입력</button>
<script>
	const number = Number(prompt("몇 명이 참가하나요?"));
	const $button = document.querySelector('button');
	const $input = document.querySelector('input');
	const $word = document.querySelector('#word');
	const $order = document.querySelector('#order');
	let word; //제시어
	let newWord; //새로 입력한 단어

	const onClickButton = () => {
		if (!word || word[word.length - 1] === newWord[0]) {
			word = newWord; //입력한 단어가 제시어가 된다.
			$word.textContent = word; //word태그선택하고 textcontetn를 word로 바꿔준다.
			const order = Number($order.textContent); //순서바꾸기
			if (order + 1 > number) {
				$order.textContent = 1;
			}
			else {
				$order.textContent = order + 1;
			}

		}
		else {
			alert("틀렸습니다!");
		}
		$input.value = ''; //input태그선택하고 안의 값을 비워준다.
		$input.focus();
	};
	const onInput = (event) => {
		newWord = event.target.value;
	};

	$button.addEventListener('click', onClickButton);
	$input.addEventListener('input', onInput);
</script>
</body>

</html>

💡 추가과제: 쿵쿵따 만들기

구현해본다음 해설을 보려고한다. 아직 구현은 못해봤지만 첫 번째 if문 조건에 word.length === 3이라는 조건을 추가하면 될 것 같다.

📚 github & reference

my깃허브
렛츠기릿 자바스크립트 강의

profile
에-오

0개의 댓글