【发布时间】:2014-03-25 00:35:43
【问题描述】:
我对 JavaScript 有点陌生。我刚开始学习它,我决定制作一个“石头、纸、剪刀、蜥蜴、史波克”的游戏。这是代码:
var userChoice = prompt("Do you choose rock, paper, scissors, lizard, or spock?")
var computerChoice = Math.random();
if (computerChoice < 0.2) {
computerChoice = "rock";
} else if (computerChoice <= 0.4) {
computerChoice = "paper";
} else if (computerChoice <= 0.6) {
computerChoice = "scissors";
} else if (computerChoice <= 0.8) {
computerChoice = "lizard";
} else {
computerChoice = "spock";
}
alert("The computer chose " + computerChoice);
var compare = function(choice1, choice2){
if (choice1 === choice2) {
alert("And... It's a tie!");
}
//If the user chose rock...
else if (choice1 === "rock") {
if (choice2 === "scissors") {
alert("Rock wins!");
} else if (choice2 === "paper") {
alert("Paper wins!");
} else if (choice2 === "lizard") {
alert("Rock wins!");
} else {
alert("Spock wins!");
}
}
//If the user chose paper...
else if (choice1 === "paper") {
if (choice2 === "scissors") {
alert("Scissors wins!");
} else if (choice2 === "rock") {
alert("Paper wins!");
} else if (choice2 === "lizard") {
alert("Lizard wins!");
} else {
alert("Paper wins!");
}
}
//If the user chose scissors...
else if (choice1 === "scissors") {
if (choice2 === "paper") {
alert("Scissors wins!");
} else if (choice2 === "rock") {
alert("Rock wins!");
} else if (choice2 === "lizard") {
alert("Scissors wins!");
} else {
alert("Spock wins!");
}
}
//If the user chose lizard...
else if (choice1 === "lizard") {
if (choice2 === "scissors") {
alert("Scissors wins!");
} else if (choice2 === "rock") {
alert("Rock wins!");
} else if (choice2 === "paper") {
alert("Lizard wins!");
} else {
alert("Lizard wins!");
}
}
//If the user chose spock...
else if (choice1 === "spock") {
if (choice2 === "scissors") {
alert("Spock wins!");
} else if (choice2 === "rock") {
alert("Spock wins!");
} else if (choice2 === "lizard") {
alert("Lizard wins!");
} else {
alert("Paper wins!");
}
}
};
compare(userChoice, computerChoice);
我想在我的代码中添加两个主要内容,但我不知道如何:
现在,如果用户输入,例如,带有大写“R”的“Rock”,它不会被识别为五个有效输入之一(石头、纸、剪刀、蜥蜴和斯波克)。有没有办法让它在用户输入有效的大写字母(或多个字母)时仍然有效?
我想添加一些内容,以便每当有人输入无效的内容(例如“树懒”)时,它会提醒他们输入无效,并再次要求他们输入石头、纸、剪刀、蜥蜴,或spock。
【问题讨论】:
-
choice1.toLowerCase() -
考虑使用
switch语句,让事情变得更加清晰,您可以指定一个“默认”,只要其他选择都不为真,该默认值就会运行,因此您可以在default: alert("sorry your selection was invalid") break;下设置 -
这个问题真的是关于石头剪刀布的问题,还是关于如何让 JavaScript 将大写输入识别为小写输入?
-
最近Too many 'if' statements? 关于简化 swith 语句,当两名玩家每人使用 4 个选项进行战斗时。它真的很相似,并且有很多很好的答案。我推荐使用矩阵方法来表示您的数据。另外,它是 PHP,但是对于这个 case 来说几乎是一样的。
标签: javascript