-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
65 lines (60 loc) · 2.01 KB
/
script.js
File metadata and controls
65 lines (60 loc) · 2.01 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const bodyEl = document.querySelector("body");
const btns = document.querySelectorAll(".btn");
const result = document.querySelector(".result");
const computerScoreSpan = document.querySelector(".computer-score");
const playerScoreSpan = document.querySelector(".player-score");
const gameResult = document.querySelector(".game-result");
function getComputerChoice() {
const random = Math.floor(Math.random() * 3) + 1;
switch (random) {
case 1:
return "rock";
break;
case 2:
return "paper";
break;
case 3:
return "scissors";
break;
}
}
let humanScore = 0;
let computerScore = 0;
function playGame() {
function playRound(humanChoice, computerChoice) {
if (
(humanChoice === "rock" && computerChoice === "paper") ||
(humanChoice === "paper" && computerChoice === "scissors") ||
(humanChoice === "scissors" && computerChoice === "rock")
) {
result.textContent = `You lose! ${computerChoice} beats ${humanChoice}`;
computerScore += 1;
computerScoreSpan.textContent = computerScore;
} else if (
(computerChoice === "rock" && humanChoice === "paper") ||
(computerChoice === "paper" && humanChoice === "scissors") ||
(computerChoice === "scissors" && humanChoice === "rock")
) {
result.textContent = `You win! ${humanChoice} beats ${computerChoice}`;
humanScore += 1;
playerScoreSpan.textContent = humanScore;
} else {
result.textContent = `Draw! ${humanChoice} and ${computerChoice}`;
}
if (computerScore === 5) {
btns.forEach((btn) => btn.remove());
bodyEl.removeChild(result);
gameResult.textContent = `Game Over! Computer wins the game`;
} else if (humanScore === 5) {
btns.forEach((btn) => btn.remove());
bodyEl.removeChild(result);
gameResult.textContent = `Game Over! player wins the game`;
}
}
btns.forEach((btn) => {
btn.addEventListener("click", (e) => {
playRound(e.target.id, getComputerChoice());
});
});
}
playGame();