Chess Game Object Model
Problem Design an object-oriented model for a chess game covering the board, the pieces, the players, and move validation, and explain how the design accommodates the special rules.
Requirements
Piece.isValidMove(from: Square, to: Square, board: Board) -> boolBoard.getPiece(square) -> Piece?,Board.applyMove(move) -> MoveResultGame.makeMove(player, from, to) -> MoveResult— enforces turn order and legalityGame.getStatus() -> GameStatus(IN_PROGRESS, CHECK, CHECKMATE, STALEMATE, DRAW)
Core design
- Abstract
Piecebase class holding colour and an abstractisValidMove(from, to, board); concreteKing,Queen,Rook,Bishop,Knight,Pawnsubclasses each own their movement rule. This is the polymorphism payoff — adding a fairy piece means adding one class, not editing a switch. Boardholds an 8x8 grid ofPiecereferences (or null/emptySquareobjects), and knows only geometry and occupancy — not turn order.Moveis a value object (from, to, piece, captured piece, promotion, flags). Making it explicit is what enables undo, move history, and notation output.Playerholds colour and captured pieces;Gameis the controller that owns turn order, invokes validation, applies the move, then recomputes status.- Two-tier validation: pseudo-legal (does the piece move that way, is the path clear, is the target not own-colour) lives on
Piece; full legality (does this move leave my own king in check) lives onGame, since a piece cannot see the whole game state's king safety.
Discussion points
- Special moves are where naive designs break: castling needs king/rook "has moved" state plus three squares free of attack; en passant needs the previous move; promotion means the board must swap a piece instance mid-game. Discuss carrying these in
Moveflags plus a smallGameState(castling rights, en-passant target) rather than scattering booleans across pieces. - Check detection: generate opponent moves and test attack on the king square — simple but O(pieces x moves). Discuss caching an attack map vs. recomputing.
- Checkmate vs. stalemate differ only by whether the king is currently attacked; both require "no legal move exists", so legal-move generation must be shared.
- Trade-off: piece-owned rules (open to extension) vs. a central rules engine (easier to handle cross-piece rules like en passant).
- Draw conditions — fifty-move rule, threefold repetition, insufficient material — need position hashing and history, not just the current board.
- Undo/redo falls out naturally from an immutable
Movelog; discuss restoring captured pieces and castling rights on undo.
asked …