LLD

Full Designs

Snake and Ladder

The rules fit on the back of the box, so the interview is about everything around them: a board that is data and is checked before anyone plays, a die that a test can control, house rules that differ from family to family, and an online game where one roll request can arrive twice.

"Design snake and ladder" sounds like a children's game, and a weak answer treats it like one. It hard-codes a 100-cell array, writes Snake and Ladder classes with a move() each, calls Math.random() inside the game loop, and has one while loop that asks each player in turn. The game runs. Nothing about it can be tested, configured or played over a network.

The interviewer is checking whether the design survives its follow-ups. Some families need an exact roll to finish, and others bounce back. Three sixes in a row costs the turn. A board that a designer typed in can contain a mistake. The game moves to a server, where two phones ask to roll at the same moment. Each of these breaks a different part of the weak answer.

This article walks through the question the way a 45 minute interview goes. We ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.

One roll at a glance
Ravi's phone sends roll("Ravi") (1). Inside the game's lock, Game checks that it is Ravi's turn and asks its Die for a number (2). The FinishRule says which cell the roll reaches (3), and the Board moves the token along a snake or a ladder if one starts there (4): Ravi's 4 lands on the ladder at 4 and climbs to 25. The phone gets back a TurnResult (5).Ravi's phone sends roll("Ravi") (1). Inside the game's lock, Game checks that it is Ravi's turn and asks its Die for a number (2). The FinishRule says which cell the roll reaches (3), and the Board moves the token along a snake or a ladder if one starts there (4): Ravi's 4 lands on the ladder at 4 and climbs to 25. The phone gets back a TurnResult (5).
A roll arrives as a call. The game checks the turn, rolls its own die and moves the token, all under one lock. Ravi's phone sends roll("Ravi") (1). Inside the game's lock, Game checks that it is Ravi's turn and asks its Die for a number (2). The FinishRule says which cell the roll reaches (3), and the Board moves the token along a snake or a ladder if one starts there (4): Ravi's 4 lands on the ladder at 4 and climbs to 25. The phone gets back a TurnResult (5).

Ask before you design

The question is vague on purpose, and each answer below changes the code. The right-hand column says how.

QuestionWhat we assumeWhat it changes
Only the 100-cell board?Any board from 10 to 1,000 cellsThe size is a constructor argument
Where are the snakes and ladders?Given as data when the board is builtThe board takes a list of jumps and checks it
How many players?Two to six, playing in a fixed orderA list of names and a turn index
What dice?One six-sided die; the game must be repeatableThe die is an interface, with a seeded and a scripted one
Do you need an exact roll to finish?It depends on the house; both rules are neededAn interface for the finishing rule
Does a six give another turn?Yes, and three sixes in a row end the turnTwo numbers kept per turn
Can two tokens share a cell?Yes, nothing happens when they meetNo capture logic
How do rolls arrive?From phones, through a server, as callsThe game answers calls; it does not run a loop
Who rolls the die: the phone or the server?The serverThe game rolls, and the caller only asks

The last row matters most. If a phone sends the number it rolled, a player can send a 6 every time. The game rolls the die itself, so the caller can only ask for a roll, and a test can still decide what the die shows.

Requirements

Functional:

  1. A board has N cells, numbered 1 to N, and any number of snakes and ladders. A board that breaks one of the rules below is refused when it is built, and so is a game whose last cell no run of rolls can reach.
  2. Two to six players take turns in a fixed order. Every token starts off the board, at 0.
  3. A roll moves the token forward by the number rolled. Landing on the foot of a ladder or the head of a snake moves it to the other end.
  4. The finishing rule is chosen per game: either a roll past the last cell is lost, or it bounces back off the last cell.
  5. Under the classic rules, a six gives another roll, and the third six in a row ends the turn and puts the token back where the turn started.
  6. The first token to reach the last cell wins, and the game ends.
  7. A request to roll out of turn, by an unknown player, or after the game has ended is refused, and nothing changes.
  8. A game can be played again exactly, from its seed or from its recorded rolls.

Out of scope: playing on for second place, capturing a token, a time limit per turn, and saving a game. We come back to these at the end as follow-ups.

Everything lives in memory, as is normal for a low-level design interview.

What the code itself must handle:

  • Two threads at once. Roll requests arrive from several phones, and one phone can send the same request twice.
  • Rules that change. The finishing rule differs from house to house, and so does the rule on sixes.
  • Testable. A test must be able to say exactly what the die rolls.

Finding the classes

From nouns to classes
Game, board, die, the finishing rule, the rule on sixes, a roll that was played and the answer to a request are kept. A snake and a ladder become one Jump record, with a JumpKind enum. Player, token, cell, turn and a score across games are crossed out: a player is a name plus whoever calls roll(), a token is an int in the game's positions, a cell is a number, a turn is one field of Game, and a score across games is out of scope.Game, board, die, the finishing rule, the rule on sixes, a roll that was played and the answer to a request are kept. A snake and a ladder become one Jump record, with a JumpKind enum. Player, token, cell, turn and a score across games are crossed out: a player is a name plus whoever calls roll(), a token is an int in the game's positions, a cell is a number, a turn is one field of Game, and a score across games is out of scope.
Snakes and ladders become one record. The player, the token and the cell become a name and two numbers. Game, board, die, the finishing rule, the rule on sixes, a roll that was played and the answer to a request are kept. A snake and a ladder become one Jump record, with a JumpKind enum. Player, token, cell, turn and a score across games are crossed out: a player is a name plus whoever calls roll(), a token is an int in the game's positions, a cell is a number, a turn is one field of Game, and a score across games is out of scope.

A player is not a class here, for the same reason as on the Tic-Tac-Toe page: a roll arrives as a call to roll(name), so the game never waits for anyone. The nouns that need thought are the snake and the ladder.

Decision

Should a snake and a ladder be two classes?

A Snake class and a Ladder class, each with its own move()

This is the shape most drawings start with. The two classes hold the same two numbers and do the same thing: move a token from one cell to another. The only difference is the direction, and a class per direction means two places to check, store and look up.

One Jump record with from and to; the direction says which it isOur pick

