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:
How to create interactive web applications
The power of JavaScript for gaming
Working with user input and random numbers
Creating animations and visual feedback
Building a program people actually want to use!
🎲 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 RollerimportrandomimportreimportjsonfromtypingimportDict, ListclassDiceRoller:
"""A complete Python dice roller with advanced features"""def__init__(self):
self.history = []
defparse_dice_notation(self, notation: str) -> Dict:
"""Parse dice notation like '3d6+5' into components"""match = re.match(r'(\d+)d(\d+)([+-]\d+)?', notation)
ifmatch:
return {
'dice_count': int(match.group(1)),
'sides': int(match.group(2)),
'modifier': int(match.group(3) or'0')
}
raiseValueError(f"Invalid dice notation: {notation}")
defroll_single_die(self, sides: int = 6) -> int:
"""Roll one die"""returnrandom.randint(1, sides)
defroll_dice(self, notation: str) -> Dict:
"""Roll dice according to notation and return detailed results"""parsed = self.parse_dice_notation(notation)
rolls = []
for_inrange(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)
returnresultdefget_history(self, limit: int = 10) -> List[Dict]:
"""Get recent roll history"""returnself.history[-limit:]
defsave_to_file(self, filename: str = 'dice_rolls.json'):
"""Save roll history to file"""withopen(filename, 'w') asf:
json.dump(self.history, f, indent=2)
defget_statistics(self) -> Dict:
"""Calculate statistics from roll history"""ifnotself.history:
return {'total_rolls': 0}
all_rolls = [roll['total'] for roll inself.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 executionif __name__ == "__main__":
roller = DiceRoller()
test_rolls = ["2d6", "3d6+2", "1d20", "4d4-1"]
forrollintest_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 --><divclass="dice-container"><divclass="dice">1</div><divclass="dice">1</div><divclass="dice">1</div></div><!-- Input field and button --><inputtype="text"placeholder="e.g., 3d6+5"><buttononclick="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.5sease-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 rollerimportrandomimportreimportjsonfromtypingimportDict, List# Advanced parsing with regular expressionsdefparse_dice_notation(notation: str) -> Dict:
"""Parse dice notation like '3d6+5' into components"""match = re.match(r'(\d+)d(\d+)([+-]\d+)?', notation)
ifmatch:
return {
'dice_count': int(match.group(1)),
'sides': int(match.group(2)),
'modifier': int(match.group(3) or'0')
}
raiseValueError(f"Invalid dice notation: {notation}")
# Object-oriented programmingclassDiceRoller:
defroll_dice(self, notation: str) -> Dict:
"""Main rolling method with detailed results"""parsed = self.parse_dice_notation(notation)
rolls = [random.randint(1, parsed['sides'])
for _ inrange(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:
Add different dice types: Support d4, d8, d10, d12, d20
Add a history: Keep track of the last 10 rolls
File output: Save roll results to a text file
Statistics: Calculate average rolls and totals
GUI version: Use tkinter for a graphical interface