HTML Game Using JavaScript DiceRoll

Hello Developers, in this tutorial you are going to learn HTML Game using JavaScript where I will show you how you can actually create a game with the help of an example. So in this example, you will learn a very interesting game i.e. Pig game(rolling dice) using JavaScript. The game goes around for the first one to reach the final score. It is a two-player game.

The Game Rules: HTML Game Using JavaScript

The game has 2 players, playing in rounds-
  •  In each turn, a player rolls dice as many times as he wishes. Each result gets added to his ROUND score but, if the player rolls a 1, all his ROUND score gets lost.
  • After that, it’s the next player’s turn.
  •  The player can choose to ‘Hold’, which means that his ROUND score gets added to his GLOBAL score. After that, it’s the next player’s turn.
  •  The first player to reach the final Score or 100 points on GLOBAL score wins the game(You can set the winning final scores at the start of the game).

The HTML CODE:

To create HTML Game Using JavaScript: First, you need to create the game interface for which the code is provided to you below.

Second, you need to proper id or class to the different fields so that you can do JS DOM manipulation and CSS formatting with them.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <link href="https://fonts.googleapis.com/css?family=Lato:100,300,600" rel="stylesheet" type="text/css">
        <link type="text/css" rel="stylesheet" href="style.css">
        
        <title>Pig Game</title>
    </head>

    <body>
        <div class="wrapper clearfix">
            <div class="player-0-box active">
                <div class="Players-Name" id="n-0">Player 1</div>
                <div class="Players-Score" id="s-0">43</div>
                <div class="player-current-box">
                    <div class="player-current-label">Current</div>
                    <div class="player-current-score" id="currentPlayer-0">11</div>
                </div>
            </div>
            
            <div class="player-1-box">
                <div class="Players-Name" id="n-1">Player 2</div>
                <div class="Players-Score" id="s-1">72</div>
                <div class="player-current-box">
                    <div class="player-current-label">Current</div>
                    <div class="player-current-score" id="currentPlayer-1">0</div>
                </div>
            </div>
            
            <button class="btn-new">New game</button>
            <button class="btn-roll">Roll dice</button>
            <button class="btn-hold">Hold</button>
            
            <input type="text" placeholder="Final score" class="final-score">
            
            <img src="dice-5.png" alt="Dice" class="dice" id="dice-1">
           
        </div>
        
        <script src="script.js"></script>
        
    </body>
</html>

JavaScript code for the game

Now you need to write the JavaScript code for your game.

This js code contains 4 global variables, 3 event listeners, and 2 functions.

Below is the code that you need to write.

var Scores, RoundScores, PlayerActive, Playing;

start();


document.querySelector('.btn-roll').addEventListener('click', function() {
    if(Playing) {
        // 1. Random number
        var dice = Math.floor(Math.random() * 6) + 1;

        //2. Display the result
       
        var diceDOM = document.querySelector('.dice');
        diceDOM.style.display = 'block';
        diceDOM.src = 'dice-' + dice + '.png';


        //3. Update the round score IF the rolled number was NOT a 1
        if (dice !== 1) {
            //Add score
            RoundScores += dice;
            document.querySelector('#currentPlayer-' + PlayerActive).textContent = RoundScores;
        } else {
            //Next player
            nextPlayer();
        }
    }    
});


document.querySelector('.btn-hold').addEventListener('click', function() {
    if (Playing) {
        // Add CURRENT score to GLOBAL score
        Scores[PlayerActive] += RoundScores;

        // Update the UI
        document.querySelector('#s-' + PlayerActive).textContent = Scores[PlayerActive];
        
        var input = document.querySelector('.final-score').value;
        var winningScore;
        
        // Undefined, 0, null or "" are COERCED to false
        // Anything else is COERCED to true
        if(input) {
            winningScore = input;
        } else {
            winningScore = 100;
        }
        
        // Check if player won the game
        if (Scores[PlayerActive] >= winningScore) {
            document.querySelector('#n-' + PlayerActive).textContent = 'Winner!';
            document.getElementById('dice-1').style.display = 'none';
           
        
            document.querySelector('.player-' + PlayerActive + '-box').classList.add('winner');
            document.querySelector('.player-' + PlayerActive + '-box').classList.remove('active');
            Playing = false;
        } else {
            //Next player
            nextPlayer();
        }
    }
});

