gpt4 book ai didi

javascript - 石头剪刀布 Javascript 函数

转载 作者:行者123 更新时间:2023-11-30 12:51:52 28 4
gpt4 key购买 nike

我现在有我的石头剪刀布 JS 游戏的代码。在我的比较功能中,我尝试对其进行编程,以便在未输入“Rock”、“Paper”或“Scissors”时显示警告消息。但是它不起作用,当我输入与有效的 3 个选项不同的字符串时,我没有得到任何响应。

var userChoice = prompt("Rock, Paper, or Scissors");
var computerChoice = Math.random();

var compchoice = function ()
{
if (computerChoice <= 0.34)
{
return computerChoice = "Rock";
}
else if(computerChoice <= 0.67 && computerChoice >= 0.35)
{
return computerChoice = "Paper";
}
if (computerChoice >= 0.68)
{
return computerChoice = "Scissors";
}

};

var compare = function (choice1, choice2)
{
if (computerChoice === "Rock" || "Paper" || "Scissors")
{
if (choice1 === choice2)
{
return alert("The result is a tie!");
}

else if (choice1 === "Rock")
{
if (choice2 === "Scissors")
{
return alert("Rock crushes Scissors!");
}
else if (choice2 === "Paper")
{
return alert("Paper covers Rock!");
}
}
if (choice1 === "Scissors")
{
if (choice2 === "Rock")
{
return alert("Rock crushes Scissors!");
}
else if (choice2 === "Paper")
{
return alert("Scissors cuts Paper!");
}
}
else if (choice1 === "Paper")
{
if (choice2 === "Rock")
{
return alert("Paper covers Rock!");
}
else if (choice2 === "Scissors")
{
return alert("Scissors cuts Paper!");
}
}
}
else
{
return alert("Please type Rock, Paper, or Scissors next time");
}
};

compchoice();

compare(userChoice, computerChoice);

有什么原因吗?

最佳答案

computerChoice === "摇滚"|| “纸” || “剪刀” 始终为真,因为它解析为:

(computerChoice === "Rock") || ("Paper") || ("Scissors")

"Paper" 是一个真值。

此外,您似乎在比较 computerChoice,而不是 userChoice

固定:

if (userChoice === "Rock" || userChoice === "Paper" || userChoice === "Scissors")

或者:

// array and indexOf
if (["Rock", "Paper", "Scissors"].indexOf(userChoice) > -1)
// doesn't work in IE8

或者:

// regex
if (/^(Rock|Paper|Scissors)$/.test(userChoice))

关于javascript - 石头剪刀布 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20692926/

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