LOW LEVEL DESIGN · MACHINE CODING · HARD · 27 OF 42

Design a Chess Game: Low-Level Design with Java Code

The hardest board game round, designed and coded: a board with en passant and castling state, pieces as a class hierarchy with shared sliding and stepping logic, moves as Commands that undo themselves, legal moves by make and unmake, check, checkmate and stalemate, castling, en passant and promotion, perft tests that prove the move generator, and the follow-ups, with a full Java 17 solution.

Patterns usedCommand

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
1 / 24

Press play to hear the narration, or step through at your own pace. The full Java code is below.

Full Java solution

One file, Java 17, 522 lines, with a small main() demo. Save it as Chess.java, then run javac Chess.java && java Chess.

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

/** Chess: polymorphic pieces, legal move generation, check, mate, stalemate, special moves, undo. */
public class Chess {

    // ---------- the model ----------
    enum Color {
        WHITE, BLACK;

        Color other() { return this == WHITE ? BLACK : WHITE; }
    }

    enum Status { ACTIVE, CHECK, CHECKMATE, STALEMATE }

    /** A square: file 0..7 is a..h, rank 0..7 is 1..8. */
    record Square(int file, int rank) {
        static Square of(String s) { return new Square(s.charAt(0) - 'a', s.charAt(1) - '1'); }

        boolean onBoard() { return file >= 0 && file < 8 && rank >= 0 && rank < 8; }

        Square plus(int df, int dr) { return new Square(file + df, rank + dr); }

        @Override
        public String toString() { return "" + (char) ('a' + file) + (char) ('1' + rank); }
    }

    // ---------- pieces: each one knows how it moves ----------
    abstract static class Piece {
        final Color color;

        Piece(Color color) { this.color = color; }

        abstract char letter();

        /** Squares this piece attacks from 'from' (used for check detection). */
        abstract List<Square> attacks(Board b, Square from);

        /** Squares it may move to, ignoring whether its own king is left in check. */
        List<Square> targets(Board b, Square from) {
            List<Square> out = new ArrayList<>();
            for (Square s : attacks(b, from)) {
                Piece p = b.at(s);
                if (p == null || p.color != color) out.add(s);
            }
            return out;
        }

        char symbol() { return color == Color.WHITE ? Character.toUpperCase(letter()) : letter(); }
    }

    /** Shared helper for pieces that move one step in fixed directions (king, knight). */
    abstract static class Stepper extends Piece {
        Stepper(Color c) { super(c); }

        abstract int[][] steps();

        @Override
        List<Square> attacks(Board b, Square from) {
            List<Square> out = new ArrayList<>();
            for (int[] d : steps()) {
                Square s = from.plus(d[0], d[1]);
                if (s.onBoard()) out.add(s);
            }
            return out;
        }
    }

    /** Shared helper for pieces that slide until blocked (rook, bishop, queen). */
    abstract static class Slider extends Piece {
        Slider(Color c) { super(c); }

        abstract int[][] directions();

        @Override
        List<Square> attacks(Board b, Square from) {
            List<Square> out = new ArrayList<>();
            for (int[] d : directions()) {
                Square s = from.plus(d[0], d[1]);
                while (s.onBoard()) {
                    out.add(s);
                    if (b.at(s) != null) break; // blocked: the blocker itself is attacked
                    s = s.plus(d[0], d[1]);
                }
            }
            return out;
        }
    }

