在我的Javascript数字猜谜游戏中添加一个猜谜循环

2w3rbyxf  于 2022-10-30  发布在  Java
关注(0)|答案(2)|浏览(200)

我是Javascript新手,我开发了一个简单的数字猜谜游戏。该程序生成一个1-10之间的随机数,并提示你猜得太高或太低。如果你猜对了,你就赢了。
我想改进这个版本,给玩家3次猜测,之后玩家要么赢,要么输。我知道这是用循环完成的,但我一辈子都搞不懂怎么做。我试过使用while循环,但它不起作用。这是我的代码,谢谢大家的帮助:

<script>
    var rannum = Math.floor((Math.random() * 10) + 1); //generates a random number and stores it in the rannum variable

        function submitanswer(){  //This function analyzes player response and is called by the submit button
            var playerguess = document.getElementById("guess"); //grabs whatever the player types in and stores it in the playerguess variable
            if (playerguess.value == rannum){ //if the value of playerguess is the same as rannum then the player wins
                alert("You win!");
                location.reload();
            }
            if (playerguess.value > rannum){ //if the player's guess is higher than the random number alert too high
                alert("Too high!");
                document.getElementById("guess").value='';
            }

            else if (playerguess.value < rannum){ //if the player's guess is lower than the random number alert too low
                alert("Too low!");
                document.getElementById("guess").value='';
            }

        }
        function reloaD(){ //start over by generating a new number
            document.getElementById("guess").value='';
            location.reload();
        }                           

    </script>
    </body>
</html>
7hiiyaii

7hiiyaii1#

所以这是我如何继续你的游戏..我会尽我最大的努力让你明白我的逻辑。
首先,您需要一个输入框,用户将输入他/她的猜测和一个按钮提交该猜测:

Your Guess: <input type='text' id='guess'>
<button id="checkBtn">Check</button>

然后是一个关于按钮点击的事件监听器。在这个监听器中,我从输入框中获取用户的猜测值,并将其发送到另一个函数,该函数将检查猜测值是否正确,是低还是高。同时,我还保留了一个计数器,它将在每次按钮点击时递增。用户将只能检查到maxGuesses,最初为3。当计数器等于max guesses时,这是当游戏结束,我禁用按钮,所以没有更多的输入。

document.getElementById('checkBtn').onclick = function (){
    var guess = document.getElementById('guess').value;
    checkGuess(guess);
    counter++;

    if(counter == maxGuesses) {
        alert("Game Over");
        document.getElementById("checkBtn").disabled = true;
    }
}

检查猜得太高,太低或正确的猜测是简单的逻辑,因为你使用,三个条件。2在正确的猜测,用户将显示“你赢了!”3和按钮将再次被禁用,因为游戏现在结束了。

function checkGuess(guess){
    if (guess == rannum){ //if the value of playerguess is the same as rannum then the player wins
        alert("You win!");
        document.getElementById("checkBtn").disabled = true;
    }
    if (guess > rannum){ //if the player's guess is higher than the random number alert too high
        alert("Too high!");
        document.getElementById("guess").value='';
    }

    else if (guess < rannum){ //if the player's guess is lower than the random number alert too low
    alert("Too low!");
         document.getElementById("guess").value='';
     }
}

  • 编辑:* 我添加了重新启动功能,以及。通过添加一个重新启动按钮,这是最初隐藏display: none
<button id="restart" style="display:none">Restart</button>

当用户获胜或游戏结束(达到最大猜测数)时,它将显示。

document.getElementById("restart").style.display='block'; //making it visible

然后,当用户点击重新启动,所有的值重置,重新启动按钮消失,游戏再次开始。

document.getElementById('restart').onclick = function (){
    rannum = Math.floor((Math.random() * 10) + 1);
    counter = 0;  
    guess = 0;
    document.getElementById("checkBtn").disabled = false;
    document.getElementById("guess").value='';
    document.getElementById("restart").style.display='none';
}

thtygnil

thtygnil2#

这里不需要使用循环。您可以使用一个变量来跟踪还剩下多少个猜测。每次计算答案时,将该变量减1。如果减到0,游戏就输了。
我还对您的代码进行了一些其他改进,即:

  • 对代码使用单独的JS文件。
  • 将程式码 Package 在立即叫用的函数运算式中,以避免遗漏任何全局变量。
  • 为变量提供了一些更易读的名称。
  • 仅从DOM中提取DOM元素一次。
  • 替换了alert(),支持将答案直接放在DIV中。
  • 删除了页面重新加载-这是没有必要在这里,你可以只是重置游戏的状态.

文件索引.html:

<!DOCTYPE html>
<html>
    <head>
        <title>Guess the number</title>
    </head>
    <body>
        <form>
            <input type="text" id="guess" />
            <input type="submit" id="submitAnswer" value="Check answer" />
        </form>
        <div id="answer"></div>
        <script src="game.js"></script>
    </body>
</html>

文件game.js:

(function () {

    var guessesLeft, randomNumber, guessInput, submitButton, answerDisplay, maxGuesses;

    maxGuesses = 3;

    // Load all the element references from the DOM
    // so that we don't need to do that every time we chek the answer
    guessInput = document.getElementById("guess");
    submitButton = document.getElementById("submitAnswer");

    // Let's use a DIV element to display the answer.
    // It's nicer than using alert().
    answerDisplay = document.getElementById("answer");

    answerDisplay.innerHTML = "Please make a guess!";

    submitButton.addEventListener("click", function (event) {
        event.stopPropagation();
        event.preventDefault();
        checkAnswer();
    });

    initGame();

    function initGame () {
        guessesLeft = maxGuesses;
        randomNumber = Math.floor(Math.random() * 10 + 1);
        guessInput.value = "";
    }

    function checkAnswer () {

        if (guessInput.value == randomNumber) {
            answerDisplay.innerHTML = "You win! " + randomNumber + " is correct. " +
                "Please input your next guess to start again.";
            initGame();
            return;
        }
        else if (guessInput.value > randomNumber) {
            answerDisplay.innerHTML = "Too high!";
        }
        else {
            answerDisplay.innerHTML = "Too low!";
        }

        guessesLeft -= 1;

        if (guessesLeft === 0) {
            answerDisplay.innerHTML += " No guesses left - you lost!";
            initGame();
        }
    }

}());

相关问题