制作小型游戏,玩家必须猜测存储的颜色。 预期的最终结果是当玩家正确猜测时,显示消息并且背景颜色改变。但是,我的背景颜色仅在您关闭对话框后才会更改。
这是代码。有问题的部分就在最后
<!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>
答案 0 :(得分:0)
问题是,警报框会在响应之前停止JavaScript流。您可以通过使用setTimeout
函数在调用警告框之前设置一毫秒的延迟来解决此问题:
else {
document.body.style.background = colors[target];
setTimeout(makeTimeoutFunc(), 1); // 1 millsecond
return false;
}
...
function makeTimeoutFunc() {
return function() {
alert("Congratulations!\n\n" + "You guessed " + colors[target] + "\n\nThis is correct!\n\n" + "It took you " + guess_count + " guesses");
}
}
我创建了一个展示此here的JSFiddle。
希望这有帮助! :)