我写了颜色猜测javascript代码的代码。但问题是每次运行此代码时,它选择相同的颜色而不是选择随机颜色。我想知道是否有人帮助我。我将非常感激!
<head>
<title>Color Guessing Game</title>
<meta name="author" content="Wajeb Saab">
</head>
<body onload="do_game()">
<script>
var target_color;
var target_index;
var guessed_color;
var guesses = 0;
var color = ["red", "blue", "yellow", "crimson", "darkorange", "olive", "silver", "steelblue", "tomato", "green"];
var finished = false;
function do_game()
{
color.sort();
var random_number = Math.random() * (color.length-1);
target_index = Math.floor(random_number);
target_color = color[target_index];
alert("Hint: The target color is " + target_color);
var text = "I am thinking of one of these colors:\n\n" + color.join(", ")
+ "\n\n What color am I thinking of?";
while(!finished)
{
guessed_color = prompt(text);
guesses++;
finished = check_guess();
}
myBody=document.getElementsByTagName("body")[0];
myBody.style.background = target_color;
}
function check_guess()
{
if(color.indexOf(guessed_color) < 0) // check if guessed color is not included in array
{
alert("Sorry, I don't recognize your color.\n\n" + "Please try again.");
return false;
}
else if(guessed_color > target_color)
{
alert("Sorry, your guess is not correct!\n\n" + "Hint: your color is alphabetically higher than mine.\n\n"
+ "Please try again.");
return false;
}
else if(guessed_color < target_color)
{
alert("Sorry, your guess is not correct!\n\n" + "Hint: your color is alphabetically lower than mine.\n\n"
+ "Please try again.");
return false;
}
else
{
alert("Congratulations! You have guessed the color!\n\n" + "It took you " + guesses + " guesses to finish the game.\n\n"
+ "You can see the color in the background.");
return true;
}
}
</script>
</body>
答案 0 :(得分:0)
问题是你需要在check_guesses()函数中返回true时重置guessed_color和target_color,然后你需要将finished = false设置为do_game()函数的第一行。像这样......
function do_game() {
finished = false;
color.sort();
var random_number = Math.random() * (color.length - 1);
target_index = Math.floor(random_number);
console.log(target_index);
target_color = color[target_index];
var text = "I am thinking of one of these colors:\n\n" + color.join(", ") + "\n\n What color an I thinking of?";
while(!finished) {
guessed_color = prompt(text);
guesses++;
finished = check_guesses();
}
}
function check_guesses() {
if(color.indexOf(guessed_color) < 0) {
console.log("Sorry I don't know what color that is");
return false;
} else if(guessed_color > target_color) {
console.log("Incorrect!\n\n Your color is Alphabetically higher than mine");
return false;
} else if(guessed_color < target_color) {
console.log("Incorrect\n\n Your color is lower than mine");
return false;
} else {
console.log("You WIN!");
guessed_color = null;
target_color = null;
return true;
}
}
截至目前,你设置了颜色,然后检查它,但是当你返回true时没有重置它,游戏结束,颜色被设置,所以下次你运行它时它将是相同的颜色。
答案 1 :(得分:0)
谢谢,但我的问题通过应用来解决。
颜色= color.sort();