我想创建猜谜游戏,用户应该在提示中输入正确的颜色

I wanna to create guessing game, where user should put a right color in prompt

你能帮我看看这段代码吗? 我想创建猜谜游戏,用户应该在提示中输入正确的颜色。

计算机猜测 - 一种颜色,用户应该给出正确答案 - 哪种颜色是正确的。我尝试为其创建正确的代码,但无法正常工作。 也许是变量或 indexOf 的问题,或者其他…… 先谢谢你

    var target;
    var guess_input;
    var finished = false;
    var colors;  
    var presentOrNot;

    colors = ["aqua", "black", "white"];

    function do_game() {
        var random_color = colors[Math.floor(Math.random() * colors.length)];
        target = random_color; 
        alert (target);

        while (!finished) {
            guess_input = prompt("I am thinking of one of these colors:\n\n" + colors + "\n\n What color am I thinking of?");
            guesses += 1;
            finished = check_guess ();
        }
    }
    function check_guess () {
        presentOrNot = colors.indexOf(guess_input);
        if (presentOrNot == target) {
            alert ("It is my random color");
            return true;
        }
        else {
            alert("It isn't my random color");
            return false;
        }
     }

indexOf returns 索引 (0,1,2..),但 target 是实际颜色 (aqua, black ,..)。试试这个

function check_guess () {
    if (guess_input.toLowerCase() === target) {
        alert ("It is my random color");
        return true;
    }
    else {
        alert("It isn't my random color");
        return false;
    }
}

或者,这也应该有效

function check_guess () {
    presentOrNot = colors.indexOf(guess_input);
    if (presentOrNot === colors.indexOf(target)) {
        alert ("It is my random color");
        return true;
    }
    else {
        alert("It isn't my random color");
        return false;
    }
}

我将 == 更改为 ===,即 javascript 中的 usually what you want

prompt 命令 returns 一个 string 值。

在您的 while 循环中,您声明 guess_input,将所有 prompt 放入 Number() 函数中。

我编辑并更正了您的代码。试试这个

var target;
    var guess_input;
    var finished = false;
    var colors;  
    var presentOrNot;
    var guesses = 0; /*initialized variable*/

    colors = ["aqua", "black", "white"];

    function do_game() {
        var random_color = colors[Math.floor(Math.random() * colors.length)];
        target = random_color; 
        alert (target);

        while (!finished) {
            guess_input = prompt("I am thinking of one of these colors:\n\n" + colors + "\n\n What color am I thinking of?");
            guesses += 1;
            finished = check_guess ();
            
            if(guesses === 3) {
             break;
            }
        }
        
    }
    function check_guess () {
        presentOrNot = colors.indexOf(guess_input);
        if (colors[presentOrNot] === target) {
            alert ("It is my random color");
            return true;
        }
        else {
            alert("It isn't my random color");
            return false;
        }
     }   
     //start the game---
     do_game();