我是javascript的新手并尝试做一个简单的猜色游戏,这是我的代码:
<!doctype html>
<html>
<head>
<title>Guessing Color Game</title>
</head>
<body onload="do_game()">
<script>
var target;
var colors;
var finished = false;
var guess_input;
var guesses = 0;
var random_number = Math.random() * 11;
var random_number_index = Math.floor(random_number);
colors = ["Aqua", "Black", "Blue", "Brown", "Cyan", "Grey", "Green", "Orange", "Red", "White", "Yellow"];
target = colors[random_number_index];
function do_game() {
alert("Hello mate, wanna play a game???");
alert("You gotta guess a color, alright???");
alert("Available colors are: \n\n0. Aqua \n1. Black \n2. Blue \n3. Brown \n4. Cyan \n5. Grey \n6. Green \n7. Orange" +
" \n8. Red \n9. White \n10. Yellow");
alert("Random color to guess is " + target + ", which is index " + random_number_index + " in the array");
while (!finished) {
guess_input = prompt("Write the name of your chosen color please:").toLowerCase();
guesses++;
finished = check_guess();
}
}
function check_guess() {
if (target == guess_input)
return true;
}
</script>
</body>
</html>
我的问题在于check_guess()函数:由于目标不能与guess_input进行比较而导致无限循环。为什么会这样?
答案 0 :(得分:1)
您正在使用小写target
检查guess_input
颜色。
相反,将.toLowerCase()
应用于target
和guess_input
,或两者都不适用。
您需要检查.toLowerCase()
target
颜色与guess_input
的颜色。
所以你需要做的唯一改变如下:
colors[random_number_index].toLowerCase();
var target;
var colors;
var finished = false;
var guess_input;
var guesses = 0;
var random_number = Math.random() * 11;
var random_number_index = Math.floor(random_number);
colors = ["Aqua", "Black", "Blue", "Brown", "Cyan", "Grey", "Green", "Orange", "Red", "White", "Yellow"];
target = colors[random_number_index].toLowerCase();
function do_game() {
alert("Hello mate, wanna play a game???");
alert("You gotta guess a color, alright???");
alert("Available colors are: \n\n0. Aqua \n1. Black \n2. Blue \n3. Brown \n4. Cyan \n5. Grey \n6. Green \n7. Orange" +
" \n8. Red \n9. White \n10. Yellow");
alert("Random color to guess is " + target + ", which is index " + random_number_index + " in the array");
while (!finished) {
guess_input = prompt("Write the name of your chosen color please:").toLowerCase();
guesses++;
finished = check_guess();
}
}
function check_guess() {
console.log(target, guess_input)
if (target == guess_input)
return true;
}
do_game();
答案 1 :(得分:-1)
试试这个:
function check_guess() {
if (target === guess_input) {
return true;
}
}