Compile Ready
All low level design problems
Low Level Design/Intermediate/Games

Design Ludo

Multiple players, tokens, dice, home paths, and turn/capture rules — multiplayer state modelled cleanly.

Intermediate 50m interview 16m read Low frequency Popularity 68
State Strategy Observer Factory Method Amazon Flipkart

Problem Statement

Design the object model for a Ludo game with two to four players, a color-specific path for each player, four tokens per player, dice rolls, captures, safe cells, and win detection.

The interview focus is not rendering the board. It is the turn and state model: a token needs a 6 to leave home, movement must be validated before state changes, finishing needs an exact count, captures happen only on non-safe common cells, and turn advancement must handle extra turns without corrupting the game.

Business context

Ludo is a strong multiplayer LLD exercise because a small board game creates many edge cases: token state transitions, per-color coordinate systems, dice-driven randomness, legal move selection, capture rules, and winner detection.

Interviewers use it to see whether you can separate rules from orchestration. A good design keeps board math in Board, move validation in a MovementStrategy, token lifecycle in Token, and the turn loop in LudoGame.

Functional Requirements

  • Support two to four players, each assigned a distinct color and exactly four tokens.

  • Represent a common circular path plus a color-specific home lane and finish cell.

  • Roll a six-sided dice at the start of every turn.

  • Allow a token to leave home only when the dice roll is 6.

  • Move active tokens by the dice value and reject moves that overshoot the finish cell.

  • Finish a token only when the move lands on the finish step exactly.

  • Capture opponent tokens that land on the same non-safe common path cell and send them home.

  • Keep safe cells immune from capture, including color start cells.

  • Advance turns correctly, including an extra turn after rolling 6.

  • Detect the winner when all four tokens of a player are finished.

Non-Functional Requirements

Rule correctness

Every state mutation must be preceded by a legality check. Illegal moves should leave token positions, turn order, and winner state unchanged.

Extensibility

Variants such as no extra turn on 6, three consecutive sixes, blockades, or custom safe cells should be added by replacing strategies or board configuration.

Deterministic testing

The dice is injected behind an interface so tests can use scripted rolls while production uses random rolls.

Encapsulation

Tokens expose transitions such as leaveHome, moveTo, finish, and sendHome instead of letting callers mutate raw position fields.

Observable gameplay

The game emits events for rolls, moves, captures, skipped turns, and winners so a UI, logger, or test harness can react without being embedded in the domain.

Requirement Clarification

QHow many players should the base design support?

Assume two to four players. Each player has one color and four tokens. The constructor rejects duplicate colors and unsupported player counts.

QDoes rolling a 6 grant another turn?

Yes for the base rules. The turn loop keeps the same current player after a legal or skipped turn caused by a roll of 6, unless that move wins the game.

QCan a token enter the finish area with a higher roll than needed?

No. The move is illegal unless the target step is at most the finish step, and a token finishes only when it lands exactly on that step.

QCan captures happen inside the home lane?

No. Captures are checked only while a token is on the common circular path. Home lanes and finish cells are color-specific.

QDo we need user input, graphics, or networking?

Not in the core design. LudoGame exposes a turn loop and events; UI and network adapters can call into it or observe it later.

UML Class Diagram

Rendering diagram…
The model separates **token lifecycle**, **board coordinate rules**, **movement validation**, and **turn orchestration**. The game owns the loop, while strategies and observers provide replaceable policies and outputs.

Sequence Diagram

Rendering diagram…
A turn rolls the dice, chooses a legal token, delegates validation and mutation to the movement strategy, lets the board resolve captures, then updates game state and notifies observers.

Entity Identification

LudoGame

Aggregate root and turn manager. Holds players, board, dice, movement rules, observers, current player index, game state, and winner.

playersboarddicemovementStrategyobserverscurrentPlayerIndexstatewinner

Player

Represents one participant and owns four tokens of a single color. It answers hasWon by checking that all tokens are finished.

colortokens

Token

