-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
64 lines (56 loc) · 1.93 KB
/
Copy pathscript.js
File metadata and controls
64 lines (56 loc) · 1.93 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
let userScore = 0;
let compScore = 0;
const userScorePara = document.getElementById("player-score");
const compScorePara = document.getElementById("computer-score");
const choices = document.querySelectorAll(".choice");
const msgResult = document.getElementById("result-text");
const genCompChoice = () => {
const options = ["rock", "paper", "scissors"];
const randIdx = Math.floor(Math.random() * 3);
return options[randIdx];
};
const showWinner = (userWin, userChoice, compChoice) => {
if (userWin) {
userScore++;
userScorePara.innerText = userScore;
msgResult.innerText = "You Win!";
msgResult.style.backgroundColor = "green";
msgResult.style.color = "white";
} else {
compScore++;
compScorePara.innerText = compScore;
msgResult.innerText = "You Lose!";
msgResult.style.backgroundColor = "red";
msgResult.style.color = "white";
}
};
const drawGame = () => {
msgResult.innerText = "TIE!";
msgResult.style.backgroundColor = "yellow";
msgResult.style.color = "black";
};
const playGame = (userChoice) => {
const compChoice = genCompChoice();
console.log("User =", userChoice);
console.log("Comp =", compChoice);
if (userChoice === compChoice) {
drawGame();
} else {
let userWin = true;
if (userChoice === "rock") {
userWin = compChoice === "paper" ? false : true;
} else if (userChoice === "paper") {
userWin = compChoice === "scissors" ? false : true;
} else {
userWin = compChoice === "rock" ? false : true;
}
showWinner(userWin, userChoice, compChoice);
}
};
// Add event listeners for user choices
choices.forEach((choice) => {
choice.addEventListener("click", () => {
const userChoice = choice.getAttribute("id");
playGame(userChoice);
});
});