Design a Chess Game

Design the object model for a two-player chess game that runs in a single process: the board, the six kinds of pieces and how each one moves, whose turn it is, and the record of moves played.

The engine must refuse illegal moves, including moves that would leave your own king attacked, and it must say after every move whether the side to play is in check, checkmated or stalemated. A UI and network layer will sit on top later, so the core should expose a small, clean API.

You do not have to implement every rule. Agree with the interviewer on a simplified but correct core (castling and en passant can be left as extensions), then spend most of the 45 minutes on the class hierarchy and on how check and checkmate are detected.

Use the LLD board for your class diagram and the LLD code tab to write and run your classes.

Design Path · Low-Level Design · problem 61 of 70

Ask before you design. Try answering each yourself, then compare.

  1. Do we need castling, en passant and under-promotion?
    Typical answer

    Leave castling and en passant as extensions; promote pawns to a queen automatically. Design so they can be added.

  2. Is this two humans on one device, or do we need an AI opponent?
    Typical answer

    Two humans calling the same Game object. An AI player is a follow-up.

  3. How are moves given to the engine?
    Typical answer

    As a source and destination square in coordinate form, like e2 to e4. Full algebraic notation parsing is out of scope.

  4. Which game-ending conditions matter?
    Typical answer

    Checkmate and stalemate. Resignation is easy to add; repetition and the fifty-move rule are follow-ups.

  5. Do we need move history and undo?
    Typical answer

    Keep a history of moves played. Undo is a follow-up, but the design should not make it hard.

  6. Any performance target?
    Typical answer

    Validating a move should feel instant (well under 100 ms). This is not a search engine, so clarity beats speed.

Which piece behaviours are really the same algorithm with different parameters? A rook and a bishop differ only in direction.
Split move generation into two steps: where can this piece go, and does that leave my king attacked?
To know whether a move leaves you in check, what is the simplest thing you can do with the board?
Checkmate and stalemate share one question. What is it, and what separates the two answers?
Pawns move one way and capture another. Where does that difference show up in your API?

Requirements

Functional

  • Set up the standard starting position.
  • Accept a move for the side to play and reject it if it is illegal for that piece or leaves its own king in check.
  • After each move, report active, check, checkmate or stalemate.
  • Record every move played, including captures.

Non-functional

  • Move validation under 100 ms on a laptop, even with full legal-move generation.
  • Adding a new piece type or rule should not require editing the Game class.
  • The core is deterministic and has no I/O, so it can be unit-tested and reused behind any UI.

Out of scope

  • Castling, en passant and under-promotion (discuss as extensions).
  • Clocks, rating, matchmaking and networking.
  • A computer opponent.

Class design

Pieces. Piece is abstract with two methods: targets (squares it could move to, ignoring king safety) and attacks (squares it threatens, which equals targets for everything except the pawn). Rook, bishop, queen, king and knight are all VectorPieces: each walks a set of direction vectors up to a reach and stops at the first occupied square, so a new subclass is just two class attributes. Pawn is the special case: forward pushes only onto empty squares, a double step from its start rank, and diagonal captures.

Board. Holds a map from square to piece. after(src, dst) returns a new board with the move applied, which makes 'try the move and see' trivial. in_check finds the king and asks whether any enemy piece attacks it; legal_moves keeps only targets whose resulting board leaves your own king safe.

Game. Owns the turn, the status and the Move history. move validates ownership and legality, records the move, swaps the turn and re-evaluates: no legal replies plus check is checkmate, no legal replies without check is stalemate. Special moves plug in by extending move generation, not the Game loop.

Open the LLD board and press Reference to see the class diagram.

Patterns used

  • Template-style polymorphism: VectorPiece implements the ray walk once and subclasses only supply vectors and reach.
  • Factory: Board.standard() builds the opening position in one place, so variants like Chess960 can add their own factory.
  • Immutable value objects: Board.after returns a new board and Move is frozen, which makes legality checks and history safe.
  • State: GameStatus drives what the Game accepts; a finished game rejects further moves.

Reference implementation

from abc import ABC, abstractmethod
from dataclasses import dataclass
from enum import Enum
from typing import Dict, List, Optional, Tuple

Square = Tuple[int, int]  # (file 0-7 = a-h, rank 0-7 = 1-8)


def parse(s: str) -> Square:
    return "abcdefgh".index(s[0]), int(s[1]) - 1


