I'm kind of new to JavaScript. I just started learning it, and I decided to make a 'Rock, Paper, Scissors, Lizard, Spock' game. Here is the code:
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);
There are 2 main things that I want to add to my code but I don't know how to:
Right now, if the user inputs, for example, 'Rock' with a capital 'R', it doesn't get recognized as one of the five valid inputs (rock, paper, scissors, lizard, and spock). Is there a way to make it so that if the user inputs something valid with a capital letter (or letters) it will still be valid?
I want to add something so that whenever someone puts in something invalid (e.g. "sloth") it will alert them that their input is invalid and will ask them, again, to put in rock, paper, scissors, lizard, or spock.