document.querySelector('.btn-new').addEventListener('click', start);

function nextPlayer() {
    //Next player
    PlayerActive === 0 ? PlayerActive = 1 : PlayerActive = 0;
    RoundScores = 0;

    document.getElementById('currentPlayer-0').textContent = '0';
    document.getElementById('currentPlayer-1').textContent = '0';

    document.querySelector('.player-0-box').classList.toggle('active');
    document.querySelector('.player-1-box').classList.toggle('active');

    document.querySelector('.dice').style.display = 'none';
}


function start() {
    Scores = [0, 0];
    PlayerActive = 0;
    RoundScores = 0;
    Playing = true;
    
    document.querySelector('.dice').style.display = 'none';

    document.getElementById('s-0').textContent = '0';
    document.getElementById('s-1').textContent = '0';
    document.getElementById('currentPlayer-0').textContent = '0';
    document.getElementById('currentPlayer-1').textContent = '0';
    document.getElementById('n-0').textContent = 'Player 1';
    document.getElementById('n-1').textContent = 'Player 2';
    document.querySelector('.player-0-box').classList.remove('winner');
    document.querySelector('.player-1-box').classList.remove('winner');
    document.querySelector('.player-0-box').classList.remove('active');
    document.querySelector('.player-1-box').classList.remove('active');
    document.querySelector('.player-0-box').classList.add('active');
}

Working Of JavaScript Code:

First, you need to declare 4 global variables. Then immediately invoke start function after it.

So that the start function executes at the beginning of the program.

The score variable will store the global scores for each of the players.

RoundScores will store the round scores for each player.

PlayerActive will store the currently active player.

Playing variable is used as a boolean data type to check that the game begins or not.

var Scores, RoundScores, PlayerActive, Playing;

start();

*This start function is explained later in this post.

Adding event listeners

1) Adding Dice-Roll EventListener

First of all, check that if the game starts by setting the boolean Playing variable in an if condition.

