-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrock-paper-scissors.js
89 lines (77 loc) · 2.2 KB
/
rock-paper-scissors.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
let playerScore = 0;
let computerScore = 0;
const message = document.querySelector("#message");
const winnerArea = document.querySelector("#winner");
document.querySelectorAll(".rps-button").forEach(function (button) {
button.addEventListener("click", playRound);
});
document.querySelector("#reset-button").addEventListener("click", reset);
reset(); // reset to initialize game
function playRound(e) {
if (computerScore === 5 || playerScore === 5) {
reset();
playRound(e);
return;
}
const playerSelection = e.target.id;
const computerSelection = computerPlay();
// flag to determine message to return
let playerWins = false;
if (playerSelection === computerSelection) {
message.textContent = "Tie!";
return;
} else if (
(playerSelection === "rock" && computerSelection === "scissors") ||
(playerSelection === "scissors" && computerSelection === "paper")
) {
playerWins = true;
} else {
playerWins = false;
}
if (playerWins) {
++playerScore;
updateScores();
message.textContent = `You Win! ${playerSelection} beats ${computerSelection}`;
if (playerScore === 5) {
winnerArea.textContent = "You Win! :)";
winnerArea.classList.add("win");
// alert("You Win!");
}
} else {
++computerScore;
updateScores();
message.textContent = `You Lose! ${computerSelection} beats ${playerSelection}`;
if (computerScore === 5) {
winnerArea.textContent = "Computer Wins :(";
winnerArea.classList.add("lose");
// alert("computer wins!");
}
}
}
function updateScores() {
document.querySelector("#computer-score").textContent = computerScore;
document.querySelector("#player-score").textContent = playerScore;
}
function computerPlay() {
// return randomly rock, paper or scissors
switch (Math.floor(Math.random() * 3)) {
case 0:
return "rock";
case 1:
return "paper";
case 2:
return "scissors";
default:
return "scissors";
}
}
function reset() {
playerScore = 0;
computerScore = 0;
updateScores();
message.textContent = "Make a play to start";
winnerArea.textContent = "";
winnerArea.classList.forEach((cls) => {
winnerArea.classList.remove(cls);
});
}