-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
63 lines (55 loc) · 1.76 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
const selectionButtons = document.querySelectorAll("[data-selection]");
const finalColumn = document.querySelector("[data-final-column]");
const computerScoreSpan = document.querySelector("[data-computer-score]");
const playerScoreSpan = document.querySelector("[data-player-score]");
const SELECTIONS = [
{
name: "rock",
emoji: "✊",
beats: "scissors",
},
{
name: "paper",
emoji: "✋",
beats: "rock",
},
{
name: "scissors",
emoji: "✌",
beats: "paper",
},
];
selectionButtons.forEach((selectionButton) => {
selectionButton.addEventListener("click", (e) => {
const selection = SELECTIONS.find(
(selection) => selection.name === selectionButton.dataset.selection
);
makeSelection(selection);
});
});
function makeSelection(selection) {
const computerSelection = randomSelection();
const playerWinner = isWinner(selection, computerSelection);
const computerWinner = isWinner(computerSelection, selection);
addSelectionResult(computerSelection, computerWinner);
addSelectionResult(selection, playerWinner);
if (playerWinner) incrementScore(playerScoreSpan);
else if (computerWinner) incrementScore(computerScoreSpan); // else draw
}
function incrementScore(scoreSpan) {
scoreSpan.innerText = parseInt(scoreSpan.innerText) + 1;
}
function addSelectionResult(selection, winner) {
const div = document.createElement("div");
div.innerText = selection.emoji;
div.classList.add("result-selection");
if (winner) div.classList.add("winner");
finalColumn.after(div);
}
function isWinner(selection, opponentSelection) {
return selection.beats === opponentSelection.name;
}
function randomSelection() {
const randomIndex = Math.floor(Math.random() * SELECTIONS.length);
return SELECTIONS[randomIndex];
}