-
Notifications
You must be signed in to change notification settings - Fork 0
/
Game_logic.js
86 lines (77 loc) · 2.46 KB
/
Game_logic.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
const buttons = Array.from(document.getElementsByClassName('selectable'))
const user_results = document.querySelector('#user-results')
const ai_results = document.querySelector('#ai-results')
const won_text = document.querySelector('#won-text')
const the_game = document.querySelector('.game-container')
const display_results = document.querySelector('.winner-container')
const display_score = document.querySelector('#score')
const reset_game = document.querySelector('#reset')
//winning combination criteria
const WINNER_COMBO = [
{
'selected': 'rock',
'beats': 'scissors',
'icon': '👊'
},
{
'selected': 'paper',
'beats': 'rock',
'icon': '👋'
},
{
'selected': 'scissors',
'beats': 'paper',
'icon': '✌️'
},
]
let PLAYER_SCORE = 0
buttons.forEach( button => {
button.addEventListener('click', e => {
switch(e.target.id) {
case 'rock':
calculateWinner(WINNER_COMBO[0], ai_selected())
break;
case 'paper':
calculateWinner(WINNER_COMBO[1], ai_selected())
break;
case 'scissors':
calculateWinner(WINNER_COMBO[2], ai_selected())
break;
}
})
})
//Ai functionality
function ai_selected() {
const randomIndec = Math.floor(Math.random() * WINNER_COMBO.length)
return WINNER_COMBO[randomIndec]
}
//winner function
function calculateWinner(user, ai) {
if(user.beats == ai.selected) {
display_score.innerHTML = PLAYER_SCORE += 1
updateUI(user, ai, 'you win')
return
}
if(user.selected == ai.selected) {
display_score.innerHTML = PLAYER_SCORE
updateUI(user, ai, 'draw')
return
}
updateUI(user, ai, 'you lose')
}
//updating the UI after winning or losing
function updateUI(user, ai, outcome_text) {
user_results.innerHTML= user.icon
user_results.classList.add('${user.selected}')
ai_results.innerHTML = ai.icon
ai_results.classList.add('${ai.selected}')
won_text.innerHTML = outcome_text
the_game.classList.add('hide')
display_results.classList.remove('hide')
}
reset_game.addEventListener('click', () => {
the_game.classList.remove('hide')
display_results.classList.add('hide')
user_results.className= 'selectable'
ai_results.className= 'selectable'
})