Create a Two-Player Dice Game in JavaScript Mastery in Action

I created a dice game where two players take turns, aiming to reach a score of 100. While developing this project, I dived deeper into JavaScript concepts like event listeners, functions, and the DRY (Don’t Repeat Yourself) principle. The game keeps track of both players’ scores—current and total—and alternates their turns seamlessly. It’s interactive and showcases the importance of structured JavaScript coding.

Here’s the complete code for your dice game project, integrating HTML, CSS, and JavaScript for functionality:

HTML Code:

code<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="styles.css">
<title>Pig Game</title>
</head>
<body>
<main>
<!-- Player 1 Section -->
<section class="player player--0 player--active">
<h2 class="name" id="name--0">Player 1</h2>
<p class="score" id="score--0">0</p>
<div class="current">
<p class="current-label">Current</p>
<p class="current-score" id="current--0">0</p>
</div>
</section>

<!-- Player 2 Section -->
<section class="player player--1">
<h2 class="name" id="name--1">Player 2</h2>
<p class="score" id="score--1">0</p>
<div class="current">
<p class="current-label">Current</p>
<p class="current-score" id="current--1">0</p>
</div>
</section>

<!-- Dice and Buttons -->
<img src="dice-5.png" alt="Playing dice" class="dice hidden" />
<button class="btn btn--new">🔄 New game</button>
<button class="btn btn--roll">🎲 Roll dice</button>
<button class="btn btn--hold">📥 Hold</button>
</main>
<script src="script.js"></script>
</body>
</html>

CSS Code (styles.css):

codebody {
font-family: Arial, sans-serif;
margin: 0;
background-color: #f7f7f7;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}

main {
display: flex;
flex-direction: row;
justify-content: space-between;
width: 50%;
}

.player {
flex: 1;
padding: 20px;
background-color: white;
margin: 10px;
text-align: center;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.player--active {
background-color: #d1e7dd;
}

.score {
font-size: 2rem;
margin: 10px 0;
}

.current {
margin-top: 20px;
}

button {
margin: 10px;
padding: 10px 20px;
font-size: 1rem;
border: none;
border-radius: 5px;
cursor: pointer;
}

button:hover {
background-color: #007bff;
color: white;
}

.dice {
width: 100px;
height: 100px;
display: block;
margin: 0 auto;
}

.hidden {
display: none;
}

JavaScript Code (script.js):

code'use strict';

// Selecting elements
const player0El = document.querySelector('.player--0');
const player1El = document.querySelector('.player--1');
const score0El = document.querySelector('#score--0');
const score1El = document.querySelector('#score--1');
const current0El = document.querySelector('#current--0');
const current1El = document.querySelector('#current--1');
const diceEl = document.querySelector('.dice');
const btnNew = document.querySelector('.btn--new');
const btnRoll = document.querySelector('.btn--roll');
const btnHold = document.querySelector('.btn--hold');

// Starting conditions
let scores, currentScore, activePlayer, playing;

const init = function () {
scores = [0, 0];
currentScore = 0;
activePlayer = 0;
playing = true;

score0El.textContent = 0;
score1El.textContent = 0;
current0El.textContent = 0;
current1El.textContent = 0;

diceEl.classList.add('hidden');
player0El.classList.add('player--active');
player1El.classList.remove('player--active');
player0El.classList.remove('player--winner');
player1El.classList.remove('player--winner');
};
init();

// Switching player
const switchPlayer = function () {
currentScore = 0;
document.querySelector(`#current--${activePlayer}`).textContent = 0;
activePlayer = activePlayer === 0 ? 1 : 0;
player0El.classList.toggle('player--active');
player1El.classList.toggle('player--active');
};

// Rolling dice functionality
btnRoll.addEventListener('click', function () {
if (playing) {
// 1. Generate a random dice roll
const dice = Math.trunc(Math.random() * 6) + 1;

// 2. Display dice
diceEl.classList.remove('hidden');
diceEl.src = `dice-${dice}.png`;

// 3. Check for rolled 1
if (dice !== 1) {
// Add dice to current score
currentScore += dice;
document.querySelector(
`#current--${activePlayer}`
).textContent = currentScore;
} else {
// Switch to next player
switchPlayer();
}
}
});

// Holding the score
btnHold.addEventListener('click', function () {
if (playing) {
// 1. Add current score to active player's score
scores[activePlayer] += currentScore;
document.querySelector(`#score--${activePlayer}`).textContent =
scores[activePlayer];

// 2. Check if player's score >= 100
if (scores[activePlayer] >= 100) {
// Finish the game
playing = false;
diceEl.classList.add('hidden');

document
.querySelector(`.player--${activePlayer}`)
.classList.add('player--winner');
document
.querySelector(`.player--${activePlayer}`)
.classList.remove('player--active');
} else {
// Switch to the next player
switchPlayer();
}
}
});

// Resetting the game
btnNew.addEventListener('click', init);

How It Works:

See the result output click here Run Compiler after open this file in new tab than you will click just Run button the game to the starting showing result.

Rolling the Dice:

Generates a random number (1-6).

Displays the corresponding dice image.

If it’s 1, the turn switches to the next player.

Hold Button:

Saves the current score to the total score.

Checks if the player has reached the winning score of 100.

New Game:

Key Features:

  1. Players Section:
    • Each player has a name (Player 1 and Player 2) and a score section.
    • The current class section tracks the score for the ongoing turn.
  2. Dice Display:
    • An image of the dice (dice-5.png) shows the rolled number dynamically.
  3. Game Buttons:
    • Roll Dice: Generates a random number and updates the current score.
    • Hold: Saves the current score to the total and switches the turn.
    • New Game: Resets all scores and starts fresh.

Script Explanation:

To make the game functional, I used JavaScript to handle:

  1. Event Listeners: For button clicks (Roll, Hold, and New Game).
  2. Game Logic: Determines when to switch players, update scores, and declare a winner.
  3. Dynamic Updates: Alters DOM elements (like scores and dice) dynamically.

Related blog posts