-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
42 lines (34 loc) · 1.27 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
const buttons = document.querySelectorAll("button");
const resultEl = document.getElementById("result");
const playerScoreEl = document.getElementById("user-score");
const computerScoreEl = document.getElementById("computer-score");
let playerScore = 0;
let computerScore = 0;
buttons.forEach((button) => {
button.addEventListener("click", () => {
const result = playRound(button.id, computerPlay());
resultEl.textContent = result;
});
});
function computerPlay() {
const choices = ["rock", "paper", "scissors"];
const randomChoice = Math.floor(Math.random() * choices.length);
return choices[randomChoice];
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
return "It's a tie!";
} else if (
(playerSelection === "rock" && computerSelection === "scissors") ||
(playerSelection === "paper" && computerSelection === "rock") ||
(playerSelection === "scissors" && computerSelection === "paper")
) {
playerScore++;
playerScoreEl.textContent = playerScore;
return "You win! " + playerSelection + " beats " + computerSelection;
} else {
computerScore++;
computerScoreEl.textContent = computerScore;
return "You lose! " + computerSelection + " beats " + playerSelection;
}
}