A jump that goes up is a ladder, and a jump that goes down is a snake. The board stores one map from a starting cell to a jump, and a token's move does one lookup whatever the kind. kind() answers the question when a screen needs to draw the right picture.

board/Jump.javalines 7–20 of 20
public record Jump(int from, int to) {    public Jump {        if (from < 1 || to < 1) {            throw new IllegalArgumentException("A jump starts and ends on a cell numbered from 1, not " + from + " to " + to);        }        if (from == to) {            throw new IllegalArgumentException("A jump from " + from + " must go somewhere");        }    }     public JumpKind kind() {        return to > from ? JumpKind.LADDER : JumpKind.SNAKE;    }}

Data or behaviour?

Some classes only carry data: a jump, a roll that was played, the house rules on sixes, and the answer to a request. In Java these are records: classes whose fields are fixed when they are created, with equals, hashCode and toString written for us. Fixed sets of values are enums: JumpKind and Outcome.

game/Move.javalines 9–17 of 17
public record Move(String player, int roll, int from, int landed, int to) {    public Move {        Objects.requireNonNull(player, "player");    }     public boolean tookAJump() {        return landed != to;    }}

A Move records where the roll took the token (landed) and where it ended (to). The two differ only when a snake or a ladder started on the cell it landed on.

The class diagram

The classes and how they connect
Game uses a Board, a Die, a FinishRule and TurnRules, and owns its list of moves. The Board owns its jumps. SeededDie and ScriptedDie implement Die. ExactFinish and BounceBack implement FinishRule. Game creates a TurnResult for every request. Move, Jump, TurnResult and TurnRules are records; JumpKind and Outcome are enums.Game uses a Board, a Die, a FinishRule and TurnRules, and owns its list of moves. The Board owns its jumps. SeededDie and ScriptedDie implement Die. ExactFinish and BounceBack implement FinishRule. Game creates a TurnResult for every request. Move, Jump, TurnResult and TurnRules are records; JumpKind and Outcome are enums.
Game coordinates. The die and the finishing rule are interfaces it is given. Game uses a Board, a Die, a FinishRule and TurnRules, and owns its list of moves. The Board owns its jumps. SeededDie and ScriptedDie implement Die. ExactFinish and BounceBack implement FinishRule. Game creates a TurnResult for every request. Move, Jump, TurnResult and TurnRules are records; JumpKind and Outcome are enums.

The classes fall into three groups:

  • Data: Jump, Move, TurnResult, TurnRules, JumpKind and Outcome. These are records and enums.
  • The core: Game and its Board. The board never changes once built. The game holds the positions, the turn and the moves, and keeps them correct under many threads.
  • Rules and outside systems: Die, for something the game cannot control, and FinishRule, for a rule that changes from house to house. Each has two implementations.

Building it

A board that is checked once

A board is a size and a list of jumps. The constructor checks the list before anything else can use it.

