0
我正在尝试制作一个程序,用于生成用户猜测的随机数。这也限制了用户可以猜的次数(或应该)随机数猜测游戏 - 限制猜测次数
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,则该程序起作用。我怎样才能解决它,所以它可以在任何价值?我也赞赏其他改进建议。
提前致谢!
我不明白这种方法如何工作。 'while'循环会一遍又一遍地检查'document.numForm.number.value'中的相同值,而不给用户输入另一个值的机会。你需要摆脱循环,每按一次按钮就增加一次'numGuesses'。 –