Create Dice Rolling Game using HTML, CSS, and JavaScript

Faraz

By Faraz -

Learn how to create a dice rolling game using HTML, CSS, and JavaScript. Follow our easy-to-understand guide with clear instructions and code examples.


create-dice-rolling-game-using-html-css-and-javascript.webp

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

Creating simple games is a fun and effective way to learn web development. In this tutorial, we’ll guide you through the process of making a dice rolling game using HTML, CSS, and JavaScript. This project is perfect for beginners who want to practice their coding skills while building something interactive and enjoyable.

We’ll cover everything step by step, from setting up the HTML structure to adding styles with CSS and making the dice roll with JavaScript. By the end of this tutorial, you’ll have a fully functional dice rolling game that you can play and share with others.

Source Code

Step 1 (HTML Code):

First, you need to create the basic structure of your game using HTML. This will include the dice, a button to roll the dice, and a section to display the result.

Here's an explanation of each part of the code:

<!DOCTYPE html>

  • This declaration defines the document type and version of HTML (in this case, HTML5).

<html lang="en">

  • The <html> tag wraps the entire HTML document. The lang="en" attribute specifies that the language of the document in English.

<head>

The <head> section contains meta-information about the HTML document, such as its title and links to stylesheets or scripts.

  • <meta charset="UTF-8" />: Defines the character encoding for the document as UTF-8.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0" />: Ensures the page is responsive, meaning it adapts to the width of the device's screen.
  • <title>Dice Rolling Game</title>: Sets the title of the webpage, which appears on the browser tab.
  • <link rel="stylesheet" href="styles.css" />: Links an external CSS file named styles.css to style the HTML elements.

<body>

  • The <body> tag contains the main content of the webpage that users will interact with.
  • <div class="dice">
  • This <div> creates a container for the dice. The class "dice" can be used for styling in the CSS.
  • <div class="cube">
  • This <div> represents the dice's cube, with six faces for each possible outcome.
  • Dice Faces: Each <div> inside "cube" represents a different face of the dice, labeled as "one", "two", "three", "four", "five", and "six".
  • <span class="point">: These <span> elements represent the dots (pips) on the dice. Depending on the face, some spans have the class "point" (representing a dot), while others are left empty to show the pattern of the dice.
  • <div class="pagination">
  • This <div> contains the controls for the dice game.
  • <button class="role">Roll</button>: A button to roll the dice.
  • <div class="text">Choose a Number:</div>: Displays the text "Choose a Number:" to guide the user.
  • <div class="number-choosing">: Contains controls for choosing a number between 1 and 6.
  • <input type="number" class="input" min="1" max="6" value="1"/>: An input field that allows users to enter a number from 1 to 6.
  • <button class="plus"></button>: A button to increase the number.
  • <button class="minus"></button>: A button to decrease the number.

<div class="result">

This <div> will display the results of the dice roll.

  • <div class="message"></div>: This element will show a message based on the result.
  • <div class="choose"></div>: This element will display the user's chosen number.

<script src="script.js"></script>

  • This line includes an external JavaScript file named script.js, which will handle the logic and interactivity of the game, like rolling the dice, checking if the user's choice matches the result, and displaying messages.

Step 2 (CSS Code):

Next, add some styles to make the game look good. You can create a styles.css file to define the look and feel of your game. Let's break down the CSS code:

Universal Styles

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
  • *: Applies to all elements on the page.
  • padding: 0; and margin: 0;: Removes any default padding and margin.
  • box-sizing: border-box;: Ensures that padding and border are included in the element's total width and height.

Body Styles

body {
  padding: 80px 10px 20px;
  display: flex;
  place-items: center;
  flex-direction: column;
  font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
}
  • padding: 80px 10px 20px;: Adds padding around the body content.
  • display: flex;: Uses flexbox layout.
  • place-items: center;: Centers items horizontally and vertically.
  • flex-direction: column;: Aligns child elements in a column.
  • font-family: Specifies the fonts to use.

