我使用javascript构建了一个颜色猜谜游戏。 如果在函数do_game中,循环不起作用。如果我在do_game之外得到它,它只是在check_guess中的第一个用于所有选项。请帮我解决这个问题。
var chosen;
var userInputText;
var finished = false;
var guesses = 0;
var colors = ["aqua", "azure", "beige", "brown", "chocolate", "coral", "crismon", "gold", "lime", "linen", "snow", "tomato"];
/*
One way to set the background color of a web page is
myBody=document.getElementsByTagName("body")[0];
myBody.style.background=name_of_color;*/
function do_game() {
"use strict";
chosen = colors[Math.floor(Math.random() * colors.length)];
while(!finished) {
userInputText = prompt("I am thinking of one of these colors: \n\n aqua, azure, beige, brown, chocolate, coral, crismon, gold, lime, linen, snow, tomato\n\nWhat color am I thinking of?");
guesses += 1;
finished = check_guess();
};
}
function check_guess() {
"use strict";
var idx = colors.indexOf(userInputText);
if(idx === -1) {
alert("Sorry, I don't recognize your color\n\n" + "Please try again.");
return false;
}
if(userInputText > chosen) {
alert("Sorry, your guess is not correct!\n\n" + "Hint: your color is alphabitcally higher than mine.\n\n" + "Please try again.");
return false;
}
if(userInputText < chosen) {
alert("Sorry, your guess is not correct!\n\n" + "Hint: your color is alphabitcally lower than mine.\n\n" + "Please try again.\n\n");
return false;
}if (userInputText === chosen) {
alert("Congratulations! You have guesses the color!" + "It took you " + guesses + " to finish the game!" + "You can see the colour in the background");
return true;
}
}
答案 0 :(得分:0)
此处未更新猜测值
guesses = +1;
用
替换它guesses += 1
或
guesses++
答案 1 :(得分:0)
这里的问题是全局变量。一旦调用一次后check_guess()设置为true,它将阻止循环运行。把它放在do_game()函数中。
function do_game() {
"use strict";
var finished = false;
chosen = colors[Math.floor(Math.random() * colors.length)];
while(!finished) {
userInputText = prompt("I am thinking of one of these colors: \n\n aqua, azure, beige, brown, chocolate, coral, crismon, gold, lime, linen, snow, tomato\n\nWhat color am I thinking of?");
guesses += 1;
finished = check_guess();
};
}