    static final int[][] STRAIGHT = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };
    static final int[][] DIAGONAL = { {1, 1}, {1, -1}, {-1, 1}, {-1, -1} };
    static final int[][] ALL_DIRS = { {1, 0}, {-1, 0}, {0, 1}, {0, -1}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1} };
    static final int[][] KNIGHT = { {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2} };

    static final class King extends Stepper {
        King(Color c) { super(c); }

        @Override
        char letter() { return 'k'; }

        @Override
        int[][] steps() { return ALL_DIRS; }
    }

    static final class Knight extends Stepper {
        Knight(Color c) { super(c); }

        @Override
        char letter() { return 'n'; }

        @Override
        int[][] steps() { return KNIGHT; }
    }

    static final class Rook extends Slider {
        Rook(Color c) { super(c); }

        @Override
        char letter() { return 'r'; }

        @Override
        int[][] directions() { return STRAIGHT; }
    }

    static final class Bishop extends Slider {
        Bishop(Color c) { super(c); }

        @Override
        char letter() { return 'b'; }

        @Override
        int[][] directions() { return DIAGONAL; }
    }

    static final class Queen extends Slider {
        Queen(Color c) { super(c); }

        @Override
        char letter() { return 'q'; }

        @Override
        int[][] directions() { return ALL_DIRS; }
    }

    /** The odd one: moves straight, captures diagonally, may move two from its start, en passant. */
    static final class Pawn extends Piece {
        Pawn(Color c) { super(c); }

        @Override
        char letter() { return 'p'; }

        int dir() { return color == Color.WHITE ? 1 : -1; }

        @Override
        List<Square> attacks(Board b, Square from) {
            List<Square> out = new ArrayList<>();
            for (int df : new int[] {-1, 1}) {
                Square s = from.plus(df, dir());
                if (s.onBoard()) out.add(s);
            }
            return out;
        }

        @Override
        List<Square> targets(Board b, Square from) {
            List<Square> out = new ArrayList<>();
            Square one = from.plus(0, dir());
            if (one.onBoard() && b.at(one) == null) {
                out.add(one);
                int startRank = color == Color.WHITE ? 1 : 6;
                Square two = from.plus(0, 2 * dir());
                if (from.rank() == startRank && b.at(two) == null) out.add(two);
            }
            for (Square s : attacks(b, from)) {
                Piece p = b.at(s);
                if ((p != null && p.color != color) || s.equals(b.enPassant)) out.add(s);
            }
            return out;
        }
    }

    static Piece fromLetter(char ch) {
        Color c = Character.isUpperCase(ch) ? Color.WHITE : Color.BLACK;
        return switch (Character.toLowerCase(ch)) {
            case 'k' -> new King(c);
            case 'q' -> new Queen(c);
            case 'r' -> new Rook(c);
            case 'b' -> new Bishop(c);
            case 'n' -> new Knight(c);
            case 'p' -> new Pawn(c);
            default -> throw new IllegalArgumentException("unknown piece " + ch);
        };
    }

    // ---------- the board ----------
    static final int WK = 1, WQ = 2, BK = 4, BQ = 8; // castling rights bits

    static final class Board {
        private final Piece[][] cells = new Piece[8][8];
        Square enPassant;   // square a pawn can capture onto, or null
        int castling;       // WK | WQ | BK | BQ

        Piece at(Square s) { return cells[s.file()][s.rank()]; }

        void put(Square s, Piece p) { cells[s.file()][s.rank()] = p; }

        Square kingOf(Color c) {
            for (int f = 0; f < 8; f++)
                for (int r = 0; r < 8; r++)
                    if (cells[f][r] instanceof King && cells[f][r].color == c) return new Square(f, r);
            throw new IllegalStateException("no " + c + " king");
        }

        boolean attacked(Square target, Color by) {
            for (int f = 0; f < 8; f++)
                for (int r = 0; r < 8; r++) {
                    Piece p = cells[f][r];
                    if (p != null && p.color == by && p.attacks(this, new Square(f, r)).contains(target))
                        return true;
                }
            return false;
        }

        /** Load the piece placement and castling rights from a FEN-style string. */
        static Board parse(String fen) {
            String[] parts = fen.split(" ");
            Board b = new Board();
            String[] rows = parts[0].split("/");
            for (int i = 0; i < 8; i++) {
                int f = 0;
                for (char ch : rows[i].toCharArray()) {
                    if (Character.isDigit(ch)) f += ch - '0';
                    else b.put(new Square(f++, 7 - i), fromLetter(ch));
                }
            }
            String rights = parts.length > 2 ? parts[2] : "-";
            if (rights.indexOf('K') >= 0) b.castling |= WK;
            if (rights.indexOf('Q') >= 0) b.castling |= WQ;
            if (rights.indexOf('k') >= 0) b.castling |= BK;
            if (rights.indexOf('q') >= 0) b.castling |= BQ;
            if (parts.length > 3 && !parts[3].equals("-")) b.enPassant = Square.of(parts[3]);
            return b;
        }

        String render() {
            StringBuilder sb = new StringBuilder();
            for (int r = 7; r >= 0; r--) {
                sb.append("  ").append(r + 1).append(' ');
                for (int f = 0; f < 8; f++) {
                    Piece p = cells[f][r];
                    sb.append(p == null ? '.' : p.symbol()).append(f < 7 ? " " : "\n");
                }
            }
            return sb.append("    a b c d e f g h\n").toString();
        }
    }

    // ---------- moves: Command objects that can undo themselves ----------
    static final class Move {
        final Square from, to;
        final Piece piece;
        final Piece promotion;      // new piece for a promotion, else null
        final Square captureAt;     // differs from 'to' only for en passant
        final Square rookFrom, rookTo; // set only for castling
        Piece captured;             // filled in by execute()
        private Square prevEnPassant;
        private int prevCastling;

        Move(Square from, Square to, Piece piece, Piece promotion, Square captureAt,
             Square rookFrom, Square rookTo) {
            this.from = from;
            this.to = to;
            this.piece = piece;
            this.promotion = promotion;
            this.captureAt = captureAt;
            this.rookFrom = rookFrom;
            this.rookTo = rookTo;
        }

        void execute(Board b) {
            prevEnPassant = b.enPassant;
            prevCastling = b.castling;
            captured = b.at(captureAt);
            b.put(captureAt, null);
            b.put(from, null);
            b.put(to, promotion != null ? promotion : piece);
            if (rookFrom != null) {
                b.put(rookTo, b.at(rookFrom));
                b.put(rookFrom, null);
            }
            boolean doubleStep = piece instanceof Pawn && Math.abs(to.rank() - from.rank()) == 2;
            b.enPassant = doubleStep ? new Square(from.file(), (from.rank() + to.rank()) / 2) : null;
            b.castling &= ~(rightsLostAt(from) | rightsLostAt(to)); // king or rook moved, or rook captured
        }

        void undo(Board b) {
            if (rookFrom != null) {
                b.put(rookFrom, b.at(rookTo));
                b.put(rookTo, null);
            }
            b.put(to, null);
            b.put(from, piece);
            b.put(captureAt, captured);
            b.enPassant = prevEnPassant;
            b.castling = prevCastling;
        }

        static int rightsLostAt(Square s) {
            return switch (s.toString()) {
                case "e1" -> WK | WQ;
                case "h1" -> WK;
                case "a1" -> WQ;
                case "e8" -> BK | BQ;
                case "h8" -> BK;
                case "a8" -> BQ;
                default -> 0;
            };
        }

        String uci() {
            return "" + from + to + (promotion == null ? "" : String.valueOf(promotion.letter()));
        }

        @Override
        public String toString() {
            String s = Character.toUpperCase(piece.letter()) + " " + from + "-" + to;
            if (rookFrom != null) s += " (castles)";
            else if (!captureAt.equals(to)) s += " (en passant)";
            if (promotion != null) s += " (promotes to " + Character.toUpperCase(promotion.letter()) + ")";
            return s;
        }
    }

    // ---------- the game ----------
    private final Board board;
    private Color turn;
    private final Deque<Move> history = new ArrayDeque<>();

    Chess(String fen) {
        this.board = Board.parse(fen);
        String[] parts = fen.split(" ");
        this.turn = parts.length > 1 && parts[1].equals("b") ? Color.BLACK : Color.WHITE;
    }

    static Chess standard() { return new Chess("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq -"); }

    /** Every move the side to move may legally make. */
    List<Move> legalMoves() {
        List<Move> legal = new ArrayList<>();
        for (Move m : pseudoMoves(turn)) {
            m.execute(board);
            if (!board.attacked(board.kingOf(turn), turn.other())) legal.add(m); // own king must be safe
            m.undo(board);
        }
        return legal;
    }

    private List<Move> pseudoMoves(Color side) {
        List<Move> out = new ArrayList<>();
        for (int f = 0; f < 8; f++)
            for (int r = 0; r < 8; r++) {
                Square from = new Square(f, r);
                Piece p = board.at(from);
                if (p == null || p.color != side) continue;
                for (Square to : p.targets(board, from)) {
                    boolean ep = p instanceof Pawn && to.equals(board.enPassant) && board.at(to) == null;
                    Square capAt = ep ? new Square(to.file(), from.rank()) : to;
                    if (p instanceof Pawn && (to.rank() == 0 || to.rank() == 7)) {
                        for (Piece promo : List.of(new Queen(side), new Rook(side), new Bishop(side),
                                new Knight(side)))
                            out.add(new Move(from, to, p, promo, capAt, null, null));
                    } else {
                        out.add(new Move(from, to, p, null, capAt, null, null));
                    }
                }
                if (p instanceof King) addCastling(out, from, p);
            }
        return out;
    }

    /** Castling: rights still held, squares between empty, king not in, through or into check. */
    private void addCastling(List<Move> out, Square kingSq, Piece king) {
        int rank = king.color == Color.WHITE ? 0 : 7;
        if (!kingSq.equals(new Square(4, rank))) return;
        Color enemy = king.color.other();
        int kingSide = king.color == Color.WHITE ? WK : BK, queenSide = king.color == Color.WHITE ? WQ : BQ;
        if (board.attacked(kingSq, enemy)) return;
        if ((board.castling & kingSide) != 0 && empty(rank, 5, 6)
                && !board.attacked(new Square(5, rank), enemy) && !board.attacked(new Square(6, rank), enemy))
            out.add(new Move(kingSq, new Square(6, rank), king, null, new Square(6, rank),
                    new Square(7, rank), new Square(5, rank)));
        if ((board.castling & queenSide) != 0 && empty(rank, 1, 3)
                && !board.attacked(new Square(3, rank), enemy) && !board.attacked(new Square(2, rank), enemy))
            out.add(new Move(kingSq, new Square(2, rank), king, null, new Square(2, rank),
                    new Square(0, rank), new Square(3, rank)));
    }

    private boolean empty(int rank, int fromFile, int toFile) {
        for (int f = fromFile; f <= toFile; f++) if (board.at(new Square(f, rank)) != null) return false;
        return true;
    }

    /** Play a move written like "e2e4" or "e7e8q". Rejects anything that is not legal right now. */
    Move play(String uci) {
        Status s = status();
        if (s == Status.CHECKMATE || s == Status.STALEMATE)
            throw new IllegalStateException("game over: " + s);
        for (Move m : legalMoves()) {
            boolean defaultQueen = m.promotion instanceof Queen && m.uci().equals(uci + "q");
            if (!m.uci().equals(uci) && !defaultQueen) continue;
            m.execute(board);
            history.push(m);
            turn = turn.other();
            return m;
        }
        throw new IllegalArgumentException("illegal move " + uci + " for " + turn);
    }

    /** Undo the last move: the Command reverses itself, then the turn flips back. */
    Move undo() {
        if (history.isEmpty()) throw new IllegalStateException("nothing to undo");
        Move m = history.pop();
        m.undo(board);
        turn = turn.other();
        return m;
    }

    Status status() {
        boolean inCheck = board.attacked(board.kingOf(turn), turn.other());
        boolean canMove = !legalMoves().isEmpty();
        if (canMove) return inCheck ? Status.CHECK : Status.ACTIVE;
        return inCheck ? Status.CHECKMATE : Status.STALEMATE;
    }

    Color turn() { return turn; }

    /** Count leaf positions at a depth: the standard way to prove a move generator is correct. */
    long perft(int depth) {
        if (depth == 0) return 1;
        long n = 0;
        for (Move m : legalMoves()) {
            m.execute(board);
            turn = turn.other();
            n += perft(depth - 1);
            turn = turn.other();
            m.undo(board);
        }
        return n;
    }

    // ---------- demo ----------
    static void check(boolean ok, String what) {
        if (!ok) throw new AssertionError(what);
    }

    static Chess playAll(Chess g, String moves) {
        for (String uci : moves.split(" ")) {
            Move m = g.play(uci);
            System.out.println("  " + g.turn().other() + ": " + m + " -> " + g.status());
        }
        return g;
    }

    public static void main(String[] args) {
        // 1. The shortest checkmate: two weak white moves, and the black queen mates.
        System.out.println("Quick checkmate:");
        Chess g = playAll(standard(), "f2f3 e7e5 g2g4 d8h4");
        System.out.print(g.board.render());
        check(g.status() == Status.CHECKMATE, "should be checkmate");
        try {
            g.play("a2a3");
            throw new AssertionError("moved after mate");
        } catch (IllegalStateException e) {
            System.out.println("Rejected: " + e.getMessage());
        }

        // 2. Undo: the queen goes back to d8 and it is Black's move again.
        Move undone = g.undo();
        System.out.println("Undo " + undone + ": " + g.turn() + " to move, " + g.status());
        check(g.status() == Status.ACTIVE && g.turn() == Color.BLACK, "undo should restore the position");

        // 3. Illegal moves: a king step that is too long, the wrong side, a blocked rook, a pin.
        Chess p = playAll(standard(), "e2e4 e7e5");
        for (String bad : List.of("e1e3", "d7d5", "a1a3")) {
            try {
                p.play(bad);
                throw new AssertionError("accepted " + bad);
            } catch (IllegalArgumentException e) {
                System.out.println("Rejected: " + e.getMessage());
            }
        }
        Chess pin = new Chess("4k3/4r3/8/8/8/8/4B3/4K3 w - -");
        check(pin.legalMoves().stream().noneMatch(m -> m.from.equals(Square.of("e2"))),
                "pinned bishop moved");
        System.out.println("Pinned bishop on e2 has 0 legal moves");

        // 4. Special moves, each followed by undo to show the Command restores everything.
        System.out.println("Castling, en passant, promotion:");
        Chess c = playAll(new Chess("r3k2r/8/8/8/8/8/8/R3K2R w KQkq -"), "e1g1 e8c8");
        check(c.board.at(Square.of("f1")) instanceof Rook && c.board.at(Square.of("d8")) instanceof Rook,
                "rooks should jump over");
        Chess e = playAll(standard(), "e2e4 a7a6 e4e5 d7d5 e5d6");
        check(e.board.at(Square.of("d5")) == null, "en passant should remove the d5 pawn");
        e.undo();
        check(e.board.at(Square.of("d5")) instanceof Pawn, "undo should bring the pawn back");
        Chess q = playAll(new Chess("8/P6k/8/8/8/8/8/K7 w - -"), "a7a8");
        check(q.board.at(Square.of("a8")) instanceof Queen, "pawn should become a queen");

        // 5. Stalemate: no legal move, but not in check.
        System.out.println("Stalemate:");
        Chess s = playAll(new Chess("7k/8/6K1/8/8/8/5Q2/8 w - -"), "f2f7");
        check(s.status() == Status.STALEMATE, "should be stalemate");

        // 6. Perft: leaf counts that every correct move generator must match.
        long start3 = standard().perft(3);
        long tricky3 = new Chess("r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq -").perft(3);
        System.out.println("Perft: start depth 3 = " + start3 + ", special-move test depth 3 = " + tricky3);
        check(start3 == 8902 && tricky3 == 97862, "move generator is wrong");
    }
}

