2Brute2Best
πŸ”₯0
P19

Design Chess With Move Validation & Full Undo/Redo

Hard High-frequency interview topic Pro OnlyFactory MethodStrategyCommandMemento
⚑ 30-Second Interview Cheat SheetP19 · 45-Min Design Plan
3 Patterns Combined
1. Scope Boundaries

In a 45-minute LLD interview, the interviewer assesses your ability to decouple piece movement geometry from board state and implement reversible action history. Scope the design to: an 8x8 board representation, piece movement validation via IMoveRule strategies with raycast obstruction checking, piece assembly via PieceFactory, and reversible MoveCommand executions encapsulating captured piece Mementos for full bidirectional undo() and redo(). Special rules like en passant, castling, and pawn promotion can be discussed as advanced rules.

2. Core Noun Entities
ChessGamestateful-class
Boardstateful-class
Piecestateful-class
IMoveRuleinterface
3. Hotspot β†’ Pattern
Piece movement geometric validation and path obstacle raycasting β†’ Strategy Pattern (IMoveRule hierarchy: RookRule, BishopRule, KnightRule, etc.)
Reversible move execution, captured piece restoration, and redo history β†’ Command Pattern + Memento Pattern (MoveCommand storing captured piece snapshot)
Piece creation and strategy binding β†’ Factory Method (PieceFactory)
01

Problem statement & clarifying requirements

Design an extensible 2-player Chess Engine supporting piece movement validation and full bidirectional Undo/Redo. Each piece type (Pawn, Rook, Knight, Bishop, Queen, King) follows distinct movement geometries and path obstruction checks, piece creation is centralized via a Factory Method, and moves are executed as reversible Commands encapsulating Memento snapshots so that undos seamlessly resurrect captured pieces back onto the board.

Questions you should ask the interviewer first
β€œHow are different piece movement rules organized without massive switch statements?”

Each piece delegates its movement logic to a dedicated IMoveRule Strategy (RookRule, BishopRule, KnightRule, PawnRule, etc.) that inspects rank/file deltas and intermediate board obstruction.

β€œHow does Undo handle captured enemy pieces?”

The Command + Memento pattern: before mutating the board, MoveCommand snapshots the destination piece (if any). Calling undo() restores the moved piece to its origin and resurrects the captured piece at the destination.

β€œWhat happens to the Redo stack when a user makes a new move after an undo?”

In accordance with standard Command history semantics, executing any new move invalidates and clears the Redo stack, branching into a new timeline.

β€œHow are turns enforced between players?”

The ChessGame context tracks currentTurn (White / Black). A move is rejected immediately if the piece at the source square does not match the active player's color.

02

First, sketch the design yourself

Spend 5 minutes listing the classes, who owns whom, and which interface hides the part that changes.

  1. 1.

    Separate piece identity and color from movement geometry: a Piece has a Color and a type_, but delegates spatial validation to an interchangeable IMoveRule.

  2. 2.

    Notice that Knights jump over pieces, while Rooks, Bishops, and Queens require an obstacle-free trajectory: encapsulate path walking in Board::isPathClear().

  3. 3.

    A move is not just source and destination coordinates: an undo must restore the entire previous tile state, making Memento snapshotting inside Command the cleanest architecture.

03

How to think through this problem (5-step walkthrough)

Step 1 Β· Scope the 45-minute target & core boundary

In a 45-minute LLD interview, the interviewer assesses your ability to decouple piece movement geometry from board state and implement reversible action history. Scope the design to: an 8x8 board representation, piece movement validation via IMoveRule strategies with raycast obstruction checking, piece assembly via PieceFactory, and reversible MoveCommand executions encapsulating captured piece Mementos for full bidirectional undo() and redo(). Special rules like en passant, castling, and pawn promotion can be discussed as advanced rules.

Step 2 Β· Extract candidate nouns (and reject false classes)

Not every noun in the prompt deserves its own class. Separate dumb data structs from stateful managers, and turn trivial nouns into fields or enums.

ChessGame
Stateful Class / Manager

