該程序是一個高低猜測遊戲,其中隨機數是從用戶輸入的特定範圍內生成的,用戶必須猜測該隨機數。使用特定範圍內的隨機數猜測遊戲
我在想,如果targetNumber或currentGuess有問題。該程序似乎工作得很好,但是當我輸入currentGuess數字時,對話框要麼再次彈出或者告訴我太大,再次嘗試,即使數字小於數字範圍。
另外,我想讓用戶在輸入targetMax和targetMin時不能輸入十進制數或其他字符。
var keepPlaying = true;
var currentGuess = 0;
var targetMax = null;
var targetMin = null;
var targetNumber = parseInt(targetMin + Math.random()*((targetMax - targetMin)+1));
var turnCounter = 1;
targetMax = prompt("Choose a whole number to set your maximum parameter.");
targetMin = prompt("Choose a whole number to set your minimum parameter.");
while (keepPlaying) {
//get a valid guess
do {
currentGuess = prompt("Please guess a whole number between " +targetMin+ " and " +targetMax+ ".", "");
}
while (!((currentGuess > targetMin) && (currentGuess <= targetMax)))
//handle the guess
if (currentGuess == targetNumber) {
alert("YOU'RE RIGHT!!!\n\nIt took you " + turnCounter + " tries to guess the number.");
keepPlaying = confirm("Do you want to play again?")
if (!keepPlaying) {
break; //not needed, just wanted to show how to exit a loop early
}
//reset game
targetNumber = parseInt(targetMin + Math.random()*((targetMax-targetMin)+1));
turnCounter = 0;
} else if (currentGuess > targetNumber) {
alert("Too big, try again.");
} else if (currentGuess < targetNumber) {
alert("Too small, try again.");
} else { //should be inaccessible
alert("There was an error parsing your guess.");
}
//update counter
turnCounter++;
}
document.write("<h1>Thank you for using my <font color='red'>AWESOME</font>, web-based guessing game.</h1>");
您在提示用戶輸入最大和最小參數之前設置您的'targetNumber'。另外,Java和Javascript不是一回事,這個問題與Java沒有任何關係。 –
@AaronD聽起來像是解決方案,你應該提交一個答案。 – Jeriko