Notes

Requirements

Scope it first. Two players, white moves first, six piece types with their normal moves. Every illegal move is rejected, including any move that leaves your own king in check. The game detects check, checkmate and stalemate, supports castling, en passant and promotion, and keeps a history with undo. Clocks, ratings, and the fifty move and repetition draw rules are out of scope, but we will show where they would go.

Ask the questions that change the code. What does a move look like? A from square and a to square, like e two to e four. How does a pawn choose its promotion? An optional fifth letter, defaulting to a queen. What ends the game? Checkmate or stalemate. Resigning and draw offers are simple extensions. A computer opponent is out of scope, but a good move generator makes it easy later.

Requirements
  • two players, white moves first
  • six piece types, standard moves
  • reject every illegal move
  • never leave your king in check
  • detect check, checkmate,
  • stalemate
  • castling, en passant, promotion
  • move history and undo
  • out of scope: clocks, rating,
  • 50-move and repetition draws
Clarify first
  • input format?
  • from and to squares: e2e4
  • promotion piece?
  • a fifth letter, default queen
  • what ends the game?
  • checkmate or stalemate
  • resign, draw offers?
  • easy extension, not now
  • computer opponent?
  • out of scope, but plan for it

Entities

Underline the nouns: game, board, square, piece, move, player. The game owns the board, whose turn it is and the move history. The board holds up to thirty two pieces on sixty four squares. The important choice is that a move is not just two squares, it is an object that knows how to apply itself and how to take itself back. That one decision makes undo, legality checks and testing simple.

