我很新的Javascript和我已经构建了一个简单的猜数字游戏。该程序会在1-10之间生成一个随机数,并在您的猜测过高或过低时提示您。如果你猜对了,你就赢了。添加一个猜测循环到我的Javascript猜数字游戏
我想通过给玩家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>
不要使用循环。等待用户执行一个操作,例如*按下按钮*或*键入一个单词*后回车。然后*继续*与逻辑:猜测是否正确?如果不是,他们是否错误地猜错了太多次?如果是这样,那么GAME OVER。 – user2864740 2014-09-11 04:09:09
对于初学者来说,创建一个可以调用的初始化函数,以便不必重新加载。你不能使用一个循环,只是一个你设置为3的计数器,当它为0时调用init。init将使用你的生成器,并重置计数器 – mplungjan 2014-09-11 04:10:21