-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
92 lines (80 loc) · 2.58 KB
/
app.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
90
91
92
let userScore = 0;
let compScore = 0;
const scoreLimit = 5;
const choices = document.querySelectorAll(".choice");
const msg = document.querySelector("#msg");
const resetBtn = document.querySelector("#reset");
const userScorePara = document.querySelector("#user-score");
const compScorePara = document.querySelector("#comp-score");
const genCompChoice = () => {
const options = ["rock", "paper", "scissors"];
const randIdx = Math.floor(Math.random() * 3);
return options[randIdx];
};
const drawGame = () => {
msg.innerText = "It's a draw! Play again.";
msg.style.backgroundColor = "#081b31";
};
const showWinner = (userWin, userChoice, compChoice) => {
if (userWin) {
userScore++;
userScorePara.innerText = userScore;
msg.innerText = `You win! ${userChoice} beats ${compChoice}`;
msg.style.backgroundColor = "green";
} else {
compScore++;
compScorePara.innerText = compScore;
msg.innerText = `You lost! ${compChoice} beats ${userChoice}`;
msg.style.backgroundColor = "red";
}
};
const checkGameOver = () => {
if (userScore >= scoreLimit) {
msg.innerText = "Congratulations! You won the game!";
msg.style.backgroundColor = "gold";
disableChoices();
} else if (compScore >= scoreLimit) {
msg.innerText = "Game Over! The computer won the game!";
msg.style.backgroundColor = "darkred";
disableChoices();
}
};
const disableChoices = () => {
choices.forEach(choice => choice.disabled = true);
};
const enableChoices = () => {
choices.forEach(choice => choice.disabled = false);
};
const resetGame = () => {
userScore = 0;
compScore = 0;
userScorePara.innerText = userScore;
compScorePara.innerText = compScore;
msg.innerText = "Game has been reset. Start playing!";
msg.style.backgroundColor = "#081b31";
enableChoices();
};
const playGame = (userChoice) => {
const compChoice = genCompChoice();
if (userChoice === compChoice) {
drawGame();
} else {
let userWin;
if (userChoice === "rock") {
userWin = compChoice === "scissors";
} else if (userChoice === "paper") {
userWin = compChoice === "rock";
} else {
userWin = compChoice === "paper";
}
showWinner(userWin, userChoice, compChoice);
checkGameOver();
}
};
choices.forEach(choice => {
choice.addEventListener("click", () => {
const userChoice = choice.getAttribute("id");
playGame(userChoice);
});
});
resetBtn.addEventListener("click", resetGame);