THN Interview Prep

Design Chess (LLD)

1. Requirements

  • Functional

    • 8x8 board with standard piece placement; enforce legal moves per piece type.
    • Detect check, checkmate, stalemate; support castling and en passant with rules encoding.
    • Maintain move history for repetition and half-move clock if implementing draw rules.
  • Non-Functional

    • Move validation should be fast for interactive play; extensible for variant pieces.
    • Clear separation: rules engine vs UI vs persistence.
  • Assumptions / Out of Scope

    • Network multiplayer transport omitted; same process two players or engine vs engine.

2. Core Entities

EntityResponsibilityKey Attributes
GameSession orchestrationboard, currentSide, status, moveHistory
Board8x8 cellscells grid
CellSquare occupantrow, column, piece optional
PieceBehavior templatecolor, type, hasMoved
MoveAtomic plyfromSquare, toSquare, promotion
RuleEngineValidates and appliesreferences game rules
GameStatusTerminal detectioninProgress, checkmate, stalemate, draw

3. Class Diagram

Loading diagram…

4. State / Sequence Diagram (where relevant)

Loading diagram…

5. Design Patterns Applied

  • Strategy — Different Piece subclasses or strategy objects for movement. Strategy pattern.
  • Memento — Snapshot board for undo or repetition detection. Memento pattern.
  • Visitor (optional) — Traverse board for attack maps. Visitor pattern.

6. Implementation

Go

package chess

type Color int
type PieceKind int

type Piece struct {
    Color     Color
    Kind      PieceKind
    HasMoved  bool
}

type Board struct {
    Cells [8][8]*Piece
}

type Move struct {
    FromRow, FromCol int
    ToRow, ToCol     int
    Promotion        PieceKind
}

type Game struct {
    Board        Board
    SideToMove   Color
    Moves        []Move
}

func (game *Game) SubmitMove(move Move) error { /* delegates RuleEngine */ }

JavaScript

class Piece {
  constructor({ color, kind }) {
    this.color = color;
    this.kind = kind;
    this.hasMoved = false;
  }
}

class Game {
  constructor() {
    this.board = Board.initialStandard();
    this.sideToMove = 'white';
    this.moveHistory = [];
  }
  submitMove(move) { /* ... */ }
}

7. Concurrency / Thread Safety

  • Collisions: Rare for single UI; backend chess server must serialize moves per gameId.
  • Granularity: One mutex per game session.
  • Go: sync.Mutex on Game if shared across goroutines.
  • JavaScript: Single-threaded; immutability of board snapshots simplifies reasoning.

8. Extensibility & Followups

  • Bitboards for high-performance move generation.
  • UCI adapter wrapping RuleEngine for stockfish-style integration.
  • Variants: odd-sized boards via strategy injection per variant id.
  • Edge cases: insufficient material draws, threefold repetition tracking.

Last updated on

Spotted something unclear or wrong on this page?

On this page