我对 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”,它不会被识别为五个有效输入(岩石、纸、剪刀、蜥蜴和史波克)之一。有没有办法让它在用户输入有效的大写字母(或多个字母)时仍然有效?
我想添加一些东西,以便每当有人输入无效的东西(例如“懒惰”)时,它会提醒他们他们的输入无效,并再次要求他们放入石头、纸、剪刀、蜥蜴或斯波克。