【发布时间】:2015-06-30 02:01:29
【问题描述】:
我正在尝试用 Javascript 编写剪刀石头布游戏。我在 HTML 文件中使用 3 个图像作为按钮。我遇到了用于检查胜利的功能的问题。每次点击一个按钮,我会得到玩家选择和电脑选择不同的值,但是当两者进行比较时,只会得到比较函数中的最后一个值。例如,当我单击“Rock”时,计算机将选择“Paper” - 但 Javascript 会读取我们都选择了“Scissors”(我的比较函数中的最后一个值)。有什么建议吗?
/* SET ALL VARIABLES */
//set choice variables
var p1Choice;
var p2Choice;
var cChoice;
//set the rock image to act as a button
function rockSelected (p1Choice) {
p1Choice = "R";
alert (p1Choice);
}
//set the paper image to act as a button
function paperSelected (p1Choice) {
p1Choice = "P";
alert (p1Choice);
}
//set the scissor image to act as a button
function scissorSelected (p1Choice) {
p1Choice = "S";
alert (p1Choice);
}
function cpuSelect (cChoice) {
cChoice = Math.random();
if (cChoice <= 0.33) {
cChoice = "R"
alert (cChoice)}
else if (cChoice >= 0.34 && cChoice <= 0.66)
{cChoice = "P";
alert (cChoice);}
else
{cChoice = "S";
alert (cChoice);}
}
//check user imput against computer selection
function compare (p1Choice, cChoice) {
if (p1Choice == "R") {
if (cChoice == "R") {
alert ("player chose rock, cpu chose rock - it was a tie");
return "it was a tie";
}
else if (cChoice == "P") {
alert ("player chose rock, cpu chose paper - Paper wins!");
return "paper wins";
}
else {
alert ("player chose rock, cpu chose scissors - rock wins");
return "rock wins";
}
}
else if (p1Choice == "P") {
if (cChoice == "R") {
alert ("player chose paper, cpu chose rock - paper wins");
return "paper wins";
} else if (cChoice == "P") {
alert ("player chose paper, cpu chose paper - it was a tie");
return "it was a tie";
} else {
alert ("player chose paper, cpu chose scissors -scissors wins");
return "scissors wins";
}
}
else {
if (cChoice == "R") {
alert ("player chose scissors, cpu chose rock - rock wins");
return "rock wins";
} else if (cChoice == "P") {
alert ("player chose scissors, cpu chose paper - scissors wins");
return "scissors wins";
} else {
alert ("player chose scissors, cpu chose scissors - it was a tie");
return "it was a tie";
}
}
}
【问题讨论】:
-
你有没有打电话给
compare()? -
附带说明,您的代码格式不是 bueno (并且完全不一致)。您应该遵循样式指南,例如,github.com/airbnb/javascript
-
我在 HTML 文件中的按钮上调用了比较函数。
标签: javascript html