class Color(Enum):
    WHITE = "white"
    BLACK = "black"

    @property
    def other(self) -> "Color":
        return Color.BLACK if self is Color.WHITE else Color.WHITE


class GameStatus(Enum):
    ACTIVE, CHECK, CHECKMATE, STALEMATE = "active", "check", "checkmate", "stalemate"


class Piece(ABC):
    symbol = "?"

    def __init__(self, color: Color):
        self.color = color

    @abstractmethod
    def targets(self, board: "Board", sq: Square) -> List[Square]:
        """Squares this piece could move to, ignoring whether its own king is left in check."""

    def attacks(self, board: "Board", sq: Square) -> List[Square]:
        return self.targets(board, sq)

    def __str__(self):
        return self.symbol.upper() if self.color is Color.WHITE else self.symbol


class VectorPiece(Piece):
    """Moves along fixed vectors, up to `reach` steps; covers rook, bishop, queen, king and knight."""
    vectors: Tuple[Square, ...] = ()
    reach = 7

    def targets(self, board, sq):
        out = []
        for df, dr in self.vectors:
            for step in range(1, self.reach + 1):
                t = (sq[0] + df * step, sq[1] + dr * step)
                if not board.on_board(t):
                    break
                other = board.at(t)
                if other is None or other.color is not self.color:
                    out.append(t)
                if other is not None:
                    break                       # blocked by any piece
        return out


STRAIGHT = ((1, 0), (-1, 0), (0, 1), (0, -1))
DIAGONAL = ((1, 1), (1, -1), (-1, 1), (-1, -1))


class Rook(VectorPiece):
    symbol, vectors = "r", STRAIGHT


class Bishop(VectorPiece):
    symbol, vectors = "b", DIAGONAL


class Queen(VectorPiece):
    symbol, vectors = "q", STRAIGHT + DIAGONAL


class King(VectorPiece):
    symbol, vectors, reach = "k", STRAIGHT + DIAGONAL, 1


class Knight(VectorPiece):
    symbol, reach = "n", 1
    vectors = ((1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2))


class Pawn(Piece):
    symbol = "p"

    def targets(self, board, sq):
        d, (f, r) = (1 if self.color is Color.WHITE else -1), sq
        out = [t for t in self.attacks(board, sq) if board.at(t) and board.at(t).color is not self.color]
        if board.on_board((f, r + d)) and board.at((f, r + d)) is None:
            out.append((f, r + d))
            if r == (1 if self.color is Color.WHITE else 6) and board.at((f, r + 2 * d)) is None:
                out.append((f, r + 2 * d))
        return out

    def attacks(self, board, sq):
        d = 1 if self.color is Color.WHITE else -1
        return [t for t in ((sq[0] - 1, sq[1] + d), (sq[0] + 1, sq[1] + d)) if board.on_board(t)]


class Board:
    def __init__(self, grid: Optional[Dict[Square, Piece]] = None):
        self.grid: Dict[Square, Piece] = dict(grid or {})

    @staticmethod
    def standard() -> "Board":
        """Factory for the opening position."""
        b, back = Board(), [Rook, Knight, Bishop, Queen, King, Bishop, Knight, Rook]
        for f, cls in enumerate(back):
            b.grid[(f, 0)], b.grid[(f, 7)] = cls(Color.WHITE), cls(Color.BLACK)
            b.grid[(f, 1)], b.grid[(f, 6)] = Pawn(Color.WHITE), Pawn(Color.BLACK)
        return b

    @staticmethod
    def on_board(sq: Square) -> bool:
        return 0 <= sq[0] < 8 and 0 <= sq[1] < 8

    def at(self, sq: Square) -> Optional[Piece]:
        return self.grid.get(sq)

    def after(self, src: Square, dst: Square) -> "Board":
        """A copy of the board with one move applied (pawns reaching the last rank become queens)."""
        b = Board(self.grid)
        piece = b.grid.pop(src)
        if isinstance(piece, Pawn) and dst[1] in (0, 7):
            piece = Queen(piece.color)
        b.grid[dst] = piece
        return b

    def in_check(self, color: Color) -> bool:
        king = next(sq for sq, p in self.grid.items() if isinstance(p, King) and p.color is color)
        return any(king in p.attacks(self, sq) for sq, p in self.grid.items() if p.color is not color)

    def legal_moves(self, color: Color) -> List[Tuple[Square, Square]]:
        return [(sq, t) for sq, p in list(self.grid.items()) if p.color is color
                for t in p.targets(self, sq) if not self.after(sq, t).in_check(color)]

    def render(self) -> str:
        return "\n".join(f"{r + 1} " + " ".join(str(self.grid.get((f, r), ".")) for f in range(8))
                         for r in range(7, -1, -1)) + "\n  a b c d e f g h"


