Build a Dice Rolling Game

Learn to create random numbers and build an interactive dice game!

What You'll Learn

  • ✅ Generate random numbers with Math.random()
  • ✅ Round numbers with Math.floor()
  • ✅ Create interactive buttons
  • ✅ Update the DOM dynamically
  • ✅ Add visual effects and animations
  • ✅ Build a two-dice game with scoring

Understanding Random Numbers - The Foundation of Games

🎲 Why Randomness Matters in Programming

Random numbers power countless applications:

  • 🎮 Video games - enemy spawn locations, loot drops, critical hits
  • 🎰 Casino games - slot machines, card shuffling, roulette wheels
  • 📊 Data science - random sampling, simulations, A/B testing
  • 🔒 Security - password generation, encryption keys
  • 🎯 Games - dice rolls, coin flips, random events

In this lesson, we'll master random number generation by building a dice game!

🔢 How Computers Generate Random Numbers

Here's the truth: Computers can't actually generate TRULY random numbers!

Why not?

  • Computers follow algorithms (step-by-step instructions)
  • Algorithms are deterministic (same input → same output)
  • True randomness requires unpredictable physical processes

What do they do instead?

They use pseudorandom number generators (PRNGs):

  • Start with a "seed" value (often current time in milliseconds)
  • Apply complex mathematical formulas
  • Produce numbers that APPEAR random
  • For games and most apps, this is perfect!

JavaScript's Math.random() is a PRNG that's plenty random for our dice game!

📐 Understanding Math.random() - The Core Function

JavaScript's Math.random() generates a random decimal between 0 (inclusive) and 1 (exclusive).

What does \"0 inclusive, 1 exclusive\" mean?

  • Inclusive: Can include 0 → 0.000000 is possible
  • Exclusive: Never reaches 1 → 0.999999 is closest it gets
  • So you get: 0 ≤ random < 1

Example outputs:

Math.random()  →  0.1234567
Math.random()  →  0.8765432
Math.random()  →  0.0000123
Math.random()  →  0.9999876
Math.random()  →  0.5555555

Each time you call it, you get a different number!

🎯 Converting Random Decimals to Dice Numbers (1-6)

The problem: Math.random() gives us decimals, but we need whole numbers 1 through 6!

The solution - 4 steps:

Math.floor(Math.random() * 6) + 1

Let's break this down step-by-step:

Step 1: Math.random()

  • Generates: 0.0 to 0.999...
  • Example: 0.7382

Step 2: Multiply by 6

  • Formula: Math.random() * 6
  • Generates: 0.0 to 5.999...
  • Example: 0.7382 * 6 = 4.4292

Step 3: Math.floor() - Round DOWN

  • Formula: Math.floor(Math.random() * 6)
  • Generates: 0, 1, 2, 3, 4, or 5
  • Example: Math.floor(4.4292) = 4
  • Why floor? It rounds DOWN to nearest integer

Step 4: Add 1

  • Formula: Math.floor(Math.random() * 6) + 1
  • Generates: 1, 2, 3, 4, 5, or 6
  • Example: 4 + 1 = 5
  • Why +1? Shifts range from 0-5 to 1-6!

Visual breakdown:

0.000 - 0.166  →  0  →  1
0.167 - 0.333  →  1  →  2
0.334 - 0.500  →  2  →  3
0.501 - 0.667  →  3  →  4
0.668 - 0.834  →  4  →  5
0.835 - 0.999  →  5  →  6

🧮 Understanding Math.floor() vs Math.ceil() vs Math.round()

JavaScript has three rounding functions:

Math.floor() - Always rounds DOWN

Math.floor(4.1) = 4
Math.floor(4.5) = 4
Math.floor(4.9) = 4

Think: Floor is the ground, go DOWN to reach it!

Math.ceil() - Always rounds UP

Math.ceil(4.1) = 5
Math.ceil(4.5) = 5
Math.ceil(4.9) = 5

Think: Ceiling is above, go UP to reach it!

Math.round() - Rounds to NEAREST

Math.round(4.1) = 4
Math.round(4.5) = 5
Math.round(4.9) = 5

Think: Standard rounding - .5 and above goes up!

⚠️ Why we use floor() for dice:

  • We need consistent distribution across all numbers
  • floor() gives us exactly 0-5, then we add 1
  • round() would give uneven distribution!

🎨 Making Dice Visual with CSS and HTML

A dice display needs:

  • Container: A div to hold the dice
  • Dice Box: A square element showing the number
  • Text Display: Shows messages like "You rolled a 6!"

CSS properties for a good dice:

width: 120px;           // Square size
height: 120px;
font-size: 80px;        // Big number
font-weight: bold;
display: flex;          // Center the number
align-items: center;    // Vertically
justify-content: center; // Horizontally
border-radius: 20px;    // Rounded corners
box-shadow: ...;        // 3D depth effect

⚡ Understanding setInterval() for Animations

How do we create a rolling animation effect?

