-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
77 lines (65 loc) · 2.64 KB
/
script.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
let userscore = 0;
let computerscore = 0;
// --------------------------------------------------------------------------------------------------
const choices = document.querySelectorAll(".box");
const result = document.querySelector("#result");
const userscoredata = document.querySelector("#user-score");
const computerscoredata = document.querySelector("#computer-score");
// --------------------------------------------------------------------------------------------------
choices.forEach((box) => {
box.addEventListener("click", () => {
const userchoice = box.getAttribute("id")
playgame(userchoice)
})
})
// --------------------------------------------------------------------------------------------------
const generatecomputerchoice = () => {
const options = ["rock", "paper", "scissor"]
const randomindex = Math.floor(Math.random() * 3);
return options[randomindex];
}
// --------------------------------------------------------------------------------------------------
const playgame = (userchoice) => {
console.log("User Choice =", userchoice)
const computerchoice = generatecomputerchoice();
console.log("Computer Choice =", computerchoice)
if (userchoice === computerchoice) {
// draw game
console.log("Draw!")
result.innerText = "[ Game Is Draw! ]";
result.style.backgroundColor = "white";
}
else {
let userwin = true;
if (userchoice === "rock") {
// paper, scissor
userwin = computerchoice === "paper" ? false : true;
}
else if (userchoice === "paper") {
// rock, scissor
userwin = computerchoice === "scissor" ? false : true;
}
else {
// rock, paper
userwin = computerchoice === "rock" ? false : true;
}
showwinner(userwin, userchoice, computerchoice);
}
}
// --------------------------------------------------------------------------------------------------
const showwinner = (userwin, userchoice, computerchoice) => {
if (userwin) {
console.log("You Win!")
userscore++;
userscoredata.innerText = userscore;
result.innerText = `[ You Win! Your ${userchoice} beats Computer's ${computerchoice} ]`;
result.style.backgroundColor = "green";
}
else {
console.log("You Loose!")
computerscore++;
computerscoredata.innerText = computerscore;
result.innerText = `[ You Loose! Computer's ${computerchoice} beats Your ${userchoice} ]`;
result.style.backgroundColor = "red";
}
}