Build a Dice Roll Simulator using HTML CSS and JavaScript
Tags: javascript, html, css, frontend
Published: 2023-04-25 13:05:01

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6d8jbrlsgouog2pz1nut.png)



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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6rgfu0bubqin3wtyazn2.png)


![The complete dice game before being played](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/102vblda3kue8g3vklnp.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jqr1jbv0mbe6frp6e9dd.png)

Then you either hit the **enter key** or **tab key**. And if you are not a VSCode user, you can go to [Emmet Documentation](https://docs.emmet.io/) 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

```HTML
<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>
```

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 <head> 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](https://utopia.fyi/type/calculator/?c=200,14,1.125,560,32,1.25,5,3,&s=0.75%7C0.5%7C0.25,1.5%7C2%7C3%7C4%7C6,s-l&g=s,l,xl,12) 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](https://img.freepik.com/free-photo/starry-night-sky_1048-11828.jpg) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/odnpl4mjk8z83jupj4da.png)


…CSS contd


![CSS styles](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tr2eob7am7isrjo5azzb.png)


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

![The app after styling](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xly0pckcizfgdlphwss5.png)


**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 </body>

***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.querySelecto`r, and `document.querySelectorAll`. (I prefer using document.querySelector).


![JavaScript selectors](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6tgtutyce5c5ccomo62v.png)



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()](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vyd7rz71a885ebrk5fgr.png)


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()](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u5fw0ei2bpguyuukv2m6.png)


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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wvti0wj3cqjihw6kkww8.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/trhemr6qq54w44jgmn8x.png)


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 **&#9856;** (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.random `is 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kx76x7cwmqv9hzs4s8s2.png)

`let historyList = [];`


![declaring a variable](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7a1eavys9oiws5twim8f.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z4n8iaqkw7euyvy7r3tq.png)

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` (our` historyList.length` is 0 so it will keep looping through each time a dice is rolled and keep updating the list provided that` i` 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](https://codepen.io/obere4u/pen/YzJZgoM) 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.