【发布时间】:2014-09-11 04:04:11
【问题描述】:
我是 Javascript 的新手,我已经构建了一个简单的数字猜谜游戏。该程序会生成一个介于 1-10 之间的随机数,并在您的猜测过高或过低时提示您。如果你猜对了,你就赢了。
我想通过给玩家 3 次猜测来改进当前版本,之后玩家要么赢,要么输。我知道这是通过循环完成的,但我一生都无法弄清楚如何做。我尝试过使用 while 循环,但它不起作用。这是我的代码,谢谢大家的帮助:
<script>
var rannum = Math.floor((Math.random() * 10) + 1); //generates a random number and stores it in the rannum variable
function submitanswer(){ //This function analyzes player response and is called by the submit button
var playerguess = document.getElementById("guess"); //grabs whatever the player types in and stores it in the playerguess variable
if (playerguess.value == rannum){ //if the value of playerguess is the same as rannum then the player wins
alert("You win!");
location.reload();
}
if (playerguess.value > rannum){ //if the player's guess is higher than the random number alert too high
alert("Too high!");
document.getElementById("guess").value='';
}
else if (playerguess.value < rannum){ //if the player's guess is lower than the random number alert too low
alert("Too low!");
document.getElementById("guess").value='';
}
}
function reloaD(){ //start over by generating a new number
document.getElementById("guess").value='';
location.reload();
}
</script>
</body>
</html>
【问题讨论】:
-
不要使用循环。等待用户执行操作,例如按下按钮或在输入单词后按回车。然后按照逻辑继续:猜对了吗?如果不是,他们是不是猜错了太多次?如果是这样,那么游戏结束。
-
对于初学者,创建一个您可以调用的初始化函数,这样您就不必重新加载。您不能使用循环,只能使用您设置为 3 的计数器并在它为 0 时调用 init。init 将拥有您的生成器,并重置计数器
标签: javascript numbers