[자바스크립트] 인프런 - 렛츠기릿 자바스크립트 - 5강

June·2021년 7월 26일
0

숫자야구 순서도 그리기

<html>
<head>
  <meta charset="utf-8">
  <title>숫자야구</title>
</head>
<body>
<form id="form">
  <input type="text" id="input">
  <button>확인</button>
</form>
<div id="logs"></div>
<script>
  const $input = document.querySelector('#input');
  const $form = document.querySelector('#form');
  const $logs = document.querySelector('#logs');

  const numbers = []; // [1, 2, 3, 4, 5, 6, 7, 8, 9]
  for (let n = 0; n < 9; n += 1) {
    numbers.push(n + 1);
  }
  const answer = []; // [3, 1, 4, 6]
  for (let n = 0; n < 4; n += 1) { // 네 번 반복
    const index = Math.floor(Math.random() * numbers.length); // 0~8 정수 
    answer.push(numbers[index]);
    numbers.splice(index, 1);
  }
  console.log(answer);

  const tries = [];
  function checkInput(input) { // 3146,   314,  3144
    if (input.length !== 4) { // 길이는 4가 아닌가
      return alert('4자리 숫자를 입력해 주세요.');
    }
    if (new Set(input).size !== 4) { // 중복된 숫자가 있는가
      return alert('중복되지 않게 입력해 주세요.');
    }
    if (tries.includes(input)) { // 이미 시도한 값은 아닌가
      return alert('이미 시도한 값입니다.');
    }
    return true;
  } // 검사하는 코드

  function defeated() {
    const message = document.createTextNode(`패배! 정답은 ${answer.join('')}`);
    $logs.appendChild(message);
  }

  let out = 0;
  $form.addEventListener('submit', (event) => {
    event.preventDefault();
    const value = $input.value;
    $input.value = '';
    const valid = checkInput(value);
    if (!valid) return;
    // 입력값 문제없음
    if (answer.join('') === value) { // [3, 1, 4, 6] -> '3146'
      $logs.textContent = '홈런!';
      return;
    }
    if (tries.length >= 9) {
      defeated();
      return;
    }
    // 몇 스트라이크 몇 볼인지 검사
    let strike = 0;
    let ball = 0;
    // answer: 3146,  value: 1347
    for (let i = 0; i < answer.length; i++) {
      const index = value.indexOf(answer[i]);
      if (index > -1) { // 일치하는 숫자 발견
        if (index === i) { // 자릿수도 같음
          strike += 1;
        } else { // 숫자만 같음
          ball += 1; 
        }
      }
    }
    if (strike === 0 && ball === 0) {
      out++;
      $logs.append(`${value}:아웃`, document.createElement('br'));
    } else {
      $logs.append(`${value}:${strike} 스트라이크 ${ball}`, document.createElement('br'));
    }
    if (out === 3) {
      defeated();
      return;
    }
    tries.push(value);
  });
</script>
</body>
</html>

랜덤 사용하기(Math.random)

무작위로 숫자 네 개 뽑기

  const $input = document.querySelector('#input');
  const $form = document.querySelector('#form');
  const $logs = document.querySelector('#logs');

  const numbers = []; // [1, 2, 3, 4, 5, 6, 7, 8, 9]
  for (let n = 0; n < 9; n += 1) {
    numbers.push(n + 1);
  }
  const answer = []; // [3, 1, 4, 6]
  for (let n = 0; n < 4; n += 1) { // 네 번 반복
    const index = Math.floor(Math.random() * numbers.length); // 0~8 정수 
    answer.push(numbers[index]);
    numbers.splice(index, 1);
  }

인덱스를 랜덤값으로 뽑아서 numbers에 접근하고 숫자를 뽑는다. 해당 인덱스의 숫자는 제거한다.

입력값 검증하기

input이 있으면 form으로 감싸고 form에다가 eventListener를 다는 것이 표준이다.

$form.addEventListener('submit', (event) => {
  event.preventDefault(); //기본 동작 막기
});

form이나 a태그의 기본동작은 화면의 새로고침과 거의 비슷하다. 그렇게하면 변수값이 다 날아가기 때문에 preventDefault()로 기본 동작의 작동을 막아야한다.

  const tries = [];
  function checkInput(input) { // 3146,   314,  3144
    if (input.length !== 4) { // 길이는 4가 아닌가
      return alert('4자리 숫자를 입력해 주세요.');
    }
    if (new Set(input).size !== 4) { // 중복된 숫자가 있는가
      return alert('중복되지 않게 입력해 주세요.');
    }
    if (tries.includes(input)) { // 이미 시도한 값은 아닌가
      return alert('이미 시도한 값입니다.');
    }
    return true;
  }

  $form.addEventListener('submit', (event) => {
    event.preventDefault();
    const value = $input.value;
    $input.value = '';
    const valid = checkInput(value);
	...
  });

홈런인지 검사해서 표시하기

    // 입력값 문제없음
    if (answer.join('') === value) { // [3, 1, 4, 6] -> '3146'
      $logs.textContent = '홈런!';
      return;
    }
    if (tries.length >= 9) {
      defeated();
      return;
    }

몇 볼 몇 스트라이크인지 계산하기

    // 몇 스트라이크 몇 볼인지 검사
    let strike = 0;
    let ball = 0;
    // answer: 3146,  value: 1347
    for (let i = 0; i < answer.length; i++) {
      const index = value.indexOf(answer[i]);
      if (index > -1) { // 일치하는 숫자 발견
        if (index === i) { // 자릿수도 같음
          strike += 1;
        } else { // 숫자만 같음
          ball += 1; 
        }
      }
    }
    if (strike === 0 && ball === 0) {
      out++;
      $logs.append(`${value}:아웃`, document.createElement('br'));
    } else {
      $logs.append(`${value}:${strike} 스트라이크 ${ball}`, document.createElement('br'));
    }

셀프 체크 - 아웃 만들기

    if (strike === 0 && ball === 0) {
      out++;
      $logs.append(`${value}:아웃`, document.createElement('br'));
    } else {
      $logs.append(`${value}:${strike} 스트라이크 ${ball}`, document.createElement('br'));
    }
    if (out === 3) {
      defeated();
      return;
    }
    tries.push(value);

나중에 removeAddEventListener를 추가해서 게임이 끝난 이후에는 클릭해도 입력을 안받게 할 수도 있다.

배열 forEach, map, fill 알아보기

const answer = [3, 1, 4, 6];
const value = '3214';
let strike = 0;
let ball = 0;
answer.forEach((element, i) => {
  const index = value.indexOf(element);
  if (index > -1 ) { //일치하는 숫자 발견
    if (index === i){ // 자릿수도 같음
      strike += 1;
    } else { //숫자만 같음
      ball += 1;
    }
  }
 }
});

forEach가 for보다는 성능은 안좋다. 함수를 만들고 함수를 호출하기 때문이다. 하지만 가독성이나 편리함에서 이득을 본다.

const array = [1,2,3,4];
const result = [];
for (let i = 0; i < 4; i++) {
  result.push(array[i] * 2);
}

array.map((element, i) => {
  return element * 2;
})

기존 배열은 안바뀌고 새로운 배열에 값이 저장되는 것이다.

0개의 댓글