There is no decision-making in snake and ladder. Nobody chooses a move; the dice decide everything. So the design question is not about players at all. It is about three things: keeping the board legal, testing code whose behaviour depends on random numbers, and making the house rules (what happens past 100, what a six earns you) swappable, because every family in India plays a slightly different version and your interviewer has one in mind too.
This is a common machine-coding round prompt: 60 to 90 minutes, working code, then questions. The version below is about 230 lines of Python or 210 of Java.
Rules to settle before writing a class
The core is not up for debate:
- A board of cells 1 to N (100 by default). Tokens start off the board, at 0.
- Snakes take you from a higher cell down to a lower one; ladders take you up. Landing on the start of either moves you to its end.
- Two or more players take turns rolling one six-sided die. First to reach cell N exactly wins, and the game stops there.
- The board is validated when it is built. A bad board is a construction error, not something you discover in the middle of a game.
Then ask about the house rules. These are the questions that show you have actually played the game:
- A roll that would go past 100? Most people play “stay where you are” (exact finish). Some play “bounce back”: on 97, a 5 takes you to 100 and back 2, to 98. Support both.
- Does a six give another roll? Usually yes. And three sixes in a row cancels the whole turn: the token goes back to where it was when the turn started. Make this a switch.
- Does a token need a six to come onto the board? Some families play that way. I leave it out by default and list it as an extension, because it is one more
ifonce the rest is clean.
Out of scope unless asked: a UI, networking, accounts, betting or coins, saving games, and ranking every player after the first finishes (that one is a follow-up below). Concurrency is not a concern inside one game; turns are sequential.
The model
Board owns its size and a single map from start cell to end cell. A ladder is a jump whose end is bigger than its start; a snake is one whose end is smaller. That is the whole difference.
I’ll argue this point, because most solutions online have Snake and Ladder classes, often both extending an abstract Jump. Look at what each class would do: hold two integers and move the token from one to the other. The only behaviour that differs is the label in a log message, and that falls out of comparing the two numbers. Two classes cost you two places to change, and a validation rule like “no snake head at the top cell” ends up written twice. One map is enough. If the interviewer pushes for separate types, offer an enum JumpKind derived from the direction, and keep one code path.
The rest:
Diceis an interface withroll()andmax_face.RandomDiewraps a random source;FixedDicereplays a scripted list of rolls. The game never knows which one it has.EndRuleanswers one question: given a position and a roll, where does the token land?ExactFinishandBounceBackimplement it.Playeris a name and a position. That is all it needs to be here.Gameowns the turn order (a deque you rotate), the six-rule bookkeeping and the winner. Eachroll()call is one roll of the die and returns aRollResultdescribing what happened.RollResultis an immutable record: who rolled, what, from where, to where, a note (snake, ladder, overshoot, cancelled turn), whether the same player goes again, and whether they won.
There is no Cell class. A hundred objects that each hold “maybe a jump” are a map with extra steps.
classDiagram
class Game {
+board: Board
+dice: Dice
+end_rule: EndRule
+six_rules: bool
+players: deque~Player~
+winner: Player | None
-sixes: int
-turn_start: int
+roll() RollResult
+play() Player
}
class Board {
+size: int
-jumps: dict~int, int~
+resolve(cell) int
+kind(start) str
}
class Player {
+name: str
+pos: int
}
class RollResult {
+player: str
+roll: int
+start: int
+end: int
+note: str
+again: bool
+won: bool
}
class Dice {
<<interface>>
+roll() int
+max_face int
}
class RandomDie
class FixedDice
class EndRule {
<<interface>>
+target(pos, roll, size) int
}
class ExactFinish
class BounceBack
Game "1" *-- "1" Board
Game "1" *-- "2..*" Player
Game --> Dice
Game --> EndRule
Game ..> RollResult : returns
Dice <|.. RandomDie
Dice <|.. FixedDice
EndRule <|.. ExactFinish
EndRule <|.. BounceBackWhere the patterns are
Strategy for the dice. This is the one that matters, and the reason is testing, not flexibility. With random.randint buried inside Game, the only way to test “three sixes cancels the turn” is to run games until it happens and hope. With an injected Dice, the test hands the game FixedDice([6, 6, 6]) and asserts the token is back where it started. The scripted game in the demo exercises a ladder, a snake, the extra roll on a six, the three-sixes rule, an overshoot and a win on an extra roll, in 20 deterministic rolls. Two loaded dice, a pair of dice summed, or a die with eight faces are all new classes with no change to Game.
Strategy for the end rule. Exact finish versus bounce back is a real disagreement between players, so it gets an interface. It is a one-method interface; in Python you could pass a plain function, and I would not argue with that.
Validation in the constructor. Board refuses to exist in a bad state: a jump starting on the last cell (a snake on 100 makes the game unwinnable), a jump that starts and ends on the same cell, an end that is off the board, or a jump that lands on the start of another jump. That last one is a design choice. Chained jumps can be allowed by resolving in a loop, but then you have to detect cycles (a snake from 40 to 12 plus a ladder from 12 to 40 loops forever), and it is simpler to say no. Say which you picked and why.
Considered and dropped:
- Separate
SnakeandLadderclasses. Argued above. - A
Builderfor the board. A board is a size and a map. A builder adds a class to save no typing. It starts paying off if boards come from config files with themes, images and per-cell rules. - Observer for game events. Tempting for “print the log” or “update the UI”.
roll()already returns aRollResult; whoever calls it can print, render or send it over a socket. Add listeners when several independent consumers need events and you do not control the loop. - Singleton dice. Two games in the same process would share one random sequence, and tests could no longer inject a script. The opposite of what the design is for.
- State pattern for the turn. The only turn state is “how many sixes so far” and “where did this turn start”. Two integers.
The code
Run on Python 3.13.5 and OpenJDK 21; both print exactly the same output, because the random die uses the same small linear congruential generator in both files rather than each language’s library. It takes the high bits of the generator’s state: with a power-of-two modulus the lowest bit simply alternates 0, 1, 0, 1, so state % 6 on the raw value would alternate odd and even faces. The files, plus an exact expected-length calculation, are in course-code/low-level-design/14/ in the course repository.
Three details worth reading closely:
_turn_startis captured on the first roll of a turn, not on every roll. On a third six the token goes back there, which can undo a ladder climbed earlier in the same turn.- An overshoot with a six still earns another roll in this code. Some people play that it does not. It is one condition to change, and a good thing to raise yourself.
- Winning ends the game immediately, even on a roll that would otherwise grant another roll.
Python
"""Snake and ladder low-level design: validated board, injectable dice, pluggable end rule, six rules.
Run: python3 snake_ladder.py
"""
from __future__ import annotations
from abc import ABC, abstractmethod
from collections import deque
from dataclasses import dataclass
class InvalidBoard(Exception):
pass
class GameOver(Exception):
pass
class Board:
"""Cells 1..size. jumps maps a start cell to an end cell: end > start is a ladder, end < start a snake."""
def __init__(self, size: int, jumps: dict[int, int]):
for start, end in jumps.items():
if not (1 <= start < size):
raise InvalidBoard(f"jump from {start}: must start between 1 and {size - 1}")
if not (1 <= end <= size) or end == start:
raise InvalidBoard(f"jump {start}->{end}: end must be another cell on the board")
if end in jumps:
raise InvalidBoard(f"jump {start}->{end} lands on the start of {end}->{jumps[end]}")
self.size, self.jumps = size, dict(jumps)
def resolve(self, cell: int) -> int:
return self.jumps.get(cell, cell)
def kind(self, start: int) -> str:
return "ladder" if self.jumps[start] > start else "snake"
class Dice(ABC):
@abstractmethod
def roll(self) -> int: ...
@property
@abstractmethod
def max_face(self) -> int: ...
class Lcg:
"""Tiny deterministic RNG so the Python and Java demos print the same games."""
def __init__(self, seed: int):
self.state = seed
def next_int(self, bound: int) -> int:
self.state = (self.state * 1103515245 + 12345) % 2**31
return (self.state >> 16) % bound # high bits: the low bits of an LCG cycle quickly
class RandomDie(Dice):
def __init__(self, rng: Lcg, faces: int = 6):
self.rng, self.faces = rng, faces
def roll(self):
return self.rng.next_int(self.faces) + 1
@property
def max_face(self):
return self.faces
class FixedDice(Dice):
"""Replays a script of rolls. This is how you unit-test a game built on randomness."""
def __init__(self, rolls, faces: int = 6):
self.rolls, self.faces = deque(rolls), faces
def roll(self):
return self.rolls.popleft()
@property
def max_face(self):
return self.faces
class EndRule(ABC):
"""What happens when a roll would carry the token past the last cell."""
@abstractmethod
def target(self, pos: int, roll: int, size: int) -> int: ...
class ExactFinish(EndRule):
def target(self, pos, roll, size):
return pos + roll if pos + roll <= size else pos # overshoot: stay put
class BounceBack(EndRule):
def target(self, pos, roll, size):
t = pos + roll
return t if t <= size else size - (t - size)
@dataclass
class Player:
name: str
pos: int = 0 # 0 = not on the board yet
@dataclass(frozen=True)
class RollResult:
player: str
roll: int
start: int
end: int
note: str
again: bool # same player rolls again
won: bool
class Game:
def __init__(self, board: Board, names: list[str], dice: Dice, end_rule: EndRule | None = None,
six_rules: bool = True):
if len(names) < 2:
raise ValueError("need at least two players")
self.board, self.dice = board, dice
self.end_rule = end_rule or ExactFinish()
self.six_rules = six_rules # max face = roll again; three in a row = turn cancelled
self.players = deque(Player(n) for n in names)
self.winner: Player | None = None
self._sixes = 0
self._turn_start = 0
def roll(self) -> RollResult:
if self.winner:
raise GameOver(f"{self.winner.name} has already won")
p = self.players[0]
if self._sixes == 0:
self._turn_start = p.pos
start, r = p.pos, self.dice.roll()
rolled_max = self.six_rules and r == self.dice.max_face
self._sixes = self._sixes + 1 if rolled_max else 0
if self._sixes == 3: # third six in one turn: undo the whole turn
p.pos = self._turn_start
self._end_turn()
return RollResult(p.name, r, start, p.pos, f"third {r} in a row, back to {p.pos}", False, False)
landed = self.end_rule.target(start, r, self.board.size)
p.pos = self.board.resolve(landed)
if landed == start:
note = "overshoot, stays"
elif p.pos != landed:
note = f"{self.board.kind(landed)} {landed}->{p.pos}"
elif landed < start + r:
note = f"bounced back from {self.board.size}"
else:
note = ""
if p.pos == self.board.size:
self.winner = p
return RollResult(p.name, r, start, p.pos, note, False, True)
if not rolled_max:
self._end_turn()
return RollResult(p.name, r, start, p.pos, note, rolled_max, False)
def _end_turn(self):
self._sixes = 0
self.players.rotate(-1)
def play(self, max_rolls: int = 100_000) -> Player:
for _ in range(max_rolls):
if self.roll().won:
return self.winner
raise RuntimeError("no winner; check the board for a trap")
# The 100-cell layout used in most Markov-chain write-ups of the game.
CLASSIC = {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 show(r: RollResult) -> None:
tail = f" ({r.note})" if r.note else ""
flag = " WINS" if r.won else (" rolls again" if r.again else "")
print(f" {r.player:<5} rolled {r.roll}: {r.start:>2} -> {r.end:>2}{tail}{flag}")
def solo_rolls(board: Board, rng: Lcg) -> int:
"""Rolls a single token needs to finish (exact finish, no six rules)."""
pos, n, rule, die = 0, 0, ExactFinish(), RandomDie(rng)
while pos != board.size:
pos = board.resolve(rule.target(pos, die.roll(), board.size))
n += 1
return n
if __name__ == "__main__":
print("1) Board validation")
for size, jumps in [(30, {30: 5}), (30, {12: 12}), (30, {3: 22, 22: 9}), (30, {8: 31})]:
try:
Board(size, jumps)
except InvalidBoard as e:
print(" rejected:", e)
print("\n2) Scripted game on a 30-cell board, exact finish")
small = Board(30, {3: 22, 5: 8, 11: 26, 20: 29, 17: 4, 19: 7, 21: 9, 27: 1})
g = Game(small, ["Asha", "Ravi"], FixedDice([3, 6, 6, 6, 4, 2, 6, 1, 5, 2, 6, 5, 2, 1, 4, 6, 1, 3, 6, 1]))
while not g.winner:
show(g.roll())
print("\n3) BounceBack rule instead: Ravi on 26 rolls a 6")
g = Game(small, ["Ravi", "Asha"], FixedDice([6]), BounceBack())
g.players[0].pos = 26
show(g.roll())
print("\n4) Rolling after the game ended")
g = Game(Board(10, {}), ["A", "B"], FixedDice([6, 1, 4]), six_rules=False)
g.play()
try:
g.roll()
except GameOver as e:
print(" rejected:", e)
print("\n5) Classic 100-cell board: 10,000 solo games, exact finish, no six rules")
classic, rng = Board(100, CLASSIC), Lcg(2026)
counts = sorted(solo_rolls(classic, rng) for _ in range(10_000))
print(f" mean {sum(counts) / len(counts):.1f} rolls, median {counts[5000]}, "
f"fastest {counts[0]}, slowest {counts[-1]}, over 100 rolls: {sum(c > 100 for c in counts)}")
print("\n6) Does going first help? 10,000 four-player games, six rules on")
wins = {n: 0 for n in ["P1", "P2", "P3", "P4"]}
for _ in range(10_000):
wins[Game(classic, list(wins), RandomDie(rng)).play().name] += 1
print(" " + ", ".join(f"{n} {w / 100:.1f}%" for n, w in wins.items()))
Java
// Snake and ladder low-level design: validated board, injectable dice, pluggable end rule, six rules.
// Run: javac SnakeLadder.java && java SnakeLadder
import java.util.*;
public class SnakeLadder {
static class InvalidBoard extends RuntimeException { InvalidBoard(String m) { super(m); } }
static class GameOver extends RuntimeException { GameOver(String m) { super(m); } }
/** Cells 1..size. jumps maps start -> end: end > start is a ladder, end < start a snake. */
static class Board {
final int size;
private final Map<Integer, Integer> jumps;
Board(int size, Map<Integer, Integer> jumps) {
for (var e : jumps.entrySet()) {
int start = e.getKey(), end = e.getValue();
if (start < 1 || start >= size)
throw new InvalidBoard("jump from " + start + ": must start between 1 and " + (size - 1));
if (end < 1 || end > size || end == start)
throw new InvalidBoard("jump " + start + "->" + end + ": end must be another cell on the board");
if (jumps.containsKey(end))
throw new InvalidBoard("jump " + start + "->" + end + " lands on the start of " + end + "->" + jumps.get(end));
}
this.size = size;
this.jumps = new HashMap<>(jumps);
}
int resolve(int cell) { return jumps.getOrDefault(cell, cell); }
String kind(int start) { return jumps.get(start) > start ? "ladder" : "snake"; }
}
interface Dice { int roll(); int maxFace(); }
/** Same LCG as the Python version, so both demos print the same games. */
static class Lcg {
private long state;
Lcg(long seed) { state = seed; }
int nextInt(int bound) {
state = (state * 1103515245L + 12345L) % (1L << 31);
return (int) ((state >> 16) % bound); // high bits: the low bits of an LCG cycle quickly
}
}
static class RandomDie implements Dice {
private final Lcg rng;
private final int faces;
RandomDie(Lcg rng) { this(rng, 6); }
RandomDie(Lcg rng, int faces) { this.rng = rng; this.faces = faces; }
public int roll() { return rng.nextInt(faces) + 1; }
public int maxFace() { return faces; }
}
/** Replays a script of rolls. This is how you unit-test a game built on randomness. */
static class FixedDice implements Dice {
private final Deque<Integer> rolls = new ArrayDeque<>();
FixedDice(int... rolls) { for (int r : rolls) this.rolls.add(r); }
public int roll() { return rolls.removeFirst(); }
public int maxFace() { return 6; }
}
/** What happens when a roll would carry the token past the last cell. */
interface EndRule { int target(int pos, int roll, int size); }
static class ExactFinish implements EndRule {
public int target(int pos, int roll, int size) { return pos + roll <= size ? pos + roll : pos; }
}
static class BounceBack implements EndRule {
public int target(int pos, int roll, int size) {
int t = pos + roll;
return t <= size ? t : size - (t - size);
}
}
static class Player {
final String name;
int pos = 0; // 0 = not on the board yet
Player(String name) { this.name = name; }
}
record RollResult(String player, int roll, int start, int end, String note, boolean again, boolean won) { }
static class Game {
final Board board;
final Dice dice;
final EndRule endRule;
final boolean sixRules; // max face = roll again; three in a row = turn cancelled
final Deque<Player> players = new ArrayDeque<>();
Player winner = null;
private int sixes = 0, turnStart = 0;
Game(Board board, List<String> names, Dice dice) { this(board, names, dice, new ExactFinish(), true); }
Game(Board board, List<String> names, Dice dice, EndRule endRule, boolean sixRules) {
if (names.size() < 2) throw new IllegalArgumentException("need at least two players");
this.board = board; this.dice = dice; this.endRule = endRule; this.sixRules = sixRules;
for (String n : names) players.add(new Player(n));
}
RollResult roll() {
if (winner != null) throw new GameOver(winner.name + " has already won");
Player p = players.peekFirst();
if (sixes == 0) turnStart = p.pos;
int start = p.pos, r = dice.roll();
boolean rolledMax = sixRules && r == dice.maxFace();
sixes = rolledMax ? sixes + 1 : 0;
if (sixes == 3) { // third six in one turn: undo the whole turn
p.pos = turnStart;
endTurn();
return new RollResult(p.name, r, start, p.pos, "third " + r + " in a row, back to " + p.pos, false, false);
}
int landed = endRule.target(start, r, board.size);
p.pos = board.resolve(landed);
String note;
if (landed == start) note = "overshoot, stays";
else if (p.pos != landed) note = board.kind(landed) + " " + landed + "->" + p.pos;
else if (landed < start + r) note = "bounced back from " + board.size;
else note = "";
if (p.pos == board.size) {
winner = p;
return new RollResult(p.name, r, start, p.pos, note, false, true);
}
if (!rolledMax) endTurn();
return new RollResult(p.name, r, start, p.pos, note, rolledMax, false);
}
private void endTurn() { sixes = 0; players.addLast(players.removeFirst()); }
Player play() {
for (int i = 0; i < 100_000; i++) if (roll().won()) return winner;
throw new IllegalStateException("no winner; check the board for a trap");
}
}
/** The 100-cell layout used in most Markov-chain write-ups of the game. */
static final Map<Integer, Integer> CLASSIC = Map.ofEntries(
Map.entry(1, 38), Map.entry(4, 14), Map.entry(9, 31), Map.entry(21, 42), Map.entry(28, 84),
Map.entry(36, 44), Map.entry(51, 67), Map.entry(71, 91), Map.entry(80, 100),
Map.entry(16, 6), Map.entry(47, 26), Map.entry(49, 11), Map.entry(56, 53), Map.entry(62, 19),
Map.entry(64, 60), Map.entry(87, 24), Map.entry(93, 73), Map.entry(95, 75), Map.entry(98, 78));
static void show(RollResult r) {
String tail = r.note().isEmpty() ? "" : " (" + r.note() + ")";
String flag = r.won() ? " WINS" : (r.again() ? " rolls again" : "");
System.out.printf(" %-5s rolled %d: %2d -> %2d%s%s%n", r.player(), r.roll(), r.start(), r.end(), tail, flag);
}
/** Rolls a single token needs to finish (exact finish, no six rules). */
static int soloRolls(Board board, Lcg rng) {
int pos = 0, n = 0;
EndRule rule = new ExactFinish();
Dice die = new RandomDie(rng);
while (pos != board.size) { pos = board.resolve(rule.target(pos, die.roll(), board.size)); n++; }
return n;
}
public static void main(String[] args) {
System.out.println("1) Board validation");
int[][] bad = {{30, 5}, {12, 12}, {3, 22, 22, 9}, {8, 31}}; // start, end pairs on a 30-cell board
for (int[] pairs : bad) {
Map<Integer, Integer> jumps = new LinkedHashMap<>();
for (int i = 0; i < pairs.length; i += 2) jumps.put(pairs[i], pairs[i + 1]);
try { new Board(30, jumps); }
catch (InvalidBoard e) { System.out.println(" rejected: " + e.getMessage()); }
}
System.out.println("\n2) Scripted game on a 30-cell board, exact finish");
Board small = new Board(30, Map.of(3, 22, 5, 8, 11, 26, 20, 29, 17, 4, 19, 7, 21, 9, 27, 1));
Game g = new Game(small, List.of("Asha", "Ravi"),
new FixedDice(3, 6, 6, 6, 4, 2, 6, 1, 5, 2, 6, 5, 2, 1, 4, 6, 1, 3, 6, 1));
while (g.winner == null) show(g.roll());
System.out.println("\n3) BounceBack rule instead: Ravi on 26 rolls a 6");
g = new Game(small, List.of("Ravi", "Asha"), new FixedDice(6), new BounceBack(), true);
g.players.peekFirst().pos = 26;
show(g.roll());
System.out.println("\n4) Rolling after the game ended");
g = new Game(new Board(10, Map.of()), List.of("A", "B"), new FixedDice(6, 1, 4), new ExactFinish(), false);
g.play();
try { g.roll(); } catch (GameOver e) { System.out.println(" rejected: " + e.getMessage()); }
System.out.println("\n5) Classic 100-cell board: 10,000 solo games, exact finish, no six rules");
Board classic = new Board(100, CLASSIC);
Lcg rng = new Lcg(2026);
int[] counts = new int[10_000];
long sum = 0;
int over100 = 0;
for (int i = 0; i < counts.length; i++) {
counts[i] = soloRolls(classic, rng);
sum += counts[i];
if (counts[i] > 100) over100++;
}
Arrays.sort(counts);
System.out.printf(" mean %.1f rolls, median %d, fastest %d, slowest %d, over 100 rolls: %d%n",
sum / 10_000.0, counts[5000], counts[0], counts[counts.length - 1], over100);
System.out.println("\n6) Does going first help? 10,000 four-player games, six rules on");
Map<String, Integer> wins = new LinkedHashMap<>();
for (String n : List.of("P1", "P2", "P3", "P4")) wins.put(n, 0);
for (int i = 0; i < 10_000; i++) {
Game game = new Game(classic, List.copyOf(wins.keySet()), new RandomDie(rng));
wins.merge(game.play().name, 1, Integer::sum);
}
StringJoiner sj = new StringJoiner(", ");
wins.forEach((n, w) -> sj.add(String.format("%s %.1f%%", n, w / 100.0)));
System.out.println(" " + sj);
}
}
Output
1) Board validation
rejected: jump from 30: must start between 1 and 29
rejected: jump 12->12: end must be another cell on the board
rejected: jump 3->22 lands on the start of 22->9
rejected: jump 8->31: end must be another cell on the board
2) Scripted game on a 30-cell board, exact finish
Asha rolled 3: 0 -> 22 (ladder 3->22)
Ravi rolled 6: 0 -> 6 rolls again
Ravi rolled 6: 6 -> 12 rolls again
Ravi rolled 6: 12 -> 0 (third 6 in a row, back to 0)
Asha rolled 4: 22 -> 26
Ravi rolled 2: 0 -> 2
Asha rolled 6: 26 -> 26 (overshoot, stays) rolls again
Asha rolled 1: 26 -> 1 (snake 27->1)
Ravi rolled 5: 2 -> 7
Asha rolled 2: 1 -> 22 (ladder 3->22)
Ravi rolled 6: 7 -> 13 rolls again
Ravi rolled 5: 13 -> 18
Asha rolled 2: 22 -> 24
Ravi rolled 1: 18 -> 7 (snake 19->7)
Asha rolled 4: 24 -> 28
Ravi rolled 6: 7 -> 13 rolls again
Ravi rolled 1: 13 -> 14
Asha rolled 3: 28 -> 28 (overshoot, stays)
Ravi rolled 6: 14 -> 29 (ladder 20->29) rolls again
Ravi rolled 1: 29 -> 30 WINS
3) BounceBack rule instead: Ravi on 26 rolls a 6
Ravi rolled 6: 26 -> 28 (bounced back from 30) rolls again
4) Rolling after the game ended
rejected: A has already won
5) Classic 100-cell board: 10,000 solo games, exact finish, no six rules
mean 38.9 rolls, median 32, fastest 7, slowest 260, over 100 rolls: 308
6) Does going first help? 10,000 four-player games, six rules on
P1 26.9%, P2 25.0%, P3 24.1%, P4 24.0%
Following the scripted game in demo 2:
- Asha’s first roll is a 3, which lands on the ladder at 3 and takes her to 22.
- Ravi rolls 6, 6, 6. The first two move him to 6 and then 12, each earning another roll. The third six cancels the turn and he goes back to 0, where the turn began, not just back by six.
- Asha on 26 rolls a 6. 32 is past 30, so with exact finish she stays, and because it was a six she rolls again. The 1 puts her on 27, the snake’s head, and she drops to 1. A six that cannot be used still bit her.
- Ravi’s 6 from 14 lands on 20, the ladder to 29, and the six gives him another roll. He rolls the 1 he needs and wins on the extra roll.
Demo 3 is the bounce-back rule from the same kind of position: 26 + 6 = 32, two past 30, so the token ends on 28. Demo 4 shows that once someone has won, roll() throws instead of quietly moving a token on a finished game.
What the simulation says
Demo 5 plays 10,000 one-player games on the classic 100-cell layout (exact finish, no six rules). The mean is 38.9 rolls, the median 32, the fastest game took 7 rolls and the slowest 260; 308 games, about 3%, needed more than 100 rolls. The mean sitting well above the median tells you the distribution has a long tail: most games are short, and a few unlucky ones keep hitting the snakes at 87, 93, 95 and 98.
You can also compute the exact answer instead of simulating. Write E[s] for the expected number of rolls to finish from cell s. Then E[100] = 0, and for every other cell E[s] = 1 + (E of the six possible next cells) / 6, where “next cell” applies the end rule and any jump. That is 100 linear equations in 100 unknowns. expected_rolls.py solves them with numpy and gets 39.23 rolls from the start, which agrees with the 38.9 from simulation. A breadth-first search over the same transitions confirms that 7 rolls is the fewest possible. The file is 30 lines, and it imports Board and ExactFinish from the game code, so the maths and the game cannot drift apart.
Demo 6 plays 10,000 four-player games with the six rules on. Player 1 won 26.9% of them, against 25% for a fair seat; players 3 and 4 won 24.1% and 24.0%. Going first is worth about two percentage points. With 10,000 games the noise on each figure is around half a point, so that edge is real, not luck. It is a small number, but it is the kind of thing an interviewer enjoys if you bring it up when they ask “is the game fair?”.
Questions you will get next
“Keep playing until everyone finishes, and show the ranking.” Instead of setting one winner, move finished players out of the deque into a finished list and end the game when one player is left. RollResult.won becomes “finished”, and the turn rotation already skips anyone not in the deque.
“Need a six to enter the board.” One condition at the top of roll(): if the player is at 0 and did not roll the maximum face, end the turn. Decide with the interviewer whether that six also earns the usual extra roll.
“Two dice.” A PairOfDice that sums two RandomDie rolls, max_face 12. The six rules no longer make sense as written; most people switch them to “doubles roll again”, which means Dice has to report more than a number. Change roll() to return a small Roll value with the total and a flag, rather than adding a second method the game must remember to call.
“Validate that the board can be won at all.” Constructor checks catch local mistakes. A board where cells 94 to 99 are all snake heads passes every one of them and still traps every token below 94. Run the same BFS as expected_rolls.py from cell 0 and reject the board if cell N is unreachable. That is O(N) and runs once.
“Thousands of games on one server.” One Game per match, moves for a given match handled one at a time (a per-match lock or a single-threaded actor per match), and the dice seeded per game so any game can be replayed from its seed for support tickets. Storing the seed and the roll log is cheaper than storing every board state.
“How would you test the random die itself?” Not by asserting exact values. Roll it 60,000 times and check each face appears roughly 10,000 times (a chi-square test if you want a number). The game tests use FixedDice and never touch randomness.
Where people lose points
- Calling
randominsideGameorPlayer. Then nothing about the game can be tested deterministically, and the interviewer’s “how do you test the three-sixes rule?” has no good answer. - One class per snake and per ladder, sometimes one per cell. Lots of classes, no behaviour. Nobody gets credit for the size of the class diagram.
- Applying only one jump and never thinking about chains. If a snake ends on a ladder start, does the token climb? Either forbid it at construction, as here, or resolve in a loop with cycle detection. Saying nothing is the mistake.
- Moving past 100 and then capping at 100. That turns “roll a 6 from 97” into a win, which is neither exact finish nor bounce back.
- Undoing only the last six on a third six. The rule cancels the whole turn. Without a saved turn-start position, a token that climbed a ladder on the first six keeps it.
while (!gameOver)with no way out. On a board with an unreachable last cell, the loop never ends. Validate reachability or cap the number of rolls, and fail loudly.- Printing from inside
Game. Return what happened and let the caller print it. The same engine then backs a console demo, a test and an API.
The next case study, the ATM, leaves board games behind. The injected-hardware trick from the dice comes back there to fake a jammed cash dispenser, but the hard part is money: what to do when the account has been debited and the notes did not all come out.
Key takeaways
- One map from start cell to end cell models both snakes and ladders; the direction tells you which is which.
- Inject the dice. A scripted die turns every house rule into a three-line deterministic test.
- Put “what happens past the last cell” behind a small rule interface; ask which version the interviewer plays.
- Validate the board when it is built: no jump on the last cell, no self-loops, no chained jumps, and ideally a reachability check.
- For “how long does a game take”, simulate, then check it against the exact Markov-chain answer (39.23 rolls on the classic board).
Exercises
- Add the “six to enter” rule behind a flag and write a two-player
FixedDicetest in which the first player only gets onto the board on their third turn. - Add a reachability check to
Boardand show it rejects a 100-cell board with snakes on 94 to 99. - Change
Gameso play continues until one player is left, and print the finishing order for a seeded four-player game. - Modify
expected_rolls.pyto useBounceBack. Is the expected game longer or shorter than with exact finish? Explain why before you run it.
Quiz
- Why is the dice an interface rather than a call to the language’s random function inside
Game? - A player on 95 rolls a 6 under exact finish, then a 6 under bounce back. Where do they end up in each case on a board with no jumps?
- Why does the game save
turn_starton the first roll of a turn instead of using “current position minus six” on a third six? - The simulated mean was 38.9 rolls and the exact answer 39.23. Why are they not equal, and which would you trust?
Show answers
- So tests can inject a scripted sequence of rolls and check exact outcomes (three sixes, overshoot, a win on an extra roll). It also lets you swap in two dice or a different number of faces without editing
Game. - Exact finish: 95 + 6 = 101 is past 100, so they stay on 95. Bounce back: one past 100, so they land on 99.
- Earlier rolls in the same turn may have hit a ladder or snake, so the token’s movement is not just the sum of the dice. Only the saved starting position undoes the whole turn correctly.
- The simulation is an average of 10,000 random samples and carries sampling error; with a spread this wide (7 to 260 rolls) a few tenths of a roll is expected. The exact linear-system answer has no sampling error, so trust 39.23, and use the simulation as a check that the model matches the game code.