javascript - color guessing game.How to stop the loop after guess is right -
how stop loop after guess 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;
× looks post code; please add more details.
how stop loop after guess right. //main function function do_game() {
var random_color = color[math.floor(math.random() * color.length)]; // random value array target = random_color; while (!finished) { guess_input_text = prompt("i thinking of 1 of these colors:- \n\n" + color.join(", ") + ".\n\nwhat color thinking of?"); guess_input = guess_input_text; guesses += 1; if( guess_input === target){ alert("your guess right.congratulations!");//finish causing problem } } } </script> </body> </html>
if didn't misunderstood question, want stop after alert guess correct.
your loop checking finished
true or not, loop will not stop if finished
still false.
the solution set finished
true
. following code should work:
function do_game() { var random_color = color[math.floor(math.random() * color.length)]; // random value array target = random_color; while (!finished) { guess_input_text = prompt("i thinking of 1 of these colors:- \n\n" + color.join(", ") + ".\n\nwhat color thinking of?"); guess_input = guess_input_text; guesses += 1; if( guess_input === target) { alert("your guess right.congratulations!"); finished = true; // can use break statement // make sure loop stop. } } }
Comments
Post a Comment