DEV Community

Cover image for Javascript: Building a Dice Game
Stephen Gachoki
Stephen Gachoki

Posted on • Updated on

Javascript: Building a Dice Game


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.


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.


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.

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

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.

//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');
const btnRoll = document.querySelector('.btn--roll');
const btnNew = document.querySelector('.btn--new');
const btnHold = document.querySelector('.btn--hold');

Enter fullscreen mode Exit fullscreen mode

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.

 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;


Enter fullscreen mode Exit fullscreen mode

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.

//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.

    //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 =
    } else {
      //switch to Next Player
Enter fullscreen mode Exit fullscreen mode

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.

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*/

Enter fullscreen mode Exit fullscreen mode

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.

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 =
    // Check if the score[activeplayer] >= 100, if true exit the game
    if (scores[activePlayer] >= 100) {
      //Finish the game
      // 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.
    // Remove the player active class from the winner to make sure the game ends.
    } else {
Enter fullscreen mode Exit fullscreen mode

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.

btnNew.addEventListener('click', function () {
//We call the init function which has all the code to revert everything to original.
Enter fullscreen mode Exit fullscreen mode


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.

Top comments (0)