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

h5qlskok  于 2023-06-28  发布在  Java
关注(0)|答案(2)|浏览(115)

我正在尝试做一个程序,它能产生一个用户可以猜的随机数。它还限制了用户可以(或应该)猜测的数量。

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,程序就能工作。我如何修复它,使它在任何值下都能工作?我还希望有其他改进建议。
先谢谢你了!

rslzwgfq

rslzwgfq1#

我觉得你不需要在这一个循环。你可以简单地说:

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;}也会有帮助。负面案例。

5gfr0r5j

5gfr0r5j2#

此更新针对:

运行代码段并在“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}`) ; 
    }

相关问题