gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:50:07 25 4
gpt4 key购买 nike

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

计算机猜测 - 一种颜色,用户应该给出正确的答案 - 哪种颜色是正确的。我尝试为其创建正确的代码,但无法正常工作。也许是变量或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 返回索引 (0,1,2..),但 target 是实际颜色 (aqua, 黑色,..)。试试这个吧

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

我将 == 更改为 === ,即 usually what you want在 JavaScript 中。

关于javascript - 我想创建猜谜游戏,用户应该在提示中输入正确的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42693642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com