-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
69 lines (60 loc) Β· 1.87 KB
/
script.js
File metadata and controls
69 lines (60 loc) Β· 1.87 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
65
66
67
68
69
const selectionButtons = document.querySelectorAll('[data-selection]');
const finalColumn = document.querySelector('[data-final-column]');
const computerScoreSpan = document.querySelector('[data-computer-score]');
const yourScoreSpan = document.querySelector('[data-your-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 selectionName = selectionButton.dataset.selection;
const selection = SELECTIONS.find(
selection => selection.name === selectionName
);
makeSelection(selection);
});
});
function makeSelection(selection) {
const computerSelection = randomSelection();
const youWin = isWinner(selection, computerSelection);
const computerWin = isWinner(computerSelection, selection);
addSelectionResult(computerSelection, computerWin);
addSelectionResult(selection, youWin);
// increment score if you or computer win
if (youWin) incrementScore(yourScoreSpan);
if (computerWin) incrementScore(computerScoreSpan);
}
// incrememnt score
function incrementScore(scoreSpan) {
scoreSpan.innerText = parseInt(scoreSpan.innerText) + 1;
}
// show selected choice and winner
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);
}
// find winner
function isWinner(selection, opponentSelection) {
return selection.beats === opponentSelection.name;
}
function randomSelection() {
const randomIndex = Math.floor(Math.random() * SELECTIONS.length);
return SELECTIONS[randomIndex];
}