Use setInterval() to repeatedly run code at timed intervals!

Basic syntax:

setInterval(function() {\n    // This code runs repeatedly\n}, 100); // Every 100 milliseconds

For a dice rolling animation:

  1. Start the interval when button is clicked
  2. Every 100ms, show a new random number
  3. After 10-15 cycles, stop the interval
  4. Show the final result

Why this creates excitement:

  • Numbers flash by quickly (like a real dice tumbling!)
  • Builds anticipation - "What will it land on?"
  • Feels more interactive than instant results

Stopping the interval:

const interval = setInterval(/* ... */);\n\n// Later, to stop:\nclearInterval(interval);

🎯 Building a Two-Dice Game - Game Logic

What makes the two-dice game interesting?

  • Roll TWO dice simultaneously
  • Calculate the total
  • Show special messages for special rolls!

Special roll messages:

  • Doubles: Both dice show same number (ex: two 4s)
  • Lucky 7: Total equals 7 (most common total!)
  • Snake Eyes: Both dice show 1 (total = 2, worst roll)
  • Boxcars: Both dice show 6 (total = 12, best roll)

Implementation with if statements:

if (dice1 === dice2) {\n    message = \"DOUBLES!\";\n} else if (total === 7) {\n    message = \"LUCKY 7!\";\n} else if (total === 12) {\n    message = \"BOXCARS!\";\n}

🎯 Interactive Exercises - Build Your Dice Game!

🎲 What You'll Build

Progress through 5 exercises to create a complete dice game:

  1. Exercise 1: Master the random dice number formula
  2. Exercise 2: Display the dice result with HTML/CSS
  3. Exercise 3: Make it interactive with a Roll button
  4. Exercise 4: Add exciting rolling animations
  5. Exercise 5: Build a two-dice game with special scoring!

💡 This lesson teaches random numbers - a concept you'll use in EVERY game you build!

Exercise 1: Generate a Random Dice Number
Not Started

Goal: Create a function that returns a random number from 1 to 6.

Use Math.random() and Math.floor() to generate the dice roll.

Hint: The formula is Math.floor(Math.random() * 6) + 1. This ensures you get whole numbers from 1 to 6. Test it multiple times to see different results!
Click "Run Code" to see random dice rolls!
Exercise 2: Display the Dice Result
Locked 🔒

Goal: Show the dice result on the screen with nice formatting.

Create HTML to display the rolled number in a styled dice box.

Hint: Use document.getElementById().textContent to update the display. The dice box should show the number, and result text should say "You rolled a X!"
Complete Exercise 1 to unlock...
Exercise 3: Add a Roll Button
Locked 🔒

Goal: Add a button that rolls the dice when clicked.

Create a button with an onclick event that triggers the roll function.

.dice-box { width: 120px; height: 120px; margin: 0 auto 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; font-size: 80px; font-weight: bold; display: flex; align-items: center; justify-content: center; border-radius: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.3); transition: all 0.3s; } #result3 { font-size: 24px; color: #667eea; font-weight: bold; margin-bottom: 20px; } .roll-btn { padding: 15px 40px; font-size: 20px; font-weight: bold; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; border-radius: 50px; cursor: pointer; box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4); transition: all 0.3s; } .roll-btn:hover { transform: translateY(-3px); box-shadow: 0 7px 20px rgba(102, 126, 234, 0.6); }
Hint: Add special styling when the player rolls a 6 (the highest number) to make it exciting! Use an if statement to check the roll value.
Complete Exercise 2 to unlock...
Exercise 4: Add Dice Animation
Locked 🔒

Goal: Make the dice spin when rolling for a more realistic effect!

Add CSS animations and JavaScript timing to create a rolling animation.

font-weight: bold; display: flex; align-items: center; justify-content: center; border-radius: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.3); transition: all 0.3s; } .dice-box.rolling { animation: spin 0.1s infinite; } @keyframes spin { 0% { transform: rotate(0deg); } 50% { transform: rotate(180deg); } 100% { transform: rotate(360deg); } } #result4 { font-size: 24px; color: #667eea; font-weight: bold; margin-bottom: 20px; } .roll-btn { padding: 15px 40px; font-size: 20px; font-weight: bold; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; border-radius: 50px; cursor: pointer; box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4); transition: all 0.3s; } .roll-btn:hover { transform: translateY(-3px); box-shadow: 0 7px 20px rgba(102, 126, 234, 0.6); } .roll-btn:disabled { opacity: 0.6; cursor: not-allowed; }
Hint: Use setInterval() to rapidly change the dice number, then clearInterval() to stop after a few cycles. Disable the button during animation to prevent spam clicking!
Complete Exercise 3 to unlock...
Exercise 5: Two Dice Game!
Locked 🔒

Final Challenge: Create a game with two dice that shows the total score!

Roll both dice together and display the sum with special messages for doubles and lucky 7s!

Hint: Special combinations to check:
Complete Exercise 4 to unlock...