-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
61 lines (53 loc) · 1.7 KB
/
script.js
File metadata and controls
61 lines (53 loc) · 1.7 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
let userScore = 0;
let compScore = 0;
let userWin;
const choices = document.querySelectorAll(".choice");
const message = document.querySelector("#m");
const userscoreN = document.querySelector('#user-score');
const compscoreN = document.querySelector('#comp-score');
const generateCompChoice = () => {
const options = ["rock", "paper", "scissors"];
const randomIdx = Math.floor(Math.random() * 3);
return options[randomIdx];
};
const showWinner = (userWin, userChoice, compChoice) => {
if (userWin) {
message.innerText = `You win! 🥳 ${userChoice} beats ${compChoice}!`;
message.style.backgroundColor = "green";
userScore++;
userscoreN.innerText=userScore;
} else {
message.innerText = `You lost! 😭 ${compChoice} beats ${userChoice}!`;
message.style.backgroundColor = "red";
compScore++;
compscoreN.innerText=compScore;
}
};
const draw = () => {
message.innerText = "It's a draw 🙄";
message.style.backgroundColor = "yellow";
};
const playGame = (userChoice) => {
const compChoice = generateCompChoice();
if (userChoice === compChoice) {
draw();
} else {
if (userChoice === "rock") {
// scissors , paper
userWin = compChoice === "paper" ? false : true;
} else if (userChoice === "paper") {
// rock, scissors
userWin = compChoice === "scissors" ? false : true;
} else {
// paper, rock
userWin = compChoice === "rock" ? false : true;
}
showWinner(userWin, userChoice, compChoice);
}
};
choices.forEach((choice) => {
choice.addEventListener("click", () => {
const userChoice = choice.getAttribute("id");
playGame(userChoice);
});
});