@dataclass(frozen=True)
class Move:
    color: Color
    piece: str
    src: Square
    dst: Square
    captured: Optional[str]

    def __str__(self):
        name = lambda sq: "abcdefgh"[sq[0]] + str(sq[1] + 1)
        return f"{self.piece}{name(self.src)}{'x' if self.captured else '-'}{name(self.dst)}"


class Game:
    def __init__(self, board: Optional[Board] = None):
        self.board = board or Board.standard()
        self.turn, self.status = Color.WHITE, GameStatus.ACTIVE
        self.history: List[Move] = []

    def move(self, src_s: str, dst_s: str) -> GameStatus:
        if self.status in (GameStatus.CHECKMATE, GameStatus.STALEMATE):
            raise ValueError("game is over")
        src, dst = parse(src_s), parse(dst_s)
        piece = self.board.at(src)
        if piece is None or piece.color is not self.turn:
            raise ValueError(f"no {self.turn.value} piece on {src_s}")
        if (src, dst) not in self.board.legal_moves(self.turn):
            raise ValueError(f"illegal move {src_s}-{dst_s}")
        captured = self.board.at(dst)
        self.history.append(Move(self.turn, str(piece), src, dst, str(captured) if captured else None))
        self.board, self.turn = self.board.after(src, dst), self.turn.other
        self.status = self._evaluate()
        return self.status

    def _evaluate(self) -> GameStatus:
        check, can_move = self.board.in_check(self.turn), bool(self.board.legal_moves(self.turn))
        if not can_move:
            return GameStatus.CHECKMATE if check else GameStatus.STALEMATE
        return GameStatus.CHECK if check else GameStatus.ACTIVE


if __name__ == "__main__":
    g = Game()
    for bad in [("e2", "e5"), ("e7", "e5")]:
        try:
            g.move(*bad)
        except ValueError as e:
            print("rejected:", e)
    for src, dst in [("f2", "f3"), ("e7", "e5"), ("g2", "g4"), ("d8", "h4")]:
        status = g.move(src, dst)
        print(f"{g.history[-1]!s:8} -> {status.value}")
    print(g.board.render())
    print("winner:", g.turn.other.value, "| moves:", " ".join(map(str, g.history)))

Trade-offs

  • Copying the board for each candidate move is simple and safe but allocates a lot; make/unmake on one board is faster but easy to get wrong.
  • A dictionary of squares is readable but slower than an array or bitboards, which only matter for search engines.
  • One class per piece type reads naturally but is more code than a data table of vectors; the hybrid used here keeps both.
  • Recomputing legal moves after every move is simple but repeats work that incremental attack maps would avoid.

What a strong answer shows

  • Uses a piece hierarchy where shared movement logic lives once, not copied into six classes.
  • Separates pseudo-legal moves from legal moves and filters by king safety.
  • Detects check by asking whether enemy pieces attack the king square, with pawn attacks handled separately from pushes.
  • Defines checkmate and stalemate correctly in terms of legal moves.
  • Keeps turn, history and status in a Game object distinct from the Board.
  • Explains how castling, en passant or undo would fit without rewriting the core.

Mistakes to avoid

  • Putting all movement rules in one giant switch inside the Board or Game.
  • Forgetting that a move is illegal when it exposes your own king, for example moving a pinned piece.
  • Treating a pawn's forward push as an attack, which produces false checks.
  • Calling it checkmate whenever the king cannot move, ignoring blocks and captures by other pieces.
  • Mutating the real board to test a move and forgetting to restore it on every path.

Follow-ups to expect

  • How would you add castling? (A King rule needing move history: neither piece has moved, path empty and not attacked.)
  • How would you support undo? (Replay history from the start, or store the captured piece in each Move and reverse it.)
  • How would you detect threefold repetition? (Hash each position plus side to move and count occurrences.)
  • How would you plug in a computer player? (A Player interface; the AI picks from Board.legal_moves with a search.)

Practice next

Next Post Previous Post
No Comment
Add Comment
comment url