在JavaScript中的岩石,纸,剪刀 [英] Rock, Paper, Scissors in JavaScript
问题描述
我正在制作我的第一个游戏(Rock Paper Sissors),当我遇到 userChoice 剪刀和 computerChoice <时,我遇到了一个问题/ strong>是摇滚,该计划无法将胜利者视为摇滚。我可以让程序给我任何其他组合的赢家。
I'm working on making my first game (Rock Paper Sissors) and I ran into an issue where when the userChoice is scissors and the computerChoice is rock, the program cannot return the winner as rock. I can get the program to give me the winner for any other combination.
我的代码在这里:
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
var compare = function(choice1, choice2) {
if(choice1 === choice2) {
return "The result is a tie!";
}
if(choice1 === "rock") {
if(choice2 === "scissors") {
return "rock wins";
} else {
return "paper wins";
}
}
if(choice1 === "paper") {
if(choice2 === "rock") {
return "paper wins";
} else {
if(choice2 === "scissors") {
return "scissors wins";
}
}
if(choice1 === "scissors") {
if(choice2 === "rock") {
return "rock wins";
} else {
if(choice2 === "paper") {
return "scissors wins";
}
}
}
}
};
console.log("User Choice: " + userChoice);
console.log("Computer Choice: " + computerChoice);
compare(userChoice, computerChoice);
推荐答案
您无法看到最有可能发生的问题你的代码缩进不佳。正确缩进问题很清楚:
You were unable to see the issue most likely due to poor indentation of your code. Properly indented the issue is clear:
if (choice1 === "paper") {
if (choice2 === "rock") {
return "paper wins";
} else {
if (choice2 === "scissors") {
return "scissors wins";
}
}
if (choice1 === "scissors") {
if (choice2 === "rock") {
return "rock wins";
} else {
if (choice2 === "paper") {
return "scissors wins";
}
}
}
}
您的 if(choice1 ===scissors){
在之内if(choice1 ===paper){
。永远不会达到其中的代码。
Your if (choice1 === "scissors") {
is within if (choice1 === "paper") {
. The code within will never be reached.
这篇关于在JavaScript中的岩石,纸,剪刀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!