const - JS | lectureDOM & Events Fundamentals

Project III - Rolling the Dice

DOM & Events Fundamentals

In this lecture, we will start implementing our game's most important functionality, rolling the dice.

If you look at the flowchart (present in the starter folder), you will see that when the user rolls a dice, we first need to generate a random dice roll, then display it and check whether it is a one or not. If it's not, we add that dice roll to the current score, and if it is a one, we go to the next player.

To do that, we first need to react to clicking the roll button. First, we need to select the roll button element and then add an event listener or an event handler.

So here we have our three buttons, and we will start by selecting all of them.

index.html
<button class="btn btn--new">🔄 New game</button>
<button class="btn btn--roll">🎲 Roll dice</button>
<button class="btn btn--hold">📥 Hold</button>
script.js
const buttonNew = document.querySelector('.btn--new');
const buttonRoll = document.querySelector('.btn--roll');
const buttonHold = document.querySelector('.btn--hold');

We then attach the addEventListener to our roll button.

script.js
// Rolling dice functionality
buttonRoll.addEventListener('click', function () {
  // 1. Generate a random dice roll
  // 2. Display the dice
  // 3. Check if rolled a 1
});

As you can see from the above code in our event handler function, the first step is to generate a random dice roll. So let's create a dice variable.

script.js
const dice = Math.trunc(Math.random() * 6) + 1;

The dice variable does not need to be not a global variable. It does not need to be outside our event handler function because each time we roll the dice, we want to generate a new number.

The next thing we need to do from the steps described in our event handler above is to display the dice. To do that, we need to remove the hidden class. Because, remember that when initializing our game, we added the hidden class.

script.js
diceEl.classList.remove('hidden');

Now comes the interesting part. We know that the dice will be a number between one and six, and based on these numbers, we want to display the corresponding image in our files, .i.e, dice-1.png, dice-2.png, etc.

Since all our image files start with dice- and only the number changes, we can use a template literal in which we are going to inject the randomly generated number and then assign it to the image source (src) attribute. By doing this, we can dynamically load one of these six images depending on the randomly rolled dice.

script.js
diceEl.src = `dice-${dice}.png`;

So if you save everything and give it a try, it should be working great! Now all that we have to do is to keep adding the rolled dice to the current score. That's our third step in our event handler.

Remember that adding the rolled dice to the current score only happens when the rolled dice is not a one. Again, if it's a one, we switch the player. If not, we add the dice roll to the current score.

script.js
if (dice !== 1) {
  // Add rolled dice to current score
} else {
  // Switch the player
}

To add the current dice roll to the current score, we need to save that current score somewhere. Remember from the first project that we should not store any data only in the DOM. In this particular case, we should not only display this current score on the user interface. Instead, we also want the variable in our code, which always holds the current score of the current round.

So we need to define a variable for that, and that variable should not be in our event handler function because if we do that, then each time we roll a dice, the current score would be redefined.

script.js
// App variables
let currentScore = 0;

After declaring our currentScore variable, we can now update it in our if condition inside our event handler.

script.js
// App variables
if (dice !== 1) {
  // Add rolled dice to current score
  currentScore += dice;
}

And now, all we need to do is to display the score on the current player. At this point, we will display it on player one to make it a little bit simpler, but in the upcoming lectures, we will need to keep track of which player is the active player.

script.js
// We select the current scores for both players
const player0CurrentEl = document.getElementById('current--0');
const player1CurrentEl = document.getElementById('current--1');

if (dice !== 1) {
  // Add rolled dice to current score
  currentScore += dice;
  // Assign current score to active player
  player0CurrentEl.textContent = currentScore;
}

Save everything and head on to your browser and see the magic happening! 😅

You will notice that when you roll a one, nothing happens. That's the situation where we want to move to the next player, .i.e. switching the player. That's going to be the else block, and we will handle that in the next lecture.