Class diagram

Start with the small types. Color is an enum that knows its opposite. Status has four values: active, check, checkmate and stalemate. A square is a record of file and rank, both from zero to seven, so e four is file four, rank three. The board is an eight by eight array of pieces, plus two pieces of state that the position needs but the squares cannot show: the en passant square and the castling rights.

Value types and Board
enum Color { WHITE, BLACK; other() }
enum Status { ACTIVE, CHECK,
              CHECKMATE, STALEMATE }
record Square(int file, int rank)
  "e4" is file 4, rank 3

class Board {
  Piece[][] cells = new Piece[8][8];
  Square enPassant;  // or null
  int castling;      // 4 bits
}

Polymorphic pieces

Pieces are where polymorphism shines. The abstract piece class has a color and one key method: attacks, which returns the squares this piece attacks from a given square. A second method, targets, returns where it may move, which by default is the attacked squares minus those holding your own pieces. The game never asks whether something is a rook or a knight. It just calls targets on whatever piece it finds.

abstract class Piece
final Color color;
abstract char letter();
abstract List<Square> attacks(
    Board b, Square from);

List<Square> targets(Board b, Square f)
  attacks minus own pieces

Game never asks "is this a rook?"
  it calls targets() on any piece

Shared movement

Five of the six pieces fall into two families. Sliders, the rook, bishop and queen, walk in a direction until they hit the edge or a piece, and the blocking square is included because it may be a capture. Steppers, the king and knight, make a single jump in each of eight directions. So a rook is just a slider with four straight directions, and a queen is a slider with all eight. Each concrete class is a few lines.

