DEV Community

Cover image for Build a Dice Roll Simulator using HTML CSS and JavaScript
Nwosa Tochukwu
Nwosa Tochukwu

Posted on

Build a Dice Roll Simulator using HTML CSS and JavaScript

This is an article that will take us through the steps of building a single-player dice game from scratch using HTML CSS and JavaScript

By the end of the article, we would have built a fun game (though it's only a single-player, we can improve it by making it a player vs computer later).

Dice yet to be rolled

At the beginning before a dice is thrown, it will keep the record like what is above, and after the dice is thrown, it will update the record as shown below, here we have 2 dice rolled histories

Already rolled dice

The complete dice game before being played

Now let's begin……..

As we know that HTML is used for webpage layout and structure (markup, or you can call it the skeleton that has no life in it), CSS is used to beautify our webpage to look appealing to the users (we can say it’s our flesh, clothes, makeups, etc). At the same time, JavaScript makes our webpage interactive so that the user performs multiple actions on it ( do remember you MR NIGER D from our elementary school?, we can say that JavaScript is the human version of it… hahaha)... Having those in mind, let’s start building our app.

First, we create our markup using HTML.
You will first and foremost create a folder and name it anything you like, open the folder in your favorite code editor and create a file and name it index.html
**(N.B) If you are a VSCode user (that’s my favorite ) you have Emmet preinstalled for you, it allows us to use various shortcuts like getting the boilerplate of HTM5, you can just press shift + ! (! is at the top of your number 1 on your keyboard), once your press it, you will see something like this

HTML boilerplate

Then you either hit the enter key or tab key. And if you are not a VSCode user, you can go to Emmet Documentation to read on how to install it in your code editor, it does come in handy.
**
Now that we have gotten our boilerplate, we will need to add some HTML elements and rename our title to reflect the app we are building.

Now we will go ahead with the rest of the HTML code which is



<body>
    <h1>Dice Roll Simulator</h1>
    <div class="container">
        <div id="dice" class="dice">&#9860;</div>
        <!-- dice face 5 unicode &#9860; -->
        <button id="roll" type="submit">Roll Dice</button>


        <ul class="dice-history">
           <!-- dynamically gotten from JavaScript -->
           <li>Roll 1:<span>&#9860;</span></li>
           <li>Roll 2:<span>&#9860;</Roll></li>
        </ul>
    </div>

</body>


Enter fullscreen mode Exit fullscreen mode

The Unicode is gotten from this website HTML Symbols - Unicode symbols, entities, and codes

After we are done with the HTML, it’s now time to style our webpage to make it look nice.
First, we will create a file and name it sytle.css and add it to our HTML using the link tag that will be in the

tag of our HTML. Emmet allows us to type only link:css and it will complete the linking (its default CSS file name is style.css, you can rename it to your preferred filename).
After that, we will style our body tag, h1, the div with a class attribute of ‘container’, our button, and the list (li).
Styling them will make us have something like what we have below.

The custom font size can be gotten from Utopia fyi chose the font size you want for both bigger and smaller screens, it will generate the clamp code for you, copy and paste it as I did.

The background image is taken from starr-night-sky but you use any background of your choice.

In the @keyframe, you can use any value for the rotation. Why we did not use transition is because it doesn’t allow infinite animation and we have more control over the animation using the @keyframe and animation properties

CSS styles

…CSS contd

CSS styles

Once everything is done, we should have something like this below

The app after styling

Now it’s time for our JavaScript

We will create a file and name it index.js you can still name it anything you want. We will then add the script file at the very last of the body tag just right above the closing body tag

**VSCode users, type scrip:src and hit enter (same Emmet shortcut)*

In our index.js
We will need to get the following

  • The dice
  • The button
  • The button
  • The list (li for history updating)

Now we start with the first element and import it into JavaScript, we can some selectors such as getElemnetByID, getElementByClassName, document.querySelector, and document.querySelectorAll. (I prefer using document.querySelector).

JavaScript selectors

What we are doing there is getting the HTML elements and assigning them to a const variable in JavaScript so that we can manipulate them.

Since we have a button, we need to addEventListener() to it so that it can perform the function we want from it.

addEventListener()

This is the event listener that we added, now event

  • listeners take two parameters(orders)
  • The type of command we want

The function we want to perform when that command happens.
We are telling it that we need a click command and when it is clicked, we are telling it to perform diceRoll (remember that we are telling it the function we want it to perform and functions have (), but in writing the functions in an event listener like that, we do not need to include the () but there are other ways to write and include () at end of the function) so that when we click on the Button, the dice will be rolled. But now, our dice don’t roll, and remember that we created an animation in our CSS, it’s time to add it to our dice so that we can see its effects.

diceRoll()

When you look at the code, you will that we set the timeout to 1000 which is equal to 1ms. We are telling the function to remove the animation after every 1 ms. This will allow us to roll the dice again and again and again.
Now we want the dice to always display a different face (number) each time we roll it. That is why we have rollDice() function after the remove animation. We are basically saying, after every 1 ms, remove the animation and show a new face (rollDice()).

Now we have to set out what the function rollDice will be doing in the code below. Take a look at that and you will see we used 2 different Math functions (though I added a comment to it)

Math involved

We first of all need to get the number when the dice is rolled and we want it randomly. So we will be using Math.random()
function, when we say (Math.random() * 6 ).. what it does is get random numbers for us and it will start with 0 and ends at 5, (0 1 2 3 4 5) making six numbers but we know that our dice don’t have a 0 so we added (+ 1) to every number the Math.random() will generate. But we don’t what any random number with decimal, Math.floor() comes into play, its primary function is round the numbers to their nearest whole number leaving us without any decimal place. So we will wrap our Math.random() inside the Math.floor().

Now that we have our random number, we will store the value gotten in a variable (we called it rollResult).
But we can’t just display the number, we need it to be a symbol of dice, how do we do that?
We will use a function called getDiceFace() to get that. And now this function will take it as a parameter rollResult because we need to use the number gotten from the rollDice to update the dice face.

Our getDiceFace(rollResult) will look like this

Dice face function

In this getDiceFace(rollResult), we use a switch() statement which takes a parameter called rollResult. You can use an if/else if/else statement if you are comfortable with it.

In the switch(rollResult) statement, in case 1, we are saying, if rollResult is 1, it matches case 1, return (which is the Unicode for dice face 1) we do the same for all faces, and at the end, we put a default case, should incase if no of the previous cases worked (but we won’t be getting such situation due to our Math.randomis starting from 1 and ends in 6). So we will need to update the HTML code to reflect our latest rollResult.

If we should use, document.textContent or document.innerText, it will update the dice Unicode but how do we know which number it is, we need to update it to look like a dice, so we will use document.innerHTML to modify the HTML code.

Now our new dice result will take over the previous dice result shown and the code will look like this

Check the rollDice() function.

Now that everything is working perfectly, we need to get the result and update the history each time a dice is rolled.

First, we start by declaring a global variable like this, we are making it an empty array because we want it to carry some set of results.

variable declaration

let historyList = [];

declaring a variable

It doesn’t where you defined the histroyList variable, provided it is a global variable.

Now, we need to create a function that takes the rollResult and stores it in the historyList like this…

roll result

First, we are making the historyList to be empty as no dice have been rolled by using

rollHistory.innerHTML = ““

It will make our list to disappear.
Now we will loop through the historyList variable to update our historList (ourhistoryList.length is 0 so it will keep looping through each time a dice is rolled and keep updating the list provided thati is less than historyList.length)
At start i = 0
historList is 0
But once a dice is rolled, it calls the updateHistory() function in the rollDice() and update it making it 1, now the for loop will check if i is less than 1 which is true, it will update the history list by doing this
First, create an HTML element called list (li)

const listItem = document.createElement(“li”);

document.createElement() creates an HTML element and the element we want to be created will be inside the brackets wrapped with either “” double quotes or ‘’ single quotes.

Now that we have created our listItems, we need to update them and we will do so by writing some HTML code directly to it by using template literals (``), that symbol is called a backtick and it is found just right below the Tilda (~) which is above the tab key and left of number 1 key. Template literal makes us to write characters and it will be printed/displayed the same way except for codes and variables, to write a variable inside a template literal, we will use ${variableName} where variableName will be replaced by the name of the variable we want.

listItem.innerHTML = Roll ${i + 1}: <span>${getDiceFace(historyList[i])}</span>

We are simply saying, inside the li you created, write Roll + (i + 1): which Roll: 0 + 1 ( for the first iteration) and create a span element and inside the span, show the dice Face for every iteration of i.

Remember that our li is in the roll-history element and our roll-history is now rollHistory, having both in mind, we will add the newly created HTML element to it by doing this

rollHistory.appendChild(“li”);

.appendChild() attaches an element to a parent, the element to be added will be inside the brackets wrapped with either “” double quotes or ‘’ single quotes.

Congratulations, your game is ready, you can go some steps ahead and add a multi-level player, reset button and function, etc.

live site and code demo from codepn.

If you find this article helpful and you learned something from it, please like, comment, and share.

Your feedback will go a long way in helping me achieve my web development goals.

I’m Tochi, a beginner frontend web developer.
Build while having fun.

Top comments (2)

Collapse
 
ikemkrueger profile image
Ikem Krueger

The only suggestion I have is, to put the code in a GitHub repository.

Collapse
 
obere4u profile image
Nwosa Tochukwu

Thanks, I will do that