🎲 Day 1: The Dice Roller

Build Your First Interactive Python Program

🎯 What You'll Learn Today

Today is all about building something awesome! You'll create a dice roller that can handle complex rolls like "3d6+5" (roll 6-sided dice 3 times, add 5). You'll learn:

🎲 Try the Python Dice Roller!

This is what you'll build with Python - fully functional and interactive:

1
1
1
Ready to roll!

🐍 Full Python Implementation

Here's the complete Python code you'll build. This is exactly what powers the demo above:

dice_roller.py - Complete Python Dice Roller import random import re import json from typing import Dict, List class DiceRoller: """A complete Python dice roller with advanced features""" def __init__(self): self.history = [] def parse_dice_notation(self, notation: str) -> Dict: """Parse dice notation like '3d6+5' into components""" match = re.match(r'(\d+)d(\d+)([+-]\d+)?', notation) if match: return { 'dice_count': int(match.group(1)), 'sides': int(match.group(2)), 'modifier': int(match.group(3) or '0') } raise ValueError(f"Invalid dice notation: {notation}") def roll_single_die(self, sides: int = 6) -> int: """Roll one die""" return random.randint(1, sides) def roll_dice(self, notation: str) -> Dict: """Roll dice according to notation and return detailed results""" parsed = self.parse_dice_notation(notation) rolls = [] for _ in range(parsed['dice_count']): rolls.append(self.roll_single_die(parsed['sides'])) total = sum(rolls) + parsed['modifier'] result = { 'notation': notation, 'rolls': rolls, 'total': total, 'modifier': parsed['modifier'] } self.history.append(result) return result def get_history(self, limit: int = 10) -> List[Dict]: """Get recent roll history""" return self.history[-limit:] def save_to_file(self, filename: str = 'dice_rolls.json'): """Save roll history to file""" with open(filename, 'w') as f: json.dump(self.history, f, indent=2) def get_statistics(self) -> Dict: """Calculate statistics from roll history""" if not self.history: return {'total_rolls': 0} all_rolls = [roll['total'] for roll in self.history] return { 'total_rolls': len(self.history), 'average_roll': sum(all_rolls) / len(all_rolls), 'highest_roll': max(all_rolls), 'lowest_roll': min(all_rolls) } # Main execution if __name__ == "__main__": roller = DiceRoller() test_rolls = ["2d6", "3d6+2", "1d20", "4d4-1"] for roll in test_rolls: result = roller.roll_dice(roll) print(f"{roll} → {result['rolls']} = {result['total']}") print(f"\nStatistics: {roller.get_statistics()}")

🔧 Step 1: Understanding the HTML Structure

Every web app starts with HTML. This defines the "bones" - what your app looks like. Here's our dice roller structure:

The HTML Layout:

<!-- Container for our dice --> <div class="dice-container"> <div class="dice">1</div> <div class="dice">1</div> <div class="dice">1</div> </div> <!-- Input field and button --> <input type="text" placeholder="e.g., 3d6+5"> <button onclick="rollDice()">Roll Dice!</button>
💡 Why HTML matters: HTML gives your app structure. Think of it like building a house - HTML is the foundation and walls. Everything else sits on top of it.

🎨 Step 2: Making It Look Cool with CSS

CSS is like the paint and furniture - it makes your app look amazing! We use CSS to:

  • Style the dice to look like real cubes
  • Add colors that make the app fun
  • Create the rolling animation
  • Make everything responsive on mobile

Key CSS Features We Used:

/* Make dice look like real cubes */ .dice { width: 60px; height: 60px; background: white; border: 3px solid #667eea; border-radius: 10px; display: flex; align-items: center; justify-content: center; } /* Make dice rotate when rolling */ .rolling { animation: roll 0.5s ease-in-out; }

⚡ Step 3: Making It Interactive with Python

This is where the magic happens! Python is the "brains" - it handles the logic. Our complete dice roller uses modern Python features:

Key Python Features You'll Learn:

# Modern Python concepts in our dice roller import random import re import json from typing import Dict, List # Advanced parsing with regular expressions def parse_dice_notation(notation: str) -> Dict: """Parse dice notation like '3d6+5' into components""" match = re.match(r'(\d+)d(\d+)([+-]\d+)?', notation) if match: return { 'dice_count': int(match.group(1)), 'sides': int(match.group(2)), 'modifier': int(match.group(3) or '0') } raise ValueError(f"Invalid dice notation: {notation}") # Object-oriented programming class DiceRoller: def roll_dice(self, notation: str) -> Dict: """Main rolling method with detailed results""" parsed = self.parse_dice_notation(notation) rolls = [random.randint(1, parsed['sides']) for _ in range(parsed['dice_count'])] total = sum(rolls) + parsed['modifier'] return {'rolls': rolls, 'total': total}
🎯 Key Python concepts: You're learning functions, variables, lists, loops, and random number generation - the building blocks of all Python applications!

🏋️ Challenge: Enhance Your Dice Roller

Try adding these features to make your program even cooler:

  1. Add different dice types: Support d4, d8, d10, d12, d20
  2. Add a history: Keep track of the last 10 rolls
  3. File output: Save roll results to a text file
  4. Statistics: Calculate average rolls and totals
  5. GUI version: Use tkinter for a graphical interface
# Example: Add d20 support def get_dice_type(sides): if sides == 20: return "d20" elif sides == 12: return "d12" return f"d{side}"

🛠️ Step-by-Step Building Guide

Follow these steps to build your own Python dice roller:

Step 1: Set Up Your Project

# Create dice_roller.py import random import re import json from typing import Dict, List __author__ = "Your Name" __version__ = "1.0.0" print("🎲 Python Dice Roller v1.0")

Step 2: Create the Dice Roller Class

class DiceRoller: """A complete Python dice roller""" def __init__(self): self.history = [] print("Dice roller initialized!") def parse_dice_notation(self, notation): match = re.match(r'(\d+)d(\d+)([+-]\d+)?', notation) if match: return { 'dice_count': int(match.group(1)), 'sides': int(match.group(2)), 'modifier': int(match.group(3) or '0') } raise ValueError(f"Invalid notation: {notation}")

Step 3: Add Rolling Logic

def roll_dice(self, notation): """Roll dice and return detailed results""" parsed = self.parse_dice_notation(notation) rolls = [] # Roll the dice for _ in range(parsed['dice_count']): rolls.append(random.randint(1, parsed['sides'])) total = sum(rolls) + parsed['modifier'] result = { 'rolls': rolls, 'total': total, 'notation': notation } self.history.append(result) return result

Step 4: Create the Main Function

def main(): roller = DiceRoller() while True: user_input = input("Enter dice notation (or 'quit'): ") if user_input.lower() == 'quit': break try: result = roller.roll_dice(user_input) print(f"Rolled: {result['rolls']} = {result['total']}") except ValueError as e: print(f"Error: {e}") if __name__ == "__main__": main()

✅ Key Takeaways

  • You built your first complete Python program with real functionality!
  • Python's clean syntax makes complex logic easy to read and understand
  • Object-oriented programming organizes your code into reusable components
  • Regular expressions let you parse complex text patterns like "3d6+5"
  • Error handling makes your program robust and user-friendly
  • This same foundation powers websites, apps, games, and data analysis!
🚀 Next level: Add a web interface using Flask or Django, or create a GUI version with Tkinter!

🎉 Ready for Day 2?

Tomorrow you'll build a Fortune Teller that uses conditionals to create magical responses!

Marking complete will unlock Day 2!