숫자야구 prompt

박서현·2023년 8월 16일
0
post-thumbnail
  • 숫자야구 readline 이 방법은 readline을 사용하여 입력을 받아서 진행이 된다.
  • 입력받는 방법이 까다롭고 코드가 어려운것같아 더 쉽게 코드를 작성 해 보았다.
  • readline이 아닌 prompt를 사용하여 입력받는다.
// 각 자리수의 숫자가 다른 3자리 난수 만들기
function getRandomNum() {
    let num = [] 
    while(num.length < 3) {
        const ranNum = Math.floor(Math.random() * 10);
        if (!num.includes(ranNum)) {
            num.push(ranNum)
        }
    }
    return num.join("");
}

async function baseball() {
    let count = 0
    const answer = getRandomNum();
    alert("컴퓨터가 숫자를 생성하였습니다. 답을 맞춰보세요!")
    let isCorrect = false;
    while (!isCorrect) {
        let countB = 0
        let countS = 0
        const line = prompt("3자리 정수를 입력해주세요", "3자리 정수 입력");
        
        if(line.length !== 3 || isNaN(line)) {
            alert("3자리 정수를 입력해야합니다.")
            continue;
        }  

        count++
        alert(`${count}번째 시도 : ${line}`)

        for(let i = 0; i < line.length; i++) {
            if (line[i] === answer[i]) {
                countS++;
                continue;
            }

            if (answer.includes(line[i])) {
                countB++;
            }
        }

        if (countS === 3) {
            alert(`축하합니다!! 정답은 ${answer}이고, ${count}번 만에 맞추셨어요!`);
            isCorrect = true
            return;
        } 

        alert(`스크라이크: ${countS}번, 볼: ${countB}`)

    }
    
}

0개의 댓글