Slider and Stepper
Slider.attacks(): for each direction,
  walk until the edge or a piece
  (include the blocker)
Rook: 4 straight directions
Bishop: 4 diagonal directions
Queen: all 8

Stepper.attacks(): one step each way
King: 8 neighbours
Knight: 8 L-shaped jumps

The pawn

The pawn is the odd one out, so it overrides targets. It moves one square forward if that square is empty, two from its starting rank if both are empty, and diagonally only to capture, or onto the en passant square. Its attacks method still returns both diagonals even when they are empty, because a pawn guards those squares, and that matters when we ask whether a king is in check.

Pawn.targets()
one ahead if empty
two ahead from the start rank,
  if both squares are empty
diagonal: only to capture, or
  onto board.enPassant

attacks(): the two diagonals,
  even if they are empty
  (needed for check detection)

Command: Move

Each move is a Command object. It holds the from and to squares, the piece, an optional promotion piece, the square where a capture happens, which is different only for en passant, and the rook squares for castling. Execute saves the old en passant square and castling rights, remembers what it captured, then moves the pieces. Undo puts every piece and every bit of state back exactly as it was.

class Move
from, to, piece, promotion
captureAt   // differs for en passant
rookFrom, rookTo   // castling only

execute(b): save old en passant and
  castling, remember the captured
  piece, move pieces, update state
