JavaScript

[JavaScript] 야구게임 구현하기

yeeebin 2022. 12. 10. 15:38

index.html

<!DOCTYPE html>
<html lang="ko">
<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>
    <link rel="stylesheet" href="style.css"/>
    <script type="module" src="App.js"></script>
</head>
<body>
    <label for="input">정답은?</label>
    <input type="number" id="input" name="input"/>
    <button id="submit">도전</button>
    <div id="result">결과</div>

</body>
</html>

style.css

body::after{
    position: absolute;
    content: "";
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-image: url('./src/images/BaseBallImg.jpg');
    background-repeat: no-repeat;
    opacity: 0.5;
    z-index: -1;
}

label {
    display: block;
    padding: 10px;
    width: max-content;
}

#submit{
    background-color: black;
    color: white;
}

#result{
    margin: 10px;
    padding: 10px;
    width: 300px;
    text-align: center;
    background-color: black;
    color: white;
}

🔴 4자리의 정답(난수) 생성

- 중복되는 숫자가 없어야 하므로 while문을 이용하여 중복되지 않는 숫자를 하나씩 추가하도록 구현

let answer = []; //정답의 4자리 수가 저장되는 배열

while(answer.length != 4){
    let num = Math.floor(Math.random() * 10); //1의 자리 난수 생성
    if(answer.indexOf(String(num)) == -1){ //중복되는 숫자가 없는 경우에만 추가
        answer.push(String(num));
    }
}

 

🟠 '도전'버튼에 이벤트 리스너 추가

- try_num(시도 횟수)를 이용하여 10회 초과시 alert창을 띄움.

- isValid 함수를 이용해 입력값이 올바른지 확인

- print_result 함수를 이용해 결과 출력

let try_num = 1; // 시도 횟수
const btn_submit = document.getElementById("submit");

btn_submit.addEventListener('click', () => {
    if(try_num > 10){
        alert(`쓰리아웃!! 정답: ${answer.join("")}`);
    } else{
        let input = document.getElementById("input").value.split("");
        if(isValid(input)){
            print_result(check_answer(input, answer), input, try_num++);
        } 
    }
});

 

🟡 isValid 함수 : 입력값이 유효한지를 확인하는 함수

- 입력된 숫자가 배열로 저장된  input을 인자로 받음.

- input의 길이가 4가 아니면 alert창을 띄우고 false를 반환

- indexOf()를 이용해 중복된 숫자가 포함되어 있으면 alert창을 띄우고 false를 반환

- 위의 두 조건을 만족하면 true를 반환

//중복숫자가 있는지, 4개의 숫자가 입력됐는지 확인
function isValid(input){
    if(input.length != 4){
        alert("숫자 4자리를 입력해주세요!");
        return false;
    } else{
        for(let i = 0; i < input.length-1; i++){
            if(input.indexOf(input[i], i+1) != -1){
                alert("중복된 숫자가 포함되어 있습니다. 모두 다른 숫자를 입력하세요.");
                return false;
            }
        }
    }
    return true;
}

 

🟢 check_answer 함수 : 입력값과 정답을 비교하는 함수

- 입력값에 대한 배열 input과 정답 배열 answer을 인자로 받음

- 이미 isValid에서 통과한 후 실행되는 함수이기 때문에 input은 길이가 4이고, 중복숫자가 없는 상태

- input과 answer의 같은자리에 같은 숫자가 있으면 strike는 1증가이고, 같은자리는 아니지만 같은 숫자가 포함되어 있으면 ball을 1 증가 시킴.

- strike와 ball을 값으로 가지는 배열 반환

//입력값과 정답 비교 함수
function check_answer(input, answer){
    let strike = 0;
    let ball = 0;
    for(let i = 0; i < input.length; i++){
        if(input[i] == answer[i]) strike++;
        else if(answer.indexOf(input[i]) != -1) ball++;
    }

    return [strike, ball];
}

 

🔵 print_result 함수 : 결과를 출력하는 함수

- strike와 ball을 값으로 가지는 배열 result, 입력값에 대한 배열 input, 시도 횟수 try_num을 인자로 받음.

- result[0] (strike)가 4라면 모든 숫자의 위치가 맞다는 의미이므로 홈런!

 ▶원래 '정답은?'이라고 적혀있던 label에 정답 표시하고, 결과창에 홈런 출력

- 홈런이 아니라면 결과를 결과출력 div의 innerHTML에 추가.

//결과 출력 함수
function print_result(result, input, try_num){
    let innerHTML = `<br/>${try_num}차 시도 : ${input.join("")}, `;
    if(result[0] == 4){
        innerHTML += "홈런!!!"
        const label = document.getElementsByTagName("label")[0];
        label.innerHTML = `${answer.join("")}`;
    } else innerHTML += `STRIKE: ${result[0]}, BALL: ${result[1]}`;

    const div_result = document.getElementById("result");
    div_result.innerHTML += innerHTML;
};

 

 

구현 결과

https://github.com/bin000527/JS_Study/tree/main/BaseballGame