[JS] 야구게임

게코젤리·2022년 9월 30일
0
post-thumbnail

개요

10회 안에 성공해야하는 야구게임, 반복문, Math.random()
github: https://github.com/raquim47/study/blob/main/zero/js/baseball.html
github.io: https://raquim47.github.io/study/zero/js/baseball
유튜브강의: https://youtu.be/MlANtfGIlzI

순서도

html 구성

<form id="form">
  <input type="text" id="input">
  <button>확인</button>
</form>
<div id="logs"></div>

javascript

  1. 4자리 무작위 숫자 뽑기
Math.random() // --> 0 <= x < 1
Math.random() * 9 // --> 0 <= x < 9
Math.random() * 9 + 1 // --> 1 <= x < 10
Math.floor(Math.random() * 9 + 1) 
// parseInt(Math.random() * 9 + 1) -> floor가 더 빠름 
// --> x = (1,2,3,4,5,6,7,8,9)
// index로 사용한다면 index는 0부터 시작, 1~9값을 얻고 싶다면 0~8
  • fill(), map()을 활용해서 배열 만들기
//기존 for
const num = [];
for (let i = 0; i < 9; i++) {
  num.push(i + 1);
}
// fill, map 활용
const num = Array(9).fill().map((el, i) => i + 1);
const $input = document.querySelector('#input');
const $form = document.querySelector('#form');
const $logs = document.querySelector('#logs');

const num = [];
for (let i = 0; i < 9; i++) {
  num.push(i + 1);
}

const answer = [];
for (let i = 0; i < 4; i++) {
  // index니까 0~8
  const index = Math.floor(Math.random() * (num.length - i));
  answer.push(num[index]);
  num.splice(index, 1)
}
  1. input 입력값이 형식에 맞는 지 검사
  • new Set(), includes() 함수
const checkInput = (input) => {
  if (input.length !== 4) {
    return alert('4자리 숫자를 입력해주세요');
  }
  if (new Set(input).size !== 4) {
    return alert('중복되지 않은 숫자를 입력해주세요');
  }
  if (tries.includes(input)) {
    return alert('이미 입력한 값입니다');
  }
  return true;
}
const onSubmitForm = (e) => {
  e.preventDefault();	
  const value = $input.value;
  $input.value = ''
  if (checkInput(value)){
  	// input값이 형식에 맞을 때 실행코드
  }
  tries.push(value);
}
  1. 홈런인지, 10번 시도했는지 검사
  • 아래의 코드를 중복 제거
if (checkInput(value)) {
  if(value === answer.join('')){
    $logs.append(`${value}: 홈런`) ;
    $input.disabled = true;
    return;
  }
  if(tries.length >= 9){
    const message = document.createTextNode(`패배! 정답은 ${answer.join('')}`)
    $logs.append(message);
    return;
  }
  tries.push(value);
}
if (!checkInput(value)) {
  return; 

} 
if(value === answer.join('')){
  $logs.innerText = '홈런';
  return;
}
if(tries.length >= 9){
  const message = document.createTextNode(`패배! 정답은 ${answer.join('')}`)
  $logs.append(message);
  return;
}
tries.push(value);
  1. 볼, 스트라이크, 아웃 검사
  • 아웃 부분을 더 간결하게 할 수 있을 지 고민해보자.
// 함수 바깥에  let out = 0; 변수 생성
let strike = 0;
let ball = 0;
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}: ${out} 아웃 ${strike} 스트라이크 ${ball}`, document.createElement('br'));
tries.push(value);
if(out === 3){
  $logs.append(`패배! 정답은 ${answer.join('')}`);
  $input.disabled = true;
}

0개의 댓글