undo(b): put everything back
  exactly as it was

Legal moves

How do we find legal moves without writing special code for every pin and check? Generate pseudo moves first: everything the pieces could do by their movement rules. Then for each one, execute it, ask whether our own king is now attacked, and undo it. If the king is safe, the move is legal. This single test handles pins, moving out of check, blocking a check and discovered attacks, all without extra rules.

legalMoves()
for (Move m : pseudoMoves(turn)) {
  m.execute(board);
  Square k = board.kingOf(turn);
  if (!board.attacked(k, enemy))
    legal.add(m);
  m.undo(board);
}

pins, checks, discovered checks:
  all handled by this one test

Check detection

Check detection reuses the same polymorphism. A square is attacked if any enemy piece includes it in its attacks list. A king is in check when its own square is attacked by the other color. This is simple and correct; it scans the board, which is fine for a game between people. A chess engine would use faster tricks, which is a good follow-up to mention.

Board.attacked(target, by)
for every square with a piece p
  of color by:
  if p.attacks(this, sq)
        .contains(target)
    return true
return false

in check: attacked(kingOf(c),
                   c.other())

Flow: one move

Walk one move. The player sends e two to e four. If the game is already over, it is rejected. Otherwise the game lists the legal moves and looks for one that matches the text. If none matches, the move is illegal, whatever the reason: wrong piece, blocked path, wrong turn or a pin. If it matches, the move executes on the board, goes on the history stack, and the turn passes to the other color.

play(uci)
if status is CHECKMATE or
  STALEMATE: throw game over
for (Move m : legalMoves())
  if m.uci() matches:
    m.execute(board)
    history.push(m)
    turn = turn.other()
    return m
