我有以下数字猜谜游戏。这是我上课的任务。每次我运行代码时,"你有" + i +"剩余的机会......"语句返回i为0.如何使每次用户按下确认按钮时,它会循环一次,然后减少1? 我需要在赋值循环和重置按钮!
<body>
<!-- GAME INSTRUCTIONS -->
<h1>Number Guessing Game</h1>
<p>A random number between 1 and 100 has been generated. Can you guess it?</p>
<!-- FORM (Includes button to confirm guess, input box, and output box) -->
<form id="Input" name="Input">
<input name="guess" placeholder="Insert your guess" type="number">
<input name="requestInfo" onclick="getResults()" type="button" value="Confirm">
<p></p>
<textarea cols="50" name="results" readonly="true" rows="8"></textarea>
<p></p><input name="newGame" onclick="resetGame()" type="button" value="Start New Game">
</form><!-- JAVASCRIPT START -->
<script type="text/javascript">
// Define variables
var num = Math.floor(Math.random() * 100) + 1;
var turns = 10;
function checkNumber() {
var guess = parseFloat(document.Input.guess.value);
while (turns > 0) {
if (guess == num) {
turns = 0;
document.Input.results.value = "Congratulations, you won! The mystery number was " + num + ".";
} else if (guess < num) {
turns--;
document.Input.results.value = "Your guess was too low. Turns remaining: " + turns;
} else if (guess > num) {
turns--;
document.Input.results.value = "Your guess was too high. Turns remaining: " + turns;
}
}
}
function resetGame() {
turns = 10;
num = Math.floor(Math.random() * 100) + 1;
document.Input.guess.value = "";
document.Input.results.value = "";
}
function getResults() {
checkNumber();
}
</script>
</body>
答案 0 :(得分:0)
循环时根本不需要;只需使用 if 。
此外,你需要把我放在外面以便反映出变化。
<script type="text/javascript">
// Define variables
var i = 5;
var num = Math.floor(Math.random() * 100) + 1;
function checkNumber() {
var guess = parseFloat(document.Input.guess.value);
if(i > 0) {
if (guess == num){
i = 0;
document.Input.results.value = "Congratulations, you won!";}
else if (guess < num){
i--;
document.Input.results.value = "Your guess was too low. You have " + i + " chances remaining before a new game starts.";
}
else if (guess > num){
i--;
document.Input.results.value = "Your guess was too high. You have " + i + " chances remaining before a new game starts.";
}
}
}
function getResults(){
checkNumber();
}
</script>
答案 1 :(得分:0)
在函数
之外声明我var i =5;
function checkNumber() {
var num = Math.floor(Math.random() * 100) + 1;
var guess = parseFloat(document.Input.guess.value);
while (i > 0) {
if (guess == num){
i = 0;
document.Input.results.value = "Congratulations, you won!";}
else if (guess < num){
i--;
document.Input.results.value = "Your guess was too low. You have " + i + " chances remaining before a new game starts.";
}
else if (guess > num){
i--;
document.Input.results.value = "Your guess was too high. You have " + i + " chances remaining before a new game starts.";
}
}
}
答案 2 :(得分:0)
调用您的函数checkNumber
时,num
已初始化,guess
也是如此。然后,您在while循环guess
次中将相同的num
与i
进行比较。你应该移动这一行
var guess = parseFloat(document.Input.guess.value);
在while循环中。