Dice Rolling Game Using HTML CSS And JavaScript

Dice Rolling Game Using HTML CSS And JavaScript

Introduction

Hey coders, welcome to another new blog. In this article we’ll build a Dice Roll Simulator game. This is a simple and basic game which all of us has played in our childhood. We simply roll a dice and got a random number. In this article we’ve made a dice roll game which will give us a random number on the dice.
We’ve used HTML CSS and JavaScript technologies to build our dice roll simulator game. The HTML code sets up the basic structure of our game and build the components of our game. Next, the CSS code design and make interactive our dice roll game. Lastly, using the JavaScript code we adds functionality to our code.
To create this type of games, you just need the knowledge of HTML CSS and JavaScript. If you’re good in these 3 technologies then you’re good to go. By the end of this article you’ll definitely some useful and valuable insight of HTML CSS and JavaScript which will surely enhance your coding skills.

HTML (index.html)

Get Discount on Top Educational Courses

Brand NameDiscount InformationCoupon Codes Link
Educative.io20% discount on Educative courses and plans
W3Schools20% discount on W3Schools courses
KodeKloud10% discount on KodeKloud courses and plans
GeeksforGeeks30% discount on GeeksforGeeks courses
Target Test Prep20% discount on Target Test Prep
Coding Ninjas₹5000 discount on Coding Ninjas courses
Skillshare40% discount on Skillshare
DataCamp50% discount on DataCamp
365 Data Science57% discount on 365 Data Science Plans
Get SmarterFlat 20% discount on Get Smarter courses
SmartKeedaFlat 40% discount on SmartKeeda courses
StackSocial20% discount on StackSocial courses

This is our HTML code which sets up the basic structure of Dice Roll Simulator game. This code creates the basic components for our game which we’ll design and makes interactive later in CSS and JS code. Let’s understand the code.

  • <!DOCTYPE html> : This define that our document is an HTML code document.
  • <html lang=”en”> : The root element of document , with language set as English.
  • <title> : This sets the title of the webpage as “Dice roll simulator.
  • <link> : This tag links external links to our code file.
  • <h1>: This tag displays main heading with the text “Dice Roll Simulator”.
  • <div class=”dice” id=”dice”>: This is a div element for the dice, with a default number showing 6. This contains a class and id “dice”.
  • <button id=”roll-button”> : This is button with the text “Roll Dice” with a id of “roll-button”. This is to roll the dice.
  • <ul id=”roll-history”> : An empty unordered list with an ID of “roll-history” where dice roll history will be shown.
  • <script> : This tag adds external JavaScript file to add interactive functionality to our game.
				
					

  
    
    
    
    <title>codewithcurious.com - Dice Roll Simulator</title>

    
    
  
  
    <h1>Dice Roll Simulator</h1>
    <div class="dice" id="dice">&#9860;</div>
    <button id="roll-button">Roll Dice</button>
    <ul id="roll-history">
      &lt;!-- <li>Roll 1: <span>&#9856;</span></li>
      <li>Roll 2: <span>&#9860;</span></li> --&gt;
    </ul>
    
  


				
			

CSS (Style.css)

This is our CSS code which design our Dice Roll Simulator game. CSS design the webpages and make it good looking. Let’s understand the code.

  • The body tag sets the font “Open Sans”. Body aligns the text center and sets the margin 0.
  • H1 sets the font size of 3rem and a margin top of 2rem.
  • The .dice class sets font size of 7rem with margin of 5px. A animation duration and a animation fill mode is set to this .dice class.
  • A roll animation added to the .roll-animation class.
  • An animation named roll defines using keyframes. It starts with no rotation and ends with a full 720 deg rotation along both X and Y axes.
  • Next, we styles the button element. It takes Bg color of light blue sky, text color of white, font size and some padding. Cursor set as pointer, border radius of 1rem with some transition applied to the button element.
  • On the button hover we’ve changed the background color of the button.
  • ul removes the default list styling. It remove padding and sets max-width of 600px.
  • li sets a font size of 1.5rem for list items. It adds padding, margin, background color and border radius with rounded corner. It uses box shadow for list items and centers the element using flexbox properties.
  • Span of li takes font size of 3rem with the margin right of 1rem.
				
					body {
  font-family: "Open Sans", sans-serif;
  text-align: center;
  margin: 0;
}

