-
Notifications
You must be signed in to change notification settings - Fork 3
/
RPS.js
62 lines (54 loc) · 1.72 KB
/
RPS.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
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 yourWinner = isWinner(selection, computerSelection)
const computerWinner = isWinner(computerSelection, selection)
addSelectionResult(computerSelection, computerWinner)
addSelectionResult(selection, yourWinner)
if (yourWinner) incrementScore(yourScoreSpan)
if (computerWinner) incrementScore(computerScoreSpan)
}
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]
}