"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.
Ask before you design
The question is vague on purpose, and each answer below changes the code. The right-hand column says how.
| Question | What we assume | What it changes |
|---|---|---|
| Only the 100-cell board? | Any board from 10 to 1,000 cells | The size is a constructor argument |
| Where are the snakes and ladders? | Given as data when the board is built | The board takes a list of jumps and checks it |
| How many players? | Two to six, playing in a fixed order | A list of names and a turn index |
| What dice? | One six-sided die; the game must be repeatable | The 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 needed | An interface for the finishing rule |
| Does a six give another turn? | Yes, and three sixes in a row end the turn | Two numbers kept per turn |
| Can two tokens share a cell? | Yes, nothing happens when they meet | No capture logic |
| How do rolls arrive? | From phones, through a server, as calls | The game answers calls; it does not run a loop |
| Who rolls the die: the phone or the server? | The server | The 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:
- 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.
- Two to six players take turns in a fixed order. Every token starts off the board, at 0.
- 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.
- The finishing rule is chosen per game: either a roll past the last cell is lost, or it bounces back off the last cell.
- 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.
- The first token to reach the last cell wins, and the game ends.
- A request to roll out of turn, by an unknown player, or after the game has ended is refused, and nothing changes.
- 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
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.
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.
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.
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 fall into three groups:
- Data:
Jump,Move,TurnResult,TurnRules,JumpKindandOutcome. These are records and enums. - The core:
Gameand itsBoard. 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, andFinishRule, 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.
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.
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.
/** 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.
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.
@Override public int roll() { if (next == rolls.size()) { throw new IllegalStateException("The script has no rolls left after " + rolls.size()); } return rolls.get(next++); }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.
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.
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.
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.
/** * 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.
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.
/** 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.
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 inmoves()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
rollingflag is cleared in afinally. It guards against a die that calls back into the game, which the lock section explains.
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.
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);} public int moveTo(int from, int roll, int lastCell) { int target = from + roll; return target <= lastCell ? target : from; } public int moveTo(int from, int roll, int lastCell) { int target = from + roll; return target <= lastCell ? target : lastCell - (target - lastCell); }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.
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"); } }}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.
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.
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:
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.
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.
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.
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:
/** 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.
| S.No. | The question | What we chose | Why |
|---|---|---|---|
| 1 | Should a snake and a ladder be two classes? | One Jump record with from and to; the direction says which it is | One map and one lookup, whatever the kind |
| 2 | When is a bad board caught? | When the board is built, in the constructor | Mistakes show up before a roll, and play needs no checks |
| 3 | Who rolls the die? | The game rolls through a Die it is given | The server owns the roll, and a test controls it |
| 4 | Where do the players' positions live? | In Game, in an array in turn order | Everything one roll changes sits behind one lock |
| 5 | Change 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 state | A failing die or rule leaves the game as it was |
| 6 | A house rule: a class or a setting? | The finishing rule is a class, the rule on sixes is a record of numbers | Different logic is a class; different numbers are data |
| 7 | What happens on the third six? | The token goes back to where the turn started | Three sixes cost the whole turn, ladders included, for two fields |
| 8 | Where does the lock go? | One private lock per game, around each method that reads or changes the game | The turn check, the roll and the move happen as one step |
Here is Ravi's roll from the overview, end to end:
- Ravi's phone calls
roll("Ravi").rollchecks that the name is not null, then takes the game's lock withsynchronized (lock), so no other request for this game can run until it is done. - Under the lock,
rollfinds Ravi's seat inseatOf, checks that nobody has won, and checks that his seat iscurrent. All three pass. Had any failed,rollwould return a refusal here, before the die is touched. - With
rollingset,die.roll()returns 4. This is the outside call, made under the lock so that each roll belongs to exactly one request. ThenfinishRule.moveTo(0, 4, 100)returns 4, and both answers are checked against the die's faces and the board. - Only now does the state change.
board.landingOn(4)returns 25, the top of the ladder.rollwrites 25 intopositions, adds theMovetomoves, and callspassTheTurn, which makes Meeracurrent, clears the count of sixes and setsturnStartto her cell. rollreturnsTurnResult(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.
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"); } }}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:
== 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 boardNotice 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. UnderBounceBack, 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
ScriptedDiegive the same moves.
Follow-up questions
| The interviewer asks | What changes | What 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 roll | Game, Board |
| Play on for second and third place? | Game keeps a list of finishers instead of one winner, and skips them when the turn passes | Board, 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 so | Board, the die, the finishing rules |
| A time limit per turn? | Game takes a Clock, and a late request passes the turn with a new Outcome | Board, the die, the finishing rules |
| Show the game live to spectators? | Game tells listeners after each move: the Observer pattern | Board, 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 freely | Game'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 repeat | Board, the die, the rules |
| A board generated at random? | A new class that builds the list of jumps, and the Board constructor still checks it | Game, 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
SnakeandLadderclasses. 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
Jumprecord, and the board checks every jump once, when it is built. Dieis an interface: aSeededDiefor real games, and aScriptedDiefor 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. rollworks 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.