Then, you need to add this event listener which will be functional on the ‘click’ of a mouse button and you need to give the dice image id to it. document.querySelector(‘.btn-roll’).addEventListener(‘click’, function(){}

then you need to write an anonymous function and in this function, you need to do the following things.

Firstly create a random number in the rage of 1 to 6(this random number will depict the numbers on the dice) and store it in a variable called dice. Then to display the results first create variable called diceDom which store the dice image number var diceDOM = document.querySelector(‘.dice’); Then if the game start first shows the image by using the block of display method. Now display the dice images in the Browser acc to the number from random numbers by typing dice DOM.src = ‘dice-‘ + dice + ‘.png’;

Updating Round Scores in UI

Now you need to Update the round score IF the rolled number was NOT a 1 in the UI.

First, you need to check with the if statement whether dice rolled 1 or not and if not then add the dice rolled number to a variable called RoundScore  if (dice !== 1) { RoundScores += dice; After that update in the UI by typing document.querySelector(‘#currentPlayer-‘ + PlayerActive).textContent = RoundScores; in the same if block.

Else if the dice rolled a 1 then call this function nextPlayer();

document.querySelector('.btn-roll').addEventListener('click', function() {
    if(Playing) {
        // 1. Random number
        var dice = Math.floor(Math.random() * 6) + 1;

        //2. Display the result
       
        var diceDOM = document.querySelector('.dice');
        diceDOM.style.display = 'block';
        diceDOM.src = 'dice-' + dice + '.png';


        //3. Update the round score IF the rolled number was NOT a 1
        if (dice !== 1) {
            //Add score
            RoundScores += dice;
            document.querySelector('#currentPlayer-' + PlayerActive).textContent = RoundScores;
        } else {
            //Next player
            nextPlayer();
        }
    }    
});

2) Adding Hold button EventListener

Now, you need to create another event listener for hold button by document.querySelector(‘.btn-hold’).addEventListener(‘click’, function() {}. This will help create an event listener with the hold button id and will call the anonymous function when the hold button is clicked.

The anonymous function working
As the hold button gets clicked the round scores get added up to the Global score and the next player gets its turn.

So first you need to add the round scores to global score by Scores[PlayerActive] += RoundScores; here, Scores array will take the active player and then add the current player round score data to the global score.

Second, you need to update the user interface in the browser which will be done by the dom manipulation document.querySelector(‘#s-‘ + PlayerActive).textContent = Scores[PlayerActive]; The .textContent helps in manipulation/changing of the global score in html.

Now you need to write var input = document.querySelector(‘.final-score’).value; This input variable will store the final game score count which the user sets before starting the game. The document.querySelector(‘.final-score’).value; helps in retriving of the data from the input field on the web page.

Now declare a variable winningScore where you will store the final game benchmark taken from the user and then create an if statement to save it. If in case the user doesn’t enter the final game over score then by default set it to 100 in the else statement.

if(input) { winningScore = input; }

else { winningScore = 100; }

Check if the player won the game while pressing the hold button and submitting its round score to the global score.

To check that first you need to write an if condition and check whether Global score is greater than or equals to the final score or not and if it’s equal then the currently active player wins the game and print Winner! in the browser. And then again set the image display to none to hide the image as the game finishes.

The style.display property sets or returns the element’s display type.

After that, you need to assign the winner class to the currently active player. The winner class is basically used for styling and CSS purpose of the winning player.

Then you need to remove the active player class from the currently active player by document.querySelector(‘.player-‘ + PlayerActive + ‘-box’).classList.remove(‘active’); With which you can also remove that red dot icon from the active player profile box. 

The classList.remove(‘active’) is a js property to remove classes from the particular assigned object.And after that set the playing to false so the game stops.

And now you need to write the else block that is because if the player doesn’t win the game then the game continues and its the next players turn. by calling the nextPlayer() function.

document.querySelector('.btn-hold').addEventListener('click', function() {
    if (Playing) {
        // Add CURRENT score to GLOBAL score
        Scores[PlayerActive] += RoundScores;

        // Update the UI
        document.querySelector('#s-' + PlayerActive).textContent = Scores[PlayerActive];
        
        var input = document.querySelector('.final-score').value;
        var winningScore;
        
        // Undefined, 0, null or "" are COERCED to false
        // Anything else is COERCED to true
        if(input) {
            winningScore = input;
        } else {
            winningScore = 100;
        }
        
        // Check if player won the game
        if (Scores[PlayerActive] >= winningScore) {
            document.querySelector('#n-' + PlayerActive).textContent = 'Winner!';
            document.getElementById('dice-1').style.display = 'none';
           
        
            document.querySelector('.player-' + PlayerActive + '-box').classList.add('winner');
            document.querySelector('.player-' + PlayerActive + '-box').classList.remove('active');
            Playing = false;
        } else {
            //Next player
            nextPlayer();
        }
    }
});

3) Adding New Game EventListener

First, you need to write the select the new game id by document.querySelector(‘.btn-new’). Then you need to add the event listener to it which will be invoked on the mouse click option and will call the start function.

document.querySelector('.btn-new').addEventListener('click', start);

Adding The Functions

Adding nextPlayer() Funtion

First, you need to write the ternary operator and set the active player to 0 which means that the currently active player write now is player 0 and then check if the value of the active player is 1 or 0 if the value is equal to 1 then change the currently active player to 0 and if the value is 0 then set the currently active player value is 1. This toggle will change the currently active player. PlayerActive === 0 ? PlayerActive = 1 : PlayerActive = 0;    After that set the RoundScores to zero.

And also set the initial round scores to zero by :

document.getElementById(‘currentPlayer-0’).textContent = ‘0’;

document.getElementById(‘currentPlayer-1’).textContent = ‘0’;

After that simulatneoulsy you need to toogle the active class which also contains css with it according to the currently active player by

document.querySelector(‘.player-0-box’).classList.toggle(‘active’);

document.querySelector(‘.player-1-box’).classList.toggle(‘active’);

The classList.toogle helps in adding and removing the active class to the currently active player.

Then you need to hide the display of the dice image by setting style.display property to none.

function nextPlayer() {
    //Next player
    PlayerActive === 0 ? PlayerActive = 1 : PlayerActive = 0;
    RoundScores = 0;

    document.getElementById('currentPlayer-0').textContent = '0';
    document.getElementById('currentPlayer-1').textContent = '0';

    document.querySelector('.player-0-box').classList.toggle('active');
    document.querySelector('.player-1-box').classList.toggle('active');

    document.querySelector('.dice').style.display = 'none';
}

Adding start() Function

This function is called at the beginning of the game or when we want to start a new game. So firstly you need to set everything to zero i.e. Scores, PlayerActive, and RoundScores. Scores = [0, 0]; PlayerActive = 0; RoundScores = 0; Then you need to start the game so set Playing is equals to true. After that set the dice image to none to hide the dice when the game loads. by typing document.querySelector(‘.dice’).style.display = ‘none’; 

Explanation:- We set the Scores to zero so that to reset the new game with player scores as zero. Then we set PlayerActive to zero so that the first player to start the game is player 1. Then we set the RoundScores to zero because as any value left from the last game would now again gets reset to zero.

Now all the variables are set/reset to zero, so now we have to display that initial zero value in the web browser

Now you have to do DOM manipulation by getting the id’s of the respective fields and setting it to zero on browser

First, you will set the global scores to zero by:-

    document.getElementById(‘s-0’).textContent = ‘0’;
    document.getElementById(‘s-1’).textContent = ‘0’;

Then you need to set the current set the round scores of players to zero by:-

    document.getElementById(‘currentPlayer-0’).textContent = ‘0’;
    document.getElementById(‘currentPlayer-1’).textContent = ‘0’;

Now if someone wins the game the player name is changed to the winner so you need to change back the player name and reset it “Player 1” and “Player 2” and to change that you simply need to write this line:-
    document.getElementById(‘n-0’).textContent = ‘Player 1’;
    document.getElementById(‘n-1’).textContent = ‘Player 2’;

Now once after someone wins the game you need to change back the CSS also to set to the original start and for that, you need to remove the winner class and active class which also contains CSS styling for the player winning.
So you need to simply remove these two classes from both the players even if the class is not present in a player, but we don’t know who wins the game. So we remove it from both the player by:-
    document.querySelector(‘.player-0-box’).classList.remove(‘winner’);
    document.querySelector(‘.player-1-box’).classList.remove(‘winner’);
    document.querySelector(‘.player-0-box’).classList.remove(‘active’);
    document.querySelector(‘.player-1-box’).classList.remove(‘active’);

Now you just need to make the first player as the active player at the start of the game. So add the active class to first player id by:-
    document.querySelector(‘.player-0-box’).classList.add(‘active’);

function start() {
    Scores = [0, 0];
    PlayerActive = 0;
    RoundScores = 0;
    Playing = true;
    
    document.querySelector('.dice').style.display = 'none';

    document.getElementById('s-0').textContent = '0';
    document.getElementById('s-1').textContent = '0';
    document.getElementById('currentPlayer-0').textContent = '0';
    document.getElementById('currentPlayer-1').textContent = '0';
    document.getElementById('n-0').textContent = 'Player 1';
    document.getElementById('n-1').textContent = 'Player 2';
    document.querySelector('.player-0-box').classList.remove('winner');
    document.querySelector('.player-1-box').classList.remove('winner');
    document.querySelector('.player-0-box').classList.remove('active');
    document.querySelector('.player-1-box').classList.remove('active');
    document.querySelector('.player-0-box').classList.add('active');
}

OUTPUT: HTML Game Using JavaScript

Below is the screenshot of the output of our HTML5 game that I have just created in javaScript:

JavaScript HTML5 Game

Remark: You can also create more HTML Game Using JavaScript by using a popular library of JavaScript i.e. React which helps in making more powerful and interactive games.

 

Also, read: Find angle between hour hand and minute hand in JavaScript

 

Leave a Reply

Your email address will not be published. Required fields are marked *