LOW LEVEL DESIGN · MACHINE CODING · EASY · 11 OF 42

Design Snakes and Ladders: Machine Coding in Java

A favourite machine coding round, designed and coded: requirements, a board built and validated by a Builder, snakes and ladders as one Jump type, dice and finish rules as Strategies, a turn queue, an Observer for moves, turn checks for online play, and how the same model stretches to tic-tac-toe and the snake game, with a full Java 17 solution.

Patterns usedObserverStrategyBuilder

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
1 / 19

Press play to hear the narration, or step through at your own pace. The full Java code is below.

Full Java solution

One file, Java 17, 247 lines, with a small main() demo. Save it as SnakesAndLadders.java, then run javac SnakesAndLadders.java && java SnakesAndLadders.

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

/** Multiplayer snakes and ladders: a configurable board, pluggable dice and finish rules, strict turns. */
public class SnakesAndLadders {

    // ---------- the model ----------
    record Player(String name) {}

    /** A snake goes down (to is smaller), a ladder goes up. One type: the board treats both the same. */
    record Jump(int from, int to) {
        boolean isSnake() { return to < from; }

        @Override
        public String toString() { return from + " to " + to; }
    }

    enum Status { IN_PROGRESS, FINISHED }

    record Move(Player player, int roll, int from, int to, String via) {}

    /** Immutable board: built once, validated once, shared freely between games. */
    static final class Board {
        final int size;
        private final Map<Integer, Integer> jumps;

        private Board(int size, Map<Integer, Integer> jumps) {
            this.size = size;
            this.jumps = Map.copyOf(jumps);
        }

        /** Where a token ends up after landing on cell c (follows a chain of jumps). */
        int resolve(int c) {
            int cell = c;
            while (jumps.containsKey(cell)) cell = jumps.get(cell);
            return cell;
        }

        Integer jumpFrom(int c) { return jumps.get(c); }

        static Builder builder(int size) { return new Builder(size); }

        /** Builder: add snakes and ladders, then build() checks every rule before the board exists. */
        static final class Builder {
            private final int size;
            private final Map<Integer, Integer> jumps = new LinkedHashMap<>();

            Builder(int size) {
                if (size < 10) throw new IllegalArgumentException("board too small");
                this.size = size;
            }

            Builder snake(int head, int tail) { return add(new Jump(head, tail), true); }

            Builder ladder(int bottom, int top) { return add(new Jump(bottom, top), false); }

            private Builder add(Jump j, boolean snake) {
                if (j.isSnake() != snake || j.from() == j.to())
                    throw new IllegalArgumentException("bad direction " + j);
                if (j.from() <= 1 || j.from() >= size || j.to() < 1 || j.to() > size)
                    throw new IllegalArgumentException("out of range " + j);
                if (jumps.putIfAbsent(j.from(), j.to()) != null)
                    throw new IllegalArgumentException("two jumps start at " + j.from());
                return this;
            }

            Board build() {
                for (int start : jumps.keySet()) { // walking a chain must never loop
                    Set<Integer> seen = new HashSet<>();
                    int cell = start;
                    while (jumps.containsKey(cell))
                        if (!seen.add(cell)) throw new IllegalArgumentException("jump cycle at " + start);
                        else cell = jumps.get(cell);
                }
                return new Board(size, jumps);
            }
        }
    }

    // ---------- strategies ----------
    interface Dice { int roll(); }

    /** n dice with f faces; a seeded Random makes a game replayable. */
    record RandomDice(int count, int faces, Random rnd) implements Dice {
        public int roll() {
            int sum = 0;
            for (int i = 0; i < count; i++) sum += 1 + rnd.nextInt(faces);
            return sum;
        }
    }

    /** Scripted dice for tests: the same rolls every run. */
    static final class FixedDice implements Dice {
        private final Deque<Integer> rolls;

        FixedDice(int... rolls) {
            this.rolls = new ArrayDeque<>();
            for (int r : rolls) this.rolls.add(r);
        }

        public int roll() { return rolls.remove(); }
    }

    /** What happens when a roll overshoots the last cell. */
    interface FinishRule { int land(int pos, int roll, int last); }

    static final FinishRule EXACT = (pos, roll, last) -> pos + roll > last ? pos : pos + roll;
    static final FinishRule BOUNCE = (pos, roll, last) -> {
        int t = pos + roll;
        return t > last ? last - (t - last) : t;
    };

    interface GameListener { void onMove(Move m); }

    // ---------- the game ----------
    private final Board board;
    private final Dice dice;
    private final FinishRule finish;
    private final Deque<Player> turns = new ArrayDeque<>();
    private final Map<Player, Integer> position = new HashMap<>();
    private final List<GameListener> listeners = new ArrayList<>();
    private Status status = Status.IN_PROGRESS;
    private Player winner;

    SnakesAndLadders(Board board, Dice dice, FinishRule finish, List<Player> players) {
        if (players.size() < 2) throw new IllegalArgumentException("need at least two players");
        this.board = board;
        this.dice = dice;
        this.finish = finish;
        for (Player p : players) {
            turns.addLast(p);
            position.put(p, 0); // 0 = off the board
        }
    }

    void subscribe(GameListener l) { listeners.add(l); }

    /** One turn. synchronized + a whose-turn check: a second click or a stale client cannot move twice. */
    synchronized Move play(Player who) {
        if (status == Status.FINISHED)
            throw new IllegalStateException("game over, " + winner.name() + " won");
        Player p = turns.peekFirst();
        if (!p.equals(who)) throw new IllegalStateException("not " + who.name() + "'s turn");
        int roll = dice.roll();
        int from = position.get(p);
        int landed = finish.land(from, roll, board.size);
        Integer jump = board.jumpFrom(landed);
        int to = board.resolve(landed);
        String via = jump == null ? "" : (jump < landed ? "snake" : "ladder");
        position.put(p, to);
        turns.addLast(turns.removeFirst());
        if (to == board.size) {
            status = Status.FINISHED;
            winner = p;
        }
        Move m = new Move(p, roll, from, to, via);
        for (GameListener l : listeners) l.onMove(m);
        return m;
    }

    synchronized Player current() { return turns.peekFirst(); }

    synchronized Status status() { return status; }

    synchronized Player winner() { return winner; }

    synchronized int positionOf(Player p) { return position.get(p); }

    // ---------- demo ----------
    static Board classicBoard() {
        return Board.builder(100)
                .ladder(4, 14).ladder(9, 31).ladder(21, 42).ladder(28, 84).ladder(51, 67).ladder(72, 91)
                .snake(17, 7).snake(54, 34).snake(62, 19).snake(87, 36).snake(95, 75).snake(98, 79)
                .build();
    }

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

    public static void main(String[] args) {
        Board board = classicBoard();
        Player host = new Player("Host"), guest = new Player("Guest");

        // 1. A scripted game: ladder, snake, then an exact finish.
        SnakesAndLadders g = new SnakesAndLadders(board,
                new FixedDice(4, 6, 6, 5, 1, 6, 6, 2, 3, 3, 5, 4, 6, 5, 5, 1, 3),
                EXACT, List.of(host, guest));
        g.subscribe(m -> System.out.println(m.player().name() + " rolls " + m.roll() + ": " + m.from()
                + " -> " + m.to() + (m.via().isEmpty() ? "" : " " + m.via())));
        while (g.status() == Status.IN_PROGRESS) g.play(g.current());
        System.out.println("Winner: " + g.winner().name());
        check(g.winner().equals(host), "host should win the scripted game");

        // 2. Turns are enforced.
        SnakesAndLadders t = new SnakesAndLadders(board, new FixedDice(3, 3), EXACT, List.of(host, guest));
        try {
            t.play(guest);
            throw new AssertionError("guest moved out of turn");
        } catch (IllegalStateException e) {
            System.out.println("Rejected: " + e.getMessage());
        }

        // 3. Finish rules: from 97 a roll of 5 stays (exact) or bounces back to 98, then a snake to 79.
        check(EXACT.land(97, 5, 100) == 97, "exact finish should stay");
        check(board.resolve(BOUNCE.land(97, 5, 100)) == 79, "bounce should hit the snake at 98");
        System.out.println("Finish rules: exact stays at 97, bounce lands on 98 and slides to 79");

        // 4. Bad boards never get built.
        for (Runnable bad : List.<Runnable>of(
                () -> Board.builder(100).snake(100, 5).build(),
                () -> Board.builder(100).ladder(10, 20).snake(20, 10).build(),
                () -> Board.builder(100).ladder(30, 10).build())) {
            try {
                bad.run();
                throw new AssertionError("invalid board accepted");
            } catch (IllegalArgumentException e) {
                System.out.println("Invalid board: " + e.getMessage());
            }
        }

        // 5. Random games with four players always finish.
        List<Player> four = List.of(new Player("Red"), new Player("Blue"), new Player("Green"),
                new Player("Yellow"));
        int maxTurns = 0;
        for (int seed = 0; seed < 200; seed++) {
            Dice dice = new RandomDice(1, 6, new Random(seed));
            SnakesAndLadders r = new SnakesAndLadders(board, dice, BOUNCE, four);
            int turnsTaken = 0;
            while (r.status() == Status.IN_PROGRESS) {
                r.play(r.current());
                check(++turnsTaken < 10_000, "game did not end");
            }
            check(r.positionOf(r.winner()) == 100, "winner must be on 100");
            maxTurns = Math.max(maxTurns, turnsTaken);
        }
        System.out.println("200 random 4-player games finished, longest took " + maxTurns + " turns");
    }
}

Notes

Requirements

Start with the rules. The board has N cells, a hundred by default. Snakes take you down, ladders take you up. Two or more players take turns: roll the dice, move forward, follow any snake or ladder you land on. The first player to reach the last cell wins. The board size, the snakes, the ladders and the dice must all be configurable. Graphics and chat are out of scope.

Clarify the edge cases, because each one becomes a rule. What if a roll goes past the last cell? Usually you stay put; some houses bounce back. One die or two? Configurable. Can a ladder end on a snake's head? Yes, follow the chain, but never in a loop. Does the game stop at the first winner? Yes for now; full rankings are an extension. An extra turn on a six? Not now, but the design should make it easy.

Requirements
  • board of N cells, default 100
  • snakes take you down,
  • ladders take you up
  • two or more players, in turns
  • roll the dice, move, follow
  • any snake or ladder
  • first to the last cell wins
  • board size, snakes, ladders,
  • dice: all configurable
  • out of scope: graphics, chat
Clarify first
  • roll past the last cell?
  • stay put (or bounce back)
  • one die or two?
  • configurable
  • snake head on a ladder top?
  • allowed, follow the chain
  • game ends at first winner?
  • yes; ranking is an extension
  • extra turn on a six?
  • not now, easy to add

Entities

Underline the nouns: game, board, snake, ladder, player, dice. One insight simplifies everything: a snake and a ladder are the same thing, a jump from one cell to another. A snake goes down and a ladder goes up, but the board treats both identically, so they become a single Jump type. The game owns the board, the players' positions, a turn queue and the dice.

Class diagram

In code, the small things are records. A player is a name. A jump is a from and a to, and it knows it is a snake when it goes down. A move records who rolled what, where they started, where they ended and whether a snake or ladder was involved, which is perfect for a replay log. Positions live in the game as a map from player to cell, with zero meaning not on the board yet.

Value types
record Player(String name)
record Jump(int from, int to) {
  boolean isSnake() { return to < from; }
}
enum Status { IN_PROGRESS, FINISHED }
record Move(Player p, int roll,
            int from, int to, String via)

positions: Map<Player, Integer>
  0 means not on the board yet

Builder: the board

The board uses the Builder pattern. You add ladders and snakes fluently, and build checks every rule before a board exists: no jump may start on the first or last cell, a ladder must go up and a snake down, one cell has at most one jump, and following jumps must never loop forever. After build, the board is immutable, so many games can share one board safely.

Board.builder(100)
.ladder(4, 14).ladder(28, 84)
.snake(17, 7).snake(98, 79)
.build()

rejected while building:
  jump starts on cell 1 or the last
  ladder that goes down
  two jumps from one cell
  a cycle: 10 up to 20, 20 down to 10
Board is immutable after build()

Strategy: dice

Dice is a Strategy with one method, roll. RandomDice takes the number of dice, the faces, and a Random, so a seeded Random gives a replayable game. FixedDice returns a scripted list of rolls, which is how you write a test that proves a ladder or a win happens exactly when expected. Mentioning that testability is the reason for the interface scores easy points.

Dice
interface Dice { int roll(); }

record RandomDice(int count, int faces,
                  Random rnd)
  sum of count rolls of 1..faces

FixedDice(4, 6, 6, 5, ...)
  returns a scripted sequence

loaded dice, crooked dice: new class

Strategy: finishing

What happens when you overshoot the last cell differs from house to house, so it is a second strategy. The exact rule keeps you where you are. The bounce rule walks you back by the overshoot. From ninety-seven, a five keeps you on ninety-seven with the exact rule, but bounces you to ninety-eight with the other, straight onto a snake. The game does not care which rule it was given.

FinishRule
interface FinishRule {
  int land(int pos, int roll, int last);
}
EXACT: pos + roll > last ? pos
                          : pos + roll
BOUNCE: overshoot by k, go back k

from 97 roll 5:
  EXACT stays on 97
  BOUNCE lands on 98, snake to 79

Turns

Turn order is a double-ended queue. The current player is at the head. After a move, take them off the front and put them at the back. That one structure makes the usual extensions trivial: an extra turn on a six means simply not rotating, a player who leaves is removed from the queue, and a reverse-order rule walks the other way.

Turn queue
Deque<Player> turns

current = turns.peekFirst()
after a move:
  turns.addLast(turns.removeFirst())

extra turn on a six: skip the rotate
player leaves: remove from the deque
reverse order card: iterate backwards

Flow: a turn

Walk one turn. Reject the call if the game is over or it is not this player's turn. Roll the dice, ask the finish rule where the token lands, then ask the board to resolve any snakes and ladders, following a chain if one jump ends on another. Store the new position, rotate the queue, and if the player reached the last cell, mark the game finished. Finally notify listeners and return the move.

play(player)
if finished: throw game over
if player != turns.peek: throw
roll = dice.roll()
landed = finish.land(pos, roll, size)
to = board.resolve(landed)
positions.put(player, to)
rotate the turn queue
if to == size: FINISHED, winner
notify listeners with the Move
return the Move

Flow: winning

Winning is a single comparison after jumps are applied, because a ladder could carry you straight onto the last cell. Here is the scripted game from the demo: the host climbs four ladders, rolls a five from ninety-seven and stays put under the exact rule, then rolls the three needed to win. After that, any call to play throws, so a late click cannot move a token in a finished game.

A scripted game
  • Host 4: 0 to 14 ladder
  • Guest 6: 11 to 7 snake
  • Host 1: 20 to 42 ladder
  • Host 3: 48 to 67 ladder
  • Host 5: 67 to 91 ladder
  • Host 6: 91 to 97
  • Host 5: 97 to 97 (overshoot)
  • Host 3: 97 to 100, wins
  • any later play() throws

Observer

The game should not print anything or draw anything itself. Instead it publishes each move to listeners: the Observer pattern. The console view, a graphical board, a replay log and a statistics counter all subscribe the same way. The demo prints every move through a listener, and a test could subscribe a list and assert the exact sequence of moves.

Concurrency

In a single process with one keyboard there is no concurrency, so say that. Online is different: two requests can arrive for the same game at once, or the same player can double click. Make play synchronized on the game and check whose turn it is inside the lock, so the second request is rejected. Different games have different locks and never wait on each other, and the immutable board is shared freely.

Online, many games
  • play() is synchronized per game
  • games never block each other
  • whose-turn check inside the lock:
  • a double click is rejected
  • or: one single-threaded actor
  • per game, moves in a queue
  • board is immutable: shared
  • safely by every game

Extensibility

Interviewers will add rules. An extra turn on a six, cancelled on the third six in a row, is a counter and a skipped rotate. Full rankings mean removing winners from the queue and playing on. Special cells, like a skip-a-turn square, generalise Jump into a cell effect. Saving a game is the positions, the queue and the move log. Each change lands in one class.

Extension points
  • extra turn on a six: skip
  • the rotate, cap at three
  • full rankings: keep playing,
  • remove winners from the queue
  • power-ups, special cells: a
  • CellEffect per cell
  • bigger board: builder args
  • save and resume: positions +
  • queue + the Move log

Other games

The same skeleton fits other board games. Tic-tac-toe keeps the players and the turn queue, swaps the board for an N by N grid and the move for a row and column, and checks a win in constant time by counting marks per row, column and diagonal. The snake game has no turns, just a tick loop: the snake is a deque of cells, each tick adds a head and drops the tail unless food was eaten, and you lose when the head hits a wall or the body.

Same model, other games
  • tic-tac-toe:
  • Board = N x N grid of symbols
  • Move = (row, col), no dice
  • win: track row, col, diagonal
  • counts, O(1) per move
  • snake game:
  • no turns, a tick loop instead
  • snake = deque of cells
  • move: add head, drop tail
  • unless food was eaten
  • lose: head hits wall or body

Testing

The full code is below the player. Scripted dice drive a complete game and assert the host wins. Then it checks a guest cannot move out of turn, both finish rules on the same position, and three broken boards that the builder refuses. Finally two hundred seeded random games with four players all finish, the longest taking three hundred and twenty eight turns, with the winner on the last cell every time.

Run it
Host rolls 4: 0 -> 14 ladder
Guest rolls 6: 11 -> 7 snake
Host rolls 3: 97 -> 100
Winner: Host
Rejected: not Guest's turn
Invalid board: out of range 100 to 5
Invalid board: jump cycle at 10
200 random 4-player games finished,
  longest took 328 turns

Follow-ups

Expect follow-ups. Why not separate snake and ladder classes? They have identical behaviour, so one type avoids duplication. How do you prevent loops? Walk every chain at build time. How do you test randomness? Inject the dice and seed it. The expected length of a game is a Markov chain over the cells. And a million concurrent games means the game state lives in a store keyed by game id, with one writer per game.

Follow-ups to expect
  • why one Jump, not Snake + Ladder?
  • how do you stop jump loops?
  • how would you test randomness?
  • inject Dice, seed the Random
  • expected game length?
  • a Markov chain over cells
  • million games at once?
  • stateless service, game state
  • in a store keyed by game id

Say it like this

The short version to say out loud. A board, built and validated by a builder, holds jumps, because snakes and ladders are one type. Dice and the finish rule are strategies, so tests can script them. Turns rotate through a deque, every move is published to observers, and play checks whose turn it is under a per-game lock.

In the interview
  • "A Board built and validated by
  • a Builder holds Jumps: snakes
  • and ladders are one type. Dice
  • and the finish rule are
  • strategies, turns are a deque,
  • moves go to observers, and play
  • checks whose turn it is under
  • a per-game lock."

Interview questions

Why model snakes and ladders as one Jump type?

Both move a token from one cell to another; only the direction differs. One record with from and to removes duplicate code, and isSnake() is a derived property. The board resolves any landing cell the same way.

How do you make sure the board configuration is valid?

A Builder collects snakes and ladders and validates in build(): jumps stay inside the board and never start on the first or last cell, ladders go up and snakes down, one jump per cell, and walking every chain must not revisit a cell. The resulting Board is immutable.

Why is Dice an interface?

So the rule can change (two dice, loaded dice) without touching Game, and so tests can inject a FixedDice with scripted rolls or a RandomDice with a seeded Random. Deterministic rolls make every rule testable.

How do you handle a roll that overshoots the last cell?

A FinishRule strategy decides: the exact rule keeps the token in place, the bounce rule moves it back by the overshoot. The game calls finish.land(pos, roll, last) and then resolves jumps, so a bounce can still land on a snake.

How are turns managed?

An ArrayDeque of players: the head is the current player, and after a move it is moved to the back. An extra turn means not rotating, and a player leaving is a removal. play() rejects calls from anyone who is not at the head.

What changes for an online multiplayer version?

Requests for one game can race, so play() is synchronized per game (or each game is a single-threaded actor) and the whose-turn check happens inside the lock. Different games never contend, and the immutable board is shared across games.

How does the same design extend to tic-tac-toe?

Keep players, the turn queue and the observer; replace the board with an N x N grid and a move with a cell. Track counts per row, column and both diagonals so each move checks for a win in O(1).

How would you design the snake game with the same ideas?

It is tick based, not turn based. The snake is a deque of cells plus a set for O(1) collision checks; each tick adds a new head and removes the tail unless food was eaten, and the game ends when the head hits a wall or the body.