<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
<html>
<head>
<title>Game</title>
<script type="text/javascript" src="game.js"></script>
</head>
<body>
<h1>GameSite</h1>
<p> This program will generate a random number. Please input your guess in the box!</p>
<button onclick="guessGame()">Press me to play a quick game!</button>
<script>
function guessGame(){
number = Math.floor(Math.random()*11);
document.write(number);
var guess = prompt("Guess a number: ");
do {
guess = prompt("Keep guessing!");
if (number < guess) {
prompt("You've guessed too high!");
} else if (number > guess) {
prompt("You've guessed too low!");
} else document.write("Good Job!");
} while (guess != number);
}
</script>
</body>
</html>
我遇到循环问题。它循环很好,但是如果我在if语句后移动了guess语句,那么每次都会返回到该语句。如果我把它放在if语句之外,那么它似乎实际上不允许我猜出一个有效的数字。很难解释:\
答案 0 :(得分:5)
我建议只使用一个提示并将其分配给变量。
function guessGame() {
var number = Math.random() * 11 | 0,
guess,
text = 'Guess a number:';
do {
guess = prompt(text);
if (number < guess) {
text = "You've guessed too high!";
} else if (number > guess) {
text = "You've guessed too low!";
}
} while (guess != number);
document.write("Good Job!");
}
guessGame();
答案 1 :(得分:1)
试试这个:
System.exit
while循环将一直运行,直到猜到正确的数字,然后它将终止。
编辑:对不起,输入错误的错误
答案 2 :(得分:0)
当您不需要用户的回复时,我建议您使用alert
function guessGame(){
number = Math.floor(Math.random()*11);
var guess;
do {
guess = prompt("Guess a number: "); // you should handle string input here
if (number < guess) {
alert("You've guessed too high!");
alert("Keep guessing!");
} else if (number > guess) {
alert("You've guessed too low!");
alert("Keep guessing!");
}
} while (guess != number);
alert("Good Job!");
}
答案 3 :(得分:0)
相信我,我是一名程序员。
strtrim