随机数猜测游戏 - 限制猜测次数

时间:2017-03-20 05:29:58

标签: javascript html

我试图创建一个生成用户猜测的随机数的程序。它还限制了用户可以做出(或者应该是)的猜测次数。

     var highLimit = 5;
        var randNum = Math.floor((Math.random() * highLimit) + 1);
        var allowedGuesses = 2;
        var numGuesses = 0;

        function guessingGame() {
            if (numGuesses <= allowedGuesses) {                    

               do {
                    inputNum = document.numForm.number.value;
                    inputNum = parseInt(inputNum);


                    if (inputNum < randNum && inputNum > 1) {
                        document.numForm.gameResults.value = "Sorry, your guess was too low.";
                        numGuesses++;
                    }

                    else if (inputNum > randNum && inputNum < highLimit) {
                        document.numForm.gameResults.value = "Sorry, your guess was too high.";
                        numGuesses++;
                    }
                    else if (inputNum == randNum) {
                        document.numForm.gameResults.value = "Congratulations! You guessed correctly.";
                        numGuesses++;
                    }

                    else {
                        document.numForm.gameResults.value = "Your guess was out of the desired parameters. Please guess again.";
                        numGuesses--;
                    }

                } while(numGuesses < allowedGuesses && inputNum != randNum);

            }

                else {
                    document.numForm.gameResults.value = "Sorry, you have reached the allowed number of guesses, which is " + allowedGuesses + "." + " Click 'New Game' to try again.";
                }
            return false;
        }

        numGuesses = 0;
        function newGame() {
                randNum = Math.floor((Math.random() * highLimit) + 1);
                guessingGame();
                return false;
           }

HTML:

 <form name = "numForm">
        <fieldset>
            <label for = "randNum">Enter a number between 1 and 5: </label>
            <input type = "text" name = "number" value = "" id = "randNum" size = "1" maxlength = "1" />
        </fieldset>
        <input class = "button" type = "button" name = "submit" onclick = "guessingGame()" value = "Submit Number"  />

        <input class = "button" type = "reset" name = "newGame" onclick = "newGame()" value = "New Game" />
        <fieldset>
            <textarea name = "gameResults"  onclick = "" readonly = "true" value = "" rows = "5" cols = "40" ></textarea>
        </fieldset>
    </form>

现在,由于highLimit设置为5,程序停留在无限循环中。但如果我将其设置为10,则程序可以运行。我该如何修复它以便它能以任何价值运行?我还要感谢其他改进建议。

提前致谢!

2 个答案:

答案 0 :(得分:0)

我认为你不需要这个循环。你可以简单地说:

function guessingGame() {
    if (numGuesses < 0){numGuesses=0;}
    if ((numGuesses < allowedGuesses) && (inputNum != randNum)) {                    
            inputNum = document.numForm.number.value;
            inputNum = parseInt(inputNum);


            if (inputNum < randNum && inputNum > 1) {
                document.numForm.gameResults.value = "Sorry, your guess was too low.";
                numGuesses++;
            }

            else if (inputNum > randNum && inputNum < highLimit) {
                document.numForm.gameResults.value = "Sorry, your guess was too high.";
                numGuesses++;
            }
            else if (inputNum == randNum) {
                document.numForm.gameResults.value = "Congratulations! You guessed correctly.";
                numGuesses++;
            }

            else {
                document.numForm.gameResults.value = "Your guess was out of the desired parameters. Please guess again.";
                numGuesses--;
            }
    }

        else {
            document.numForm.gameResults.value = "Sorry, you have reached the allowed number of guesses, which is " + allowedGuesses + "." + " Click 'New Game' to try again.";
        }
    return false;
}

if (numGuesses < 0){numGuesses=0;}也会有所帮助。对于否定案例。

答案 1 :(得分:0)

这是更新:

<块引用>

运行代码段并在“0 次尝试”中发誓

我是这样做的:但是如果 4 年后您仍然需要它,您将不得不用指定的输入和输出替换“提示”和“警报”:

 let maximum = parseInt(prompt('Enter the maximum number!') );
    while(!maximum) {
      maximum = parseInt (prompt('Please enter a valid number') )
    }
    const targetNum = Math.floor(Math.random()*maximum)+1;
    let attempts =0;
    let maxAttempts = Math.ceil(maximum/2);

    // ==== Uncomment the line below to cheat --> ======

    // console.log(targetNum)

    let guess = parseInt(prompt(`Enter your first guess!, you have ${maxAttempts} attempts (press 'q' anytime to escape from this hellish nightmare)`));
    while(parseInt(guess) !==targetNum && attempts < maxAttempts-1)  {
     
      if (typeof(guess) === 'string' && guess.toLowerCase() ==='q') {break;}
      attempts++;
      if(guess>targetNum) {
        guess = (prompt(`Too High! Enter new guess! attempts left: ${maxAttempts- attempts} (press 'q' anytime to escape from this hellish nightmare)`))
      }else {
        guess= (prompt(`Too low! Entere a new Guess! attempts left: ${maxAttempts- attempts} (press 'q' anytime to escape from this hellish nightmare)`))
      }
    } 
    if(typeof(guess) === 'string' && guess.toLowerCase() ==='q') {
      alert(`You gave up after ${attempts} attempts`); 
    }
    else if(attempts >= maxAttempts-1) {alert(`Oops, your ${maxAttempts} attempts ran out, the number was ${targetNum}: Verification : ${targetNum==guess}`);}
    else {
    alert(`Good job, you got it ${attempts+1} attempts!, the number was ${targetNum}: Verification : ${targetNum==guess}`) ; 
    }