gpt4 book ai didi

javascript - Rock Paper Scissors Lizard Spock 游戏逻辑偶尔输出错误的赢家,我不知道为什么

转载 作者:行者123 更新时间:2023-11-29 21:32:35 25 4
gpt4 key购买 nike

我是 JavaScript 的新手。我只是不明白为什么这有时会给错误的赢家。它表示当用户选择 Rock 而计算机选择 Paper 时,Rock 获胜。其他几种组合也出现了错误。谁能告诉我哪里出错了?谢谢!

var userChoice = prompt("Do you choose Rock, Paper, Scissors, Lizard or Spock?");
var computerChoice = Math.random();
if (computerChoice < 0.21) {
computerChoice = "Rock";
} else if(computerChoice > 0.20 && computerChoice < 0.41) {
computerChoice = "Paper";
} else if(computerChoice >0.40 && computerChoice < 0.61) {
computerChoice = "Scissors";
} else if(computerChoice > 0.60 && computerChoice < 0.81) {
computerChoice = "Lizard";
} else {
computerChoice = "Spock";
}
console.log("The player chooses: " + userChoice);
console.log("The computer chooses: " + computerChoice);
function compare(choice1, choice2) {
if(choice1 === choice2) {
console.log("The result is a tie!");
} else if(choice1 === "Rock") {
if(choice2 === "Scissors" || "Lizard") {
console.log("Rock wins!");
} else if(choice2 === "Paper") {
console.log("Paper wins!");
} else {
console.log("Spock wins");
}
} else if(choice1 === "Paper") {
if(choice2 === "Rock" || "Spock") {
console.log("Paper wins!");
} else if(choice2 === "Scissors") {
console.log("Scissors wins!");
} else {
console.log("Lizard wins!");
}
} else if(choice1 === "Scissors") {
if(choice2 === "Paper" || "Lizard") {
console.log("Scissors wins!");
} else if(choice2 === "Rock") {
console.log("Rock wins!");
} else {
console.log("Spock wins!");
}
} else if(choice1 === "Lizard") {
if(choice2 === "Paper" || "Spock") {
console.log("Lizard wins!");
} else if(choice2 === "Rock") {
console.log("Rock wins!");
} else {
console.log("Spock wins!");
}
} else if(choice1 === "Spock") {
if(choice2 === "Rock" || "Scissors") {
console.log("Spock wins!");
} else if(choice2 === "Paper") {
console.log("Paper wins!");
} else {
console.log("Lizard wins!");
}
}
}
compare(userChoice, computerChoice);

最佳答案

您已经多次犯同样的错误。以第一个为例。这:

if(choice2 === "Scissors" || "Lizard") {

… 意思是:

如果

  • choice2 === "Scissors"是一个真值
  • “蜥蜴”是一个真正的值(value)

…“蜥蜴”总是是一个真值。

您需要完整描述病情:

choice2 === "Scissors" || choice2 === "Lizard"

……或者使用数组

["Scissors", "Lizard"].indexOf(choice2) > -1

关于javascript - Rock Paper Scissors Lizard Spock 游戏逻辑偶尔输出错误的赢家,我不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35821218/

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