[복습] 쿵쿵따 게임 만들기

uoah·2023년 2월 6일

Training

목록 보기
8/20
post-thumbnail

🕹️ 쿵쿵따 게임 만들기

[조건]
・ 단어는 3글자여야 한다.
・ 참여 인원을 입력하지 않고 취소를 누를 경우 코드는 실행되지 않는다.

const number = Number(prompt('참가 인원을 입력해 주세요'));

prompt 취소를 누를 경우 값은 null 이 된다. 그 값이 Number 함수에 들어가면 NaN이 된다. NaNif문 에 들어가면 항상 false로 취급되므로 number 가 null 이면 i문 내부에서는 실행되지 않으므로 if문 으로 감싸준다.

const number = Number(prompt('참가 인원을 입력해 주세요'));

if(number){
  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] && newWord.length === 3 )){
      word = newWord;
      $word.textContent = word;
      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);

}

🚨 오류 발생

첫 번째 제시어는 3글자가 아니여도 게임이 진행되는 오류 발생


✅ 이유

우선순위 문제로 a||b에서는 a가 먼저 실행된다.
!word 가 true 이면 뒤에 코드와 상관없이 true 가 나오므로 뒤에 코드는 실행조차 하지 않는다.


💡 해결

우선순위를 바꿔 준다.
newWord.length === 3 을 가장 우선으로 두고 뒤에 나머지 조건들을 넣는다.

const number = Number(prompt('참가 인원을 입력해 주세요'));
if(number){
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 (newWord.length === 3 && (!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;
    }
    $input.focus();
  } else { 
    alert ('GAME OVER');
  }
  $input.value = '';
};

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

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

}

💟 결과

0개의 댓글