我很新的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