1
製作一個小遊戲,玩家必須猜測存儲的是什麼顏色。 預期的最終結果是,當玩家正確猜測消息顯示並且背景顏色改變時。然而,我的背景顏色只有在你關閉對話框後纔會改變。背景顏色變化的意外延遲
這裏是代碼。有問題的部分是在最後
<!DOCTYPE HTML>
<html>
<body onload="do_game()">
<script>
var colors = ["blue","red","yellow","green","brown",
"magenta","purple","aqua","coral",
"violet","pink","grey","cyan","black","white"];
var target;
var guess_count = 0;
var guess_input;
var game_end; false;
function do_game(){ //Start of function do_game //
colors.sort();
target = Math.floor(Math.random() * colors.length);
alert(colors[target]);
do {
guess_input = prompt(
"I am thinking of one of these colors \n\n" +
colors +"\n\nWhat color am I thinking of?")
guess_count ++;
}
while (check_guess());
} //end of function do_game //
function check_guess(){ //start of function check_guess//
var color_guess = colors.indexOf(guess_input);
if (color_guess < 0)
alert("I don't recognise that color!\n\n"
+ "Please try again");
else if (color_guess < target)
alert("Sorry your guess is not correct!\n\n"
+ "Hint: Your guess is aphebetically lower\n\n"
+ "Please try again!");
else if (color_guess > target)
alert("Sorry your guess is not correct!\n\n"
+ "Hint: Your guess is aphebetically higher\n\n"
+ "Please try again!");
else {
document.body.style.background = colors[target];
alert("Congratulations!\n\n" + "You guessed " + colors[target]
+ "\n\nThis is correct!\n\n"
+ "It took you " + guess_count + " guesses");
return false;
}
return true;
}
</script>
</body>
</html>
您正在使用一個警告框,它將停止執行Javascript,直到它被回覆。您應該使用通知'div'(或類似的東西)與用戶溝通。 – Sablefoste