-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
98 lines (77 loc) · 2.71 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
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
95
96
97
98
'use strict';
//selecting elements
const player0EL = document.querySelector('.player--0');
const player1EL = document.querySelector('.player--1');
const score0El = document.querySelector('#score--0');
const score1El = document.getElementById('score--1');
const diceEl = document.querySelector('.dice');
const current0EL=document.getElementById('current--0');
const current1EL=document.getElementById('current--1');
const btnNew = document.querySelector('.btn--new');
const btnRoll = document.querySelector('.btn--roll');
const btnHold = document.querySelector('.btn--hold');
let scores,currentScore,activePlayer,playing;
//starting values
scores = [0,0];
currentScore=0;
activePlayer=0;
const init = function () {
playing = true;
diceEl.classList.add('hidden'); currentScore=document.querySelector('.current-score').textContent;
currentScore = 0;
score0El.textContent=0;
score1El.textContent=0;
current0EL.textContent=0;
current1EL.textContent=0;
scores[0]=0;
scores[1]=0;
document.querySelector(`.player--${activePlayer}`).classList.add('player--active');
document.querySelector(`.player--${activePlayer}`).classList.remove('player--winner');
}
const switchPlayer = function () {
currentScore = 0;
document.getElementById(`current--${activePlayer}`).textContent=currentScore;
activePlayer= activePlayer == 0 ? 1:0;
player0EL.classList.toggle('player--active');
player1EL.classList.toggle('player--active');
}
init();
//Rolling dice functinality
btnRoll.addEventListener('click', function () {
if(playing){
// 1-generating a random dice roll
const dice = Math.trunc(Math.random()*6)+1;
// 2-display dice
diceEl.classList.remove('hidden');
diceEl.src = `dice-${dice}.png`;
// 3-check for rolled 1 : if true
if(dice != 1){
//add dice to the current score
currentScore += dice;
document.getElementById(`current--${activePlayer}`).textContent=currentScore;
}else{
//Switch to other player
switchPlayer();
}
}
});
btnHold.addEventListener('click',function(){
if(playing){
scores[activePlayer] += currentScore;
document.getElementById(`score--${activePlayer}`).textContent = scores[activePlayer];
if(scores[activePlayer] >= 100){
playing = false;
diceEl.classList.add('hidden');
document.querySelector(`.player--${activePlayer}`).classList.remove('player--active');
document.querySelector(`.player--${activePlayer}`).classList.add('player--winner');
current0EL.textContent=0;
current1EL.textContent=0;
}
else{
switchPlayer();
}
}
});
btnNew.addEventListener('click',function(){
init();
});