board/Board.javalines 23–49 of 71
    public Board(int size, List<Jump> jumps) {        if (size < MIN_SIZE || size > MAX_SIZE) {            throw new IllegalArgumentException("A board has " + MIN_SIZE + " to " + MAX_SIZE + " cells, not " + size);        }        Objects.requireNonNull(jumps, "jumps");        Map<Integer, Jump> byStart = new HashMap<>();        for (Jump jump : jumps) {            Objects.requireNonNull(jump, "jump");            if (jump.from() > size || jump.to() > size) {                throw new IllegalArgumentException("The jump " + jump.from() + " to " + jump.to() + " leaves a board of " + size + " cells");            }            if (jump.from() == size) {                throw new IllegalArgumentException("Nothing can start on the last cell, " + size);            }            if (byStart.putIfAbsent(jump.from(), jump) != null) {                throw new IllegalArgumentException("Two jumps start at cell " + jump.from());            }        }        // A jump that ends where another starts would chain, and chains are how cycles form.        for (Jump jump : byStart.values()) {            if (byStart.containsKey(jump.to())) {                throw new IllegalArgumentException("The jump " + jump.from() + " to " + jump.to() + " ends where another jump starts");            }        }        this.size = size;        this.jumpsByStart = Map.copyOf(byStart);    }

Notice what it refuses, and why each rule exists:

  • A jump that leaves the board (line 31). A ladder to cell 120 on a 100-cell board would put a token nowhere.
  • A jump from the last cell (line 34). A snake on cell 100 would take the win away from the player who reached it.
  • Two jumps from one cell (line 37). The map would keep one and quietly drop the other.
  • A jump that ends where another starts (line 43). A ladder from 10 to 30 with a snake at 30 is a chain. A token would need two moves for one roll, and two jumps that point at each other's start would form a loop with no end. Refusing chains rules out loops too.

The Jump record checks its own two numbers: each must be 1 or more, and they must differ. Once the constructor finishes, the board is a fixed map, so it needs no lock and many games can share one board.

Decision

When is a bad board caught?

When a token lands on the bad cell

The game would follow jumps until it stops on a plain cell, and complain if it finds a loop. The mistake then shows up in the middle of a game, as a crash that a player sees, long after the designer typed it.

When the board is built, in the constructorOur pick

Every rule is checked once, before a single roll. A board that passes needs no checks during play: landingOn is one map lookup, because a jump's end is never another jump's start. The cost is that the board must be fully known up front, which it is. These checks catch broken boards, not every typing mistake: a ladder typed the wrong way round is a valid snake.

A mistake in a board is a programmer's or a designer's mistake, so the constructor throws IllegalArgumentException with a message that names the jump. Players never see these. A refused request to roll is different, and it comes back as an answer, as we see below.

board/Board.javalines 55–59 of 71
    /** Where a token that lands on this cell ends up: the jump's end, or the cell itself. */    public int landingOn(int cell) {        Jump jump = jumpsByStart.get(cell);        return jump == null ? cell : jump.to();    }

A die the test can control

The game needs random numbers, but a test needs to know what was rolled. Die is an interface with two methods.

dice/Die.javalines 7–13 of 13
public interface Die {    /** The number of faces. A roll is 1 to faces. */    int faces();     /** One roll, from 1 to faces. */    int roll();}

SeededDie wraps a java.util.Random made from a seed, so the same seed gives the same rolls. ScriptedDie rolls a fixed list, in order, and throws once the list runs out.

dice/ScriptedDie.javalines 29–35 of 36
    @Override    public int roll() {        if (next == rolls.size()) {            throw new IllegalStateException("The script has no rolls left after " + rolls.size());        }        return rolls.get(next++);    }
Decision

Who rolls the die?

The phone rolls and sends the number

The server would trust whatever number arrived. A changed app could send a 6 every time, and nothing on the server could tell. Replaying a game would also need the phones.

The game calls Math.random() itself

The server is in charge, but nothing outside the game can decide the roll. A test of "three sixes in a row" would have to try seeds until one happened to roll three sixes.

The game rolls through a Die it is givenOur pick

The server owns the roll, and the caller can only ask for one. A real game gets a SeededDie; a test or a replay gets a ScriptedDie and says exactly what happens. The cost is one interface and two small classes.

The die is like a clock: something outside the code that the design takes through its constructor, so a test can stand in for it.

Where the tokens live

Game holds the state of one game in a few fields.

game/Game.javalines 27–42 of 221
    private final Object lock = new Object();    private final Board board;    private final List<String> players;    private final Map<String, Integer> seatOf;    private final Die die;    private final int faces;    private final FinishRule finishRule;    private final TurnRules rules;    private final int[] positions;    private final List<Move> moves = new ArrayList<>();    private int current;    private int sixesInARow;    private int turnStart;    private String winner;    /** True while the die or the finish rule runs, so one that calls back into the game is refused. */    private boolean rolling;

positions is an array in turn order, and seatOf maps a name to its index. current is the index of the player whose roll it is. sixesInARow and turnStart serve the rule on sixes.

Decision

Where do the players' positions live?

A Player object for each player, holding its own position

Each Player would have a position field and a move() method. The turn, the sixes and the winner would still live in Game, so one roll would change two objects, and both would need the same lock to stay in step.

In Game, in an array in turn orderOur pick

Everything one roll changes sits in one object, behind one lock. A player is a name, and seatOf turns the name into an index. The cost is that a screen asks the game for positions instead of asking a player, which positions() answers with a copy.

The constructor checks the setup before the game exists.

game/Game.javalines 44–73 of 221
    public Game(Board board, List<String> players, Die die, FinishRule finishRule, TurnRules rules) {        this.board = Objects.requireNonNull(board, "board");        Objects.requireNonNull(players, "players");        if (players.size() < MIN_PLAYERS || players.size() > MAX_PLAYERS) {            throw new IllegalArgumentException("A game has " + MIN_PLAYERS + " to " + MAX_PLAYERS + " players, not " + players.size());        }        Map<String, Integer> seats = new HashMap<>();        for (int seat = 0; seat < players.size(); seat++) {            String name = Objects.requireNonNull(players.get(seat), "player");            if (name.isBlank()) {                throw new IllegalArgumentException("A player needs a name");            }            if (seats.putIfAbsent(name, seat) != null) {                throw new IllegalArgumentException("Two players are called " + name);            }        }        this.die = Objects.requireNonNull(die, "die");        this.faces = die.faces();        if (faces < 2 || faces >= board.lastCell()) {            throw new IllegalArgumentException("A die of " + faces + " faces needs 2 or more faces and a board of more cells");        }        this.finishRule = Objects.requireNonNull(finishRule, "finishRule");        this.rules = Objects.requireNonNull(rules, "rules");        if (!canReachTheEnd(board, faces, finishRule, rules)) {            throw new IllegalArgumentException("No run of rolls reaches cell " + board.lastCell() + " on this board");        }        this.players = List.copyOf(players);        this.seatOf = Map.copyOf(seats);        this.positions = new int[players.size()];    }

It refuses fewer than two or more than six players, a blank name, and two players with the same name, because seatOf would then send both players' requests to one seat. It also refuses a die that is not smaller than the board. That rule keeps a bounce inside the board. A roll can overshoot the last cell by at most one less than the number of faces, so the bounce never goes below cell 1. The last check (line 67) is a search. From cell 0, it tries every roll, follows the finishing rule and any jump, and stops once some run of rolls reaches the last cell. It follows the rule on sixes too. It tracks how many sixes the turn has had, and skips the six that would end the turn, because that six moves the token back. Take a 10-cell board where every cell from 4 to 9 is the head of a snake to 1. It passes the board's own rules, but with a six-sided die no game on it could end. The search visits each cell once for each count of sixes and tries each face from there. It costs about cells × the limit on sixes × faces steps, once per game. A finishing rule that answers a cell off the board is refused here too, with the same message as during play.

game/Game.javalines 176–213 of 221
    /**     * Whether some run of rolls takes a token from 0 to the last cell, so a game     * can end. It searches over the cell and the sixes rolled so far in the turn,     * because a six that ends the turn moves the token back instead.     */    private static boolean canReachTheEnd(Board board, int faces, FinishRule finishRule, TurnRules rules) {        int last = board.lastCell();        int limit = rules.sixGivesAnotherTurn() ? rules.sixesThatEndTheTurn() : 1;        boolean[][] seen = new boolean[last + 1][limit];        Deque<int[]> toVisit = new ArrayDeque<>();        seen[0][0] = true;        toVisit.add(new int[] {0, 0});        while (!toVisit.isEmpty()) {            int[] state = toVisit.poll();            int cell = state[0];            int sixes = state[1];            for (int roll = 1; roll <= faces; roll++) {                boolean six = rules.sixGivesAnotherTurn() && roll == faces;                if (six && sixes + 1 == limit) {                    continue;                }                int landed = finishRule.moveTo(cell, roll, last);                if (landed < 0 || landed > last) {                    throw new IllegalStateException("The finish rule moved a token to " + landed);                }                int to = board.landingOn(landed);                if (to == last) {                    return true;                }                int nextSixes = six ? sixes + 1 : 0;                if (!seen[to][nextSixes]) {                    seen[to][nextSixes] = true;                    toVisit.add(new int[] {to, nextSixes});                }            }        }        return false;    }

Like a bad board, a bad setup is a programmer's mistake, so each of these throws.

Asking to roll

A request first goes through three checks, each of which returns a refusal.

game/Game.javalines 76–90 of 221
    public TurnResult roll(String player) {        Objects.requireNonNull(player, "player");        synchronized (lock) {            refuseCallsFromTheRules();            Integer seat = seatOf.get(player);            if (seat == null) {                return TurnResult.refused(Outcome.UNKNOWN_PLAYER, 0);            }            int from = positions[seat];            if (winner != null) {                return TurnResult.refused(Outcome.GAME_OVER, from);            }            if (seat != current) {                return TurnResult.refused(Outcome.NOT_YOUR_TURN, from);            }

An unknown name, a finished game and a request out of turn each come back as a TurnResult with the reason. The screen can treat the first as a bug in the app, show "the game is over" for the second, and show "wait for Ravi" for the third. A refused request returns before the die is touched, so it does not use up a roll. A phone that sends one request twice gets NOT_YOUR_TURN for the second copy, and the screen can ignore it. The exception is a first copy that rolls a six: the turn still belongs to the sender, so the second copy plays the extra roll. A follow-up below closes that gap. The Tic-Tac-Toe page argues the same choice of an answer over an exception for things a person does.

game/Outcome.javalines 3–16 of 16
/** What happened to one request to roll. The last three are refusals, and change nothing. */public enum Outcome {    MOVED,    ANOTHER_TURN,    TOO_MANY_SIXES,    WON,    NOT_YOUR_TURN,    GAME_OVER,    UNKNOWN_PLAYER;     public boolean refused() {        return this == NOT_YOUR_TURN || this == GAME_OVER || this == UNKNOWN_PLAYER;    }}

Working out the move before changing anything

The die and the finishing rule are code the game was given. Either one can throw, or answer something impossible. The game asks both, checks both answers, and only then changes its state.

game/Game.javalines 91–110 of 221
            int roll;            int landed;            boolean six;            boolean tooManySixes;            // Work out the whole move first. Nothing changes until the die and the rule have answered.            rolling = true;            try {                roll = die.roll();                if (roll < 1 || roll > faces) {                    throw new IllegalStateException("A " + faces + "-faced die rolled " + roll);                }                six = rules.sixGivesAnotherTurn() && roll == faces;                tooManySixes = six && sixesInARow + 1 == rules.sixesThatEndTheTurn();                landed = tooManySixes ? turnStart : finishRule.moveTo(from, roll, board.lastCell());                if (landed < 0 || landed > board.lastCell()) {                    throw new IllegalStateException("The finish rule moved a token to " + landed);                }            } finally {                rolling = false;            }

Notice three things:

  • Nothing has changed yet. If die.roll() throws, the exception goes to the caller and the game is exactly as it was. The same player can ask again. One thing has moved on, though: a die that rolled before the finishing rule threw has used up that number. After a failure, the seed no longer replays the game, but the recorded rolls in moves() still do.
  • Impossible answers are refused (lines 99 and 105). A six-faced die that rolls 7, or a rule that sends a token to cell 101, throws IllegalStateException. These are programmer errors, so they are loud.
  • The rolling flag is cleared in a finally. It guards against a die that calls back into the game, which the lock section explains.
Decision

Change the state as you go, or work out the move first?

Move the token, then ask the rule about the finish

This is how the steps read in English. But if the rule then throws, the token has already moved and the turn has not passed. The game is half way through a move, and the next request sees a position no roll produced.

Work out the roll, the landing cell and the jump first, then change the stateOur pick

The state changes in one block, after every outside call has answered. A failure anywhere before that block leaves the game as it was. The cost is a few local variables.

Finishing: exact roll or bounce back

The two finishing rules give the same answer for every roll except one that would pass the last cell.

rules/FinishRule.javalines 7–10 of 10
public interface FinishRule {    /** A cell from 0 to lastCell. Returning from means the token stays where it is. */    int moveTo(int from, int roll, int lastCell);}
rules/ExactFinish.javalines 6–9 of 10
    public int moveTo(int from, int roll, int lastCell) {        int target = from + roll;        return target <= lastCell ? target : from;    }
rules/BounceBack.javalines 6–9 of 10
    public int moveTo(int from, int roll, int lastCell) {        int target = from + roll;        return target <= lastCell ? target : lastCell - (target - lastCell);    }
One roll, two rules
On the left, under ExactFinish, 15 plus 6 is 21, which is past 20, so the roll is lost and Asha stays on 15. Her next roll needs exactly 5. On the right, under BounceBack, the token goes 5 steps up to 20 and 1 step back to 19. A snake starts on 19, so Asha slides down to 7.On the left, under ExactFinish, 15 plus 6 is 21, which is past 20, so the roll is lost and Asha stays on 15. Her next roll needs exactly 5. On the right, under BounceBack, the token goes 5 steps up to 20 and 1 step back to 19. A snake starts on 19, so Asha slides down to 7.
On a 20-cell board, Asha is on 15 and rolls a 6. On the left, under ExactFinish, 15 plus 6 is 21, which is past 20, so the roll is lost and Asha stays on 15. Her next roll needs exactly 5. On the right, under BounceBack, the token goes 5 steps up to 20 and 1 step back to 19. A snake starts on 19, so Asha slides down to 7.

The bounce can end on a snake, and the game handles that the same way as any other landing: board.landingOn runs after the rule, whichever rule it is.

Sixes: a setting, not a class

The rule on sixes also differs from house to house. Some give another roll on a six and some do not, and the number of sixes that end the turn varies. Those differences are a switch and a number, so they live in a record.

game/TurnRules.javalines 9–21 of 21
public record TurnRules(boolean sixGivesAnotherTurn, int sixesThatEndTheTurn) {    public static final TurnRules CLASSIC = new TurnRules(true, 3);    public static final TurnRules PLAIN = new TurnRules(false, 0);     public TurnRules {        if (sixGivesAnotherTurn && (sixesThatEndTheTurn < 2 || sixesThatEndTheTurn > 10)) {            throw new IllegalArgumentException("A turn ends after 2 to 10 sixes in a row, not " + sixesThatEndTheTurn);        }        if (!sixGivesAnotherTurn && sixesThatEndTheTurn != 0) {            throw new IllegalArgumentException("Without extra turns there is no limit on sixes to set");        }    }}
Decision

A house rule: a class or a setting?

Every house rule behind its own interface

A SixRule interface with a ThreeSixesRule and a NoSixesRule would follow the same shape as FinishRule. But the classes would differ only in two numbers, and each new limit would be a new class.

Every house rule as a flag in Game

Game would take a boolean bounce and a boolean sixes. That is small today, but the finishing rule is behaviour, and the next variation of it would add another if to Game.

The finishing rule is a class, the rule on sixes is a record of numbersOur pick

A rule whose logic differs becomes a class, and a rule whose numbers differ becomes data. This matches the Strategy pattern page's own test: if two options differ only in their numbers, not in their logic, they are one class with different data. The cost is two kinds of configuration instead of one.

The third six

Once the move is known and checked, roll changes the state and decides what happens next.

game/Game.javalines 111–128 of 221
            int to = board.landingOn(landed);            positions[seat] = to;            moves.add(new Move(player, roll, from, landed, to));            if (to == board.lastCell()) {                winner = player;                return new TurnResult(Outcome.WON, roll, from, to);            }            if (tooManySixes) {                passTheTurn();                return new TurnResult(Outcome.TOO_MANY_SIXES, roll, from, to);            }            if (six) {                sixesInARow++;                return new TurnResult(Outcome.ANOTHER_TURN, roll, from, to);            }            passTheTurn();            return new TurnResult(Outcome.MOVED, roll, from, to);        }

Notice the order. A token that reaches the last cell wins at once, even on a six, so a winning six gives no extra roll. A third six never wins: line 104 picks turnStart instead of asking the finishing rule, even when the six would reach the last cell. After the win check, the third six ends the turn, and an ordinary six gives another roll.

Three sixes in a row
Asha's turn starts on 7. Her first six takes her to 13, where the ladder climbs to 46, and she rolls again. Her second six takes her to 52, and she rolls again. Her third six ends the turn: the token goes back to 7, where the turn started, and the outcome is TOO_MANY_SIXES. Then it is Ravi's turn.Asha's turn starts on 7. Her first six takes her to 13, where the ladder climbs to 46, and she rolls again. Her second six takes her to 52, and she rolls again. Her third six ends the turn: the token goes back to 7, where the turn started, and the outcome is TOO_MANY_SIXES. Then it is Ravi's turn.
Under the classic rules, the third six undoes the whole turn. Asha's turn starts on 7. Her first six takes her to 13, where the ladder climbs to 46, and she rolls again. Her second six takes her to 52, and she rolls again. Her third six ends the turn: the token goes back to 7, where the turn started, and the outcome is TOO_MANY_SIXES. Then it is Ravi's turn.
Decision

What happens on the third six?

Only the third roll is lost; the token stays where the second six left it

This needs nothing extra: the third six moves nothing and passes the turn. But the player keeps everything the first two sixes gained, ladders included, so the penalty is one roll, not the turn.

The token goes back to where the turn startedOur pick

turnStart remembers the cell at the start of each turn, and sixesInARow counts sixes within it. The third six sends the token back to turnStart and passes the turn. The undo covers snakes too: a second six that slid down a snake is moved back up. The cost is two fields, and one method resets them when the turn passes: sixesInARow goes back to 0, and turnStart moves to the next player's cell.

That one place is passTheTurn:

game/Game.javalines 170–174 of 221
    private void passTheTurn() {        current = (current + 1) % players.size();        sixesInARow = 0;        turnStart = positions[current];    }

turnStart is the cell where the next player's token sits when their turn begins. It is never the foot of a ladder or the head of a snake, because a token always ends a move after any jump.

Many phones, one game

On a server, the three phones send their requests on different threads, and a phone can send one request twice. Every method of Game that reads or changes its state takes one private lock, so the turn check, the roll and the move happen as one step.

The race the lock prevents is a check-then-act race. Two copies of Asha's request can both read "it is Asha's turn" before either has moved her token. Without the lock, both can then roll and move it, and the turn passes twice, so the next player is skipped.

One request, sent twice
On the left, with no lock, both copies of roll("Asha") see that it is Asha's turn before either has moved her token. Both roll, so Asha moves twice and the turn passes twice, skipping Ravi. On the right, the first copy holds the game's lock while it checks, rolls and moves. The second copy waits, then finds it is no longer Asha's turn and gets NOT_YOUR_TURN.On the left, with no lock, both copies of roll("Asha") see that it is Asha's turn before either has moved her token. Both roll, so Asha moves twice and the turn passes twice, skipping Ravi. On the right, the first copy holds the game's lock while it checks, rolls and moves. The second copy waits, then finds it is no longer Asha's turn and gets NOT_YOUR_TURN.
Without the lock, the turn check and the roll are two steps. With it, they are one. On the left, with no lock, both copies of roll("Asha") see that it is Asha's turn before either has moved her token. Both roll, so Asha moves twice and the turn passes twice, skipping Ravi. On the right, the first copy holds the game's lock while it checks, rolls and moves. The second copy waits, then finds it is no longer Asha's turn and gets NOT_YOUR_TURN.

demo/RaceCheck.java plays 2,000 games of three players, with two threads per player, like a player with a phone that sends every tap twice. After each game, it takes the recorded rolls and plays them again in a fresh game, asking for whoever's turn it is. The replay matches only if no turn was skipped, no roll was played twice and no token moved out of turn.

$ java demo.RaceCheck
Games played, each by six phone threads: 2000
Games where a request crashed: 0
Games whose moves do not replay in turn order: 0

With the lock, the last two lines are 0. We also ran it with the lock removed from roll. In every run, nearly every game had a request crash, all of them on the guard against calls back. Without the lock, one thread sees the rolling flag another thread has set. Dozens more games finished with moves that do not replay.

Decision

Where does the lock go?

No lock: one thread per game, with requests queued

A server can give each game a queue and one worker. That works, but Game would then be unsafe to use any other way, and the rule would live in server code far from the class it protects.

A lock per player

Each player's requests would wait for each other. But the turn belongs to the whole game: Asha's roll passes the turn to Ravi. Asha's lock and Ravi's lock would both be needed, and the order of taking them would invite a deadlock.

One private lock per game, around each method that reads or changes the gameOur pick

The lock is a private object, so outside code cannot hold it and stall a game. The two getters players() and board() take no lock, because they return fields that never change. roll holds it for a die roll, a rule call, a map lookup and a few writes. Different games never share a lock, so a server can run thousands of games side by side.

The die and the finishing rule run under the lock, so a slow die would hold up every player in that game. Java's synchronized lock is reentrant. A die that held the Game could call roll from inside its own roll and get straight in, making a move in the middle of another. roll sets rolling while the die and the rule run, and refuses such a call:

game/Game.javalines 215–220 of 221
    /** The lock is reentrant, so without this a die could make a move in the middle of another. */    private void refuseCallsFromTheRules() {        if (rolling) {            throw new IllegalStateException("The die and the finish rule must not call back into the game");        }    }

The nested call throws IllegalStateException, and the nested move never happens. If the die lets that exception out, the outer request fails too, and the game is unchanged, because nothing has changed before the die answers.

The final design

Game is the core. It owns the positions, the turn, the moves and the one lock, and it reaches the die and the finishing rule only through Die and FinishRule. The Board is fixed data that many games can share, and TurnRules holds the house rules that are only numbers.

The design we built
The classes from the class diagram, in the same places, with names only. Amber badges number the decisions in the table below. Game carries 4, 5, 7 and 8. Jump carries 1, Board carries 2, Die carries 3 and TurnRules carries 6. FinishRule carries a Strategy tag.The classes from the class diagram, in the same places, with names only. Amber badges number the decisions in the table below. Game carries 4, 5, 7 and 8. Jump carries 1, Board carries 2, Die carries 3 and TurnRules carries 6. FinishRule carries a Strategy tag.
Each decision lands on one class. One interface carries a pattern. The classes from the class diagram, in the same places, with names only. Amber badges number the decisions in the table below. Game carries 4, 5, 7 and 8. Jump carries 1, Board carries 2, Die carries 3 and TurnRules carries 6. FinishRule carries a Strategy tag.
S.No.The questionWhat we choseWhy
1Should a snake and a ladder be two classes?One Jump record with from and to; the direction says which it isOne map and one lookup, whatever the kind
2When is a bad board caught?When the board is built, in the constructorMistakes show up before a roll, and play needs no checks
3Who rolls the die?The game rolls through a Die it is givenThe server owns the roll, and a test controls it
4Where do the players' positions live?In Game, in an array in turn orderEverything one roll changes sits behind one lock
5Change the state as you go, or work out the move first?Work out the roll, the landing cell and the jump first, then change the stateA failing die or rule leaves the game as it was
6A house rule: a class or a setting?The finishing rule is a class, the rule on sixes is a record of numbersDifferent logic is a class; different numbers are data
7What happens on the third six?The token goes back to where the turn startedThree sixes cost the whole turn, ladders included, for two fields
8Where does the lock go?One private lock per game, around each method that reads or changes the gameThe turn check, the roll and the move happen as one step

Here is Ravi's roll from the overview, end to end:

  1. Ravi's phone calls roll("Ravi"). roll checks that the name is not null, then takes the game's lock with synchronized (lock), so no other request for this game can run until it is done.
  2. Under the lock, roll finds Ravi's seat in seatOf, checks that nobody has won, and checks that his seat is current. All three pass. Had any failed, roll would return a refusal here, before the die is touched.
  3. With rolling set, die.roll() returns 4. This is the outside call, made under the lock so that each roll belongs to exactly one request. Then finishRule.moveTo(0, 4, 100) returns 4, and both answers are checked against the die's faces and the board.
  4. Only now does the state change. board.landingOn(4) returns 25, the top of the ladder. roll writes 25 into positions, adds the Move to moves, and calls passTheTurn, which makes Meera current, clears the count of sixes and sets turnStart to her cell.
  5. roll returns TurnResult(MOVED, 4, 0, 25), and the lock is released as the block ends. Ravi's phone shows the climb, and Meera's next request is the one that will pass the turn check.

The complete code

Click a class name in any file to open it, or use the tree. Find searches every file.

gameGame.java
package game; import java.util.ArrayDeque;import java.util.ArrayList;import java.util.Deque;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Objects;import java.util.Optional; import board.Board;import dice.Die;import rules.FinishRule; /** * One game on one board. Players are names, and a roll arrives as a call to * roll(name) from a screen or a server. The game rolls the die itself. Every * method that reads or changes the game takes one lock, so requests arriving * on many threads are handled one at a time. */public class Game {    public static final int MIN_PLAYERS = 2;    public static final int MAX_PLAYERS = 6;     private final Object lock = new Object();    private final Board board;    private final List<String> players;    private final Map<String, Integer> seatOf;    private final Die die;    private final int faces;    private final FinishRule finishRule;    private final TurnRules rules;    private final int[] positions;    private final List<Move> moves = new ArrayList<>();    private int current;    private int sixesInARow;    private int turnStart;    private String winner;    /** True while the die or the finish rule runs, so one that calls back into the game is refused. */    private boolean rolling;     public Game(Board board, List<String> players, Die die, FinishRule finishRule, TurnRules rules) {        this.board = Objects.requireNonNull(board, "board");        Objects.requireNonNull(players, "players");        if (players.size() < MIN_PLAYERS || players.size() > MAX_PLAYERS) {            throw new IllegalArgumentException("A game has " + MIN_PLAYERS + " to " + MAX_PLAYERS + " players, not " + players.size());        }        Map<String, Integer> seats = new HashMap<>();        for (int seat = 0; seat < players.size(); seat++) {            String name = Objects.requireNonNull(players.get(seat), "player");            if (name.isBlank()) {                throw new IllegalArgumentException("A player needs a name");            }            if (seats.putIfAbsent(name, seat) != null) {                throw new IllegalArgumentException("Two players are called " + name);            }        }        this.die = Objects.requireNonNull(die, "die");        this.faces = die.faces();        if (faces < 2 || faces >= board.lastCell()) {            throw new IllegalArgumentException("A die of " + faces + " faces needs 2 or more faces and a board of more cells");        }        this.finishRule = Objects.requireNonNull(finishRule, "finishRule");        this.rules = Objects.requireNonNull(rules, "rules");        if (!canReachTheEnd(board, faces, finishRule, rules)) {            throw new IllegalArgumentException("No run of rolls reaches cell " + board.lastCell() + " on this board");        }        this.players = List.copyOf(players);        this.seatOf = Map.copyOf(seats);        this.positions = new int[players.size()];    }     /** Rolls for this player if it is their turn, and moves their token. Refusals change nothing. */    public TurnResult roll(String player) {        Objects.requireNonNull(player, "player");        synchronized (lock) {            refuseCallsFromTheRules();            Integer seat = seatOf.get(player);            if (seat == null) {                return TurnResult.refused(Outcome.UNKNOWN_PLAYER, 0);            }            int from = positions[seat];            if (winner != null) {                return TurnResult.refused(Outcome.GAME_OVER, from);            }            if (seat != current) {                return TurnResult.refused(Outcome.NOT_YOUR_TURN, from);            }            int roll;            int landed;            boolean six;            boolean tooManySixes;            // Work out the whole move first. Nothing changes until the die and the rule have answered.            rolling = true;            try {                roll = die.roll();                if (roll < 1 || roll > faces) {                    throw new IllegalStateException("A " + faces + "-faced die rolled " + roll);                }                six = rules.sixGivesAnotherTurn() && roll == faces;                tooManySixes = six && sixesInARow + 1 == rules.sixesThatEndTheTurn();                landed = tooManySixes ? turnStart : finishRule.moveTo(from, roll, board.lastCell());                if (landed < 0 || landed > board.lastCell()) {                    throw new IllegalStateException("The finish rule moved a token to " + landed);                }            } finally {                rolling = false;            }            int to = board.landingOn(landed);            positions[seat] = to;            moves.add(new Move(player, roll, from, landed, to));            if (to == board.lastCell()) {                winner = player;                return new TurnResult(Outcome.WON, roll, from, to);            }            if (tooManySixes) {                passTheTurn();                return new TurnResult(Outcome.TOO_MANY_SIXES, roll, from, to);            }            if (six) {                sixesInARow++;                return new TurnResult(Outcome.ANOTHER_TURN, roll, from, to);            }            passTheTurn();            return new TurnResult(Outcome.MOVED, roll, from, to);        }    }     /** Whose roll it is, or empty once someone has won. */    public Optional<String> turn() {        synchronized (lock) {            return winner == null ? Optional.of(players.get(current)) : Optional.empty();        }    }     public Optional<String> winner() {        synchronized (lock) {            return Optional.ofNullable(winner);        }    }     /** Each player's cell, in turn order. 0 means the token has not entered the board. */    public Map<String, Integer> positions() {        synchronized (lock) {            Map<String, Integer> copy = new LinkedHashMap<>();            for (int seat = 0; seat < players.size(); seat++) {                copy.put(players.get(seat), positions[seat]);            }            return copy;        }    }     /** Every roll played so far, first to last. */    public List<Move> moves() {        synchronized (lock) {            return List.copyOf(moves);        }    }     public List<String> players() {        return players;    }     public Board board() {        return board;    }     private void passTheTurn() {        current = (current + 1) % players.size();        sixesInARow = 0;        turnStart = positions[current];    }     /**     * Whether some run of rolls takes a token from 0 to the last cell, so a game     * can end. It searches over the cell and the sixes rolled so far in the turn,     * because a six that ends the turn moves the token back instead.     */    private static boolean canReachTheEnd(Board board, int faces, FinishRule finishRule, TurnRules rules) {        int last = board.lastCell();        int limit = rules.sixGivesAnotherTurn() ? rules.sixesThatEndTheTurn() : 1;        boolean[][] seen = new boolean[last + 1][limit];        Deque<int[]> toVisit = new ArrayDeque<>();        seen[0][0] = true;        toVisit.add(new int[] {0, 0});        while (!toVisit.isEmpty()) {            int[] state = toVisit.poll();            int cell = state[0];            int sixes = state[1];            for (int roll = 1; roll <= faces; roll++) {                boolean six = rules.sixGivesAnotherTurn() && roll == faces;                if (six && sixes + 1 == limit) {                    continue;                }                int landed = finishRule.moveTo(cell, roll, last);                if (landed < 0 || landed > last) {                    throw new IllegalStateException("The finish rule moved a token to " + landed);                }                int to = board.landingOn(landed);                if (to == last) {                    return true;                }                int nextSixes = six ? sixes + 1 : 0;                if (!seen[to][nextSixes]) {                    seen[to][nextSixes] = true;                    toVisit.add(new int[] {to, nextSixes});                }            }        }        return false;    }     /** The lock is reentrant, so without this a die could make a move in the middle of another. */    private void refuseCallsFromTheRules() {        if (rolling) {            throw new IllegalStateException("The die and the finish rule must not call back into the game");        }    }}
Click a class name in the code to open its fileJava · 221 lines · 729 in the project

The demo plays the start of a game of three and the same short game under each finishing rule. Then it shows a die that fails, a seeded game and a replay of its rolls, and five refused setups:

$ java demo.Main
== A game of three on the 100-cell board ==
  Asha rolls 4: 0 to 4, ladder up to 25. MOVED
  Asha asks to roll: NOT_YOUR_TURN
  Ravi rolls 6: 0 to 6. ANOTHER_TURN
  Ravi rolls 6: 6 to 12. ANOTHER_TURN
  Ravi rolls 6: too many sixes, back to 0. TOO_MANY_SIXES
  Meera rolls 3: 0 to 3. MOVED
  Asha rolls 2: 25 to 27, snake down to 5. MOVED
  Kabir asks to roll: UNKNOWN_PLAYER
Positions: {Asha=5, Ravi=0, Meera=3}, next: Ravi

== The same rolls on a 20-cell board, under each finish rule ==
ExactFinish:
  Asha rolls 3: 0 to 3, ladder up to 11. MOVED
  Ravi rolls 2: 0 to 2. MOVED
  Asha rolls 4: 11 to 15. MOVED
  Ravi rolls 2: 2 to 4. MOVED
  Asha rolls 6: 15 to 15. MOVED
  Ravi rolls 1: 4 to 5. MOVED
  Asha rolls 5: 15 to 20. WON
  Ravi asks to roll: GAME_OVER
BounceBack:
  Asha rolls 3: 0 to 3, ladder up to 11. MOVED
  Ravi rolls 2: 0 to 2. MOVED
  Asha rolls 4: 11 to 15. MOVED
  Ravi rolls 2: 2 to 4. MOVED
  Asha rolls 6: 15 to 19, snake down to 7. MOVED
  Ravi rolls 1: 4 to 5. MOVED
  Asha rolls 5: 7 to 12. MOVED
  Ravi rolls 3: 5 to 8. MOVED

== A die that fails ==
  Asha rolls 5: 0 to 5. MOVED
  Ravi asks to roll: The script has no rolls left after 1
  Positions: {Asha=5, Ravi=0}, next: Ravi

== A seeded game, and a replay of its recorded rolls ==
Seed 42: Meera wins after 68 rolls
Replay of those 68 rolls: Meera wins, same moves: true

== Boards that are refused ==
A chain: The jump 10 to 30 ends where another jump starts
A snake on the last cell: Nothing can start on the last cell, 100
A ladder off the board: The jump 95 to 120 leaves a board of 100 cells
Two jumps from one cell: Two jumps start at cell 8
A board no roll can finish: No run of rolls reaches cell 10 on this board

Notice five things in the output:

  • A refused request costs nothing. Asha's second request, out of turn, and Kabir's, who is not playing, are refused, and Ravi's first roll is still the next number on the die: his 6.
  • The third six undoes the whole turn. Ravi rolls 6, 6 and 6, reaches 12, and goes back to 0, where his turn started. Meera rolls next.
  • The two finishing rules part at one roll. On the 20-cell board, Asha's 6 from 15 is lost under ExactFinish, and she wins on her next turn with a 5. Under BounceBack, the same 6 bounces to 19 and slides down the snake to 7, so the game goes on.
  • A failing die changes nothing. The scripted die has one roll, so Ravi's request throws, and the positions and the turn are as they were before he asked.
  • The recorded rolls replay the game. The seeded game ends with Meera winning after 68 rolls, and the same 68 rolls fed through a ScriptedDie give the same moves.

Follow-up questions

The interviewer asksWhat changesWhat does not
Two dice instead of one?A Die that adds two rolls. The six rule then needs to say "a double six", so Game's check of the highest face changes, and the setup search and the roll check use the totals the dice can make (2 to 12)Board, the finishing rules
A roll past the end moves the token back by the whole roll?A new FinishRule that returns Math.max(0, from - roll) for such a rollGame, Board
Play on for second and third place?Game keeps a list of finishers instead of one winner, and skips them when the turn passesBoard, the die, the finishing rules
Landing on another token sends it home?Game checks the other positions after each move. Outcome may gain a value to say soBoard, the die, the finishing rules
A time limit per turn?Game takes a Clock, and a late request passes the turn with a new OutcomeBoard, the die, the finishing rules
Show the game live to spectators?Game tells listeners after each move: the Observer patternBoard, the die, the rules
Save a game and resume it later?Store the board, the players, the rules and the recorded rolls. Resuming plays them again through a Die that rolls the recorded numbers first and then rolls freelyGame's logic
A tap sent twice right after a six?roll takes a request id; Game keeps the last id and result per player and returns that result for a repeatBoard, the die, the rules
A board generated at random?A new class that builds the list of jumps, and the Board constructor still checks itGame, Board

Most rows change Game, because the turn and the positions live there. Only the two dice row changes what a six means, and only the finishing rule and the random board are a new class with nothing else touched. Saying which classes change and which do not, with each class named, is the point of the follow-up.

What the interviewer looks for

Mid-level

A mid-level candidate builds a working game: a board with snakes and ladders, turns in order, a die and a winner. They can explain the code and fix a bug when one is pointed out.

Senior

A senior candidate makes the board data and checks it when it is built, puts the die behind an interface so a test controls it, and keeps refused requests separate from errors. They put the finishing rule behind an interface and can say why the rule on sixes is only numbers.

Staff+

A staff candidate also sees the game as a server's object: requests from many phones, a request sent twice, and a die that must stay on the server. They work out each move before changing any state, put one lock around the turn check and the move, and explain how a game can be replayed from its rolls.

Common mistakes

  • Separate Snake and Ladder classes. They hold the same two numbers and differ only in direction.
  • Calling Math.random() inside the game. Nothing can then test three sixes in a row or replay a game.
  • Trusting the roll a phone sends. A changed app can roll a 6 every time.
  • Following jumps in a loop during play. A chain or a loop in the board then shows up mid-game; checking the board once when it is built removes both.
  • Moving the token before the rules have answered. A rule that throws leaves the game half way through a move.
  • Checking the turn and moving the token with no lock. A request sent twice moves the token twice and skips the next player.
  • Giving another turn on a winning six. The token that reaches the last cell has won, and the game is over.

Summary

  • A roll arrives as a call to roll(name), and the game rolls its own die, so a phone can only ask.
  • A snake and a ladder are one Jump record, and the board checks every jump once, when it is built.
  • Die is an interface: a SeededDie for real games, and a ScriptedDie for tests and replays.
  • The finishing rule is a class behind FinishRule; the rule on sixes is a record of numbers.
  • The third six sends the token back to turnStart, the cell where the turn began.
  • roll works out the whole move before changing anything, so a failing die or rule leaves the game as it was.
  • One private lock per game turns the turn check, the roll and the move into one step, so a request sent twice is one roll. The exception is right after a six, which the follow-up on request ids closes.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.