这里的问题是这样的:每次我运行这段代码时,它运行良好,但是当它出错时我没有执行while循环再次迭代游戏,我无法找到问题。
<!DOCTYPE html>
<html>
<head>
<title>Color guessing game</title>
</head>
<body onload="do_game()">
<script>
var color = ["Black","Blue","Brown","Cyan","GoldenRod","Green","Maroon","Olive","Pink","Red"];
var target;
var finished = false;
var guess_input;
var guesses;
function do_game() {
var target_index = Math.random() * 10;
var target = Math.floor(target_index);
alert(color[target]);
while(!finished) {
guess_input = prompt("I am thinking of one of these colors: \n\n" +
"Black,Blue,Brown,Cyan,GoldenRod,Green, Maroon,Olive,Pink,Red \n\n"
+ "What color am i thinking of?");
guesses +=1;
finished = check_guess();
}
}
myBody.style.background=name_of_color;
</script>
</body>
</html>
答案 0 :(得分:0)
您从未定义过函数check_guess
。
当浏览器尝试在该行上执行代码时,它发出错误并且脚本停止。
寻找&#34;开发人员工具&#34;或浏览器中的类似菜单项,您将看到其中显示的错误。
我的猜测也是您的脚本在变量myBody
和name_of_color
方面存在问题,这些变量也不会出现在您的脚本中。但是既然你说'#34;它运作良好&#34;可能有些事情你没有向我们展示。
答案 1 :(得分:0)
你的问题中缺少一些东西(我们不知道什么是check_guess ??),但我尝试做一些工作,让你非常接近你正在寻找的东西。希望这个解决方案可以帮到你。
var color = ["Black", "Blue", "Brown", "Cyan", "GoldenRod", "Green", "Maroon", "Olive", "Pink", "Red"];
var target;
var finished = false;
var guess_input;
var guesses;
var randomComputerGuess;
function do_game() {
var target_index = Math.floor(Math.random() * 10);
alert(color[target_index]);
randomComputerGuess = color[target_index];
while (!finished) {
guess_input = prompt("I am thinking of one of these colors: \n\n" +
"Black,Blue,Brown,Cyan,GoldenRod,Green, Maroon,Olive,Pink,Red \n\n" + "What color am i thinking of?");
if (randomComputerGuess === guess_input) {
alert("Good Job! You guessed it.");
finished = true;
//document.style.background=color[target_index];
}
}
}
<body onload="do_game()">