循环不会终止在JS中猜测游戏

时间:2015-10-12 22:19:19

标签: javascript html

在提示符中,我的循环应该在最终用户键入" magenta"时终止。它目前没有。我错过了什么?我知道这是一个非常基本的猜色游戏,我打算扩展,但我想在继续进行一些改进之前先解决这个问题....谢谢!



var target = "magenta";
var guess_input_text;
var guess_input;
var finished = false;

function do_game() {

    alert("The correct color is " + target + "!");

    while (!finished) {
        guess_input_text = prompt("I am thinking of one of these colors:\n\n"+
                                  "blue, cyan, gold, gray, green, magenta, orange, red, white\n\n"+
                                  "What is the color I am thinking of?");
        guess_input = guess_input_text.toLowerCase();
		finished = check_guess();
    }
}

function check_guess() {

    if (guess_input = "blue") {
        return false;
    }
    if (guess_input = "cyan") {
        return false;
    }
    if (guess_input = "gold") {
        return false;
    }
    if (guess_input = "gray") {
        return false;
    }
    if (guess_input = "green") {
        return false;
    }
    if (guess_input = "orange") {
        return false;
    }
    if (guess_input = "red") {
        return false;
    }
    if (guess_input = "white") {
        return false;
    }
    if (guess_input = target) {
        return true;
    }
}




4 个答案:

答案 0 :(得分:1)

在Javascript中,比较应该使用==(强制类型)或最好是===(不强制类型)。

因此,请尝试将以下条件替换为:

if (guess_input === "blue") { ...

答案 1 :(得分:0)

这不是比较......你实际上是在这里给出一个值:

guess_input = "white"

if语句应该是这样的:

if(guess_input == "white") {
    // your code here inside
}

答案 2 :(得分:0)

试试这个:

var target = "magenta";
var guess_input;

function do_game() {
    //Prompts and makes the answer lowercase.
    guess_input = prompt("I am thinking of one of these colors:\n\n"+
                              "blue, cyan, gold, gray, green, magenta, orange, red, white\n\n"+
                              "What is the color I am thinking of?").toLowerCase();

    //Checks if the guess_input equals the target...
    if (guess_input == target) {
        alert("You are correct! The answer is " + target + "!");
    } else {//Not equals target...
        alert("You are incorrect! The correct answer is " + target + "!");
    }
}

do_game();

答案 3 :(得分:0)

您的if语句包含赋值运算符。检查时,您要分配变量:

if(guess_input = "blue") {
    //...
}

如果要比较字符串,则应使用:

if(guess_input === "blue") {
    //...
}

使用三个等号可确保它们属于同一类型。如果您只想比较值而不是类型,请使用两个:

if(guess_input == "blue") {
    //...
}

请注意,肯定有更简单的方法可以检查。最简单的是switch语句:

switch(guess_input){
    case "blue":
    case "cyan":
    case "gold":
    case "grey":
    //...
    case "white":
        return false;
    case target:
        return true;
}

但是,请注意,当字符串与其中任何字符串都不匹配时,这不会返回值(即它们输入"黄色")。

我的建议只是测试用户输入实际上是否正确。如果不是,则返回false。

if(guess_input == target){
    return true;
return false;