我正在尝试做一个程序,它能产生一个用户可以猜的随机数。它还限制了用户可以(或应该)猜测的数量。
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条答案
按热度按时间rslzwgfq1#
我觉得你不需要在这一个循环。你可以简单地说:
if (numGuesses < 0){numGuesses=0;}
也会有帮助。负面案例。5gfr0r5j2#
此更新针对:
运行代码段并在“0次尝试”中回答
我是这样做的:但是,如果4年后您仍然需要它,您将不得不使用指定的输入和输出来替换“提示”和“警报”: