On this page

Design Snake & Ladders

Snake & Ladders is a classic LLD interview problem that tests your ability to model a turn-based game with state transitions, randomness (dice), and simple rules. The key design challenges are separating the game engine from the board configuration and handling edge cases like exact-finish rules.

There's a third challenge that strong candidates name first: the dice. A game driven by randomness is only testable if the randomness is injected, so a test can choose the rolls and a simulation can replay a game from its seed. That one decision shapes the whole design, and it's the angle this page develops. It follows the LLD interview framework, and keeps the original walkthrough code, with corrections marked.

Requirements & Use Cases

Clarifying questions

QuestionTypical answerWhy it matters
How big is the board, and is it configurable?100 cells by default, configurableBoard size is data, not code
Where do snakes and ladders go?Configurable, with the classic board as a defaultThe board needs validation, because a bad layout can make the game unwinnable
What happens if a roll overshoots the last cell?The player stays putThe alternative is "bounce back". Both are common, so ask
Does a six give another roll? Is there a limit?Yes, no limit for nowThe three-sixes rule is a common follow-up (Extension C)
One die or two?One for nowTwo dice change the extra-turn rule to doubles (Extension A)
Local or online?Local, but keep online in mindOnline means rolls happen on the server, under a lock
How do we test it?Your callThe answer is "inject the dice", and it's worth volunteering

Functional Requirements

  1. Board of configurable size (default: 10x10 = 100 cells)
  2. Configurable snakes (head → tail, moves player down) and ladders (bottom → top, moves player up)
  3. 2-4 players take turns
  4. Single standard die (1-6) per roll; optionally support two dice
  5. Player starts at position 0 (off the board), must reach exactly position 100 to win
  6. If roll would exceed 100, player stays in place
  7. Rolling a 6 grants an extra turn
  8. First player to reach position 100 wins

Non-Functional Requirements

  • Deterministic game logic (given same dice rolls, same outcome)
  • Extensible for custom rules (special cells, power-ups)
  • Board configuration validated (no cyclic snakes/ladders)
  • Testable: every rule can be triggered deterministically, and a random game can be replayed from its seed

Correction (2026-11-10)

The walkthrough code below doesn't meet the validation requirement. It only rejects two jumps that start on the same cell. It accepts a snake whose head is the last cell, which makes the game unwinnable, and it accepts chains such as a snake ending at a ladder's foot. getFinalPosition applies only one jump, so a chained player stops on the foot of a ladder without climbing it. A snake 50→20 plus a ladder 20→50 would be a cycle. The complete code rejects all of these: a jump must start below the last cell, and no jump may start where another ends. That rule makes cycles impossible.

Use Cases

ActorUse Case
PlayerRoll the dice
PlayerMove token to new position
SystemApply snake (move down) or ladder (move up)
SystemGrant extra turn on rolling 6
SystemDetect winner
SystemPrevent invalid board configurations

Core entities and relationships

EntityResponsibilityNotes
Dice (interface)The only source of randomness. Returns a RollRandomDice takes an injected random generator. FixedDice replays a script
RollThe faces of one throw, with total and isDoubleA value object, so the rules can ask "was it a double?" without knowing the dice
BoardSize and jumps. Validates every jump when it's addedSnakes and ladders are one map, start cell to end cell. The direction tells them apart
GameTurn order, positions, the extra-turn rule, the winnerOwns positions as a plain array. A player is just a name here
TurnResultAn immutable record of one turnEverything a UI, a log or a test needs, without peeking inside Game

Three modelling choices are worth saying out loud:

  • Snakes and ladders are the same thing. Both are a jump from one cell to another. One map with a validation rule per direction is simpler than two classes with identical behaviour. jumpAt derives the kind from the direction.
  • Positions live in the game, not in a Player object. A player in this problem has no behaviour, only a name. Putting move() on Player (as the walkthrough does) spreads the overshoot rule across two classes. If players gain behaviour, such as AI players choosing between two tokens, promote them.
  • The dice are injected. That one decision makes every rule testable. A test can force a snake, a ladder, a six or an overshoot on the exact turn it wants, and a simulation can replay a random game from its seed.

Class Diagram

classDiagram
    class Game {
        -board: Board
        -players: Player[]
        -currentPlayerIndex: int
        -dice: Dice
        -status: GameStatus
        +play(): Player
        +playTurn(): TurnResult
        +isGameOver(): boolean
        +getWinner(): Player?
    }

    class Board {
        -size: int
        -snakes: Map~int, int~
        -ladders: Map~int, int~
        +addSnake(head: int, tail: int): void
        +addLadder(bottom: int, top: int): void
        +getFinalPosition(position: int): int
        +isWinningPosition(position: int): boolean
    }

    class Player {
        -name: string
        -position: int
        +move(steps: int, boardSize: int): int
        +setPosition(pos: int): void
        +getPosition(): int
    }

    class Dice {
        -numDice: int
        -faces: int
        +roll(): int
    }

    class TurnResult {
        -player: Player
        -diceValue: int
        -oldPosition: int
        -newPosition: int
        -hitSnake: boolean
        -hitLadder: boolean
        -extraTurn: boolean
    }

    class GameStatus {
        <<enumeration>>
        NOT_STARTED
        IN_PROGRESS
        FINISHED
    }

    Game *-- Board
    Game *-- Player
    Game *-- Dice
    Game --> GameStatus
    Game --> TurnResult
    Board --> "snakes" Map
    Board --> "ladders" Map

Class diagram for the complete code

The diagram above matches the original walkthrough code. The complete code below folds Player into the game and makes randomness an interface:

classDiagram
    class Dice {
        <<interface>>
        +roll() Roll
    }
    class RandomDice {
        -int count
        -int faces
        -Random rng
        +roll() Roll
    }
    class FixedDice {
        -Deque~Roll~ script
        +roll() Roll
    }
    class Roll {
        +List~int~ faces
        +total() int
        +isDouble() bool
    }
    class Board {
        -int size
        -Map~int, int~ jumps
        +snake(head, tail) Board
        +ladder(bottom, top) Board
        +destination(cell) int
        +jumpAt(cell) Jump
    }
    class Game {
        -int[] positions
        -int current
        -GameStatus status
        -Predicate~Roll~ extraTurn
        +playTurn(who) TurnResult
        +playToEnd(maxTurns) String
    }
    class TurnResult {
        <<record>>
    }
    Dice <|.. RandomDice
    Dice <|.. FixedDice
    Dice ..> Roll
    Game o-- Dice
    Game o-- Board
    Game ..> TurnResult

Game aggregates its Board and Dice rather than composing them. Both are passed in, which is the point: the caller decides which dice the game gets.

Key flows

One turn, with a ladder

sequenceDiagram
    participant C as Caller
    participant G as Game
    participant D as Dice
    participant B as Board
    C->>G: playTurn for ann
    G->>G: check the game isn't over and it's ann's turn
    G->>D: roll
    D-->>G: Roll with faces 2
    G->>G: 0 plus 2 is 2, within the board
    G->>B: destination of 2
    B-->>G: 38, a ladder
    G->>G: store 38, not 100 so no win, not a six so next player
    G-->>C: TurnResult from 0, landed 2, to 38, LADDER

A six, then an overshoot

sequenceDiagram
    participant G as Game
    participant D as Dice
    participant B as Board
    Note over G: bob is on 93
    G->>D: roll
    D-->>G: 6
    G->>B: destination of 99
    B-->>G: 9, a snake
    G->>G: a six, so bob rolls again
    G->>D: roll
    D-->>G: 4
    G->>B: destination of 13
    B-->>G: 13
    G->>G: not a six, so the turn passes
    Note over G: Later, on 97, a roll of 5 would reach 102. bob stays on 97.

Game status

stateDiagram-v2
    [*] --> NOT_STARTED
    NOT_STARTED --> IN_PROGRESS: first turn
    IN_PROGRESS --> IN_PROGRESS: turn without a winner
    IN_PROGRESS --> FINISHED: a player lands exactly on the last cell
    FINISHED --> [*]

FINISHED rejects every further turn. Three states with almost no behaviour of their own don't justify the State pattern. One guard at the top of playTurn does the job.

Design Patterns Used

PatternWhereWhy
StrategyDice base class with FixedDice for testingSwap random dice for deterministic dice in tests
Factory MethodcreateStandardGame() functionEncapsulate standard board setup; callers don't need to know snake/ladder positions
StateGameStatus enum controlling playTurn() behaviorGame rejects moves after FINISHED state
Template Methodplay() calls playTurn() in a loopDefines the game-loop skeleton; subclasses can override turn behavior

Correction (2026-11-10)

Three rows in this table overstated the design. play() calling playTurn() in a loop isn't Template Method, which needs a base class whose fixed algorithm calls steps that subclasses override. GameStatus is an enum with a guard, not the State pattern, which needs one object per state with its own behaviour. And createStandardGame() is a plain factory function (sometimes called a Simple Factory), not the GoF Factory Method, which is a method that subclasses override to choose what to create. The Strategy row is right.

The decisions as you'd defend them, with what you turned down:

ChoiceWhereWhyAlternative rejected
Strategy for randomnessDice with RandomDice and FixedDiceTests choose the rolls, simulations choose the seedMath.random() inside the game, testable only by subclassing or monkey-patching
Injected generatorRandomDice(count, faces, rng)The dice's own logic (range, several dice) is testable with a seeded generatorA FixedDice subclass of a concrete Dice, which inherits fields it ignores and leaves RandomDice untested
Strategy for a ruleextraTurn predicate"Six rolls again" and "doubles roll again" are both one lineA numDice == 1 check inside playTurn
Fail-fast validationBoard.snake and Board.ladderA bad board is rejected when it's built, not discovered mid-gameValidating lazily during play
Not used: Singleton for the diceIt would make every game share one generator, so no test could control it

The deeper principle is designing for testability. Anything non-deterministic, such as randomness, time or I/O, comes in through the constructor.

Implementation

Complete runnable code

Each tab is a complete file with the same design. The Java main plays a scripted game that hits every rule (ladder, six, snake, overshoot, exact finish) and then replays a seeded random game twice to show it's reproducible. The Python demo does the same. TypeScript has no seedable random generator built in, so the file includes seeded(), a 12-line Mulberry32 generator. Mulberry32 is a well-known tiny generator: fine for games and tests, not for anything security-sensitive.

// file: SnakesAndLadders.java
import java.util.*;
import java.util.function.Predicate;

record Roll(List<Integer> faces) {
    int total() { return faces.stream().mapToInt(Integer::intValue).sum(); }
    boolean isDouble() { return faces.size() > 1 && faces.stream().distinct().count() == 1; }
}

/** The only source of randomness. The game never calls a random generator itself. */
interface Dice { Roll roll(); }

final class RandomDice implements Dice {
    private final int count, faces;
    private final Random rng;                          // injected: seeded in tests, SecureRandom for money games

    RandomDice(int count, int faces, Random rng) {
        if (count < 1 || faces < 2) throw new IllegalArgumentException("need at least one die with 2 faces");
        this.count = count;
        this.faces = faces;
        this.rng = rng;
    }

    public Roll roll() {
        List<Integer> out = new ArrayList<>();
        for (int i = 0; i < count; i++) out.add(1 + rng.nextInt(faces));
        return new Roll(out);
    }
}

/** A scripted test double: returns exactly the rolls you give it. */
final class FixedDice implements Dice {
    private final Deque<Roll> script;
    FixedDice(Roll... rolls) { script = new ArrayDeque<>(List.of(rolls)); }
    static FixedDice of(int... totals) {
        return new FixedDice(Arrays.stream(totals).mapToObj(t -> new Roll(List.of(t))).toArray(Roll[]::new));
    }
    public Roll roll() {
        if (script.isEmpty()) throw new IllegalStateException("no scripted rolls left");
        return script.poll();
    }
}

enum Jump { NONE, SNAKE, LADDER }

final class Board {
    private final int size;
    private final Map<Integer, Integer> jumps = new HashMap<>();   // start cell -> end cell

    Board(int size) {
        if (size < 2) throw new IllegalArgumentException("board needs at least 2 cells");
        this.size = size;
    }

    int size() { return size; }
    Board snake(int head, int tail) {
        if (head <= tail) throw new IllegalArgumentException("a snake goes down: " + head + "->" + tail);
        return add(head, tail);
    }
    Board ladder(int bottom, int top) {
        if (bottom >= top) throw new IllegalArgumentException("a ladder goes up: " + bottom + "->" + top);
        return add(bottom, top);
    }

    private Board add(int from, int to) {
        if (from < 1 || from >= size) throw new IllegalArgumentException("a jump can't start on " + from);
        if (to < 1 || to > size) throw new IllegalArgumentException("a jump can't end on " + to);
        if (jumps.containsKey(from)) throw new IllegalArgumentException(from + " already has a jump");
        // No chains: every jump ends on a plain cell. This also makes cycles impossible.
        if (jumps.containsKey(to) || jumps.containsValue(from))
            throw new IllegalArgumentException("jumps can't chain: " + from + "->" + to);
        jumps.put(from, to);
        return this;
    }

    int destination(int cell) { return jumps.getOrDefault(cell, cell); }
    Jump jumpAt(int cell) {
        Integer to = jumps.get(cell);
        return to == null ? Jump.NONE : to < cell ? Jump.SNAKE : Jump.LADDER;
    }
}

enum GameStatus { NOT_STARTED, IN_PROGRESS, FINISHED }

record TurnResult(String player, Roll roll, int from, int landed, int to, Jump jump, boolean extraTurn, boolean won) {}

final class Game {
    static final Predicate<Roll> SINGLE_SIX = r -> r.faces().size() == 1 && r.total() == 6;

    private final Board board;
    private final List<String> players;
    private final int[] positions;                     // 0 = not on the board yet
    private final Dice dice;
    private final Predicate<Roll> extraTurn;
    private int current;
    private GameStatus status = GameStatus.NOT_STARTED;
    private String winner;

    Game(Board board, List<String> players, Dice dice) { this(board, players, dice, SINGLE_SIX); }

    Game(Board board, List<String> players, Dice dice, Predicate<Roll> extraTurn) {
        if (players.size() < 2 || players.size() > 4) throw new IllegalArgumentException("2 to 4 players");
        if (new HashSet<>(players).size() != players.size()) throw new IllegalArgumentException("names must be unique");
        this.board = board;
        this.players = List.copyOf(players);
        this.positions = new int[players.size()];
        this.dice = dice;
        this.extraTurn = extraTurn;
    }

    synchronized String currentPlayer() { return players.get(current); }
    synchronized GameStatus status() { return status; }
    synchronized Optional<String> winner() { return Optional.ofNullable(winner); }
    synchronized int position(String player) { return positions[players.indexOf(player)]; }

    /** One atomic turn: check whose turn it is, roll, move, apply a jump, decide what happens next. */
    synchronized TurnResult playTurn(String who) {
        if (status == GameStatus.FINISHED) throw new IllegalStateException("game over");
        if (!players.get(current).equals(who)) throw new IllegalStateException("not " + who + "'s turn");
        status = GameStatus.IN_PROGRESS;
        Roll roll = dice.roll();
        int from = positions[current];
        int landed = from + roll.total() > board.size() ? from : from + roll.total();   // overshoot: stay
        int to = board.destination(landed);
        positions[current] = to;
        boolean won = to == board.size();
        boolean again = !won && extraTurn.test(roll);
        if (won) { status = GameStatus.FINISHED; winner = who; }
        else if (!again) current = (current + 1) % players.size();
        return new TurnResult(who, roll, from, landed, to, board.jumpAt(landed), again, won);
    }

    synchronized TurnResult playTurn() { return playTurn(players.get(current)); }

    /** Plays until someone wins. The cap turns a bug into a failure instead of a hang. */
    String playToEnd(int maxTurns) {
        for (int i = 0; i < maxTurns && status() != GameStatus.FINISHED; i++) playTurn();
        return winner().orElseThrow(() -> new IllegalStateException("no winner after " + maxTurns + " turns"));
    }

    static Board standardBoard() {
        return new Board(100)
            .snake(99, 9).snake(95, 56).snake(62, 18).snake(48, 11).snake(36, 6)
            .ladder(2, 38).ladder(7, 14).ladder(15, 31).ladder(28, 84).ladder(51, 67).ladder(71, 91);
    }
}

public class SnakesAndLadders {
    static void check(boolean ok, String what) { if (!ok) throw new AssertionError(what); }

    public static void main(String[] args) {
        // Scripted dice make every rule reachable on purpose: ladder, six, snake, overshoot, exact finish.
        Board small = new Board(10).ladder(3, 7).snake(9, 2);
        Game g = new Game(small, List.of("ann", "bob"), FixedDice.of(3, 6, 3, 4, 1, 3));
        check(g.playTurn().jump() == Jump.LADDER && g.position("ann") == 7, "ann climbs 3->7");
        check(g.playTurn().extraTurn() && g.currentPlayer().equals("bob"), "bob's six earns another roll");
        check(g.playTurn().jump() == Jump.SNAKE && g.position("bob") == 2, "bob lands on 9 and slides to 2");
        check(g.playTurn().to() == 7, "ann at 7 rolls 4: 11 overshoots 10, so she stays");
        check(g.playTurn().to() == 7, "bob 2 + 1 = 3, up the ladder to 7");
        check(g.playTurn().won() && g.winner().orElseThrow().equals("ann"), "ann rolls exactly 3");

        // Seeded randomness makes a whole random game reproducible.
        String w1 = new Game(Game.standardBoard(), List.of("a", "b", "c"), new RandomDice(1, 6, new Random(7))).playToEnd(10_000);
        String w2 = new Game(Game.standardBoard(), List.of("a", "b", "c"), new RandomDice(1, 6, new Random(7))).playToEnd(10_000);
        check(w1.equals(w2), "same seed, same game");
        System.out.println("all checks passed, seeded winner " + w1);
    }
}
# file: snakes_and_ladders.py
from __future__ import annotations

import random
import threading
from collections import deque
from dataclasses import dataclass
from enum import Enum
from typing import Callable, Protocol


@dataclass(frozen=True)
class Roll:
    faces: tuple[int, ...]

    @property
    def total(self) -> int:
        return sum(self.faces)

    @property
    def is_double(self) -> bool:
        return len(self.faces) > 1 and len(set(self.faces)) == 1


class Dice(Protocol):
    """The only source of randomness. The game never calls `random` itself."""
    def roll(self) -> Roll: ...


class RandomDice:
    def __init__(self, count: int = 1, faces: int = 6, rng: random.Random | None = None) -> None:
        if count < 1 or faces < 2:
            raise ValueError("need at least one die with 2 faces")
        self._count, self._faces = count, faces
        self._rng = rng or random.Random()        # inject a seeded Random in tests

    def roll(self) -> Roll:
        return Roll(tuple(self._rng.randint(1, self._faces) for _ in range(self._count)))


class FixedDice:
    """A scripted test double: returns exactly the rolls you give it."""

    def __init__(self, *rolls: int | tuple[int, ...]) -> None:
        self._script = deque(Roll(r if isinstance(r, tuple) else (r,)) for r in rolls)

    def roll(self) -> Roll:
        if not self._script:
            raise RuntimeError("no scripted rolls left")
        return self._script.popleft()


class Jump(Enum):
    NONE = "none"
    SNAKE = "snake"
    LADDER = "ladder"


class Board:
    def __init__(self, size: int = 100) -> None:
        if size < 2:
            raise ValueError("board needs at least 2 cells")
        self.size = size
        self._jumps: dict[int, int] = {}

    def snake(self, head: int, tail: int) -> Board:
        if head <= tail:
            raise ValueError(f"a snake goes down: {head}->{tail}")
        return self._add(head, tail)

    def ladder(self, bottom: int, top: int) -> Board:
        if bottom >= top:
            raise ValueError(f"a ladder goes up: {bottom}->{top}")
        return self._add(bottom, top)

    def _add(self, start: int, end: int) -> Board:
        if not 1 <= start < self.size:
            raise ValueError(f"a jump can't start on {start}")
        if not 1 <= end <= self.size:
            raise ValueError(f"a jump can't end on {end}")
        if start in self._jumps:
            raise ValueError(f"{start} already has a jump")
        if end in self._jumps or start in self._jumps.values():   # no chains, so no cycles
            raise ValueError(f"jumps can't chain: {start}->{end}")
        self._jumps[start] = end
        return self

    def destination(self, cell: int) -> int:
        return self._jumps.get(cell, cell)

    def jump_at(self, cell: int) -> Jump:
        end = self._jumps.get(cell)
        if end is None:
            return Jump.NONE
        return Jump.SNAKE if end < cell else Jump.LADDER

    @staticmethod
    def standard() -> Board:
        b = Board(100)
        for head, tail in [(99, 9), (95, 56), (62, 18), (48, 11), (36, 6)]:
            b.snake(head, tail)
        for bottom, top in [(2, 38), (7, 14), (15, 31), (28, 84), (51, 67), (71, 91)]:
            b.ladder(bottom, top)
        return b


class GameStatus(Enum):
    NOT_STARTED = "NOT_STARTED"
    IN_PROGRESS = "IN_PROGRESS"
    FINISHED = "FINISHED"


@dataclass(frozen=True)
class TurnResult:
    player: str
    roll: Roll
    start: int
    landed: int
    end: int
    jump: Jump
    extra_turn: bool
    won: bool


def single_six(r: Roll) -> bool:
    return r.faces == (6,)


class Game:
    def __init__(self, board: Board, players: list[str], dice: Dice,
                 extra_turn: Callable[[Roll], bool] = single_six) -> None:
        if not 2 <= len(players) <= 4:
            raise ValueError("2 to 4 players")
        if len(set(players)) != len(players):
            raise ValueError("names must be unique")
        self._board, self._players, self._dice = board, list(players), dice
        self._extra_turn = extra_turn
        self._positions = [0] * len(players)       # 0 = not on the board yet
        self._current = 0
        self._status = GameStatus.NOT_STARTED
        self._winner: str | None = None
        self._lock = threading.Lock()

    @property
    def current_player(self) -> str:
        with self._lock:
            return self._players[self._current]

    @property
    def status(self) -> GameStatus:
        with self._lock:
            return self._status

    @property
    def winner(self) -> str | None:
        with self._lock:
            return self._winner

    def position(self, player: str) -> int:
        with self._lock:
            return self._positions[self._players.index(player)]

    def play_turn(self, who: str | None = None) -> TurnResult:
        with self._lock:                            # check, roll and move as one step
            if self._status is GameStatus.FINISHED:
                raise RuntimeError("game over")
            me = self._players[self._current]
            if who is not None and who != me:
                raise RuntimeError(f"not {who}'s turn")
            self._status = GameStatus.IN_PROGRESS
            roll = self._dice.roll()
            start = self._positions[self._current]
            landed = start if start + roll.total > self._board.size else start + roll.total
            end = self._board.destination(landed)
            self._positions[self._current] = end
            won = end == self._board.size
            again = not won and self._extra_turn(roll)
            if won:
                self._status, self._winner = GameStatus.FINISHED, me
            elif not again:
                self._current = (self._current + 1) % len(self._players)
            return TurnResult(me, roll, start, landed, end, self._board.jump_at(landed), again, won)

    def play_to_end(self, max_turns: int = 100_000) -> str:
        for _ in range(max_turns):
            if self.status is GameStatus.FINISHED:
                break
            self.play_turn()
        if self.winner is None:
            raise RuntimeError(f"no winner after {max_turns} turns")
        return self.winner


if __name__ == "__main__":
    g = Game(Board(10).ladder(3, 7).snake(9, 2), ["ann", "bob"], FixedDice(3, 6, 3, 4, 1, 3))
    assert g.play_turn().jump is Jump.LADDER and g.position("ann") == 7
    assert g.play_turn().extra_turn and g.current_player == "bob"
    assert g.play_turn().jump is Jump.SNAKE and g.position("bob") == 2
    assert g.play_turn().end == 7                  # 7 + 4 overshoots 10: stay
    assert g.play_turn().end == 7                  # bob 2 + 1 = 3, up to 7
    assert g.play_turn().won and g.winner == "ann"

    def seeded(seed: int) -> str:
        return Game(Board.standard(), ["a", "b", "c"], RandomDice(rng=random.Random(seed))).play_to_end()
    assert seeded(7) == seeded(7)
    print("all checks passed")
// file: snakesAndLadders.ts
export interface Roll { readonly faces: readonly number[] }
export const total = (r: Roll): number => r.faces.reduce((a, b) => a + b, 0);
export const isDouble = (r: Roll): boolean => r.faces.length > 1 && r.faces.every((f) => f === r.faces[0]);

/** The only source of randomness. The game never calls Math.random itself. */
export interface Dice { roll(): Roll }

/** A random number in [0, 1). Math.random fits, and so does a seeded generator. */
export type Rng = () => number;

