色彩猜谜游戏。如何在猜测正确后停止循环

时间:2015-10-10 06:56:10

标签: javascript

如果在猜对了之后如何停止循环?

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

1 个答案:

答案 0 :(得分:1)

如果我没有误解你的问题,你想在警告猜测正确后停止它。

您的循环正在检查finished是否为真,因此如果finished仍为假,您的循环将不会停止。

解决方案是将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.
        } 
    }
}