Central game context orchestrating player turns (White/Black), holding the 8x8 Board, validating active player ownership, and managing undoStack_ / redoStack_ command history.

Board
Stateful Class / Manager

Owns the 8x8 tile grid (std::shared_ptr<Piece> grid_[8][8]) and performs raycast line-of-sight obstacle checks (isPathClear(from, to)) for sliding pieces.

Piece
Stateful Class / Manager

Represents an individual chess piece on the board, binding piece color (Color), piece type (PieceType), and a reference to its specific IMoveRule strategy.

IMoveRule
Abstract Interface

Strategy interface declaring canMove(board, from, to, color) for piece-specific trajectories (RookRule, BishopRule, KnightRule, QueenRule, KingRule, PawnRule).

MoveCommand
Stateful Class / Manager

Command object encapsulating move coordinates, board mutation, and an internal Memento snapshot (capturedPiece_) enabling perfect bidirectional execute() and undo().

PieceFactory
Stateful Class / Manager

Factory Method centralizing piece instantiation and coupling pieces to their appropriate IMoveRule strategy singletons.

SquareColor / MoveHistoryString
Reject as Class β†’ Field / Method

Trap noun β€” do not create a SquareColor class for board tiles; square shading is a parity calculation (row + col) % 2 == 0. Similarly, move history should be stored as executable MoveCommand objects on an undo stack, not raw text strings that would require parsing to reverse.

Step 3 Β· Draft the naive design & spot what breaks

A naive implementation puts move validation inside a massive switch(piece.type) inside Board::move(). Adding new pieces (like fairy chess pieces) or special rules forces modifying core board logic. Even worse, attempting undo by just moving the piece back from to to from permanently destroys the captured enemy piece, making proper chess undo impossible without replaying the entire match history from move 1.

Step 4 Β· Map change hotspots to design patterns
Piece movement geometric validation and path obstacle raycasting→ Strategy Pattern (IMoveRule hierarchy: RookRule, BishopRule, KnightRule, etc.)

A monolithic switch-statement couples the board to every piece geometry; adding new piece types (e.g. Princess, Empress) violates the Open-Closed Principle.

Reversible move execution, captured piece restoration, and redo history→ Command Pattern + Memento Pattern (MoveCommand storing captured piece snapshot)

Ad-hoc coordinate swapping loses captured pieces and makes multi-level undo/redo fragile, stateful, and error-prone.

Piece creation and strategy binding→ Factory Method (PieceFactory)

Scattering piece instantiation across board setup duplicates rule bindings and complicates testing with custom pieces.

Step 5 Β· Lock down C++23 ownership, invariants & concurrency
  • βœ“

    Command-Memento reversibility invariant: For any executed MoveCommand, calling undo() restores the active piece to from and resurrects capturedPiece_ at to, restoring the board to its exact pre-move tile configuration.

  • βœ“

    Redo stack invalidation: Executing any new move immediately clears the redoStack_, preventing divergent history timelines after an undo.

  • βœ“

    Raycast line-of-sight clearance: For sliding pieces (Rook, Bishop, Queen), every intermediate square strictly between from and to along the ray must be empty (nullptr); Knights are exempt from path clearance.

04

Entities & design patterns used

Brute2Best Pro Content

Unlock Full UML Diagram & C++23 Solution

The complete UML diagram, production-ready C++23 code, follow-up extensions, and design pitfall analysis are part of Brute2Best Pro. All 7 foundation chapters are 100% free.

All 440 visual dry runs & algorithms
Interactive step-by-step playback with pointer & array state transitions
52 comprehensive LLD chapters
Interactive UML diagrams, real-world stories (Food Delivery, Trading, RPG), and practice solutions
40 C++ basics labs & hardware memory models
Vtables, byte layouts, assembly insights, and multi-threading race conditions
Production-ready C++23 source code
Modern idioms, clean contracts, time/space complexity derivations, and interview takeaways

First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.

Systems Integration

Related C++ Systems & Algorithmic Foundations

Deep dive into underlying layers