Dice Container (3D Perspective)

div.dice {
  perspective: 1000px;
  perspective-origin: 400px -200px;
  position: relative;
  left: 0;
  height: 200px;
  top: 100px;
}
  • perspective: 1000px;: Sets the 3D perspective distance.
  • perspective-origin: 400px -200px;: Adjusts the vanishing point.
  • position: relative;, left: 0;, top: 100px;: Positions the dice container.

Cube Styles

.cube {
  position: relative;
  width: 200px;
  height: 200px;
  top: -50px;
  transform-style: preserve-3d;
  transform: rotateX(0deg) rotateZ(0deg) rotateY(0deg);
  transition: 2s all ease;
}
  • position: relative;: Positions the cube relative to its container.
  • width and height: 200px;: Sets the cube size.
  • transform-style: preserve-3d;: Maintains 3D transformations.
  • transform: Initializes rotation angles.
  • transition: 2s all ease;: Adds smooth transitions.

Cube Faces

.cube div {
  position: absolute;
  width: 150px;
  height: 150px;
  background: linear-gradient(to top, #fff, #eee);
  border: #eee 3px ridge;
  display: grid;
  grid-template-columns: repeat(3, calc(100% / 3));
  grid-template-rows: repeat(3, calc(100% / 3));
}
  • position: absolute;: Positions each face of the cube.
  • background: linear-gradient(to top, #fff, #eee);: Applies a gradient background.
  • border: #eee 3px ridge;: Adds a ridged border.
  • display: grid;: Uses a grid layout.
  • grid-template-columns and grid-template-rows: Divides the face into a 3x3 grid.

Dice Points (Dots)

.cube div > span {
  display: block;
  position: relative;
  height: 100%;
  width: 100%;
}
.cube div > span.point::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 15px;
  height: 15px;
  background-color: #000;
  border-radius: 50%;
}
  • span.point::before: Adds the black dots on each face of the dice.
  • transform: translate(-50%, -50%);: Centers the dot.
  • width and height: 15px;: Sets the dot size.
  • background-color: #000;: Makes the dot black.
  • border-radius: 50%;: Makes the dot round.

Cube Face Transformations

These classes position each face of the cube correctly in 3D space:

  • .one, .two, .three, .four, .five, .six: Use transform properties to rotate and position the faces.

Pagination Controls

.pagination {
  margin-top: 150px;
  display: flex;
}
.pagination .role {
  padding: 8px 20px;
  margin-right: 10px;
  border-radius: 5px;
  font-size: 30px;
  background-color: #251e72;
  border: none;
  border-bottom: 4px solid #130f40;
  color: #fff;
  cursor: pointer;
}
  • display: flex;: Aligns pagination items horizontally.
  • background-color: #251e72;: Sets a dark blue background.
  • border-bottom: 4px solid #130f40;: Adds a darker blue bottom border.
  • cursor: pointer;: Makes the role buttons clickable.

Pagination Button Interactions

.pagination .role:active,
.pagination .role:focus {
  border-width: 2px;
  transform: translateY(2px);
}
.pagination .role:disabled {
  color: #ddd;
  background-color: #130f40;
}
  • .role:active, .role:focus: Adjust the button’s appearance when clicked or focused.
  • .role:disabled: Styles the disabled button state.

Number Choosing Input

.number-choosing {
  position: relative;
  border: 2px solid #333;
  border-radius: 5px;
  overflow: hidden;
  padding-right: 25px;
}
.pagination .input {
  display: block;
  height: 100%;
  padding: 5px 25px 5px 10px;
  border-radius: 5px;
  outline: none;
  border: none;
  font-size: 20px;
}
  • .number-choosing: Styles a container for choosing numbers.
  • .input: Styles the number input field.

Plus and Minus Buttons

.pagination .number-choosing .plus,
.pagination .number-choosing .minus {
  position: absolute;
  width: 25px;
  height: 25px;
  background-color: #eee;
  border: none;
  cursor: pointer;
}
.pagination .number-choosing .plus::before,
.pagination .number-choosing .minus::before {
  content: '';
  position: absolute;
  border: 5px solid;
}
  • .plus and .minus: Buttons to increment/decrement the number in the input field.
  • ::before: Adds arrow icons using borders.

Result Display

.result {
  margin-top: 20px;
  padding: 15px 50px;
  background-color: #fff;
  border-radius: 10px;
  font-size: 18px;
  border: 2px solid #eee;
}
.result .message {
  margin-bottom: 5px;
}
  • .result: Styles the area displaying results, such as a dice roll outcome.
  • .message: Adds spacing between result messages.
* {
  padding:0;
  margin: 0;
  box-sizing: border-box;
}
body {
  padding: 80px 10px 20px;
  display: flex;
  place-items: center;
  flex-direction: column;
  font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;
}
div.dice {
  perspective: 1000px;
  perspective-origin: 400px -200px;
  position: relative;
  left: 0;
  height: 200px;
  top: 100px;
}
.cube {
  position: relative;
  width: 200px;
  height: 200px;
  top: -50px;
  transform-style: preserve-3d;
  transform: rotateX(0deg) rotateZ(0deg) rotateY(0deg);
  transition: 2s all ease;
}
.cube div {
  position: absolute;
  width: 150px;
  height: 150px;
  background: linear-gradient(to top, #fff, #eee);
  border: #eee 3px ridge;
  display: grid;
  grid-template-columns: repeat(3, calc(100% / 3));
  grid-template-rows: repeat(3, calc(100% / 3));
}
.cube div > span {
  display: block;
  position: relative;
  height: 100%;
  width: 100%;
}
.cube div > span.point::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  width: 15px;
  height: 15px;
  background-color: #000;
  border-radius: 50%;
}
.one {
  transform: translateZ(50px);
}
.two {
  transform: rotateY(180deg) translateZ(100px);
}
.three{
  transform: rotateY(-270deg) translateX(100px);
  transform-origin: center right;
}
.four {
  transform: rotateY(-90deg) translateX(-100px);
  transform-origin: center left ;
}
.five{
  transform: rotateX(270deg) translateY(100px);
  transform-origin: bottom center;
}
.six {
  transform: rotateX(-270deg) translateY(-100px);
  transform-origin: top center;
}
.pagination {
  margin-top: 150px;
  display: flex;
}
.pagination .role {
  padding: 8px 20px;
  margin-right: 10px;
  border-radius: 5px;
  font-size: 30px;
  background-color: #251e72;
  border: none;
  border-bottom: 4px solid #130f40;
  color: #fff;
  cursor: pointer;
}
.pagination .role:active,
.pagination .role:focus {
  border-width: 2px;
  transform: translateY(2px);
}
.pagination .role:disabled {
  color: #ddd;
  background-color: #130f40;
}
.number-choosing {
  position: relative;
  border: 2px solid #333;
  border-radius: 5px;
  overflow: hidden;
  padding-right: 25px;
}
.pagination .input {
  display: block;
  height: 100%;
  padding: 5px 25px 5px 10px;
  border-radius: 5px;
  outline: none;
  border: none;
  font-size: 20px;
}
.pagination .number-choosing .plus,
.pagination .number-choosing .minus {
  position: absolute;
  top: 0;
  right: 0;
  width: 25px;
  height: 25px;
  background-color: #eee;
  border: none;
  cursor: pointer;
}
.pagination .number-choosing .minus {
  top: unset;
  bottom: 0;
}
.pagination .number-choosing .plus:hover,
.pagination .number-choosing .minus:hover {
  background-color: #ddd;
}
.pagination .number-choosing .plus::before {
  content: '';
  position: absolute;
  top: 40%;
  left: 50%;
  transform: translate(-50%,-50%);
  border: 5px solid;
  border-color: transparent transparent #000 ;
}
.pagination .number-choosing .minus::before {
  content: '';
  position: absolute;
  top: 60%;
  left: 50%;
  transform: translate(-50%,-50%);
  border: 5px solid;
  border-color: #000 transparent transparent ;
}
.pagination .input::-webkit-inner-spin-button{
  -webkit-appearance: none;
  appearance: none;
}
.pagination .text {
  line-height: 54px;
  font-size: 25px;
}
.result {
  margin-top: 20px;
  padding: 15px 50px;
  background-color: #fff;
  border-radius: 10px;
  font-size: 18px;
  border: 2px solid #eee;
}
.result .message {
  margin-bottom: 5px;
} 

Step 3 (JavaScript Code):

Now, let's add the JavaScript code to make the dice roll when you click the button. This code will randomly choose a number between 1 and 6 and update the dice accordingly. Here's an explanation of the code:

Element Selections

  • dice: Selects the .dice element, representing the dice object.
  • cube: Selects the .cube element, which is the main body of the dice that rotates.
  • btn: Selects the .role button, which triggers the dice roll.
  • rollVal: Selects the .input element, where the user enters or selects their predicted dice roll (1-6).
  • iVal: Selects the .plus button, used to increase the value in the input field.
  • dVal: Selects the .minus button, used to decrease the value in the input field.
  • choice: Selects the .result .choose element, which displays the user's choice and the rolling result.
  • message: Selects the .result .message element, which displays a message indicating whether the prediction was correct.

Variables

  • animationCount: Keeps track of how many times the dice has been rolled to create continuous animation effects.

Input Value Adjustment

  • Increasing Value: When the iVal button is clicked, the value in rollVal is increased by 1, but not beyond the maximum allowed value.
  • Decreasing Value: When the dVal button is clicked, the value in rollVal is decreased by 1, but not below the minimum allowed value.
  • Input Validation: Ensures that the value in rollVal stays between 1 and 6 when the user leaves the input field.

Keyboard Events

  • Enter Key: Pressing the "Enter" key triggers the roll button (btn).
  • Arrow Up/Down: The up and down arrow keys simulate clicking the iVal (increase) and dVal (decrease) buttons, respectively.

Rolling the Dice

  • Button Click: When the roll button (btn) is clicked, the gameStart() function is called.
  • Game Preparation: The gamePreparation() function disables input fields and buttons to prevent further interaction during the dice roll and clears previous messages.

Dice Roll Animation

  • Random Rotation: The dice (cube) is rotated by random degrees on the X, Y, and Z axes to simulate rolling.
  • Rotation Calculation: The rotation is determined by multiplying the animationCount by 90 degrees and adding a random rotation between 1 and 4 times 90 degrees on each axis.

Determining the Result

  • Rolling Values Matrix: A 3D array (rollingValues) is used to determine the dice result based on the final rotation angles (degX, degY, degZ).
  • Result Calculation: The dice's final value is calculated by referencing the appropriate values in the rollingValues array.

Displaying the Result

  • Timeout: After a 2-second delay (to simulate the rolling animation), the user's prediction and the actual roll result are displayed.
  • Message Display: If the user's prediction matches the dice result, a success message is shown. Otherwise, a failure message is displayed.

Post-Roll Actions

  • Re-enabling Input: Once the result is shown, the input fields and buttons are re-enabled for the next roll.
  • Animation Increment: The animationCount is incremented by 12 to ensure that the next roll has a different animation sequence.
const dice = document.querySelector(".dice"); // dice ibject
const cube = document.querySelector(".cube"); // dice body
const btn = document.querySelector(".role"); // button of rolling
const rollVal = document.querySelector(".input"); // input of prediected number
const iVal = document.querySelector(".plus"); // button of increasing value in input
const dVal = document.querySelector(".minus"); // button of decreasing value in input
const choice = document.querySelector(".result .choose"); // the message of details about the choice and result
const message = document.querySelector(".result .message"); // message of prediction

// variable used
let animationCount = 12;


// increasing value of input field on clicking
iVal.onclick = function() {
  if (rollVal.value < parseInt(rollVal.getAttribute("max")))
    rollVal.value++;
}
dVal.onclick = function() {
  if (rollVal.value > parseInt(rollVal.getAttribute("min")))
    rollVal.value--;
}
rollVal.onblur = function () {
  if (this.value > 6) {
    this.value = 6;
  }
  if (this.value < 1) {
    this.value = 1;
  }
}

// Events Will occuars when pressing roll
document.onkeyup = function(e) {
  if (e.key === "Enter") btn.click();
  if (e.key === "ArrowUp") iVal.click();
  if (e.key === "ArrowDown") dVal.click();
}
btn.addEventListener('click', function() {
  gameStart();
});


function gamePreparation() {
  rollVal.setAttribute("disabled", "disabled");
  btn.setAttribute("disabled", "disabled");
  iVal.setAttribute("disabled", "disabled");
  dVal.setAttribute("disabled", "disabled");
  choice.innerHTML = "";
  message.innerHTML = "";
}
function gameStart() {

  gamePreparation();

  // making random numbers in rotational directions
  let randDegX = Math.trunc(Math.random() * 4 + 1);
  let randDegY = Math.trunc(Math.random() * 4 + 1);
  let randDegZ = Math.trunc(Math.random() * 4 + 1);
  cube.style = `transform: rotateX(${animationCount * 90 + randDegX * 90}deg) rotateY(${animationCount * 90 + randDegY * 90}deg) rotateZ(${animationCount * 90 + randDegZ * 90}deg);`;

  // All Values predicted to get
  let rollingValues = [
    [
      [3, 6, 4, 5],
      [3, 6, 4, 5],
      [3, 6, 4, 5],
      [3, 6, 4, 5]
    ],
    [
      [6, 4, 5, 3],
      [1, 1, 1, 1],
      [5, 3, 6, 4],
      [2, 2, 2, 2]
    ],
    [
      [4, 5, 3, 6],
      [4, 5, 3, 6],
      [4, 5, 3, 6],
      [4, 5, 3, 6]
    ],
    [
      [5, 3, 6, 4],
      [2, 2, 2, 2],
      [6, 4, 5, 3],
      [1, 1, 1, 1]
    ],
  ];

  // Getting the real value
  let degX = ((randDegX * 90) / 90) - 1;
  let degY = ((randDegY * 90) / 90) - 1;
  let degZ = ((randDegZ * 90) / 90) - 1;
  let rollingResult = rollingValues[degX][degY][degZ];
  console.log(rollingResult);


  // Events after finition rolling animation
  setTimeout(() => {
    document.querySelector(".result .choose").innerHTML = `Your Choice: ${rollVal.value} -- Rolling Value is: ${rollingResult}`;
    if (rollingResult === +rollVal.value ) {
      document.querySelector(".result .message").innerHTML = `Fantastic you predicted right 😎`;
    } else {
      document.querySelector(".result .message").innerHTML = `Opps! you predicted Wrong 😥`;
    }
    rollVal.removeAttribute("disabled");
    btn.removeAttribute("disabled");
    iVal.removeAttribute("disabled");
    dVal.removeAttribute("disabled");
  }, 2000);

  // increment the rolling for the next press
  animationCount += 12;

}

Final Output:

create-dice-rolling-game-using-html-css-and-javascript.gif

Conclusion:

Congratulations! You’ve successfully created a dice rolling game using HTML, CSS, and JavaScript. This project not only helped you practice your coding skills but also taught you how to combine these technologies to create a fun and interactive game.

Keep experimenting with the code to add more features or improve the game’s appearance. The more you practice, the better you’ll become at web development. Share your game with friends and show off your skills!

Remember, building small projects like this one is a great way to solidify your understanding of HTML, CSS, and JavaScript.

Code by: Ahmed

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