/** Mulberry32: a tiny seeded generator, because JavaScript has no seedable built-in. */
export function seeded(seed: number): Rng {
  let a = seed >>> 0;
  return () => {
    a = (a + 0x6d2b79f5) >>> 0;
    let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}

export class RandomDice implements Dice {
  constructor(private readonly count = 1, private readonly faces = 6, private readonly rng: Rng = Math.random) {
    if (count < 1 || faces < 2) throw new RangeError("need at least one die with 2 faces");
  }
  roll(): Roll {
    return { faces: Array.from({ length: this.count }, () => 1 + Math.floor(this.rng() * this.faces)) };
  }
}

/** A scripted test double. */
export class FixedDice implements Dice {
  private readonly script: Roll[];
  constructor(...rolls: (number | number[])[]) {
    this.script = rolls.map((r) => ({ faces: Array.isArray(r) ? r : [r] }));
  }
  roll(): Roll {
    const next = this.script.shift();
    if (!next) throw new Error("no scripted rolls left");
    return next;
  }
}

export type Jump = "NONE" | "SNAKE" | "LADDER";

export class Board {
  private readonly jumps = new Map<number, number>();   // start cell -> end cell
  constructor(readonly size = 100) {
    if (size < 2) throw new RangeError("board needs at least 2 cells");
  }

  snake(head: number, tail: number): this {
    if (head <= tail) throw new RangeError(`a snake goes down: ${head}->${tail}`);
    return this.add(head, tail);
  }
  ladder(bottom: number, top: number): this {
    if (bottom >= top) throw new RangeError(`a ladder goes up: ${bottom}->${top}`);
    return this.add(bottom, top);
  }

  private add(from: number, to: number): this {
    if (from < 1 || from >= this.size) throw new RangeError(`a jump can't start on ${from}`);
    if (to < 1 || to > this.size) throw new RangeError(`a jump can't end on ${to}`);
    if (this.jumps.has(from)) throw new Error(`${from} already has a jump`);
    if (this.jumps.has(to) || [...this.jumps.values()].includes(from)) {
      throw new Error(`jumps can't chain: ${from}->${to}`);         // no chains, so no cycles
    }
    this.jumps.set(from, to);
    return this;
  }

  destination(cell: number): number { return this.jumps.get(cell) ?? cell; }
  jumpAt(cell: number): Jump {
    const to = this.jumps.get(cell);
    return to === undefined ? "NONE" : to < cell ? "SNAKE" : "LADDER";
  }

  static standard(): Board {
    return new Board(100).snake(99, 9).snake(95, 56).snake(62, 18).snake(48, 11).snake(36, 6)
      .ladder(2, 38).ladder(7, 14).ladder(15, 31).ladder(28, 84).ladder(51, 67).ladder(71, 91);
  }
}

export type GameStatus = "NOT_STARTED" | "IN_PROGRESS" | "FINISHED";

export interface TurnResult {
  player: string; roll: Roll; from: number; landed: number; to: number;
  jump: Jump; extraTurn: boolean; won: boolean;
}

export const singleSix = (r: Roll): boolean => r.faces.length === 1 && r.faces[0] === 6;

export class Game {
  protected readonly positions: number[];              // 0 = not on the board yet
  protected current = 0;
  private gameStatus: GameStatus = "NOT_STARTED";
  private winnerName: string | null = null;

  constructor(
    protected readonly board: Board,
    protected readonly players: readonly string[],
    private readonly dice: Dice,
    private readonly extraTurn: (r: Roll) => boolean = singleSix,
  ) {
    if (players.length < 2 || players.length > 4) throw new RangeError("2 to 4 players");
    if (new Set(players).size !== players.length) throw new Error("names must be unique");
    this.positions = players.map(() => 0);
  }

  get currentPlayer(): string { return this.players[this.current]; }
  get status(): GameStatus { return this.gameStatus; }
  get winner(): string | null { return this.winnerName; }
  position(player: string): number { return this.positions[this.players.indexOf(player)]; }

  // Synchronous, so it runs to completion before Node serves another request.
  playTurn(who: string = this.currentPlayer): TurnResult {
    if (this.gameStatus === "FINISHED") throw new Error("game over");
    if (who !== this.currentPlayer) throw new Error(`not ${who}'s turn`);
    this.gameStatus = "IN_PROGRESS";
    const roll = this.dice.roll();
    const from = this.positions[this.current];
    const landed = from + total(roll) > this.board.size ? from : from + total(roll);
    const to = this.board.destination(landed);
    this.positions[this.current] = to;
    const won = to === this.board.size;
    const again = !won && this.extraTurn(roll);
    if (won) { this.gameStatus = "FINISHED"; this.winnerName = who; }
    else if (!again) this.current = (this.current + 1) % this.players.length;
    return { player: who, roll, from, landed, to, jump: this.board.jumpAt(landed), extraTurn: again, won };
  }

  playToEnd(maxTurns = 100_000): string {
    for (let i = 0; i < maxTurns && this.gameStatus !== "FINISHED"; i++) this.playTurn();
    if (this.winnerName === null) throw new Error(`no winner after ${maxTurns} turns`);
    return this.winnerName;
  }
}

Run with javac -d out SnakesAndLadders.java && java -ea -cp out SnakesAndLadders and python snakes_and_ladders.py. The TypeScript passes tsc --strict, and we ran the same scripted game against it with tsx.

Compared with the walkthrough below:

  • Dice is an interface, and RandomDice takes its generator. The walkthrough's FixedDice extends Dice works as a test double, but the real dice call Math.random() directly, so their own logic can't be tested deterministically.
  • The board rejects snakes on the last cell and chained jumps. See the correction below.
  • The extra-turn rule is a parameter, so two dice can use doubles instead of a total of 6.
  • playTurn(who) checks whose turn it is, which an online game needs. playToEnd has a turn cap, so a bug fails a test instead of hanging it.

Core Classes & Interfaces

This is the original walkthrough. It runs: the TypeScript passes tsc --strict, the two tests below pass with a minimal describe/it/expect shim, and the Python plays the standard game to a winner. We also confirmed the problems in the corrections: addSnake(100, 1) and a snake-to-ladder chain are both accepted.

TypeScript Implementation

// ─── Enums ───────────────────────────────────────────────

enum GameStatus {
  NOT_STARTED = 'NOT_STARTED',
  IN_PROGRESS = 'IN_PROGRESS',
  FINISHED = 'FINISHED',
}

// ─── Turn Result ─────────────────────────────────────────

interface TurnResult {
  player: string;
  diceValue: number;
  oldPosition: number;
  intermediatePosition: number; // before snake/ladder
  newPosition: number;         // after snake/ladder
  hitSnake: boolean;
  hitLadder: boolean;
  extraTurn: boolean;
  won: boolean;
}

// ─── Dice ────────────────────────────────────────────────

class Dice {
  constructor(
    private numDice: number = 1,
    private faces: number = 6
  ) {}

  roll(): number {
    let total = 0;
    for (let i = 0; i < this.numDice; i++) {
      total += Math.floor(Math.random() * this.faces) + 1;
    }
    return total;
  }
}

// Deterministic dice for testing
class FixedDice extends Dice {
  private rolls: number[];
  private index: number = 0;

  constructor(rolls: number[]) {
    super(1, 6);
    this.rolls = rolls;
  }

  roll(): number {
    if (this.index >= this.rolls.length) {
      throw new Error('No more pre-configured rolls');
    }
    return this.rolls[this.index++];
  }
}

// ─── Player ──────────────────────────────────────────────

class Player {
  private position: number = 0;

  constructor(public readonly name: string) {}

  getPosition(): number {
    return this.position;
  }

  setPosition(pos: number): void {
    this.position = pos;
  }

  /**
   * Calculate new position after rolling.
   * If the new position exceeds boardSize, stay in place.
   */
  move(steps: number, boardSize: number): number {
    const newPos = this.position + steps;
    if (newPos > boardSize) {
      return this.position; // can't exceed board
    }
    this.position = newPos;
    return this.position;
  }
}

// ─── Board ───────────────────────────────────────────────

class Board {
  private snakes: Map<number, number> = new Map();
  private ladders: Map<number, number> = new Map();

  constructor(public readonly size: number = 100) {}

  addSnake(head: number, tail: number): void {
    if (head <= tail) {
      throw new Error(`Snake head (${head}) must be above tail (${tail})`);
    }
    if (head > this.size || tail < 1) {
      throw new Error('Snake positions must be within the board');
    }
    if (this.ladders.has(head) || this.snakes.has(head)) {
      throw new Error(`Position ${head} already has a snake or ladder`);
    }
    this.snakes.set(head, tail);
  }

  addLadder(bottom: number, top: number): void {
    if (bottom >= top) {
      throw new Error(`Ladder bottom (${bottom}) must be below top (${top})`);
    }
    if (top > this.size || bottom < 1) {
      throw new Error('Ladder positions must be within the board');
    }
    if (this.snakes.has(bottom) || this.ladders.has(bottom)) {
      throw new Error(`Position ${bottom} already has a snake or ladder`);
    }
    this.ladders.set(bottom, top);
  }

  /**
   * Apply snakes and ladders to get the final resting position.
   * Returns { position, hitSnake, hitLadder }.
   */
  getFinalPosition(position: number): {
    position: number;
    hitSnake: boolean;
    hitLadder: boolean;
  } {
    if (this.snakes.has(position)) {
      return {
        position: this.snakes.get(position)!,
        hitSnake: true,
        hitLadder: false,
      };
    }
    if (this.ladders.has(position)) {
      return {
        position: this.ladders.get(position)!,
        hitSnake: false,
        hitLadder: true,
      };
    }
    return { position, hitSnake: false, hitLadder: false };
  }

  isWinningPosition(position: number): boolean {
    return position === this.size;
  }

  getSnakes(): Map<number, number> {
    return new Map(this.snakes);
  }

  getLadders(): Map<number, number> {
    return new Map(this.ladders);
  }
}

// ─── Game ────────────────────────────────────────────────

class Game {
  private board: Board;
  private players: Player[];
  private currentPlayerIndex: number = 0;
  private dice: Dice;
  private status: GameStatus = GameStatus.NOT_STARTED;
  private winner: Player | null = null;
  private turnHistory: TurnResult[] = [];

  constructor(
    playerNames: string[],
    board: Board = new Board(),
    dice: Dice = new Dice()
  ) {
    if (playerNames.length < 2 || playerNames.length > 4) {
      throw new Error('Game requires 2-4 players');
    }
    this.players = playerNames.map((name) => new Player(name));
    this.board = board;
    this.dice = dice;
  }

  getStatus(): GameStatus {
    return this.status;
  }

  getWinner(): Player | null {
    return this.winner;
  }

  getCurrentPlayer(): Player {
    return this.players[this.currentPlayerIndex];
  }

  /** Play a single turn for the current player */
  playTurn(): TurnResult {
    if (this.status === GameStatus.FINISHED) {
      throw new Error('Game is already finished');
    }
    this.status = GameStatus.IN_PROGRESS;

    const player = this.getCurrentPlayer();
    const diceValue = this.dice.roll();
    const oldPosition = player.getPosition();

    // Move player
    const intermediatePosition = player.move(diceValue, this.board.size);

    // Apply snakes/ladders
    let hitSnake = false;
    let hitLadder = false;
    let newPosition = intermediatePosition;

    if (intermediatePosition !== oldPosition) {
      // Only apply if player actually moved (didn't exceed board)
      const result = this.board.getFinalPosition(intermediatePosition);
      newPosition = result.position;
      hitSnake = result.hitSnake;
      hitLadder = result.hitLadder;
      player.setPosition(newPosition);
    }

    // Check win condition
    const won = this.board.isWinningPosition(newPosition);
    if (won) {
      this.status = GameStatus.FINISHED;
      this.winner = player;
    }

    // Extra turn on rolling 6 (single die only)
    const extraTurn = diceValue === 6 && !won;

    const turnResult: TurnResult = {
      player: player.name,
      diceValue,
      oldPosition,
      intermediatePosition,
      newPosition,
      hitSnake,
      hitLadder,
      extraTurn,
      won,
    };

    this.turnHistory.push(turnResult);

    // Advance to next player (unless extra turn)
    if (!extraTurn) {
      this.currentPlayerIndex =
        (this.currentPlayerIndex + 1) % this.players.length;
    }

    return turnResult;
  }

  /** Play the entire game until someone wins */
  play(): Player {
    while (this.status !== GameStatus.FINISHED) {
      this.playTurn();
    }
    return this.winner!;
  }

  getTurnHistory(): TurnResult[] {
    return [...this.turnHistory];
  }

  getPlayerPositions(): Array<{ name: string; position: number }> {
    return this.players.map((p) => ({
      name: p.name,
      position: p.getPosition(),
    }));
  }
}

// ─── Usage Example ───────────────────────────────────────

function createStandardGame(playerNames: string[]): Game {
  const board = new Board(100);

  // Snakes
  board.addSnake(99, 9);
  board.addSnake(95, 56);
  board.addSnake(62, 18);
  board.addSnake(48, 11);
  board.addSnake(36, 6);

  // Ladders
  board.addLadder(2, 38);
  board.addLadder(7, 14);
  board.addLadder(15, 31);
  board.addLadder(28, 84);
  board.addLadder(51, 67);
  board.addLadder(71, 91);

  return new Game(playerNames, board);
}

Python Implementation

from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional
import random


# ─── Enums ──────────────────────────────────────────────

class GameStatus(Enum):
    NOT_STARTED = "NOT_STARTED"
    IN_PROGRESS = "IN_PROGRESS"
    FINISHED = "FINISHED"


# ─── Turn Result ────────────────────────────────────────

@dataclass
class TurnResult:
    player: str
    dice_value: int
    old_position: int
    intermediate_position: int
    new_position: int
    hit_snake: bool
    hit_ladder: bool
    extra_turn: bool
    won: bool


# ─── Dice ───────────────────────────────────────────────

class Dice:
    def __init__(self, num_dice: int = 1, faces: int = 6):
        self._num_dice = num_dice
        self._faces = faces

    def roll(self) -> int:
        return sum(
            random.randint(1, self._faces) for _ in range(self._num_dice)
        )


class FixedDice(Dice):
    """Deterministic dice for testing."""

    def __init__(self, rolls: list[int]):
        super().__init__()
        self._rolls = rolls
        self._index = 0

    def roll(self) -> int:
        if self._index >= len(self._rolls):
            raise ValueError("No more pre-configured rolls")
        value = self._rolls[self._index]
        self._index += 1
        return value


# ─── Player ─────────────────────────────────────────────

class Player:
    def __init__(self, name: str):
        self.name = name
        self._position = 0

    @property
    def position(self) -> int:
        return self._position

    @position.setter
    def position(self, value: int) -> None:
        self._position = value

    def move(self, steps: int, board_size: int) -> int:
        new_pos = self._position + steps
        if new_pos > board_size:
            return self._position  # stay in place
        self._position = new_pos
        return self._position


# ─── Board ──────────────────────────────────────────────

class Board:
    def __init__(self, size: int = 100):
        self.size = size
        self._snakes: dict[int, int] = {}
        self._ladders: dict[int, int] = {}

    def add_snake(self, head: int, tail: int) -> None:
        if head <= tail:
            raise ValueError(f"Snake head ({head}) must be above tail ({tail})")
        if head > self.size or tail < 1:
            raise ValueError("Snake positions must be within the board")
        if head in self._ladders or head in self._snakes:
            raise ValueError(f"Position {head} already occupied")
        self._snakes[head] = tail

    def add_ladder(self, bottom: int, top: int) -> None:
        if bottom >= top:
            raise ValueError(f"Ladder bottom ({bottom}) must be below top ({top})")
        if top > self.size or bottom < 1:
            raise ValueError("Ladder positions must be within the board")
        if bottom in self._snakes or bottom in self._ladders:
            raise ValueError(f"Position {bottom} already occupied")
        self._ladders[bottom] = top

    def get_final_position(
        self, position: int
    ) -> tuple[int, bool, bool]:
        """Returns (final_position, hit_snake, hit_ladder)."""
        if position in self._snakes:
            return self._snakes[position], True, False
        if position in self._ladders:
            return self._ladders[position], False, True
        return position, False, False

    def is_winning_position(self, position: int) -> bool:
        return position == self.size


# ─── Game ───────────────────────────────────────────────

class Game:
    def __init__(
        self,
        player_names: list[str],
        board: Optional[Board] = None,
        dice: Optional[Dice] = None,
    ):
        if not 2 <= len(player_names) <= 4:
            raise ValueError("Game requires 2-4 players")

        self._board = board or Board()
        self._dice = dice or Dice()
        self._players = [Player(name) for name in player_names]
        self._current_index = 0
        self._status = GameStatus.NOT_STARTED
        self._winner: Optional[Player] = None
        self._turn_history: list[TurnResult] = []

    @property
    def status(self) -> GameStatus:
        return self._status

    @property
    def winner(self) -> Optional[Player]:
        return self._winner

    @property
    def current_player(self) -> Player:
        return self._players[self._current_index]

    def play_turn(self) -> TurnResult:
        if self._status == GameStatus.FINISHED:
            raise RuntimeError("Game is already finished")

        self._status = GameStatus.IN_PROGRESS
        player = self.current_player
        dice_value = self._dice.roll()
        old_position = player.position

        # Move
        intermediate = player.move(dice_value, self._board.size)

        # Apply snakes/ladders
        hit_snake = False
        hit_ladder = False
        new_position = intermediate

        if intermediate != old_position:
            new_position, hit_snake, hit_ladder = (
                self._board.get_final_position(intermediate)
            )
            player.position = new_position

        # Win check
        won = self._board.is_winning_position(new_position)
        if won:
            self._status = GameStatus.FINISHED
            self._winner = player

        extra_turn = dice_value == 6 and not won

        result = TurnResult(
            player=player.name,
            dice_value=dice_value,
            old_position=old_position,
            intermediate_position=intermediate,
            new_position=new_position,
            hit_snake=hit_snake,
            hit_ladder=hit_ladder,
            extra_turn=extra_turn,
            won=won,
        )
        self._turn_history.append(result)

        if not extra_turn:
            self._current_index = (
                (self._current_index + 1) % len(self._players)
            )

        return result

    def play(self) -> Player:
        while self._status != GameStatus.FINISHED:
            self.play_turn()
        return self._winner  # type: ignore

    def get_player_positions(self) -> list[dict]:
        return [
            {"name": p.name, "position": p.position}
            for p in self._players
        ]


# ─── Factory ───────────────────────────────────────────

def create_standard_game(player_names: list[str]) -> Game:
    board = Board(100)

    snakes = [(99, 9), (95, 56), (62, 18), (48, 11), (36, 6)]
    for head, tail in snakes:
        board.add_snake(head, tail)

    ladders = [(2, 38), (7, 14), (15, 31), (28, 84), (51, 67), (71, 91)]
    for bottom, top in ladders:
        board.add_ladder(bottom, top)

    return Game(player_names, board)

Concurrency Considerations

Snake & Ladders is Turn-Based

Concurrency is not a primary concern because only one player acts at a time. However, in an online multiplayer version:

  • Turn lock: Only the current player's playTurn() call is accepted. Others receive an error.
  • Timeout: If a player doesn't roll within 30 seconds, auto-roll or skip.
  • State sync: After each turn, broadcast the TurnResult to all clients so their local state stays consistent.

The tip above is right that a local game has no concurrency. The online version is where the questions come from.

What's shared. One Game per room: positions, the current player, the status and the dice. Games share nothing, so there's no contention across rooms.

The races.

  1. A double click. Ann's client sends "roll" twice. Both requests see "ann's turn" before either advances it, and ann moves twice.
  2. Timeout against a late click. A timer auto-rolls for ann at 30 seconds, just as ann's own click arrives. Same race, different trigger.
  3. The generator itself. java.util.Random is thread-safe but contended under load. Python's random.Random isn't documented as thread-safe, and a RandomDice shared by many games would make each game's sequence depend on the others. Keep one generator per game, used only under the game's lock.

The locking. playTurn(who) holds the game's lock while it checks the status and the turn, rolls, moves and advances the turn (synchronized in Java, threading.Lock in Python). Both races collapse into "the second request finds it's no longer ann's turn and is rejected". The Python test suite below fires eight threads at play_turn("ann") and checks that exactly one roll happened. TypeScript needs no lock, because playTurn is synchronous and Node runs it to completion.

sequenceDiagram
    participant A as Click 1 from ann
    participant G as Game
    participant B as Click 2 from ann
    A->>G: playTurn for ann
    Note over G: lock held
    G->>G: ann's turn, roll 4, move to 4, current becomes bob
    G-->>A: TurnResult
    B->>G: playTurn for ann
    G-->>B: rejected, not ann's turn

Two more points for an online design:

  • Roll on the server. A client that sends "I rolled a 6" will soon be rolling a lot of sixes. The client sends intent, and the server's Dice produces the number.
  • Across servers, give each turn a number and apply it with a conditional write (WHERE turn_no = 17), so a retried request can't play twice. See thread-safe class design and race conditions.

Extensibility: the interviewer adds X

For each extension, say where the change goes, what stays the same, and show it. The original summary table comes first, then three extensions we built and ran.

Extensions & Follow-ups

ExtensionDesign Impact
Custom board sizeAlready supported — Board constructor takes size parameter
Two dicePass new Dice(2, 6) — player must roll doubles to start
Power-up cellsAdd SpecialCell map on Board; effects like "roll again", "move back 3"
Undo last moveStore previous state in TurnResult; add undoTurn() method
Multiplayer onlineWebSocket-based: server runs Game, broadcasts TurnResult to clients
Animated boardSeparate BoardRenderer class that takes TurnResult and animates token movement
Tournament modeTournament class manages multiple Game instances, tracks wins, advances winners

Correction (2026-11-10)

The two-dice row promised more than the code does. new Dice(2, 6) gives two dice, but nothing makes a player roll doubles to start. Worse, playTurn grants an extra turn whenever the total is 6, even though its comment says "single die only", so with two dice a 1 and a 5 rolls again. Extension A below shows the fix: return the faces, not just the total, and make the extra-turn rule a parameter.

Extension A: two dice, and doubles roll again

"The dice already return every face, so RandomDice(2, 6, rng) is the whole dice change. The rule change is one argument: pass Roll::isDouble as the extra-turn rule. Board and the turn logic don't change."

// file: TwoDice.java
import java.util.*;

public class TwoDice {
    public static void main(String[] args) {
        Board board = new Board(30).ladder(4, 20);
        // Two dice, and doubles (not a total of 6) earn another roll.
        Game scripted = new Game(board, List.of("ann", "bob"),
            new FixedDice(new Roll(List.of(2, 2)), new Roll(List.of(1, 5)), new Roll(List.of(3, 3))),
            Roll::isDouble);
        TurnResult first = scripted.playTurn();
        if (first.to() != 20 || !first.extraTurn()) throw new AssertionError("2+2 climbs to 20 and rolls again");
        TurnResult second = scripted.playTurn();
        if (second.extraTurn() || !scripted.currentPlayer().equals("bob")) throw new AssertionError("1+5 is a 6, not a double");
        if (!scripted.playTurn().extraTurn()) throw new AssertionError("bob's 3+3 is a double");

        Game random = new Game(Game.standardBoard(), List.of("ann", "bob"),
            new RandomDice(2, 6, new Random(42)), Roll::isDouble);
        System.out.println("two-dice checks passed, seeded winner " + random.playToEnd(10_000));
    }
}

This is where returning a Roll instead of an int pays off. With a plain total, "was it a double?" can't be answered, and you'd have to change the Dice interface during the interview.

Extension B: custom and random boards

"Boards come from config or from a generator. Both go through snake() and ladder(), so they get the same validation. The generator takes its random source as a parameter, like the dice."

# file: custom_boards.py
import json
import random

from snakes_and_ladders import Board, Game, RandomDice


def board_from_config(text: str) -> Board:
    """Load {"size": 50, "snakes": [[head, tail]], "ladders": [[bottom, top]]}."""
    cfg = json.loads(text)
    board = Board(cfg["size"])
    for head, tail in cfg.get("snakes", []):
        board.snake(head, tail)                    # the same validation as hand-built boards
    for bottom, top in cfg.get("ladders", []):
        board.ladder(bottom, top)
    return board


def random_board(size: int, snakes: int, ladders: int, rng: random.Random) -> Board:
    """Draw random jumps and let Board reject the bad ones. The rng is injected."""
    board, made, attempts = Board(size), {"snake": 0, "ladder": 0}, 0
    while made["snake"] < snakes or made["ladder"] < ladders:
        attempts += 1
        if attempts > 10_000:
            raise ValueError("can't fit that many jumps on this board")
        low, high = sorted(rng.sample(range(2, size), 2))
        kind = "snake" if made["snake"] < snakes else "ladder"
        try:
            board.snake(high, low) if kind == "snake" else board.ladder(low, high)
            made[kind] += 1
        except ValueError:
            continue                               # collided with an existing jump: draw again
    return board


if __name__ == "__main__":
    b = board_from_config('{"size": 50, "snakes": [[47, 3]], "ladders": [[5, 40]]}')
    assert b.destination(47) == 3 and b.destination(5) == 40
    try:
        board_from_config('{"size": 50, "snakes": [[50, 3]]}')
        raise AssertionError("a snake on the last cell must be rejected")
    except ValueError:
        pass

    one = random_board(100, 8, 8, random.Random(5))
    two = random_board(100, 8, 8, random.Random(5))
    assert one._jumps == two._jumps and len(one._jumps) == 16     # same seed, same board
    for seed in range(100):
        board = random_board(100, 10, 10, random.Random(seed))
        Game(board, ["a", "b"], RandomDice(rng=random.Random(seed))).play_to_end(10_000)
    print("custom board checks passed")

The generator uses rejection sampling: draw two cells, try to add the jump, and draw again if the board refuses it. Because the board rejects chains, a generated board can never contain a cycle, and because snake heads are drawn below the last cell, every generated board is winnable. The __main__ check generates 100 seeded boards and plays a game on each, which would hang (and hit the turn cap) if a bad board slipped through.

Extension C: three sixes in a row void the turn

"This one does touch the turn logic, so I'll put it in a subclass that wraps playTurn. It remembers where the streak started. On the third six, it moves the player back and passes the turn."

// file: threeSixes.ts
import assert from "node:assert/strict";
import { Board, FixedDice, Game, type TurnResult } from "./snakesAndLadders.ts";

/** Three sixes in a row void the whole turn: back to where the turn started, next player. */
export class ThreeSixesGame extends Game {
  private streak = 0;
  private streakStart = 0;

  override playTurn(who: string = this.currentPlayer): TurnResult {
    const me = this.current;
    if (this.streak === 0) this.streakStart = this.positions[me];
    const result = super.playTurn(who);            // all the normal rules still apply
    if (!result.extraTurn) { this.streak = 0; return result; }
    if (++this.streak < 3) return result;
    this.positions[me] = this.streakStart;         // the third six cancels the turn
    this.current = (me + 1) % this.players.length;
    this.streak = 0;
    return { ...result, to: this.streakStart, extraTurn: false };
  }
}

const g = new ThreeSixesGame(new Board(100), ["ann", "bob"], new FixedDice(6, 6, 6, 2, 6, 1));
g.playTurn(); g.playTurn();
assert.equal(g.position("ann"), 12);
const third = g.playTurn();
assert.ok(!third.extraTurn && g.position("ann") === 0 && g.currentPlayer === "bob");
g.playTurn();                                       // bob 2
g.playTurn();                                       // ann 6 starts a new streak
assert.equal(g.playTurn().to, 7);                   // then 1: the streak was reset
console.log("three-sixes checks passed");

The base class needed positions, current and players to be protected. A winning six still wins: super.playTurn reports no extra turn when the player wins, so the streak logic never sees it. If you'd rather not subclass, make the extra-turn policy an object that sees the whole streak, a stateful strategy, instead of a predicate on one roll.

Testing Strategy

Test TypeWhat to Test
UnitBoard.addSnake() rejects head <= tail
UnitBoard.addLadder() rejects bottom >= top
UnitBoard.getFinalPosition() returns snake tail, ladder top, or same position
UnitPlayer.move() stays in place if roll exceeds board size
IntegrationPlayer lands on snake → position decreases
IntegrationPlayer lands on ladder → position increases
IntegrationPlayer rolls 6 → gets extra turn
IntegrationPlayer reaches exactly 100 → game finishes
DeterministicUse FixedDice to replay exact scenarios
describe('Game', () => {
  it('should move player down on snake', () => {
    const board = new Board(100);
    board.addSnake(50, 10);

    // Roll 50 on first turn (unrealistic with 1d6, but tests logic)
    const dice = new FixedDice([50]);
    const game = new Game(['Alice', 'Bob'], board, dice);

    const result = game.playTurn();
    expect(result.hitSnake).toBe(true);
    expect(result.newPosition).toBe(10);
  });

  it('should detect winner at position 100', () => {
    const board = new Board(10); // small board for testing
    const dice = new FixedDice([5, 1, 5]); // Alice: 5, Bob: 1, Alice: 5+5=10
    const game = new Game(['Alice', 'Bob'], board, dice);

    game.playTurn(); // Alice → 5
    game.playTurn(); // Bob → 1
    game.playTurn(); // Alice → 10 (wins)

    expect(game.getStatus()).toBe(GameStatus.FINISHED);
    expect(game.getWinner()?.name).toBe('Alice');
  });
});

Testing with injected randomness

The table above lists what to test. The design decides how. Because dice are injected, there are three kinds of test, and each needs a different dice:

  1. Scripted dice for rules. FixedDice(3, 5, 2) puts a player on a snake, a ladder or one short of the end on exactly the turn the test wants. These tests read like the rules: "ann rolls 3 and climbs to 15".
  2. Seeded dice for the dice. RandomDice(rng=random.Random(1)) gives the same 60,000 rolls every run, so you can assert that every face appears and that the counts are close to uniform. The bounds below are about six standard deviations wide, so with a fixed seed the test never flakes.
  3. Seeded dice for simulation. Play hundreds of seeded games and assert invariants: every game finishes within a turn cap, and the same seed always gives the same game. This catches unwinnable boards and infinite loops.

Unseeded randomness has one legitimate use in tests: a soak test that logs its seed, so any failure can be replayed.

# file: test_snakes_and_ladders.py
import random
import threading
import unittest
from collections import Counter

from snakes_and_ladders import Board, FixedDice, Game, GameStatus, Jump, RandomDice


def game(board: Board, *rolls: int, players=("ann", "bob")) -> Game:
    return Game(board, list(players), FixedDice(*rolls))


class BoardTest(unittest.TestCase):
    def test_rejects_boards_that_break_the_game(self):
        cases = [lambda b: b.snake(100, 5),          # a snake on the last cell: nobody can win
                 lambda b: b.snake(10, 20),          # a "snake" that goes up
                 lambda b: b.ladder(0, 5)]           # off the board
        for add in cases:
            self.assertRaises(ValueError, add, Board(100))

    def test_rejects_chains_and_therefore_cycles(self):
        self.assertRaises(ValueError, lambda: Board(100).snake(50, 20).ladder(20, 50))
        self.assertRaises(ValueError, lambda: Board(100).ladder(20, 50).ladder(50, 70))
        self.assertRaises(ValueError, lambda: Board(100).ladder(20, 50).snake(30, 20))


class RuleTest(unittest.TestCase):
    def test_snake_and_ladder(self):
        g = game(Board(20).ladder(3, 15).snake(17, 4), 3, 5, 2)
        self.assertEqual((g.play_turn().jump, g.position("ann")), (Jump.LADDER, 15))
        g.play_turn()                                  # bob to 5
        self.assertEqual((g.play_turn().jump, g.position("ann")), (Jump.SNAKE, 4))

    def test_overshoot_stays_and_exact_roll_wins(self):
        g = game(Board(10), 5, 1, 4, 1, 3, 1, 1)       # ann: 5, 9, 12 overshoots so 9, then 10
        for _ in range(5):
            g.play_turn()
        self.assertEqual(g.position("ann"), 9)
        g.play_turn()
        result = g.play_turn()
        self.assertTrue(result.won)
        self.assertEqual(g.winner, "ann")
        self.assertIs(g.status, GameStatus.FINISHED)
        self.assertRaises(RuntimeError, g.play_turn)

    def test_six_rolls_again_except_when_it_wins(self):
        g = game(Board(6), 6)
        self.assertFalse(g.play_turn().extra_turn)     # the six won, so no extra turn
        g = game(Board(30), 6, 2)
        self.assertTrue(g.play_turn().extra_turn)
        self.assertEqual(g.play_turn().player, "ann")

    def test_only_the_current_player_may_roll(self):
        g = game(Board(30), 2, 2)
        self.assertRaises(RuntimeError, g.play_turn, "bob")
        g.play_turn("ann")
        self.assertEqual(g.current_player, "bob")


class RandomnessTest(unittest.TestCase):
    def test_dice_are_in_range_and_roughly_uniform(self):
        dice = RandomDice(rng=random.Random(1))
        counts = Counter(dice.roll().total for _ in range(60_000))
        self.assertEqual(set(counts), {1, 2, 3, 4, 5, 6})
        for face, n in counts.items():
            self.assertTrue(9_400 < n < 10_600, (face, n))   # about 6 standard deviations

    def test_two_dice_sum_to_2_through_12(self):
        dice = RandomDice(2, 6, random.Random(3))
        totals = {dice.roll().total for _ in range(2_000)}
        self.assertEqual(totals, set(range(2, 13)))

    def test_same_seed_same_game(self):
        def history(seed):
            g = Game(Board.standard(), ["a", "b", "c"], RandomDice(rng=random.Random(seed)))
            g.play_to_end()
            return g.winner, [g.position(p) for p in "abc"]
        self.assertEqual(history(11), history(11))

    def test_many_seeded_games_all_finish(self):
        for seed in range(300):
            g = Game(Board.standard(), ["a", "b"], RandomDice(rng=random.Random(seed)))
            self.assertIn(g.play_to_end(max_turns=10_000), ("a", "b"))


class ConcurrencyTest(unittest.TestCase):
    def test_a_double_click_rolls_once(self):
        g, rolled, start = game(Board(30), *[2] * 8), [], threading.Barrier(8)

        def click():
            start.wait()
            try:
                g.play_turn("ann")
                rolled.append(1)
            except RuntimeError:
                pass

        threads = [threading.Thread(target=click) for _ in range(8)]
        for t in threads:
            t.start()
        for t in threads:
            t.join()
        self.assertEqual((len(rolled), g.position("ann"), g.current_player), (1, 2, "bob"))


if __name__ == "__main__":
    unittest.main()

Run with python -m unittest test_snakes_and_ladders. All 11 tests pass. Writing them turned up a classic bug in our own first draft: Counter(RandomDice(rng=random.Random(1)).roll().total for _ in range(60_000)) builds a new, identically seeded generator on every iteration, so it "rolls" the same number 60,000 times. Seed once, then reuse the generator.

For a sense of scale, we simulated 100,000 solo games on the standard board above (ignoring extra turns, seed 2026). A player needs 67 rolls on average, the median is 51, and the extremes were 7 and 746. Without any snakes or ladders, the same exact-finish rule needs about 33 rolls. Numbers like these make good sanity checks for a simulation test.

Common mistakes

  1. Calling the random generator inside the game. Math.random() in playTurn makes every rule untestable except by luck. Inject the dice, and inject the dice's generator.
  2. Re-seeding inside a loop. A new Random(seed) per roll returns the same number every time. Seed once per game or per test.
  3. A snake on the last cell. Landing on it sends you down, and nobody can ever win. Reject it when the board is built.
  4. Chained jumps. A snake whose tail is a ladder's foot either leaves the player standing on a ladder they didn't climb, or needs a loop that can cycle forever. Reject chains, or follow them with cycle detection.
  5. Forgetting the overshoot rule. Moving to 102 on a 100-cell board, or wrapping to 2. Decide between "stay" and "bounce back" with the interviewer, and test it.
  6. Giving an extra turn on a winning six. The game is over. Check the win first.
  7. A turn loop with no exit. while (!finished) playTurn() hangs a test forever if the board is unwinnable. Cap it.
  8. Trusting the client's roll in an online game.
  9. Two classes for snakes and ladders with the same fields and the same behaviour, differing only in direction.

Interview follow-ups

"How do you test a game that depends on dice?" Inject the dice. Scripted dice test the rules, seeded dice test the dice, and seeded simulations test that games always end. Nothing in the domain calls a random generator directly.

"What's the expected length of a game?" Model it as a Markov chain. The state is the cell, each roll moves to one of six next states with probability 1/6, and jumps redirect states. The expected number of rolls from each cell satisfies , with . That's a linear system you can solve exactly, or you can simulate, as we did above.

"Should the dice be a Singleton?" No. One shared generator couples every game's sequence to every other game's, and no test can control it.

"Real money is involved. What changes?" Use a cryptographically secure generator (SecureRandom, Python's secrets, crypto.getRandomValues), roll on the server, and log every roll with the game and turn number for audit. The injection point stays the same.

"How would you add undo?" Store TurnResults. Each records from and to, and whether the turn advanced, so undoing a turn restores the position and the current player. With the extra-turn rule you also restore whose turn it was, which the result already implies.

"Why does TurnResult record landed as well as to?" A UI animates the token to the landing cell and then down the snake. A log needs both to explain what happened. And it makes tests precise: "landed on 9, slid to 2".

Further Reading