reply View all Tutorials & Projects

How to Create a Dice Roll Game using HTML CSS & JavaScript

In today's project we'll take a look at creating a dice roll game using HTML, CSS and JavaScript. This will allow you to "roll" dice in 2D, giving you a random set of dice after 1 second. This project is great for improving your CSS and JavaScript DOM skills, especially as a beginner to web development.

Video Tutorial

Source Code

You can find the source code for this video below.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>How to Create a Dice Roll with JavaScript</title>
	<link rel="stylesheet" href="main.css">
	<script src="main.js" defer></script>
</head>
<body>
	<div class="dice-container"></div>
	<button type="button" class="btn-roll-dice">Roll Dice</button>
</body>
</html>
main.css
.dice-container {
	display: flex;
}

.dice {
	width: 80px;
	height: 80px;
	position: relative;
	margin: 5px;
	border-radius: 10px;
	box-shadow: 0 0 10px rgba(0, 0, 0, 0.25);
}

.dice-dot {
	--top: 0%;
	--left: 0%;

	width: 15px;
	height: 15px;
	background-color: #000000;
	border-radius: 50%;

	/* Dot Positioning */
	position: absolute;
	top: var(--top);
	left: var(--left);
	transform: translateX(calc(var(--left) * -1)) translateY(calc(var(--top) * -1));
}

.btn-roll-dice {
	margin-top: 10px;
}
main.js
function createDice(number) {
	const dotPositionMatrix = {
		1: [
			[50, 50]
		],
		2: [
			[20, 20],
			[80, 80]
		],
		3: [
			[20, 20],
			[50, 50],
			[80, 80]
		],
		4: [
			[20, 20],
			[20, 80],
			[80, 20],
			[80, 80]
		],
		5: [
			[20, 20],
			[20, 80],
			[50, 50],
			[80, 20],
			[80, 80]
		],
		6: [
			[20, 20],
			[20, 80],
			[50, 20],
			[50, 80],
			[80, 20],
			[80, 80]
		]
	};

	const dice = document.createElement("div");

	dice.classList.add("dice");

	for (const dotPosition of dotPositionMatrix[number]) {
		const dot = document.createElement("div");

		dot.classList.add("dice-dot");
		dot.style.setProperty("--top", dotPosition[0] + "%");
		dot.style.setProperty("--left", dotPosition[1] + "%");
		dice.appendChild(dot);
	}

	return dice;
}

function randomizeDice(diceContainer, numberOfDice) {
	diceContainer.innerHTML = "";

	for (let i = 0; i < numberOfDice; i++) {
		const random = Math.floor((Math.random() * 6) + 1);
		const dice = createDice(random);

		diceContainer.appendChild(dice);
	}
}

const NUMBER_OF_DICE = 5;
const diceContainer = document.querySelector(".dice-container");
const btnRollDice = document.querySelector(".btn-roll-dice");

randomizeDice(diceContainer, NUMBER_OF_DICE);

btnRollDice.addEventListener("click", () => {
	const interval = setInterval(() => {
		randomizeDice(diceContainer, NUMBER_OF_DICE);
	}, 50);

	setTimeout(() => clearInterval(interval), 1000);
});

If you have any questions about this code, please leave a comment on the video.