Mini Project: Snakes and Ladders
Snakes and Ladders is pure chance: no decisions, just dice. That makes it a perfect absorbing Markov chain. In this project you build the chain for a small board, compute the expected game length exactly with the fundamental matrix, find the full distribution of the game length, check everything by simulation with a CLT error bar, and finally work out how much the first player's head start is worth.
What we are building:
| Step | Question | Concepts |
|---|---|---|
| 1. The board as a chain | What is the transition matrix? | states, transition probabilities, absorbing state |
| 2. Expected game length | How many turns on average? | fundamental matrix, expected visits |
| 3. Length distribution | How likely is a short or a long game? | , CDF, median, tail |
| 4. Simulation | Does a simulation agree? | Monte Carlo, CLT confidence interval |
| 5. Two players | Does moving first help? | independence, sums over joint outcomes |
Note: Each step is a complete program (the playground does not share variables between runs), so the board and helpers are repeated where needed.
The board has squares 1 to 36 and a start square 0 off the board. Each turn, roll a die and move forward; landing at the foot of a ladder climbs it, landing on a snake's head slides down. A roll that would overshoot 36 is wasted (you stay put). The game ends on reaching exactly 36.
| Ladders | Snakes |
|---|---|
| 3 to 16, 5 to 7, 15 to 25, 18 to 20, 21 to 32 | 12 to 2, 14 to 11, 17 to 4, 31 to 19, 35 to 22 |
Step 1: The board as a chain
States are the squares a player can rest on: 0 and every square that is not the bottom of a ladder or the head of a snake. From each state, each die face has probability ; the destination is the square after following any ladder or snake. Square 36 is absorbing.
import numpy as np
JUMPS = {3: 16, 5: 7, 15: 25, 18: 20, 21: 32, # ladders
12: 2, 14: 11, 17: 4, 31: 19, 35: 22} # snakes
END = 36
def build_chain():
P = np.zeros((END + 1, END + 1))
for s in range(END + 1):
if s == END:
P[s, s] = 1.0
continue
for roll in range(1, 7):
t = s + roll
if t > END:
t = s # overshoot: stay put
t = JUMPS.get(t, t)
P[s, t] += 1 / 6
return P
P = build_chain()
resting = [s for s in range(END + 1) if s not in JUMPS]
print("states a player can rest on:", len(resting))
print("rows sum to 1:", np.allclose(P.sum(axis=1), 1))
print("from start square 0:", {t: round(float(P[0, t]), 3) for t in range(END + 1) if P[0, t] > 0})
print("from square 33:", {t: round(float(P[33, t]), 3) for t in range(END + 1) if P[33, t] > 0})states a player can rest on: 27
rows sum to 1: True
from start square 0: {1: 0.167, 2: 0.167, 4: 0.167, 6: 0.167, 7: 0.167, 16: 0.167}
from square 33: {22: 0.167, 33: 0.5, 34: 0.167, 36: 0.167}
The matrix keeps rows for the jump squares too (they are never visited, so they do no harm). From square 33, rolls of 4, 5 and 6 overshoot and leave the player in place, so it stays with probability .
Step 2: Expected game length
With the transient states and the absorbing state 36, the fundamental matrix gives the expected number of visits to each square, and its row sums give the expected number of turns until the game ends.
import numpy as np
JUMPS = {3: 16, 5: 7, 15: 25, 18: 20, 21: 32, 12: 2, 14: 11, 17: 4, 31: 19, 35: 22}
END = 36
def build_chain():
P = np.zeros((END + 1, END + 1))
for s in range(END + 1):
if s == END:
P[s, s] = 1.0
continue
for roll in range(1, 7):
t = s + roll
t = s if t > END else t
P[s, JUMPS.get(t, t)] += 1 / 6
return P
P = build_chain()
Q = P[:END, :END]
N = np.linalg.inv(np.eye(END) - Q)
turns = N.sum(axis=1)
print("expected turns from the start:", round(turns[0], 3))
visits = N[0]
top = np.argsort(-visits)[:5]
print("most visited squares (expected visits per game):", [(int(s), round(float(visits[s]), 3)) for s in top])
print("expected turns from square 30:", round(turns[30], 3), " from 34:", round(turns[34], 3))expected turns from the start: 20.374
most visited squares (expected visits per game): [(34, 2.492), (22, 1.441), (33, 1.416), (32, 1.37), (0, 1.0)]
expected turns from square 30: 10.809 from 34: 10.115
The start square is visited exactly once. The squares near the end are visited often because overshooting wastes turns there: the last few squares are the slowest part of the game.
Step 3: The distribution of the game length
The expected value hides how variable the game is. Starting from , the probability of having finished by turn is the last entry of , the CDF of the game length . From it we read the median, the most likely length and the tail.
import numpy as np
JUMPS = {3: 16, 5: 7, 15: 25, 18: 20, 21: 32, 12: 2, 14: 11, 17: 4, 31: 19, 35: 22}
END = 36
def build_chain():
P = np.zeros((END + 1, END + 1))
for s in range(END + 1):
if s == END:
P[s, s] = 1.0
continue
for roll in range(1, 7):
t = s + roll
t = s if t > END else t
P[s, JUMPS.get(t, t)] += 1 / 6
return P
P = build_chain()
u = np.zeros(END + 1)
u[0] = 1.0
cdf = []
for n in range(1, 301):
u = u @ P
cdf.append(u[END])
cdf = np.array(cdf)
pmf = np.diff(np.concatenate([[0.0], cdf]))
print("shortest possible game:", int(np.argmax(pmf > 0)) + 1, "turns, probability", round(float(pmf[pmf > 0][0]), 5))
print("most likely length:", int(np.argmax(pmf)) + 1, "turns")
print("median length:", int(np.argmax(cdf >= 0.5)) + 1, "turns")
for n in [10, 20, 30, 50]:
print(f"P(game lasts more than {n} turns) = {1 - cdf[n - 1]:.4f}")
print("mean from the distribution:", round(float(np.sum(np.arange(1, 301) * pmf)), 3))
sd = np.sqrt(np.sum(np.arange(1, 301) ** 2 * pmf) - np.sum(np.arange(1, 301) * pmf) ** 2)
print("standard deviation:", round(float(sd), 3))shortest possible game: 3 turns, probability 0.00463
most likely length: 12 turns
median length: 17 turns
P(game lasts more than 10 turns) = 0.8026
P(game lasts more than 20 turns) = 0.3903
P(game lasts more than 30 turns) = 0.1677
P(game lasts more than 50 turns) = 0.0290
mean from the distribution: 20.374
standard deviation: 12.309
The mean computed from the distribution matches the fundamental-matrix answer of Step 2 (the tail beyond 300 turns is negligible). The distribution is right-skewed: the median is below the mean, and a few games drag on much longer, mostly because of the snake from 35 and the overshoot rule.
Step 4: Simulation with an error bar
A direct simulation plays many games with a seeded generator. By the CLT, the average length is approximately normal with standard error , so should cover the exact mean from Step 2.
import random
import math
JUMPS = {3: 16, 5: 7, 15: 25, 18: 20, 21: 32, 12: 2, 14: 11, 17: 4, 31: 19, 35: 22}
END = 36
def play(rng):
pos, turns = 0, 0
while pos != END:
turns += 1
t = pos + rng.randint(1, 6)
if t <= END:
pos = JUMPS.get(t, t)
return turns
rng = random.Random(2024)
games = 40_000
lengths = [play(rng) for _ in range(games)]
mean = sum(lengths) / games
sd = math.sqrt(sum((x - mean) ** 2 for x in lengths) / (games - 1))
half = 1.96 * sd / math.sqrt(games)
print(f"simulated mean length: {mean:.3f} +- {half:.3f}")
print(f"sample standard deviation: {sd:.3f}")
print("longest game:", max(lengths), "turns")
print("fraction longer than 30 turns:", round(sum(x > 30 for x in lengths) / games, 4))simulated mean length: 20.299 +- 0.121
sample standard deviation: 12.318
longest game: 119 turns
fraction longer than 30 turns: 0.1654
Compare the interval with the exact mean from Step 2 and the tail probability with Step 3.
Step 5: Does moving first help?
Two players take turns, and the first to reach 36 wins. Their game lengths , are independent with the distribution from Step 3. Player 1 wins if (on equal lengths, player 1 gets there first), so
import numpy as np
JUMPS = {3: 16, 5: 7, 15: 25, 18: 20, 21: 32, 12: 2, 14: 11, 17: 4, 31: 19, 35: 22}
END = 36
def build_chain():
P = np.zeros((END + 1, END + 1))
for s in range(END + 1):
if s == END:
P[s, s] = 1.0
continue
for roll in range(1, 7):
t = s + roll
t = s if t > END else t
P[s, JUMPS.get(t, t)] += 1 / 6
return P
def length_pmf(P, nmax=400):
u = np.zeros(END + 1)
u[0] = 1.0
cdf = []
for _ in range(nmax):
u = u @ P
cdf.append(u[END])
return np.diff(np.concatenate([[0.0], cdf]))
pmf = length_pmf(build_chain())
at_least = 1 - np.concatenate([[0.0], np.cumsum(pmf)[:-1]]) # P(T >= n) for n = 1, 2, ...
p1 = float(np.sum(pmf * at_least))
print(f"P(first player wins) = {p1:.4f}")
print(f"P(second player wins) = {1 - p1:.4f}")
import random
rng = random.Random(5)
def play():
pos, turns = 0, 0
while pos != END:
turns += 1
t = pos + rng.randint(1, 6)
if t <= END:
pos = JUMPS.get(t, t)
return turns
games = 30_000
wins = sum(play() <= play() for _ in range(games))
print("simulated:", round(wins / games, 4))P(first player wins) = 0.5151
P(second player wins) = 0.4849
simulated: 0.5137
Moving first is a real but modest advantage. (In the simulation the first call to play() is player 1; the comparison <= gives ties to player 1, matching the formula.)
Ideas to extend it
- Change the overshoot rule to "bounce back" (land on ) and see how the expected length changes.
- Search for the single ladder that, added to the board, shortens the expected game the most (recompute for every candidate).
- Compute the expected number of times a player slides down each snake, using the visit counts in .
- Use the spectral gap idea: the tail decays like , where is the largest eigenvalue of . Check it against Step 3.
Test yourself
In the Snakes and Ladders chain, what does a row sum of the fundamental matrix give?
- The probability of winning
- The expected number of turns until the game ends from that square
- The number of snakes
- The variance of the game length
How do you get the probability that the game has ended by turn ?
- The last entry of with concentrated on the start square
- The trace of
- The row sum of for square 36
Why is the game length distribution right-skewed?
- Dice are biased
- Snakes and the overshoot rule occasionally make games much longer, while there is a hard minimum length
- Because of the CLT
- It is symmetric