throw illegal move

Mate and stalemate

The game status falls out of two questions. Is the side to move in check, and does it have any legal move? Legal moves and no check means active. Legal moves while in check means check. No legal moves while in check is checkmate, and that side loses. No legal moves and not in check is stalemate, which is a draw. Many candidates forget stalemate, so mention it before the interviewer does.

status()
  • in check? any legal move?
  • no yes ACTIVE
  • yes yes CHECK
  • yes no CHECKMATE
  • no no STALEMATE
  • checkmate: the mover loses
  • stalemate: a draw

Castling

Castling is a king move that also moves a rook, so the move object simply carries the rook's from and to squares. It is allowed when the right is still held, the squares between are empty, and the king is not in check, does not pass through an attacked square and does not land on one. Rights are four bits on the board. Any move from or to the king's or rook's home square clears them, which also covers a rook being captured.

Castling, white king side
  • right WK still held
  • (king and h1 rook never moved)
  • f1 and g1 are empty
  • e1, f1, g1 not attacked
  • Move(e1 to g1, rook h1 to f1)
  • any move from or to e1 or h1
  • clears the right, even a
  • capture of the rook

En passant

En passant needs one piece of memory. When a pawn moves two squares, the board records the square it skipped. On the very next move only, an enemy pawn beside it may capture onto that skipped square, and the pawn removed is the one that moved, not a piece on the target square. That is why a move has a separate capture square. Every other move clears the en passant square, and undo restores it.

En passant
  • black plays d7 to d5
  • board.enPassant = d6
  • white pawn on e5 may capture
  • onto d6; the pawn removed
  • is on d5: captureAt = d5
  • any other move clears it
  • undo restores both the d5 pawn
  • and the old en passant square

Promotion

Promotion is handled when moves are generated. A pawn that reaches the last rank produces four moves, one for each piece it can become: queen, rook, bishop or knight. Execute places the new piece instead of the pawn, and undo puts the pawn back. The input can name the piece with a fifth letter, and without one we pick the queen, which is what players want almost every time.

Promotion
if pawn reaches rank 1 or 8:
  for (Piece p : List.of(new Queen(c),
      new Rook(c), new Bishop(c),
      new Knight(c)))
    out.add(new Move(.., p, ..))

play("a7a8")  -> queen by default
play("a7a8n") -> knight
undo: the pawn comes back

Undo

Undo is now trivial. Pop the last move from the history stack, call its undo method, and flip the turn back. Because each move saved the captured piece, the old en passant square and the old castling rights, the board returns to exactly the earlier position, including after castling, en passant and promotion. Redo is a second stack. This is the classic reason to use the Command pattern.

Demo: quick mate

The demo plays the shortest possible checkmate. White pushes the f pawn one square, black opens with e five, white pushes the g pawn two squares, and the black queen jumps to h four. The white king is attacked, and every legal-move test fails, so the status is checkmate. Any further move is rejected. Then undo takes the queen back to d eight and the game is live again.

The shortest mate
  • white: f2 to f3
  • black: e7 to e5
  • white: g2 to g4
  • black: queen d8 to h4
  • white king on e1 is attacked
  • no legal move escapes:
  • CHECKMATE, black wins
  • a2a3 now: rejected, game over

Testing

How do you know the move rules are right? Use a perft test: count every position reachable to a given depth and compare with numbers the chess community has published. From the starting position, depth three gives eight thousand nine hundred and two. A busy test position full of castling, en passant and promotion gives ninety seven thousand eight hundred and sixty two at depth three. Our code matches both, so make and undo are correct.

Perft: count to prove it
long perft(int depth) {
  if (depth == 0) return 1;
  for (Move m : legalMoves()) {
    m.execute(board); flip turn;
    n += perft(depth - 1);
    flip turn; m.undo(board); }
}
start, depth 3: 8,902
castling test position,
  depth 3: 97,862

Concurrency

For online play, two requests for one game can race, so make play and undo synchronized on the game, with the whose-turn check inside the lock, or run each game as a single-threaded actor that takes moves from a queue. Games never block each other. A saved game is just its move list. If someone asks about speed, mention bitboards: one sixty four bit number per piece type, so attacks become bit operations.

