odin-rock-paper-scissors/script.js

85 lines
2.3 KiB
JavaScript
Raw Normal View History

2023-09-30 10:23:21 -06:00
function getComputerChoice(){
let compAnswer = Math.floor(Math.random() * 3) + 1;
if (compAnswer === 1) {
return "rock";
} else if (compAnswer === 2) {
return "paper";
} else {
return "scissors"
}
2023-09-30 10:23:21 -06:00
}
function playRound(playerSelection, computerSelection){
p = playerSelection.toLowerCase();
c = computerSelection.toLowerCase();
2023-09-30 10:23:21 -06:00
2023-09-30 10:52:40 -06:00
if (p === c) {
//console.log("It's a tie!")
return "tie";
2023-09-30 10:52:40 -06:00
} else if (p === "rock") {
if (c === "paper") {
return "player loses";
} else { //scissors
2023-09-30 10:52:40 -06:00
return "player wins";
}
2023-09-30 10:52:40 -06:00
} else if (p === "paper") {
if (c === "scissors") {
return "player loses";
} else { //rock
2023-09-30 10:52:40 -06:00
return "player wins";
}
2023-09-30 10:52:40 -06:00
} else if (p === "scissors") {
2023-09-30 12:33:29 -06:00
if (c === "rock") {
2023-09-30 10:52:40 -06:00
return "player loses";
2023-09-30 12:33:29 -06:00
} else { //paper
2023-09-30 10:52:40 -06:00
return "player wins";
}
} else {
return "not a valid entry";
}
2023-09-30 10:23:21 -06:00
}
function game() {
let p = 0;
let c = 0;
2023-11-07 12:19:52 -07:00
while (p < 5 && c < 5) {
2023-09-30 12:33:29 -06:00
const ps = prompt("Rock, Paper, or Scissors?");
const cs = getComputerChoice();
play = playRound(ps, cs);
switch (play) {
case "player loses":
c += 1;
console.log("You lose!", cs, " beats", ps, ". You: ", p, "Computer: ", c);
break;
case "player wins":
p += 1;
console.log("You Win!", ps, " beats", cs, ". You: ", p, "Computer: ", c);
break;
case "tie":
console.log("It's a tie!", " You: ", p, "Computer: ", c);
break;
default:
console.log("Invalid selection. Please choose Rock, Paper or Scissors to play.");
}
}
if (p !== c) {
let winner = (p > c) ? true : false;
2023-09-30 10:23:21 -06:00
if (winner) {
return "You won the game " + p + " to " + c + "! Great job!" ;
} else {
return "You lost the game " + p + " to " + c + ". Better luck next time!";
}
} else if (c === 0) {
return "Uh... I don't think you played the game right. Refresh the page and try that again."
} else {
return "Whoa, you tied! Refresh for a rematch!";
}
2023-09-30 10:23:21 -06:00
}
console.log(game());