-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
75 lines (65 loc) · 2.17 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
let userScore = 0;
let computerScore= 0;
const choices = document.querySelectorAll(".choice");
const msg = document.querySelector("#msg");
const userScorePara = document.querySelector("#user-score");
const computerScorePara = document.querySelector("#computer-score");
const reset = document.querySelector(".reset");
const genComputerChoice = () => {
const options = ["rock", "paper", "scissors"];
const randIdx = Math.floor(Math.random () * 3);
return options [randIdx];
}
const drawGame = () => {
console.log("game was draw.");
msg.innerText = "Game Was Draw!";
msg.style.backgroundColor= "#181b31";
};
const showWinner = (userWin, userChoice, computerChoice) => {
if(userWin) {
userScore++;
userScorePara.innerText = userScore;
console.log("you win!");
msg.innerText = `You win! ${userChoice} beats ${computerChoice}`;
msg.style.backgroundColor= "green";
} else {
computerScore++;
computerScorePara.innerText = computerScore;
console.log ("you lose");
msg.innerText = `You lose! ${computerChoice} beats ${userChoice}`;
msg.style.backgroundColor= "red";
}
};
const playGame = (userChoice) => {
console.log("user choice= ", userChoice);
//Gernerate Computer Choice
const computerChoice = genComputerChoice ();
console.log("computer choice= ", computerChoice);
if(userChoice === computerChoice) {
drawGame()
} else {
let userWin = true;
if (userChoice === "rock") {
userWin = computerChoice === "paper" ? false : true;
} else if (userChoice === "paper") {
userWin = computerChoice === "scissors" ? false : true;
} else {
userWin = computerChoice === "rock" ? false : true;
}
showWinner(userWin, userChoice, computerChoice);
}
};
choices.forEach((choice) => {
choice.addEventListener("click", () => {
const userChoice = choice.getAttribute("id");
playGame(userChoice);
});
});
reset.addEventListener("click", () => {
userScore = 0;
computerScore = 0;
userScorePara.innerText = userScore;
computerScorePara.innerText = computerScore;
msg.innerText = "Let's Play Again!";
msg.style.backgroundColor= "#181b31";
});