Roll Dice Game using JavaScript, HTML & CSS

In this tutorial, we will be building a small dice game where the user can press the button to roll the dice. And every time the application will roll the dice and will give a new number on the output. Let’s get started.

Step 1: Create an HTML file and copy the code given below.

<!-- dice game -->
<div class= "text-center"> 
  <button class ="btn" onclick="dice()">  
    <h3> Throw the dice </h3>
  </button>
  <br> <br> 
  <div> 
    <img src ="https://codingiseasy.com/wp-content/uploads/2022/07/dice.jpg" id="dice" height="300px" width="300px">
  </div> 
</div>

Once the HTML part is completed , our page looks something like this:

Roll Dice Game with HTML

Step 2: Give it some Style with CSS

Let’s add some CSS to make the button look better. Be as creative as you can and give amazing styles to the image and the button.

.btn {
  color : red;
  background-color: black;
  border-radius : 1.2em;
  cursor : pointer;
}

You can simply create a tag inside the <head> section and paste this code. After applying CSS, the page looks like this:</p>

Roll Dice Game with CSS & HTML

Step 3: Writing JavaScript (Heart of the Game)

Now comes the most significant part of the application. We will be using the inbuilt JavaScript function .i.e Math.random() to generate random numbers between 1 and 6 for our dice game.

function dice()
{
  var x = Math.floor(Math.random()*5)+1;
  console.log(x);
  var dice = document.getElementById("dice");
  
  if(x==1)
    {
dice.src="https://codingiseasy.com/wp-content/uploads/2022/07/Dice1.jpg";
    }
  if(x==2)
    {
dice.src="https://codingiseasy.com/wp-content/uploads/2022/07/Dice2.png";
    }
  if(x==3)
    {
dice.src="https://codingiseasy.com/wp-content/uploads/2022/07/Dice3.png";
    }
  if(x==4)
    {
dice.src="https://codingiseasy.com/wp-content/uploads/2022/07/Dice4.jpg";
    }
  if(x==5)
    {
dice.src="https://codingiseasy.com/wp-content/uploads/2022/07/Dice5.png";
    }
  if(x==6)
    {
      dice.src="https://codingiseasy.com/wp-content/uploads/2022/07/Dice6.png";
    }
}

Our application is functional now and can be used to play any game that involves dice.

Roll Dice Game with JavaScript, CSS & HTML

Every time you press that button, it will generate a random number and the corresponding dice’s image will be displayed on the screen.

Hope the tutorial was interesting and informative.

Leave a Comment