我被指派创建一个色彩猜谜游戏。想法是玩家需要猜测颜色,一旦他们正确猜测背景会改变。但是,我正在努力让我的浏览器启动和运行游戏。我查看了控制台,但不理解突出显示的错误。
<body>
<script type="text/javascript">
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
window.onload = game()
var colours=["blue","purple","pink","red","green","yellow"];
// var target_index
var target
var guess_input
var finished = false;
var guesses = 0;
function game () {
var random_colours = Math.floor(Math.random()* colours.length);
target = random_colours;
while (!finished) {
guess_input = prompt ("I'm thinking of one of these colours\n" + colours + "\n What colour am I thinking of?")
guesses += 1;
finished = check_guess ();
}
}
function check_guess () {
if (guess_input == isNaN) {
alert ("I don't recgonise\n" + "Please try again");
return false;
}
if (guess_input > target) {
alert ("Your colour is alphabetically higher than mine\n" + "Please try again");
return false;
}
if (guess_input < target) {
alert ("Your colour is alphabetically lower than mine\n" + "Please try again");
return false;
}
if (guess_input == target) {
alert ("Congratulations, the colour was" + target + "it took you" + guesses + "to finish the game!" "You can see the color in the background");
return true;
}
}
</script>
</body>
</html>
答案 0 :(得分:1)
有几件事是错的。
首先,该片段有一个额外的<body><script type="text/javascript">
。删除它。
其次,在声明变量之前,您正在关联window.onload
上的函数,这将导致colour
变量在调用时未定义。只需在window.onload = game()
之前移动所有变量。
请注意,你会陷入一个循环,直到你得到正确的颜色,但我正在解决问题所带来的错误。
以下是工作片段,我敦促不要在这里跑。
var colours=["blue","purple","pink","red","green","yellow"];
// var target_index
var target
var guess_input
var finished = false;
var guesses = 0;
window.onload = game();
function game () {
var random_colours = Math.floor(Math.random() * colours.length);
target = random_colours;
while (!finished) {
guess_input = prompt ("I'm thinking of one of these colours\n" + colours + "\n What colour am I thinking of?")
guesses += 1;
finished = check_guess();
}
}
function check_guess () {
if (guess_input == isNaN) {
alert ("I don't recgonise\n" + "Please try again");
return false;
}
if (guess_input > target) {
alert ("Your colour is alphabetically higher than mine\n" + "Please try again");
return false;
}
if (guess_input < target) {
alert ("Your colour is alphabetically lower than mine\n" + "Please try again");
return false;
}
if (guess_input == target) {
alert ("Congratulations, the colour was" + target + "it took you" + guesses + "to finish the game!" + "You can see the color in the background");
return true;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
</html>