Owns token lifecycle state and position as steps from its color start. It is the only class that changes a token between HOME, ACTIVE, and FINISHED.

idownerstatestepsFromStart

Board

Encodes common path length, finish step, color entry cells, safe cells, global position conversion, and capture detection.

PATH_LENGTHFINISH_STEPentryIndexByColorsafeCells

MovementStrategy

Rule policy for movement validation and state mutation. The standard strategy enforces 6-to-enter, exact finish, and capture checks.

canMovemove

Dice

Injected source of rolls. RandomDice is production-like; ScriptedDice makes demos and tests repeatable.

roll

MoveResult

Immutable result object returned by the movement strategy. It carries legality, a human-readable message, and captured tokens.

legalmessagecapturedTokens

GameObserver

Notification seam for UI, logs, analytics, or tests. Observers receive text events without influencing game rules.

onEvent

Design Patterns Used

State

TokenState and GameState make lifecycle transitions explicit. A token cannot jump from HOME to FINISHED; it must enter, move, and finish through controlled methods.

Strategy

MovementStrategy isolates the rule set for legal movement, captures, and exact finish. Dice also uses the same idea so random and scripted roll policies are interchangeable.

Observer

GameObserver decouples gameplay from output. A console logger, UI renderer, replay recorder, or metrics collector can subscribe without changing LudoGame.

Factory Method

Player.create and LudoGame.standard centralize object creation for players, four tokens per player, board, and default rules. Callers do not assemble an inconsistent game graph by hand.

Step-by-Step Design

  1. 1Model token state before modelling the board

    A token has only three meaningful states: HOME, ACTIVE, and FINISHED. Store position as stepsFromStart only while the token is active, and expose methods that enforce legal transitions.

    enum TokenState {
        HOME, ACTIVE, FINISHED
    }
    
    public void leaveHome() {
        if (state != TokenState.HOME) {
            throw new IllegalStateException("token is not at home");
        }
        state = TokenState.ACTIVE;
        stepsFromStart = 0;
    }
  2. 2Represent each color path with relative steps

    Keep one common path of 52 cells and give each color an entry index. A token's common-path coordinate is derived from its owner color plus stepsFromStart, so each player can share the same movement code.

    public int globalPosition(Token token) {
        if (!isOnCommonPath(token)) {
            throw new IllegalArgumentException("token is not on the common path");
        }
        int entryIndex = entryIndexByColor.get(token.getOwner());
        return (entryIndex + token.getStepsFromStart()) % PATH_LENGTH;
    }
  3. 3Validate movement in a replaceable strategy

    StandardLudoMovementStrategy owns the rules: a home token needs 6, a finished token cannot move, and an active token cannot overshoot the finish step.

    public boolean canMove(Board board, Token token, int roll) {
        if (token.isFinished()) {
            return false;
        }
        if (token.isHome()) {
            return roll == 6;
        }
        return token.getStepsFromStart() + roll <= board.finishStep();
    }
  4. 4Resolve captures through the board

    After a token moves on the common path, the board checks whether the landing cell is safe. Only non-safe common cells can capture opponent tokens; home lanes and finish cells never capture.

  5. 5Keep turn flow in the game aggregate

    LudoGame rolls dice, selects the first legal token for the sample strategy, applies the move, checks for a winner, then either advances or grants an extra turn on 6. This keeps sequencing away from Board and Token.

  6. 6Publish domain events instead of printing inside rules

    Movement and turn outcomes are sent to GameObserver. The implementation includes a console observer, but tests can register an observer that stores events for assertions.

Complete Java Implementation

Loading…

Explanation of Every Class

Token

Represents one movable piece. It owns the TokenState and stepsFromStart, and exposes controlled transitions for entering, moving, finishing, and being captured.

Player

Creates and owns exactly four tokens of one PlayerColor. Its hasWon method is the winner predicate used by LudoGame after every legal move.

Dice

A small strategy interface for roll generation. RandomDice models normal play, while ScriptedDice provides deterministic rolls for demos and tests.

