<!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 = parseInt(prompt('몇 명이 참가하나요?'), 10); // 사용자에게 값을 전달받음
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 = newWord; // 입력한 단어가 제시어가 된다.
$word.textContent = word;
const order = Number($order.textContent); // 현재 순서
// *textContent는 문자! 숫자로 바꿔주는 Number함수 사용
// 현재 순서를 파악한다.
if (order + 1 > number) { // 현재 순서에 1을 더한 값이 number보다 큰가? (현재 순서가 마지막 참가자인지 확인)
$order.textContent = 1; // 맞다면 첫번째 참가자의 순서가 된다.
} else {
$order.textContent = order + 1;
}
$input.value = '';
$input.focus();
} else {
// 비어 있지 않다.
if(word[word.length - 1] === newWord[0]) { // 올바른가
word = newWord; // 입력한 단어가 제시어가 된다.
$word.textContent = word;
} else { // 올바르지 않은가
alert('올바르지 않은 단어입니다.');
$input.value = '';
$input.focus();
}
}
};
const onInput = (event) => {
newWord = event.target.value;
};
$button.addEventListener('click', onClickButton);
$input.addEventListener('input', onInput);
</script>
</body>
</html>
JavaScript
복사


