Javascript: Building a Dice Game
Tags: webdev, javascript, programming, tutorial
Published: 2023-02-13 13:52:28

### Introduction.
The dice game is a duo-player game that is very interesting to play and brings the feel of the physical dice game to the players.
The players roll the dice and their cumulative scores are updated consistently until the active player hits a 1. Hitting a 1 means that the active player loses their current scores and the game switches to the next player. You should use the hold button to update your overall score and to make sure that you do not lose your high scores before switching to the next player. The first player to hit a 100 and above cumulative points wins the game. From this game, you will learn more about the JavaScript DOM manipulation.

###Overview
This tutorial puts the DOM(Document Object Model) skills into practice. You should already have knowledge on how to manipulate the DOM. This knowledge will come in handy in our small project.

### Prerequisites.
This tutorial blog assumes that you already have HTML and CSS knowledge and you are just going to work with JavaScript to make the game functional.
This project however, will be helpful to both code newbies and intermediate programmers who want to brush their JavaScript skills.

### HTML and CSS starter files.
The starter files for the HTML and CSS of this project can be found on my GitHub page plus the images required therein: [Github](https://github.com/Stegeek/Dice-Game).

Clone the project to your local machine and let's enjoy the ride.

By now, your website should be looking like this:

![Dice-game website view](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8xvh0gro58zd31xbste4.png)

With all that set, you are now ready to begin our adventure.


### Functionality with JavaScript.
Looking at your HTML code, you can see that you have linked all the important scripts (script.js and style.css) meaning that you can work directly on separate sheets and expect all the changes to occur within the markup.

As seen in the image, the dice image shown is hard coded as well as the scores. These should be generated automatically according to the dice rolled.

#### 1. Selecting the elements.
The first step is to select all the elements that you are going to manipulate (Work with). You use the `querySelector` and the `getElementById` methods to select your elements using both the IDs and the classes.

```JavaScript
//Selecting Elements
const player0 = document.querySelector('.player--0');
const player1 = document.querySelector('.player--1');
//Final cumulative scores
const score0Element = document.querySelector('#score--0');
const score1Element = document.querySelector('#score--1');
//Current Scores and the Dice element.
const currentScore0 = document.getElementById('current--0');
const currentScore1 = document.getElementById('current--1');
const diceElement = document.querySelector('.dice');
//Buttons
const btnRoll = document.querySelector('.btn--roll');
const btnNew = document.querySelector('.btn--new');
const btnHold = document.querySelector('.btn--hold');

```
#### 2. Initializing the game.
You need to make all the elements flexible by removing the hard coded values and manipulating them using the DOM whenever the dice is rolled.
You should set the final score to begin at 0 and be updated continuously as the game progresses. The dice image too should be hidden since it is only supposed to show after the dice is rolled.

The scores accumulated by the active player are supposed to be stored in an array so that at the end of the game, they are added and displayed on their final score element.

```JavaScript
 let scores, currentScore, activePlayer, playing;

// Defining a function to initialize the whole game when called.

 const init = () => {
   scores = [0, 0];
   currentScore = 0;
   activePlayer = 0;

  //Final scores elements set to zero
   score0Element.textContent = 0;
   score1Element.textContent = 0;

 //Set surrent score elements to zero
   currentScore0.textContent = 0;
   currentScore1.textContent = 0;
   playing = true;

   diceElement.classList.add('hidden');
   player0.classList.remove('player--winner');
   player1.classList.remove('player--winner');
   player0.classList.add('player--active');
   player1.classList.remove('player--active');
 };

init();
```
#### 3. Roll Button Functionality.
The first button that you need to work with is the "Roll Dice" button. When clicked, it rolls the dice and gives us the final number rolled, displays the rolled dice to the website and checks if the dice is equal to one. If the dice rolled is equal to 1, the game switches to the next player.

```JavaScript
//Button Roll Functionality
btnRoll.addEventListener('click', function () {
  if (playing) {
    //1. Generate a random dice number between 1 and 6.
    const dice = Math.floor(Math.random() * 6) + 1;

    //2. Display dice
      // Set the image source to the rolled dice
    diceElement.src = `dice-${dice}.png`; 
     // Remove the 'hidden' class to display the dice that has been rolled.
    diceElement.classList.remove('hidden');

    //3. Check if the number is equal to 1; If true, move to the next player.
    if (dice !== 1) {
   //Update the current score of the current player. 
      currentScore += dice;
   // Display the current score to the page.
      document.getElementById(`current--${activePlayer}`).textContent =
        currentScore;
    } else {
      //switch to Next Player
      switchPlayer();
    }
  }
});
```
#### 4. Switching the players.
In the code above, if the current player rolls a 1, the game is supposed to switch to the next player. The code to switch the player is repeated twice, thus you need to create a function to reuse at both instances to keep your code DRY (Do not Repeat Yourself).
You set the active player to be from zero since we store their scores in an array and you need to access the scores using bracket notation.
```JavaScript

function switchPlayer() = {
//Display the current score of the active player.
  document.getElementById(`current--${activePlayer}`).textContent = 0;
  // Set the current scores to zero.
  currentScore = 0;
 //If active player is player 0, switches to player 1 else sets the player to 0.
  activePlayer = activePlayer === 0 ? 1 : 0;
 /*Toggles between player--active class.
 Adds the 'player--active' class to an element if it is not there and removes it if it is already there.
Already defined in the CSS file*/
  player0.classList.toggle('player--active');
  player1.classList.toggle('player--active');
};

```
#### 5. Hold Button Functionality.
The hold button is supposed to update the cumulative scores of the current player and display it, reset the current score of the active player to zero, and then switch immediately to the next player.
If the cumulative scores of the active player is equal to or greater than 100, the player is considered the winner and the winner class is added to the element which changes the background color.

```JavaScript
btnHold.addEventListener('click', function () {
  if (playing) {
    // 1. Add the current score to the player's score
    scores[activePlayer] += currentScore;
    // Display the score to the current player's scores
    document.getElementById(`score--${activePlayer}`).textContent =
      scores[activePlayer];
    // Check if the score[activeplayer] >= 100, if true exit the game
    if (scores[activePlayer] >= 100) {
      //Finish the game
      diceElement.classList.add('hidden');
      // Set playing to false so that none of the buttons works.
      playing = false;
     // Add the winner class to the active player if the score is greater or equal to 100.
      document
        .querySelector(`.player--${activePlayer}`)
        .classList.add('player--winner');
    // Remove the player active class from the winner to make sure the game ends.
      document
        .querySelector(`.player--${activePlayer}`)
        .classList.remove('player--active');
    } else {
      switchPlayer();
    }
  }
});
```

### 6. New Game button functionality.
Now that you have all buttons working well, it's time to make your "New Game" button functional. This will be easy since in the event where you click the new game button, it is supposed to initialize everything we have manipulated back to the initial content.

```JavaScript
btnNew.addEventListener('click', function () {
//We call the init function which has all the code to revert everything to original.
  init();
});
```
### Conclusion
We have looked at how we can use JavaScript to manipulate CSS styles and HTML elements in response to the clicking of buttons.
I hope you enjoyed the article and learnt something from it.