對於一個任務,我需要做一個JS數字猜謎遊戲。它需要包含一個循環來檢查用戶的猜測和重置遊戲按鈕。我的問題是讓循環工作。我想讓轉數從10開始。每次用戶做出不正確的猜測時,他們的轉數減少1,如果他們猜測正確,他們的轉數爲0.如果他們推動「開始新遊戲」按鈕,應該生成一個新的數字並且圈數應該被重置爲10.將一個循環插入一個Javascript數字猜謎遊戲
該循環並不需要是一個while循環,我只需要在代碼中爲我的任務分配一個循環。有人可以幫我嗎?
<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>
我會刪除循環,如果我可以。在學習老師需要循環完成作業之前,我做了完全相同的事情。 – Emily
如果你需要循環,你必須改變邏輯。想讓我把它寫出來嗎? –
如果可以的話,那會很棒 – Emily