본문 바로가기

FE/REACT

[리액트]js선수 지식-반복문 사용(숫자야구 게임)

▶1~9까지 숫자 중복없이 네자리수 만들고, 숫자 맞추게 하는 게임

볼: 숫자는 같은데 자리수를 틀린 경우

아웃: 다 틀린 경우

스트라이크: 숫자같고 자리수도 맞춘 경우

홈런: 4자리 다 맞춘경우

의 조건을 가지는 게임이라고 생각하면 된다.

 

▶html 작성하기 

<!DOCTYPE html>
<html lang="en">
<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>
    <form id="form">
        <input type="text" id="input">
        <button>확인</button>
    </form>
    <div id="logs"></div>
</body>
<script>
    const $input=document.querySelector('#input');
    const $form=document.querySelector('#form');
    const $logs=document.querySelector('#logs');
</script>
</html>

 

▶무작위로 숫자 뽑기

숫자를 무작위로 뽑기 위해서는 random함수를 사용해주면된다. 

Math.random() : 0-1미만의 수를 무작위로 생성해주기 때문에 1~9까지 무작위의 수를 뽑기 위해서는 Math.random()*9+1을하고 소숫점 이하의 수들을 내려주면 된다. 

그래서 최종적인 식은 Math.floor(Math.random()*9+1) 이 된다.

 

 

▶코드 구현하기

-반복문을 이용해 숫자를 넣어주기

    const numbers=[];
    for(let n=1; n<=9; n+=1)
    {
        numbers.push(n);
    }

 

▶ 4자리 숫자를 랜덤하게 뽑기 위한 알고리즘

<!DOCTYPE html>
<html lang="en">
<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>
    <form id="form">
        <input type="text" id="input">
        <button>확인</button>
    </form>
    <div id="logs"></div>
</body>
<script>
    const $input=document.querySelector('#input');
    const $form=document.querySelector('#form');
    const $logs=document.querySelector('#logs');

    const numbers=[];
    for(let n=0;n<9;n++)
    {
        numbers.push[n+1];
    }
    const answer=[];
    for(let n=0; n<4; n++){//4번 반복하도록 도와줌
        const index=Math.floor(Math.random()*(numbers.length-n));
        answer.push(numbers[index]);
        numbers.splice(index,1); //뽑은것은 삭제해줌
    }
    console.log(answer);
</script>
</html>

 

 

▶형식검사하기 

 검사해야 할 항목: 길이, 중복된 숫자 확인, 이미 시도한 값인지 확인해주어야 한다.

    function checkInput(input){ //검사하는 코드
        if(input.length!==4){
            return alert('4자리 숫자를 입력해 주세요');
        }
        if(new Set(input).size!==4){
            return alert('중복되지 않게 입력해 주세요:');
        }
        if(tries.includes(input)){//시도한 값인지 아닌지
            return alert('이미 시도한 값입니다.');
        }
        return ture;
    }

-알아서 중복을 제거해주는 배열 : new Set, length가 아닌 size로 크기를 확인

 

 

▶홈런인지 아닌지 검사하기 

  //입력값 문제 없음
        if(answer.join('')===value){
            $logs.textContent='홈런!';
            return;
        }

 

▶시도횟수가 10번을 넘어가는지 확인, 넘어간다면, 게임 종료

 

        if(tries.length>=9){//시도 횟수 확인하기 
            const message=document.createTextNode(`패배, 정답은 ${answer.join('')}`);
            $logs.appendChild(message);
            return;
        }

 

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

        //몇볼, 몇 스트라이크인지 계산하기 
        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;
                }
            }
        }

 

▶마지막으로 3스트라이크면 아웃이 되도록 한다.

        //아웃 검사
        if(strike===0&&ball===0){
            out++;
            $logs.append(`${value}:아웃`,document.createElement('br'));
        }
        else{
            $logs.append(`${value}:${strike}스트라이크${ball}볼`,document.createElement('br'));
        }
        if(out===3){
            const message=document.createTextNode(`패배, 정답은 ${answer.join('')}`);
        }