-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
94 lines (76 loc) · 2.35 KB
/
index.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const buttons = document.querySelectorAll(".pick");
const scoreEl = document.getElementById("score");
const main = document.getElementById("main");
const selection = document.getElementById("selection");
const reset = document.getElementById("reset");
const user_select = document.getElementById("user-select")
const cpu_select = document.getElementById("cpu-choice")
const winner = document.getElementById("winner");
// modal
const openModal = document.getElementById("open")
const closeModal = document.getElementById("close")
const modal = document.getElementById("modal")
const choices = ["paper", "rock", "scissors"];
let score = 0;
let userChoice;
// listeners
buttons.forEach((button) => {
button.addEventListener("click", () => {
userChoice = button.getAttribute("data-choice");
decideWinner();
});
});
reset.addEventListener("click", () => {
// show the main || hide the selection
main.style.display = "flex";
selection.style.display = "none";
});
openModal.addEventListener('click', () => {
modal.style.display = 'flex';
})
closeModal.addEventListener('click', () => {
modal.style.display = 'none';
})
function decideWinner() {
const cpuChoice = pickRandomChoice();
// update the view
updateSelection(user_select, userChoice)
updateSelection(cpu_select, cpuChoice)
if (userChoice === cpuChoice) {
// draw
winner.innerText = 'draw'
} else if (
(userChoice === "paper" && cpuChoice === "rock") ||
(userChoice === "rock" && cpuChoice === "scissors") ||
(userChoice === "scissors" && cpuChoice === "paper")
) {
// user Won
updateScore(1);
winner.innerText = 'win'
} else {
// user lost
updateScore(-1);
winner.innerText = 'lost'
}
// show the selection || hide the main
main.style.display = "none";
selection.style.display = "flex";
}
function updateScore(value) {
score += value;
scoreEl.innerText = score;
}
function pickRandomChoice() {
return choices[Math.floor(Math.random() * choices.length)];
}
function updateSelection(selectionEl, choice) {
// Class reset
selectionEl.classList.remove("btn-paper");
selectionEl.classList.remove("btn-rock");
selectionEl.classList.remove("btn-scissors");
// update the img
const image = selectionEl.querySelector("img");
selectionEl.classList.add(`btn-${choice}`);
image.src = `./images/icon-${choice}.svg`;
image.alt = choice;
}