-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
58 lines (51 loc) · 1.72 KB
/
Copy pathscript.js
File metadata and controls
58 lines (51 loc) · 1.72 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
let userScore = 0;
let compScore = 0;
const choices = document.querySelectorAll(".choice");
const msg = document.querySelector("#msg");
const userScoreElem = document.querySelector("#user-score");
const compScoreElem = document.querySelector("#comp-score");
const getCompChoice = () => {
const options = ["rock", "paper", "scissor"];
const randomIdx = Math.floor(Math.random() * 3);
console.log(randomIdx);
return options[randomIdx];
};
const drawGame = () => {
msg.innerText = "It's a draw!";
msg.style.backgroundColor = "#ffa500";
};
const showWinner = (userWin, userChoice, compChoice) => {
if (userWin) {
userScore++;
userScoreElem.innerText = userScore;
msg.innerText = `You win! ${userChoice} beats ${compChoice}`;
msg.style.backgroundColor = "green";
} else {
compScore++;
compScoreElem.innerText = compScore;
msg.innerText = `You lose! ${compChoice} beats ${userChoice}`;
msg.style.backgroundColor = "red";
}
};
const playGame = (userChoice) => {
const compChoice = getCompChoice();
if (userChoice === compChoice) {
drawGame();
} else {
let userWin = false;
if (
(userChoice === "rock" && compChoice === "scissor") ||
(userChoice === "scissor" && compChoice === "paper") ||
(userChoice === "paper" && compChoice === "rock")
) {
userWin = true;
}
showWinner(userWin, userChoice, compChoice);
}
};
choices.forEach((choice) => {
choice.addEventListener("click", () => {
const userChoice = choice.getAttribute("id").toLowerCase();
playGame(userChoice);
});
});