Free video project · Beginner
How long does Snakes and Ladders last? 🐍
Python plays 10,000 games of Snakes and Ladders to find the average game, the quickest, the longest and how often it is over in 20 rolls.
The video is out Tuesday 8 December at 6pm.
The code from the video
# How long does a game of Snakes and Ladders last?
import random
random.seed(7)
JUMPS = {1: 38, 4: 14, 9: 31, 21: 42, 28: 84, 36: 44, 51: 67, 71: 91, 80: 100,
16: 6, 47: 26, 49: 11, 56: 53, 62: 19, 64: 60, 87: 24, 93: 73, 95: 75, 98: 78}
def play():
square = 0
rolls = 0
while square < 100:
roll = random.randint(1, 6)
rolls += 1
if square + roll <= 100:
square += roll
square = JUMPS.get(square, square)
return rolls
games = []
for _ in range(10000):
games.append(play())
print("Average:", round(sum(games) / len(games), 1), "rolls")
print("Quickest:", min(games), "rolls")
print("Longest:", max(games), "rolls")
quick = 0
for g in games:
if g <= 20:
quick += 1
print(f"Over in 20 rolls or fewer: {quick / len(games):.0%}")
Run it in your browser with nothing to install, right here on this page.
Make it your own
- Add the rule that you must land exactly on 100 and see how much longer games get.
- Play with two players and find how often the first player wins.
- Find which snake is landed on most often.
Skills: dictionaries, while loops, random, functions