끝말잇기 게임 | 틀렸을 때 오류 표시하기

uoah·2023년 2월 1일

Training

목록 보기
6/20
post-thumbnail

🕹️ 게임 순서도


📍 alert

alert 을 이용하여 올바르지 않은 단어를 입력하여 틀렸을 때 게임 종료 알림창 나오게 적용하였다.

📍 $input.focus();

input 창에 커서(Cusor)가 움직이도록 (이용의 편리성을 위해서) 할 수 있다.

🧑🏻‍💻 코딩

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 = newWord;
    $word.textContent = word;
    $input.value = '';
    $input.focus();
    const order = Number($order.textContent); // 현재 순서
    if (order + 1 > number){
      $order.textContent = 1;
    } else {
      $order.textContent = order + 1;
    }
  } else {
    // 비어 있지 않은 경우
    if(word[word.length - 1] === newWord[0]) {
      // 단어가 올바른가
      word = newWord;
      $word.textContent = word;
      $input.value = '';
      $input.focus();
      const order = Number($order.textContent); // 현재 순서
      if (order + 1 > number){
        $order.textContent = 1;
      } else {
        $order.textContent = order + 1;
      }
    }else {
      alert ('GAME OVER');
      $input.value = '';
      $input.focus();
    }
  }
};

const onInput = (event) => {
  newWord = event.target.value;
};


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

0개의 댓글