Online and at scale
  • play() and undo() synchronized
  • per game, turn check inside
  • or one actor per game,
  • moves in a queue
  • games never block each other
  • save a game: the move list
  • faster engine: bitboards,
  • 64-bit masks per piece type

Extensibility

Extensions slot in cleanly. The fifty move rule is a half move counter that each move saves and restores. Threefold repetition counts position hashes in a map. Chess clocks are a timer per player. Resignation and draw offers are new statuses. A computer opponent searches over legal moves using the same execute and undo, and standard notation is a separate formatter class so the core stays clean.

Extension points
  • 50-move rule: a half-move clock
  • saved and restored by Move
  • threefold repetition: count
  • position hashes
  • clocks: a timer per player
  • resign, draw offer: new statuses
  • computer player: search over
  • legalMoves() with undo
  • notation: a MoveFormatter

Follow-ups

Expect follow-ups. Why not one big switch on piece type? Every new rule would touch it; polymorphism keeps each piece's logic together. Why make and unmake instead of copying the board? It is cheaper and the same command gives undo. How do you detect pins? You do not need to; trying the move and checking the king covers it. And testing? Perft counts against published numbers.

Follow-ups to expect
  • why not a switch on piece type?
  • why make and unmake, not copy?
  • how do you detect a pin?
  • you do not need to: try it
  • en passant and undo?
  • Move saves the old square
  • how would you add a bot?
  • how do you test it? perft
  • where does Player fit?

Say it like this

Here is the short version to say out loud. Every piece extends an abstract piece and answers which squares it attacks, with sliders and steppers sharing code. A move is a command that can execute and undo itself. Legal moves come from generating, executing, checking the king and undoing. Status comes from two questions. Castling and en passant state live on the board, and perft proves it all works.

In the interview
  • "Pieces extend Piece and answer
  • attacks(); sliders and steppers
  • share code. A Move is a Command
  • with execute and undo. Legal
  • moves: generate, execute, check
  • the king, undo. Status is two
  • questions. Castling and en
  • passant live on the Board, and
  • perft proves it all."

Interview questions

How do you model the different pieces?

An abstract Piece with a color and an attacks(board, from) method. Rook, bishop and queen extend a Slider that walks directions until blocked; king and knight extend a Stepper with fixed jumps; the pawn overrides targets() for its special forward and capture rules. The game only calls the abstract methods.

How do you make sure a move does not leave your own king in check?

Generate pseudo-legal moves from the movement rules, then execute each one, test whether your king square is attacked by the opponent, and undo it. Only moves that leave the king safe are legal. This covers pins, blocking checks and discovered attacks with one rule.

How do you tell checkmate from stalemate?

Both mean the side to move has no legal moves. If that side is in check it is checkmate and it loses; if not, it is stalemate and the game is a draw. Check is computed by asking whether the king square is attacked.

Why use the Command pattern for moves?

A move that can execute and undo itself gives you undo and redo for free, lets the legality test try a move and take it back, and makes search for a computer player possible. The move stores the captured piece and the previous en passant and castling state so undo is exact.

How is castling validated?

The castling right must still be held, meaning the king and that rook have not moved and the rook was not captured. The squares between must be empty, and the king must not be in check, pass through an attacked square or land on one. The move then relocates both king and rook.

How do you implement en passant?

When a pawn moves two squares, the board stores the square it skipped. On the next move only, an enemy pawn may capture onto that square, and the captured pawn is removed from the square beside it, so a Move has a separate captureAt square. Every move resets or restores this state.

How do you handle pawn promotion?

When a pawn move reaches the last rank, generate four moves, one each for queen, rook, bishop and knight. Executing places the new piece; undo puts the pawn back. The input can name the piece, defaulting to a queen.

How do you test a chess move generator?

With perft: count all positions reachable to a fixed depth and compare with well known values, such as 8,902 at depth 3 from the start. Special test positions with castling, en passant and promotion catch the subtle bugs that normal games rarely hit.

How would you add the fifty-move rule and threefold repetition?

Keep a half-move clock that resets on pawn moves and captures, saved and restored by each Move. For repetition, hash each position (pieces, side to move, castling, en passant) and count occurrences in a map, declaring a draw at three.

How would you make move generation faster?

Replace the 8 x 8 array with bitboards, one 64-bit number per piece type and color, so attacks become shifts and masks, and use precomputed attack tables. Check detection can also look outward from the king instead of scanning every enemy piece.