[英]color guessing game. How to stop the loop after guess is right
猜对后如何停止循环?
<!DOCTYPE html>
<html>
<body onLoad = "do_game()">
<script>
var target;
var color = ["blue", "cyan", "gray", "green", "magenta", "orange", "red", "white", "yellow"].sort();
var guess_input_text;
var guess_input;
var finished = false;
var guesses = 0;
//main function
function do_game() {
var random_color = color[Math.floor(Math.random() * color.length)]; // Get a Random value from array
target = random_color;
while (!finished) {
guess_input_text = prompt("I am thinking of one of these colors:- \n\n" +
color.join(", ") +
".\n\nWhat color am I thinking of?");
guess_input = guess_input_text;
guesses += 1;
if( guess_input === target){
alert("Your Guess is Right.Congratulations!");//finish which causing problem
}
}
}
</script>
</body>
</html>
如果我没有误解您的问题,请在警告您猜测正确之后再停止。
您的循环正在检查finished
是否为真,因此,如果finished
仍然为false,则循环不会停止。
该解决方案是将设置finished
对true
。 下面的代码应该工作:
function do_game() {
var random_color = color[Math.floor(Math.random() * color.length)]; // Get a Random value from array
target = random_color;
while (!finished)
{
guess_input_text = prompt("I am thinking of one of these colors:- \n\n" +
color.join(", ") +
".\n\nWhat color am I thinking of?");
guess_input = guess_input_text;
guesses += 1;
if( guess_input === target)
{
alert("Your Guess is Right.Congratulations!");
finished = true;
// You can also use break statement to
// make sure that the loop will stop.
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.