Board

Contains the board coordinate system: common path length, finish step, entry positions by color, safe cells, global position conversion, and capture resolution.

MovementStrategy

Defines and implements legal movement. StandardLudoMovementStrategy checks 6-to-enter, exact finish, and finished-token immobility before mutating token state.

LudoGame

Coordinates the game loop. It rolls dice, selects a legal token, delegates movement, notifies observers, grants extra turns on 6, and records the winner.

Main

A deterministic demo that builds a two-player game through the factory method, attaches a console observer, and runs a bounded number of turns.

Dry Run

Sample input

Two-player game with RED and GREEN. Assume the listed token positions before each step where needed: R1 and G1 are the active tokens, safe cells are 0, 8, 13, 21, 26, 34, 39, 47, and the finish step is 56.

StepRoll and stateMovement decisionCapture or ruleTurn outcome
1RED R1 is HOME, roll is 6R1 leaves home and lands on cell 0No capture because cell 0 is safeRED gets another turn
2RED R1 is at step 8, roll is 2R1 moves to step 10, global cell 10GREEN G1 on cell 10 is captured and sent HOMETurn advances unless variant grants extra rules
3GREEN G1 is HOME, roll is 4No token can leave homeState is unchanged because move is illegalTurn advances to RED
4RED R1 is at step 54, roll is 3Move is rejected because target step 57 overshoots 56Exact finish rule protects the stateTurn advances
5RED R1 is at step 54, roll is 2R1 lands exactly on step 56Token becomes FINISHED; no capture in home laneWinner check runs for RED

The dry run shows the three highest-risk rules: a 6 is required to enter, capture is disabled on safe cells and outside the common path, and finishing requires an exact count.

Complexity Analysis

OperationTimeSpaceNote
chooseFirstLegalTokenO(T)O(1)T is tokens per player, fixed at 4 in normal Ludo.
moveO(P × T)O(C)After validation, capture detection scans opponent tokens; C is captured tokens on the landing cell.
takeTurnO(P × T)O(C)A turn includes legal-token selection, movement, capture scan, observer notifications, and winner check.
snapshotO(P × T)O(P × T)Builds a display string for every token in the game.

With standard Ludo limits, these operations are effectively constant time. The asymptotic notation matters because the same design can support variants with more players, more tokens, or team boards.

Extensibility

Rule variants

Replace MovementStrategy to support three consecutive sixes losing the turn, no extra turn on 6, mandatory capture, or different finish rules.

Custom boards

Parameterize Board with path length, entry cells, safe cells, and finish step so regional variants do not change token or game code.

Human and bot players

Move token selection behind a TokenSelectionStrategy. The sample chooses the first legal token, but a UI or bot can choose differently.

Replay and audit

Observers can store domain events. A replay service can rebuild the game from dice rolls and selected token ids.

Alternative Designs

Explicit graph board

Represent every cell as a node with edges to the next common path cell or home-lane cell instead of computing positions with modular arithmetic.

Tradeoffs

Easier to visualize and customize, but more verbose for interviews and more error-prone to initialize by hand.

Polymorphic token states

Replace TokenState enum with HomeTokenState, ActiveTokenState, and FinishedTokenState classes that implement transition methods.

Tradeoffs

Closer to the classical State pattern, but heavy for three simple states unless many state-specific behaviors are expected.

Event-sourced game engine

Record DiceRolled, TokenMoved, TokenCaptured, and TokenFinished events and derive current state from the event log.

Tradeoffs

Great for multiplayer replay and debugging, but overkill for an in-memory interview implementation.

Common Mistakes

  • ×

    Storing one global board index on the token and forgetting that every color has a different entry cell.

  • ×

    Moving a token first and validating exact finish or capture rules afterward.

  • ×

    Allowing a home token to move on any roll instead of requiring a 6.

  • ×

    Capturing tokens on safe cells or inside a home lane.

  • ×

    Skipping winner detection after a token finishes.

  • ×

    Embedding console input or UI rendering inside Board or MovementStrategy.

  • ×

    Hard-coding random dice creation inside LudoGame, which makes tests flaky.

  • ×

    Advancing the turn incorrectly after rolling 6 or after a player has no legal move.