h1 {
  font-size: 3rem;
  margin-top: 2rem;
}

.dice {
  font-size: 7rem;
  margin: 5px;
  animation-duration: 1s;
  animation-fill-mode: forwards;
}

.roll-animation {
  animation-name: roll;
}

@keyframes roll {
  0% {
    transform: rotateY(0deg) rotateX(0deg);
  }

  100% {
    transform: rotateY(720deg) rotateX(720deg);
  }
}

button {
  background-color: #47a5c4;
  color: white;
  font-size: 1.5rem;
  padding: 1rem 2rem;
  border: none;
  border-radius: 1rem;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

button:hover {
  background-color: #2e8baf;
}

ul {
  list-style: none;
  padding: 0;
  max-width: 600px;
  margin: 2rem auto;
}

li {
  font-size: 1.5rem;
  padding: 0.5rem;
  margin: 0.5rem;
  background-color: #f2f2f2;
  border-radius: 0.5rem;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

li span {
  font-size: 3rem;
  margin-right: 1rem;
}

				
			

Javascript (Script.js)

This is our JavaScript code which adds interactivity and functionality to our Dice Roll game. This is most important code for game, because without this code our Dice Roll game won’t work. This code creates function for each condition of the game and using those function our game works properly.

  • The code first access the HTML elements using DOM and stored them in some variable using const keyword.
  • Next, we create a variable named historyList and makes it an empty array which will store the result of all dice roll.
  • The rollDice function generates a random number between 1 to 6 for the dice and shows the dice face using that random number and updates the roll history as well.
  • The updateRollHistory function first clear the old history. Then it creates the list items for each roll and append them to the roll history.
  • The getDiceFace function uses switch case statement to convert dice roll. It stops the loops once when the dice face location rached.
  • Lastly, It adds a event listener to the button element. On the click of button, it adds rolling animation. Using setTimeout function it rolls the dice after 1 second.

This is how our JavaScript code works.

				
					const buttonEl = document.getElementById("roll-button");

const diceEl = document.getElementById("dice");

const rollHistoryEl = document.getElementById("roll-history");

let historyList = [];

function rollDice() {
  const rollResult = Math.floor(Math.random() * 6) + 1;
  const diceFace = getDiceFace(rollResult);
  diceEl.innerHTML = diceFace;
  historyList.push(rollResult);
  updateRollHistory();
}

function updateRollHistory() {
  rollHistoryEl.innerHTML = "";
  for (let i = 0; i &lt; historyList.length; i++) {
    const listItem = document.createElement(&quot;li&quot;);
    listItem.innerHTML = `Roll ${i + 1}: <span>${getDiceFace(
      historyList[i]
    )}</span>`;
    rollHistoryEl.appendChild(listItem);
  }
}

function getDiceFace(rollResult) {
  switch (rollResult) {
    case 1:
      return "&#9856;";
    case 2:
      return "&#9857;";
    case 3:
      return "&#9858;";
    case 4:
      return "&#9859;";
    case 5:
      return "&#9860;";
    case 6:
      return "&#9861;";
    default:
      return "";
  }
}

buttonEl.addEventListener("click", () =&gt; {
  diceEl.classList.add("roll-animation");
  setTimeout(() =&gt; {
    diceEl.classList.remove("roll-animation");
    rollDice();
  }, 1000);
});

				
			

Output:

Disclaimer: The code provided in this post is sourced from GitHub and is distributed under the MIT License. All credits for the original code go to the respective owner. We have shared this code for educational purposes only. Please refer to the original repository for detailed information and any additional usage rights or restrictions.

3D Car Driving Game Using Html CSS And JavaScript Introduction Hello friends, welcome to today’s new blog post. Today we have created …

Dice Rolling Game Using HTML CSS And JavaScript Introduction Hey coders, welcome to another new blog. In this article we’ll build a …

Crossey Road Game Clone Using HTML CSS And JavaScript Introduction This is our HTML code which sets up the basic structure of …

Memory Card Game Using HTML CSS And JavaScript Introduction Hello coders, welcome to another new blog. Today in this article we’ll learn …

Get Huge Discounts
More Python Projects