2015-10-10 44 views
1

如何停止循环后的猜测是正确的。彩色猜测game.How猜测后停止循环是正确

<!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; 

× 它看起来像你的文章主要是代码;请添加更多的细节。

如何停止循环后的猜测是正确的。 //主要功能 功能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> 
+2

休息;警报声明后 – jeff

回答

1

如果我没有误解你的问题,你要提醒您以后的猜测是正确的,以阻止它。

你的循环检查finished是真的还是假的,所以你的循环不会停止,如果finished还是假的。

的解决方案是设置finishedtrue。下面的代码应该工作:

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. 
     } 
    } 
}