Notes
Requirements
Start with the rules. The board has N cells, a hundred by default. Snakes take you down, ladders take you up. Two or more players take turns: roll the dice, move forward, follow any snake or ladder you land on. The first player to reach the last cell wins. The board size, the snakes, the ladders and the dice must all be configurable. Graphics and chat are out of scope.
Clarify the edge cases, because each one becomes a rule. What if a roll goes past the last cell? Usually you stay put; some houses bounce back. One die or two? Configurable. Can a ladder end on a snake's head? Yes, follow the chain, but never in a loop. Does the game stop at the first winner? Yes for now; full rankings are an extension. An extra turn on a six? Not now, but the design should make it easy.
- board of N cells, default 100
- snakes take you down,
- ladders take you up
- two or more players, in turns
- roll the dice, move, follow
- any snake or ladder
- first to the last cell wins
- board size, snakes, ladders,
- dice: all configurable
- out of scope: graphics, chat
- roll past the last cell?
- stay put (or bounce back)
- one die or two?
- configurable
- snake head on a ladder top?
- allowed, follow the chain
- game ends at first winner?
- yes; ranking is an extension
- extra turn on a six?
- not now, easy to add
Entities
Underline the nouns: game, board, snake, ladder, player, dice. One insight simplifies everything: a snake and a ladder are the same thing, a jump from one cell to another. A snake goes down and a ladder goes up, but the board treats both identically, so they become a single Jump type. The game owns the board, the players' positions, a turn queue and the dice.
Class diagram
In code, the small things are records. A player is a name. A jump is a from and a to, and it knows it is a snake when it goes down. A move records who rolled what, where they started, where they ended and whether a snake or ladder was involved, which is perfect for a replay log. Positions live in the game as a map from player to cell, with zero meaning not on the board yet.
record Player(String name)
record Jump(int from, int to) {
boolean isSnake() { return to < from; }
}
enum Status { IN_PROGRESS, FINISHED }
record Move(Player p, int roll,
int from, int to, String via)
positions: Map<Player, Integer>
0 means not on the board yet Builder: the board
The board uses the Builder pattern. You add ladders and snakes fluently, and build checks every rule before a board exists: no jump may start on the first or last cell, a ladder must go up and a snake down, one cell has at most one jump, and following jumps must never loop forever. After build, the board is immutable, so many games can share one board safely.
.ladder(4, 14).ladder(28, 84) .snake(17, 7).snake(98, 79) .build() rejected while building: jump starts on cell 1 or the last ladder that goes down two jumps from one cell a cycle: 10 up to 20, 20 down to 10 Board is immutable after build()
Strategy: dice
Dice is a Strategy with one method, roll. RandomDice takes the number of dice, the faces, and a Random, so a seeded Random gives a replayable game. FixedDice returns a scripted list of rolls, which is how you write a test that proves a ladder or a win happens exactly when expected. Mentioning that testability is the reason for the interface scores easy points.
interface Dice { int roll(); }
record RandomDice(int count, int faces,
Random rnd)
sum of count rolls of 1..faces
FixedDice(4, 6, 6, 5, ...)
returns a scripted sequence
loaded dice, crooked dice: new class Strategy: finishing
What happens when you overshoot the last cell differs from house to house, so it is a second strategy. The exact rule keeps you where you are. The bounce rule walks you back by the overshoot. From ninety-seven, a five keeps you on ninety-seven with the exact rule, but bounces you to ninety-eight with the other, straight onto a snake. The game does not care which rule it was given.
interface FinishRule {
int land(int pos, int roll, int last);
}
EXACT: pos + roll > last ? pos
: pos + roll
BOUNCE: overshoot by k, go back k
from 97 roll 5:
EXACT stays on 97
BOUNCE lands on 98, snake to 79 Turns
Turn order is a double-ended queue. The current player is at the head. After a move, take them off the front and put them at the back. That one structure makes the usual extensions trivial: an extra turn on a six means simply not rotating, a player who leaves is removed from the queue, and a reverse-order rule walks the other way.
Deque<Player> turns current = turns.peekFirst() after a move: turns.addLast(turns.removeFirst()) extra turn on a six: skip the rotate player leaves: remove from the deque reverse order card: iterate backwards
Flow: a turn
Walk one turn. Reject the call if the game is over or it is not this player's turn. Roll the dice, ask the finish rule where the token lands, then ask the board to resolve any snakes and ladders, following a chain if one jump ends on another. Store the new position, rotate the queue, and if the player reached the last cell, mark the game finished. Finally notify listeners and return the move.
if finished: throw game over if player != turns.peek: throw roll = dice.roll() landed = finish.land(pos, roll, size) to = board.resolve(landed) positions.put(player, to) rotate the turn queue if to == size: FINISHED, winner notify listeners with the Move return the Move
Flow: winning
Winning is a single comparison after jumps are applied, because a ladder could carry you straight onto the last cell. Here is the scripted game from the demo: the host climbs four ladders, rolls a five from ninety-seven and stays put under the exact rule, then rolls the three needed to win. After that, any call to play throws, so a late click cannot move a token in a finished game.
- Host 4: 0 to 14 ladder
- Guest 6: 11 to 7 snake
- Host 1: 20 to 42 ladder
- Host 3: 48 to 67 ladder
- Host 5: 67 to 91 ladder
- Host 6: 91 to 97
- Host 5: 97 to 97 (overshoot)
- Host 3: 97 to 100, wins
- any later play() throws
Observer
The game should not print anything or draw anything itself. Instead it publishes each move to listeners: the Observer pattern. The console view, a graphical board, a replay log and a statistics counter all subscribe the same way. The demo prints every move through a listener, and a test could subscribe a list and assert the exact sequence of moves.
Concurrency
In a single process with one keyboard there is no concurrency, so say that. Online is different: two requests can arrive for the same game at once, or the same player can double click. Make play synchronized on the game and check whose turn it is inside the lock, so the second request is rejected. Different games have different locks and never wait on each other, and the immutable board is shared freely.
- play() is synchronized per game
- games never block each other
- whose-turn check inside the lock:
- a double click is rejected
- or: one single-threaded actor
- per game, moves in a queue
- board is immutable: shared
- safely by every game
Extensibility
Interviewers will add rules. An extra turn on a six, cancelled on the third six in a row, is a counter and a skipped rotate. Full rankings mean removing winners from the queue and playing on. Special cells, like a skip-a-turn square, generalise Jump into a cell effect. Saving a game is the positions, the queue and the move log. Each change lands in one class.
- extra turn on a six: skip
- the rotate, cap at three
- full rankings: keep playing,
- remove winners from the queue
- power-ups, special cells: a
- CellEffect per cell
- bigger board: builder args
- save and resume: positions +
- queue + the Move log
Other games
The same skeleton fits other board games. Tic-tac-toe keeps the players and the turn queue, swaps the board for an N by N grid and the move for a row and column, and checks a win in constant time by counting marks per row, column and diagonal. The snake game has no turns, just a tick loop: the snake is a deque of cells, each tick adds a head and drops the tail unless food was eaten, and you lose when the head hits a wall or the body.
- tic-tac-toe:
- Board = N x N grid of symbols
- Move = (row, col), no dice
- win: track row, col, diagonal
- counts, O(1) per move
- snake game:
- no turns, a tick loop instead
- snake = deque of cells
- move: add head, drop tail
- unless food was eaten
- lose: head hits wall or body
Testing
The full code is below the player. Scripted dice drive a complete game and assert the host wins. Then it checks a guest cannot move out of turn, both finish rules on the same position, and three broken boards that the builder refuses. Finally two hundred seeded random games with four players all finish, the longest taking three hundred and twenty eight turns, with the winner on the last cell every time.
Host rolls 4: 0 -> 14 ladder Guest rolls 6: 11 -> 7 snake Host rolls 3: 97 -> 100 Winner: Host Rejected: not Guest's turn Invalid board: out of range 100 to 5 Invalid board: jump cycle at 10 200 random 4-player games finished, longest took 328 turns
Follow-ups
Expect follow-ups. Why not separate snake and ladder classes? They have identical behaviour, so one type avoids duplication. How do you prevent loops? Walk every chain at build time. How do you test randomness? Inject the dice and seed it. The expected length of a game is a Markov chain over the cells. And a million concurrent games means the game state lives in a store keyed by game id, with one writer per game.
- why one Jump, not Snake + Ladder?
- how do you stop jump loops?
- how would you test randomness?
- inject Dice, seed the Random
- expected game length?
- a Markov chain over cells
- million games at once?
- stateless service, game state
- in a store keyed by game id
Say it like this
The short version to say out loud. A board, built and validated by a builder, holds jumps, because snakes and ladders are one type. Dice and the finish rule are strategies, so tests can script them. Turns rotate through a deque, every move is published to observers, and play checks whose turn it is under a per-game lock.
- "A Board built and validated by
- a Builder holds Jumps: snakes
- and ladders are one type. Dice
- and the finish rule are
- strategies, turns are a deque,
- moves go to observers, and play
- checks whose turn it is under
- a per-game lock."