@@ -21,28 +21,58 @@ diceEl.classList.add('hidden');
2121const scores = [ 0 , 0 ] ;
2222let currentScore = 0 ;
2323let activePlayer = 0 ;
24+ let playing = true ;
25+
26+ const switchPlayer = function ( ) {
27+ document . getElementById ( `current--${ activePlayer } ` ) . textContent = 0 ;
28+ currentScore = 0 ;
29+ activePlayer = activePlayer === 0 ? 1 : 0 ;
30+ player0El . classList . toggle ( 'player--active' ) ;
31+ player1El . classList . toggle ( 'player--active' ) ;
32+ } ;
2433
2534// Rolling dice functionality
2635btnRoll . addEventListener ( 'click' , function ( ) {
27- // 1. Generating a random dice roll
28- const dice = Math . trunc ( Math . random ( ) * 6 ) + 1 ;
29- console . log ( dice ) ;
30- // 2. Display dice
31- diceEl . classList . remove ( 'hidden' ) ;
32- diceEl . src = `dice-${ dice } .png` ;
33-
34- // 3. Check for rolled 1
35- if ( dice !== 1 ) {
36- // Add dice to current score
37- currentScore += dice ;
38- document . getElementById ( `current--${ activePlayer } ` ) . textContent =
39- currentScore ;
40- } else {
41- // Switch to next player
42- document . getElementById ( `current--${ activePlayer } ` ) . textContent = 0 ;
43- currentScore = 0 ;
44- activePlayer = activePlayer === 0 ? 1 : 0 ;
45- player0El . classList . toggle ( 'player--active' ) ;
46- player1El . classList . toggle ( 'player--active' ) ;
36+ if ( playing ) {
37+ // 1. Generating a random dice roll
38+ const dice = Math . trunc ( Math . random ( ) * 6 ) + 1 ;
39+ // 2. Display dice
40+ diceEl . classList . remove ( 'hidden' ) ;
41+ diceEl . src = `dice-${ dice } .png` ;
42+
43+ // 3. Check for rolled 1
44+ if ( dice !== 1 ) {
45+ // Add dice to current score
46+ currentScore += dice ;
47+ document . getElementById ( `current--${ activePlayer } ` ) . textContent =
48+ currentScore ;
49+ } else {
50+ // Switch to next player
51+ switchPlayer ( ) ;
52+ }
53+ }
54+ } ) ;
55+
56+ btnHold . addEventListener ( 'click' , function ( ) {
57+ if ( playing ) {
58+ // 1. Add current score to active player's score
59+ scores [ activePlayer ] += currentScore ;
60+ document . getElementById ( `score--${ activePlayer } ` ) . textContent =
61+ scores [ activePlayer ] ;
62+ // 2. Check if player's score is >= 100
63+ if ( scores [ activePlayer ] >= 10 ) {
64+ // Finish the game
65+ playing = false ;
66+ diceEl . classList . add ( 'hidden' ) ;
67+ document
68+ . querySelector ( `.player--${ activePlayer } ` )
69+ . classList . add ( 'player--winner' ) ;
70+ document
71+ . querySelector ( `.player--${ activePlayer } ` )
72+ . classList . remove ( 'player--active' ) ;
73+ } else {
74+ switchPlayer ( ) ;
75+ }
76+ // Switch to the next player
4777 }
4878} ) ;
0 commit comments