我刚刚完成了一些关于" CodeAcademy"这教会我创造一个摇滚,纸和剪刀游戏。除了我想要接收的输出外,一切正常。我没有得到出局"纸张胜利"。我得到它" paper"。我刚刚开始掌握Javascript的基础,这就是为什么我还不是一个强大的脚本编写者。
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random(0);
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
console.log("Computer: " + computerChoice);
var compare = function(choice1, choice2) {
if(choice1 === choice2) {
return ("The result is a tie!");
}
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";
}
}
}
}
};
答案 0 :(得分:0)
我认为你在选择选择时调用了比较功能。所以你将用户选择发送给该功能。现在你应该把它与computerChoice进行比较。那里的选择是什么?
答案 1 :(得分:0)
正如其他人所说,你永远不会调用你的比较函数而你永远不会返回该函数的任何值。即使你做了,你的功能也会在大多数时候失败。
你的结构:
if (choice1 === "paper") {
if (choice2 === "rock") {
return "paper wins";
} else {
if (choice2 === "scissors") {
return "scissors wins";
}
}
if (choice1 === "scissors") { //is never true because choice1 is always "paper"
if (choice2 === "rock") {
return "rock wins";
} else {
if (choice2 === "paper") {
return "scissors wins";
}
}
}
} //if choice1 === "paper" ends here
//no love for the rock?
您想要实现的目标:
if (choice1 === "paper") {
if (choice2 === "rock")
{
return "paper wins";
}
else if (choice2 === "scissors")
{
return "scissors wins";
}
}
else if (choice1 === "scissors")
{
if (choice2 === "rock")
{
return "rock wins";
}
else if (choice2 === "paper")
{
return "scissors wins";
}
}
else if (choice1 === "rock") //don't forget the rock
{
if (choice2 === "paper")
{
return "paper wins";
}
else if (choice2 === "scissors")
{
return "rock wins";
}
}
然后你必须像这样调用你的函数:
var result = compare(userChoice, computerChoice);
然后记录result
变量。在您的示例中,您记录的computerChoice
只能是&#34; paper&#34;,&#34;剪刀&#34;或者&#34;摇滚&#34;因为这是你给它的值,而不是函数的值。
由于您让用户键入他/她想要的任何内容,您显然还必须验证他们的输入,否则if / else结构将失败。