-
Notifications
You must be signed in to change notification settings - Fork 0
/
RPS.js
23 lines (19 loc) · 787 Bytes
/
RPS.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const choices = ["rock", "paper", "scissors"];
let playerInput = "";
const getPlayerInput = () => {
playerInput = prompt("Rock, Paper, or Scissors?").toLowerCase();
if (!choices.includes(playerInput)) return getPlayerInput();
return playerInput;
};
const determineWinner = (p1, p2) => {
if (p1 === p2) return "It was a tie!";
else if (Math.abs(p1 - p2) < 2) return p2 > p1 ? "CPU wins!" : "Player wins!";
else return p2 > p1 ? "Player wins!" : "CPU wins!";
};
let playerChoice = getPlayerInput();
let player = choices.findIndex((index) => index === playerChoice);
let cpu = Math.floor(Math.random() * 3);
let winner = determineWinner(player, cpu);
document.getElementById(
"h1"
).innerHTML = `Player chose ${choices[player]}, and CPU chose ${choices[cpu]}. ${winner}`;