Follow-up Interview Questions

QHow would you let a human choose which token to move?

Add a TokenSelectionStrategy with inputs player, board, roll, and legal tokens. A console, UI, or bot strategy can select a token while LudoGame still owns turn sequencing.

QHow do you support three consecutive sixes losing the turn?

Track consecutive sixes in LudoGame or a TurnPolicy strategy. When the count reaches three, skip movement, reset the count, notify observers, and advance the turn.

QHow would you make the game safe for an online multiplayer server?

Make turn execution atomic per game id, persist events or snapshots, validate that the acting user owns the current player, and publish observer events to clients after commit.

QHow do you handle blockades where two same-color tokens share a cell?

Represent occupancy per cell and add blockade checks to MovementStrategy. The board can expose occupants of a global cell while the strategy decides whether passing or landing is legal.

QWhy not put all rules inside **Token**?

Token should protect its own lifecycle, but it does not know opponents, safe cells, or turn policy. Board-aware and player-aware rules belong in MovementStrategy and Board.

Production Considerations

Persistence

Store game snapshots or append-only events so active games survive process restarts and can be resumed across devices.

Concurrency

Guard each game with a per-game lock or transactional compare-and-set on version. Two clients must not submit moves for the same turn concurrently.

Fair dice

Use a server-side dice source and record roll events. Clients should never provide final dice values in competitive online play.

Observability

Emit metrics for abandoned games, average turns, captures, illegal move attempts, and game duration. Keep enough event detail to debug disputes.

Abuse prevention

Validate player identity, turn ownership, and token ownership on every submitted move. Rate-limit repeated illegal attempts.

What Interviewers Look For

  • Did you isolate turn management from movement validation and board math?

  • Can you explain why a token stores relative steps instead of absolute cells?

  • Did you preserve invariants when a move is illegal or overshoots the finish?

  • Can you replace dice and movement policies for deterministic tests and variants?

  • Did you make captures depend on common-path position and safe-cell checks?

  • Is the winner detected from player token state rather than a separate counter that can drift?

Quiz

0/5 answered

  1. 1.Why does a token store **stepsFromStart** instead of only a global board cell?

  2. 2.Which rule should be checked before moving a token from HOME?

  3. 3.When should capture logic run?

  4. 4.What does **MovementStrategy** primarily buy in this design?

  5. 5.Why inject **Dice** instead of constructing **RandomDice** inside **LudoGame**?

Practice Variants

Add player-selected moves

Beginner

Replace first-legal-token selection with a TokenSelectionStrategy and validate user-chosen token ids before applying moves.

Support three consecutive sixes

Intermediate

Add a turn policy that tracks consecutive sixes, cancels the third move, and advances the turn with an observer event.

Implement blockades

Advanced

Allow same-color tokens to share a cell and block opponents from passing. Decide whether blockade checks belong in Board, MovementStrategy, or a new occupancy service.

Flashcards

Cheat Sheet

Entities: LudoGame, Player, Token, Board, Dice, MovementStrategy, MoveResult, GameObserver.

State: Token is HOME, ACTIVE, or FINISHED; game is NOT_STARTED, RUNNING, or FINISHED.

Movement rules: HOME needs roll 6; ACTIVE moves by dice; target must not exceed finish step 56; exact landing on 56 finishes.

Capture rules: convert relative steps to global common-path cells; capture opponents only on non-safe common cells.

Turn flow: roll dice → choose legal token → move via strategy → resolve capture → check winner → grant extra turn on 6 or advance.

Patterns: State for lifecycle, Strategy for movement and dice, Observer for events, Factory Method for standard setup.

Complexity: bounded constant for standard Ludo; generally O(P×T) per turn because capture checks may inspect all tokens.

References