LLD

Full Designs

Chess

Everyone knows the rules of chess, so the interview is about where those rules live. We give each piece type its own move rule, keep the king safe with one test instead of a rule in every piece, fit castling, en passant and promotion in cleanly, tell checkmate from stalemate, and take moves back, all the way to the start.

"Design a chess game" has a weak answer that looks complete. It draws an abstract Piece with six subclasses, each with a canMove(from, to), an 8 × 8 array, and a loop that asks two Player objects for moves. Then castling, en passant and check arrive, and each one becomes an if in a different subclass. A pinned bishop still moves, because the bishop's canMove does not know where its king is.

The interviewer is checking where the rules live. Each piece moves in its own way, but one rule covers all of them: no move may leave your own king in check. Two special moves depend on what happened earlier in the game, and the game must tell a checkmate from a stalemate. A good design gives each of these one place in the code. Tic-tac-toe covered moves that arrive as calls and refusals that come back as answers, so this page reuses those ideas and spends its words on the rules.

This article walks through the question the way a 45 minute interview goes. We ask questions, find the classes, then build the design one decision at a time. Every snippet is cut from a complete Java project that compiles and runs. The Open file button on a snippet opens the whole file in a code browser, and the full project is at the end.

One move at a glance
The caller, a screen or a server, sends a move as move(e2, e4) (1). Game looks for it in the list of legal moves it worked out earlier (2). Position.apply builds a new position from the old one, and Game adds it to its list of positions (3). Game then asks the new position for the other side's legal moves: each piece type's MoveRule lists candidates, and any candidate that leaves the king attacked is dropped (4). The caller gets back a MoveResult with the status (5).The caller, a screen or a server, sends a move as move(e2, e4) (1). Game looks for it in the list of legal moves it worked out earlier (2). Position.apply builds a new position from the old one, and Game adds it to its list of positions (3). Game then asks the new position for the other side's legal moves: each piece type's MoveRule lists candidates, and any candidate that leaves the king attacked is dropped (4). The caller gets back a MoveResult with the status (5).
Game looks the move up, Position builds the next position, and the piece rules work out what may come next. The caller, a screen or a server, sends a move as move(e2, e4) (1). Game looks for it in the list of legal moves it worked out earlier (2). Position.apply builds a new position from the old one, and Game adds it to its list of positions (3). Game then asks the new position for the other side's legal moves: each piece type's MoveRule lists candidates, and any candidate that leaves the king attacked is dropped (4). The caller gets back a MoveResult with the status (5).

Ask before you design

The question is vague on purpose, and each answer below changes the code. The right-hand column says how.

QuestionWhat we assumeWhat it changes
The full rules, with castling, en passant and promotion?Yes, all of themThe position must remember more than where the pieces stand
How does a move arrive?As a call with a from square and a to square, from a screen or a serverGame.move(from, to), and no Player class
What does a pawn become on the last rank?The player's choice: queen, rook, bishop or knightA move can carry a promotion piece, and a missing one is refused
What happens to an illegal move?It is refused with a reason, and nothing changesAn Outcome enum with one value per reason
Does the game spot check, checkmate and stalemate?Yes, after every moveThe game works out every legal move after each move
Draws by repetition or the 50-move rule, resignation?Not in this versionNo move counters and no draw offers
Is there undo?Yes, any number of moves, back to the startThe game keeps its history
Can a game start from a given position, such as a puzzle?Yes, written in FEN, the usual one-line notation for a positionA Fen reader, and a position that is checked before it is accepted
Clocks, or a computer player?NoNo clock and no move chooser
Can two moves for one game arrive at once?No: a server hands each game its moves one at a timeGame has no lock

The first row matters most. Castling and en passant depend on the past: whether a king or a rook has ever moved, and what the last move was. A board alone cannot answer that, so the design needs one object for everything the rules need to know at a given moment. That object is the Position.

Requirements

Functional:

  1. A game starts from the usual position, or from a position written in FEN, the usual one-line notation for a chess position. White moves first, and the players take turns.
  2. Each piece moves by its own rule, and a move its rule does not allow is refused.
  3. A move that leaves the mover's own king attacked is refused. This covers a pinned piece, a king stepping into check, and a move that ignores a check.
  4. A king may castle on either side if neither the king nor that rook has moved, the squares between them are empty, and the king does not start on, cross or land on an attacked square.
  5. A pawn may take en passant only on the move straight after the other pawn's two-square step.
  6. A pawn that reaches the last rank becomes the queen, rook, bishop or knight its player chooses.
  7. After every move the game reports check, checkmate or stalemate. A finished game refuses further moves.
  8. The last move can be taken back, repeatedly, back to the start, and everything it changed comes back.
  9. Every refused move gets a reason and leaves the game exactly as it was.

Out of scope: draws by threefold repetition, by the 50-move rule or by too little material, resignation and draw offers, clocks, a computer player, and writing moves in chess notation. We come back to these at the end as follow-ups.

Everything lives in memory, as is normal for a low-level design interview.

What the code itself must handle:

  • Rules full of exceptions. Castling, en passant and promotion each break the plain "one piece moves from one square to another" model. They must fit without an if for them in every class.
  • One rule over every piece. King safety applies to every move of every piece, so it should be written once.
  • Testable. A test must be able to set up any position directly, instead of reaching it by playing forty moves.
  • One thread per game. We assume a server queues each game's moves. If it does not, a private lock around each public method of Game, as in tic-tac-toe, is enough.

Finding the classes

From nouns to classes
Game, position, board, square, piece, how a piece moves, move, castling, white and black, the answer to a move, and check, mate and stalemate are kept. Player, turn, captured pieces, chess clock and referee are crossed out. A player is whoever calls move(). The turn is part of the position. Captured pieces are whatever is missing from the board. The clock is out of scope, and the game itself is the referee.Game, position, board, square, piece, how a piece moves, move, castling, white and black, the answer to a move, and check, mate and stalemate are kept. Player, turn, captured pieces, chess clock and referee are crossed out. A player is whoever calls move(). The turn is part of the position. Captured pieces are whatever is missing from the board. The clock is out of scope, and the game itself is the referee.
Most nouns become classes, records or enums. The position is the one the question never names. Game, position, board, square, piece, how a piece moves, move, castling, white and black, the answer to a move, and check, mate and stalemate are kept. Player, turn, captured pieces, chess clock and referee are crossed out. A player is whoever calls move(). The turn is part of the position. Captured pieces are whatever is missing from the board. The clock is out of scope, and the game itself is the referee.

One kept noun is not in the question at all. The position is the board plus whose move it is, which castling rights are left, and whether a pawn may be taken en passant. Another noun is a rule rather than data: how a piece moves differs for each type, so it gets an interface, MoveRule.

Decision

Does a piece know its square?

A cell object that holds its piece, and a piece that holds its cell

This is the shape of many class diagrams: a Cell with a piece field and a Piece with a position field. Every move must update both ends, and a missed update leaves a piece that thinks it is on e2 while the board has it on e4. A piece with a field that changes also cannot be shared between two positions.

A square is a coordinate, and only the board knows what stands whereOur pick

Square is a file and a rank. Board keeps a Piece[8][8] and is the one place that says what stands where. A Piece is only a colour and a type, so it never changes and two positions can share it.

Data or behaviour?

Most classes here only carry data. Square, Step, Piece, Move and MoveResult are records: classes whose fields are fixed when they are created, with equals, hashCode and toString written for us. Fixed sets of values are enums: Color, PieceType, MoveKind, CastlingRight, Outcome and Status.

piece/Piece.javalines 8–13 of 29
/** A piece is its colour and its type. It does not know which square it is on. */public record Piece(Color color, PieceType type) {    public Piece {        Objects.requireNonNull(color, "color");        Objects.requireNonNull(type, "type");    }

A piece has no hasMoved flag. Castling needs to know whether a king or rook has moved, but that answer belongs to the position, as we will see.

The class diagram

The classes and how they connect
Game owns its list of positions and creates a MoveResult for every call. Each Position owns a Board. PieceType holds one MoveRule per type, and SlidingRule, StepRule, KingRule and PawnRule implement it. Position uses those rules to find moves. Fen creates a Position from text. Apart from MoveResult, the records and enums along the bottom are drawn without arrows to keep the figure readable.Game owns its list of positions and creates a MoveResult for every call. Each Position owns a Board. PieceType holds one MoveRule per type, and SlidingRule, StepRule, KingRule and PawnRule implement it. Position uses those rules to find moves. Fen creates a Position from text. Apart from MoveResult, the records and enums along the bottom are drawn without arrows to keep the figure readable.
Game keeps the positions. A position asks each piece type's rule for moves. Game owns its list of positions and creates a MoveResult for every call. Each Position owns a Board. PieceType holds one MoveRule per type, and SlidingRule, StepRule, KingRule and PawnRule implement it. Position uses those rules to find moves. Fen creates a Position from text. Apart from MoveResult, the records and enums along the bottom are drawn without arrows to keep the figure readable.

The classes fall into three groups:

  • Data: Square, Step, Piece, Move and MoveResult, and the enums Color, PieceType, MoveKind, CastlingRight, Outcome and Status.
  • The core: Game, Position and Board. A Position never changes once built, and Game keeps the list of them.
  • Rules: MoveRule and its four implementations, one for each way of moving. Fen reads positions for puzzles and tests.

Building it

Squares and the board

A Square is a file and a rank, both from 0 to 7, so a1 is (0, 0) and e4 is (4, 3). It refuses anything off the board, and Square.of("e4") reads a name. plus(step) returns the square one Step away, or empty at the edge. Every piece rule moves with it, so no rule does its own edge check.

game/Board.javalines 15–33 of 113
/** * Which piece stands on which square. Anyone may read a board; only Position * changes one, and only a fresh copy that nobody else has seen yet. */public final class Board {    private final Piece[][] squares = new Piece[Square.SIZE][Square.SIZE];     private Board() {    }     public static Board of(Map<Square, Piece> pieces) {        Board board = new Board();        pieces.forEach((square, piece) -> board.put(Objects.requireNonNull(square), Objects.requireNonNull(piece)));        return board;    }     public Optional<Piece> pieceAt(Square square) {        return Optional.ofNullable(squares[square.rank()][square.file()]);    }

The grid is private, and so is the constructor. Anyone can read a board through pieceAt, and the methods that change one are package-private. Outside Board, only Position.apply calls put and remove, and only on a board that copy has just made, so a board that anyone else holds never changes.

Each piece type brings its own rule

Six piece types need only four rule classes. A rook, a bishop and a queen all slide until something stops them, and only their directions differ. A knight takes one jump from a fixed list. The king steps one square and can castle, and the pawn is unlike everything else. So each PieceType carries a rule object:

piece/PieceType.javalines 8–14 of 43
public enum PieceType {    KING('k', new KingRule()),    QUEEN('q', new SlidingRule(Step.ALL_AROUND)),    ROOK('r', new SlidingRule(Step.STRAIGHT)),    BISHOP('b', new SlidingRule(Step.DIAGONAL)),    KNIGHT('n', new StepRule(Step.KNIGHT_JUMPS)),    PAWN('p', new PawnRule());

A queen is a SlidingRule with all eight directions, and a rook is one with the four straight ones. The king gets its own rule because of castling, and that rule uses a StepRule inside for its plain steps.

piece/MoveRule.javalines 12–31 of 31
/** How one type of piece moves. Each PieceType holds one. */public interface MoveRule {     /** The squares a piece on from attacks: where it could capture, whatever stands there now. */    List<Square> attacks(Board board, Square from, Color color);     /**     * The moves a piece on from could make, before anyone checks that its own king     * is safe. By default these are the attacked squares not taken by its own side.     */    default List<Move> candidates(Position position, Square from, Color color) {        List<Move> moves = new ArrayList<>();        for (Square to : attacks(position.board(), from, color)) {            if (!position.board().isOccupiedBy(to, color)) {                moves.add(Move.normal(from, to));            }        }        return moves;    }}

A rule answers two different questions. attacks lists the squares the piece could capture on. candidates lists the moves it could make. For most pieces the second is the first minus the squares its own side holds, and that is the default method. A pawn breaks this, because it moves straight ahead but captures diagonally, so PawnRule overrides both.

piece/SlidingRule.javalines 20–35 of 36
    @Override    public List<Square> attacks(Board board, Square from, Color color) {        List<Square> squares = new ArrayList<>();        for (Step direction : directions) {            Optional<Square> next = from.plus(direction);            while (next.isPresent()) {                Square square = next.get();                squares.add(square);                if (board.pieceAt(square).isPresent()) {                    break;                }                next = square.plus(direction);            }        }        return squares;    }

The slide adds each square, then stops at the first piece it meets. The square with the piece is included, because that piece may be an enemy to capture. candidates drops it if the piece is our own.

Decision

A class per piece, or a rule per piece type?

An abstract Piece with a subclass per type, each with canMove(from, to)

Each subclass judges one pair of squares at a time. Finding every legal move then means asking every piece about all 64 squares. The queen repeats the rook's and the bishop's code, and a hasMoved field on the king and rooks must be put back by undo.

One method with a switch on the piece type

All the movement code is in one place, but that place grows with every special case, and a new piece type means editing it.

A Piece record, and a MoveRule held by each PieceTypeOur pick

A rule lists its moves directly, so a knight produces its eight targets instead of being asked about 64 squares. Three types share SlidingRule with different directions. A new piece, such as one that moves like a bishop or a knight, is one new enum constant with a rule that joins two lists.

A position, and a new one for every move

Position holds the board and the three facts the board cannot show: whose move it is, which castling rights are left, and the square where a pawn may be taken en passant.

game/Position.javalines 24–38 of 212
public final class Position {    private static final List<PieceType> BACK_RANK = List.of(PieceType.ROOK, PieceType.KNIGHT, PieceType.BISHOP,            PieceType.QUEEN, PieceType.KING, PieceType.BISHOP, PieceType.KNIGHT, PieceType.ROOK);     private final Board board;    private final Color sideToMove;    private final Set<CastlingRight> castlingRights;    private final Square enPassantSquare;     private Position(Board board, Color sideToMove, Set<CastlingRight> castlingRights, Square enPassantSquare) {        this.board = board;        this.sideToMove = sideToMove;        this.castlingRights = Collections.unmodifiableSet(castlingRights);        this.enPassantSquare = enPassantSquare;    }

Every field is final, and nothing changes a position after it is built. A move does not edit the board. apply copies the board, changes the copy, and returns a new position:

game/Position.javalines 168–194 of 212
    /** The position after a move. The move must be one of this position's candidates. */    Position apply(Move move) {        Board next = board.copy();        Piece piece = next.remove(move.from());        if (move.kind() == MoveKind.PROMOTION) {            piece = new Piece(piece.color(), move.promotion());        }        next.put(move.to(), piece);        if (move.kind() == MoveKind.EN_PASSANT) {            next.remove(new Square(move.to().file(), move.from().rank()));        }        if (move.kind() == MoveKind.CASTLE) {            CastlingRight right = CastlingRight.forCastle(move);            next.put(right.rookTo(), next.remove(right.rookFrom()));        }        Set<CastlingRight> rights = EnumSet.noneOf(CastlingRight.class);        for (CastlingRight right : castlingRights) {            if (!right.isLostBy(move)) {                rights.add(right);            }        }        Square passed = null;        if (move.kind() == MoveKind.DOUBLE_STEP) {            passed = new Square(move.from().file(), (move.from().rank() + move.to().rank()) / 2);        }        return new Position(next, sideToMove.opponent(), rights, passed);    }

The move's MoveKind says what happens besides one piece moving. Promotion swaps the pawn for the new piece. En passant removes a pawn from a square the move does not land on. Castling moves the rook too. The castling rights and the en passant square are worked out fresh for the new position, and we come back to both.

Decision

Change one board in place, or make a new position for each move?

One board, changed in place, with an unmake for every move

Changing one board is fast, and chess engines that search millions of positions work this way. But every kind of move needs its own exact reverse. The safety test below would have to make and unmake moves on the live game, and one missed restore corrupts it.

A new Position for every moveOur pick

apply copies 64 squares and never touches the old position. The safety test can try any move and throw the result away, and undo only has to go back to an earlier position. The cost is one board copy for every move tried, a few dozen per turn, which is small next to a person's thinking time. A computer player that searches deeply would want the first option.

Playing a move

Game keeps the positions and the legal moves for the current one, worked out after every change. move checks a request in a fixed order and answers with a MoveResult. As in tic-tac-toe, a refusal is an answer with a reason. Programmer errors throw, such as a null square or the name "z9". setUp also throws for a position that cannot happen. It rejects a side without exactly one king, a pawn on the first or last rank, and a castling right whose king or rook is not at home. It also rejects an en passant square no pawn has just crossed, and a side in check when it is not their move. A puzzle FEN typed by a person is user input, so the screen catches that exception and shows its message.

game/Game.javalines 42–69 of 133
    private MoveResult play(Square from, Square to, PieceType promotion) {        Objects.requireNonNull(from, "from");        Objects.requireNonNull(to, "to");        Position position = position();        if (status.isOver()) {            return refuse(Outcome.GAME_OVER);        }        Optional<Piece> piece = position.board().pieceAt(from);        if (piece.isEmpty()) {            return refuse(Outcome.NO_PIECE);        }        if (piece.get().color() != position.sideToMove()) {            return refuse(Outcome.NOT_YOUR_TURN);        }        List<Move> legal = matching(legalMoves, from, to);        if (legal.isEmpty()) {            boolean ruleAllows = !matching(position.candidatesFrom(from), from, to).isEmpty();            return refuse(ruleAllows ? Outcome.KING_UNSAFE : Outcome.CANNOT_MOVE_THERE);        }        Optional<Move> chosen = choose(legal, promotion);        if (chosen.isEmpty()) {            return refuse(promotion == null ? Outcome.CHOOSE_PROMOTION : Outcome.BAD_PROMOTION);        }        positions.add(position.apply(chosen.get()));        moves.add(chosen.get());        judge();        return new MoveResult(Outcome.MOVED, status);    }

The checks run in this order: the game is still on, there is a piece on from, it belongs to the side to move, and the move is in the legal list. When the move is not legal, move asks the piece's rule alone. If the rule allows the move, only the king's safety stands in the way, and the answer is KING_UNSAFE. Otherwise it is CANNOT_MOVE_THERE, so a player who drags a pinned bishop learns why it will not go. Nothing is written until every check has passed, so a refused move leaves the game exactly as it was.

Keeping the king safe

This rule is where a design with a canMove per piece breaks. A bishop on e2, with its king on e1 and an enemy rook on e8, may not move at all, though nothing in the bishop's own rule says so. The same rule stops a king stepping into check and any move that ignores a check.

A pinned bishop
On the left, the bishop on e2 stands between its king on e1 and a black rook on e8. Its SlidingRule lists nine candidates, drawn dashed, and knows nothing about the king. On the right, e2-d3 is tried on a copy: the rook on e8 now attacks e1, so the move is dropped. All nine are dropped the same way, and e2-d3 is refused with KING_UNSAFE. A straight move such as e2-e4 is not a candidate at all, so it gets CANNOT_MOVE_THERE.On the left, the bishop on e2 stands between its king on e1 and a black rook on e8. Its SlidingRule lists nine candidates, drawn dashed, and knows nothing about the king. On the right, e2-d3 is tried on a copy: the rook on e8 now attacks e1, so the move is dropped. All nine are dropped the same way, and e2-d3 is refused with KING_UNSAFE. A straight move such as e2-e4 is not a candidate at all, so it gets CANNOT_MOVE_THERE.
The bishop's rule offers nine squares. The safety test turns down all nine. On the left, the bishop on e2 stands between its king on e1 and a black rook on e8. Its SlidingRule lists nine candidates, drawn dashed, and knows nothing about the king. On the right, e2-d3 is tried on a copy: the rook on e8 now attacks e1, so the move is dropped. All nine are dropped the same way, and e2-d3 is refused with KING_UNSAFE. A straight move such as e2-e4 is not a candidate at all, so it gets CANNOT_MOVE_THERE.
game/Position.javalines 138–166 of 212
    /** Every move the side to move may make: each piece's candidates that keep the king safe. */    public List<Move> legalMoves() {        List<Move> legal = new ArrayList<>();        for (Square from : board.squaresOf(sideToMove)) {            for (Move move : candidatesFrom(from)) {                if (keepsKingSafe(move)) {                    legal.add(move);                }            }        }        return legal;    }     /** The moves the piece's own rule allows, before anyone checks the king. */    List<Move> candidatesFrom(Square from) {        Piece piece = board.pieceAt(from).orElseThrow();        return piece.type().rule().candidates(this, from, piece.color());    }     private boolean keepsKingSafe(Move move) {        if (move.kind() == MoveKind.CASTLE) {            for (Square square : CastlingRight.forCastle(move).kingPath()) {                if (isAttacked(square, sideToMove.opponent())) {                    return false;                }            }        }        return !apply(move).inCheck(sideToMove);    }

legalMoves asks each piece for its candidates, and keepsKingSafe applies each one to a copy and asks whether the mover's king is attacked there. isAttacked asks every enemy piece's rule for its attacks and looks for the king's square in them. No rule knows about pins or checks. Both come out of one question, asked after the move.

Two more cases come out right without any code of their own. A king that steps back along a checking rook's line is still attacked, because the test looks at the board after the move. An en passant capture that takes two pawns off one rank can open that rank to a rook, and the test sees the open rank. Castling is the exception: the king crosses a square that the board after the move does not show. So castling adds its own check first, at lines 158 to 164, which the next part explains.

Decision

How do we refuse a move that leaves the king in check?

Each piece's rule checks pins and checks itself

The bishop would need to know where its king is and which enemy lines cross it, and so would every other piece. A check uncovered by another piece's move, or by en passant along a rank, would need code of its own in more than one place.

Every rule lists candidates; one filter tries each and drops any that leave the king attackedOur pick

The rules stay simple, and one method holds the safety rule. The cost is one board copy and one attack scan for each candidate, and a position has a few dozen candidates.

Castling

The three special moves
Castling: kingside, f1 and g1 must be empty, and e1, f1 and g1 must not be attacked, while the rook jumps from h1 to f1. Queenside, b1, c1 and d1 must be empty, but only e1, d1 and c1 must be safe, so an attack on b1 does not matter. En passant: after black's d7-d5, the white pawn on e5 may take on d6, and the black pawn on d5 is removed. After any other move first, the chance has gone. Promotion: a pawn reaching a8 is four legal moves, one for each piece it may become.Castling: kingside, f1 and g1 must be empty, and e1, f1 and g1 must not be attacked, while the rook jumps from h1 to f1. Queenside, b1, c1 and d1 must be empty, but only e1, d1 and c1 must be safe, so an attack on b1 does not matter. En passant: after black's d7-d5, the white pawn on e5 may take on d6, and the black pawn on d5 is removed. After any other move first, the chance has gone. Promotion: a pawn reaching a8 is four legal moves, one for each piece it may become.
Each one breaks the plain one-piece-one-move model in its own way. Castling: kingside, f1 and g1 must be empty, and e1, f1 and g1 must not be attacked, while the rook jumps from h1 to f1. Queenside, b1, c1 and d1 must be empty, but only e1, d1 and c1 must be safe, so an attack on b1 does not matter. En passant: after black's d7-d5, the white pawn on e5 may take on d6, and the black pawn on d5 is removed. After any other move first, the chance has gone. Promotion: a pawn reaching a8 is four legal moves, one for each piece it may become.

Castling has five conditions. The king and that rook have never moved, and the squares between them are empty. The king is not in check, does not cross an attacked square, and does not land on one. Each of the four ways to castle is a constant of CastlingRight, which holds its squares as data:

game/CastlingRight.javalines 12–16 of 104
public enum CastlingRight {    WHITE_KINGSIDE('K', Color.WHITE, "e1", "g1", "h1", "f1", List.of("f1", "g1"), List.of("e1", "f1", "g1")),    WHITE_QUEENSIDE('Q', Color.WHITE, "e1", "c1", "a1", "d1", List.of("b1", "c1", "d1"), List.of("e1", "d1", "c1")),    BLACK_KINGSIDE('k', Color.BLACK, "e8", "g8", "h8", "f8", List.of("f8", "g8"), List.of("e8", "f8", "g8")),    BLACK_QUEENSIDE('q', Color.BLACK, "e8", "c8", "a8", "d8", List.of("b8", "c8", "d8"), List.of("e8", "d8", "c8"));

Read one row from left to right: its FEN letter, its colour, the king's start and end squares, and the rook's start and end squares. Then come the squares that must be empty, and the squares the king starts on, crosses and lands on. On the queenside, b1 must be empty but is not on the king's path, so an attack on b1 does not stop castling. KingRule offers a castling move for each right still kept whose squares are empty:

piece/KingRule.javalines 22–31 of 32
    @Override    public List<Move> candidates(Position position, Square from, Color color) {        List<Move> moves = steps.candidates(position, from, color);        for (CastlingRight right : position.castlingRights()) {            if (right.color() == color && right.squaresBetweenAreEmpty(position.board())) {                moves.add(Move.castle(right));            }        }        return moves;    }

The three attack conditions live in keepsKingSafe, shown above. Before it applies a castle, it checks every square on kingPath, and refuses the castle if any of them is attacked. So every rule about the king's safety sits in one method.

That leaves "has never moved". Instead of a flag on each piece, the position keeps the set of rights still alive, and apply drops any right that a move touches:

game/CastlingRight.javalines 67–74 of 104
    /** Any move from or to the king's or the rook's home square ends this right for good. */    boolean isLostBy(Move move) {        return touchesHome(move.from()) || touchesHome(move.to());    }     private boolean touchesHome(Square square) {        return square.equals(kingFrom) || square.equals(rookFrom);    }

A right ends when any move starts or ends on its king's or its rook's home square. That one line covers the king moving, the rook moving, and the rook being taken at home. The last case is easy to miss with flags: the taken rook never moved, so a flag check must also look for the rook on its square. A king that moves and comes back has still lost its rights, because they are gone from the set.

Decision

Where does the right to castle live?

A hasMoved flag on each king and rook

This is easy to picture. But pieces stop being plain values, undo must put each flag back, and a puzzle set up from a position has no way to say which pieces have moved.

A set of castling rights on the position, lost when a move touches a home squareOur pick

The rights are data in the position, so undo restores them by going back to an earlier position, and a FEN states them in its third field. setUp checks that each claimed right has its king and rook at home, so a right never outlives its rook.

En passant

En passant is the one rule that depends on the last move. A pawn that has just stepped two squares may be taken by an enemy pawn beside it, as if it had stepped one, but only on the very next move. The position remembers the square the pawn passed over:

game/Position.javalines 189–192 of 212
        Square passed = null;        if (move.kind() == MoveKind.DOUBLE_STEP) {            passed = new Square(move.from().file(), (move.from().rank() + move.to().rank()) / 2);        }

Every move builds a new position, and only a two-square step sets the square. So the chance lasts exactly one move, with no code to clear it later. PawnRule offers the capture when a diagonal target is that square:

piece/PawnRule.javalines 39–45 of 59
        for (Square target : attacks(board, from, color)) {            if (board.isOccupiedBy(target, color.opponent())) {                addAdvance(moves, from, target, color);            } else if (position.enPassantSquare().filter(target::equals).isPresent()) {                moves.add(Move.enPassant(from, target));            }        }

When apply plays it, the taken pawn is not on the target square. It stands beside the capturing pawn, on the target's file and the mover's rank, which is the square that line 177 of Position clears.

Decision

How does the game know en passant is allowed?

Look at the last move in the history

This works in a game played from the start. But a position set up from a puzzle has no history, and the rules would have to read the game's history instead of the position in front of them.

The position stores the square, set by a two-square step and empty after any other moveOur pick

The position alone answers every rule question, and a FEN gives the square in its fourth field. The chance cannot outlive its move, because each new position sets the square again.

Promotion

A pawn move onto the last rank is not one move but four, one for each piece the pawn may become:

piece/PawnRule.javalines 49–58 of 59
    /** A move onto the last rank is four moves, one for each piece the pawn may become. */    private static void addAdvance(List<Move> moves, Square from, Square to, Color color) {        if (to.rank() != color.promotionRank()) {            moves.add(Move.normal(from, to));            return;        }        for (PieceType type : PieceType.PROMOTIONS) {            moves.add(Move.promotion(from, to, type));        }    }

The legal list holds all four, so the request must say which one it means. If it names no piece, move refuses with CHOOSE_PROMOTION, and the screen asks the player. If it names a king or a pawn, or names a piece for a move that is not a promotion, the answer is BAD_PROMOTION. The Move record's constructor keeps the two in step: a move names a promotion piece if and only if its kind is PROMOTION. We chose not to make a queen without asking. A knight is sometimes the better piece, and a default would hide a real choice. In the demo, a knight on a8 gives check where a queen would not.

Check, checkmate or stalemate

After every move, and after every undo, judge works out the legal moves for the side now to move. The status follows from two facts:

game/Game.javalines 104–114 of 133
    /** Works out the moves and the status of the position the game is now in. */    private void judge() {        Position position = position();        legalMoves = List.copyOf(position.legalMoves());        boolean inCheck = position.inCheck(position.sideToMove());        if (legalMoves.isEmpty()) {            status = inCheck ? Status.CHECKMATE : Status.STALEMATE;        } else {            status = inCheck ? Status.CHECK : Status.NORMAL;        }    }

A side with no legal moves has lost if its king is attacked, and the game is drawn if it is not. A side with moves is either in check or not. The list judge builds is also the list the next move looks in, so the work is not wasted.

Checkmate or stalemate
Both boards come from the demo, with the white king on f7 and the black king on h8. After Qg1-g7, the black king is attacked and cannot escape: g8 and h7 are covered, and the queen on g7 is guarded by the king. That is checkmate. After Qg1-g6, the black king is not attacked, but g8, g7 and h7 are all covered and black has no other piece. That is stalemate, a draw.Both boards come from the demo, with the white king on f7 and the black king on h8. After Qg1-g7, the black king is attacked and cannot escape: g8 and h7 are covered, and the queen on g7 is guarded by the king. That is checkmate. After Qg1-g6, the black king is not attacked, but g8, g7 and h7 are all covered and black has no other piece. That is stalemate, a draw.
Both positions leave black with no legal move. Only the check tells them apart. Both boards come from the demo, with the white king on f7 and the black king on h8. After Qg1-g7, the black king is attacked and cannot escape: g8 and h7 are covered, and the queen on g7 is guarded by the king. That is checkmate. After Qg1-g6, the black king is not attacked, but g8, g7 and h7 are all covered and black has no other piece. That is stalemate, a draw.
Decision

How do we tell checkmate from stalemate?

Checkmate when the king is in check and has no safe square

This misses a check that another piece can block, or a checking piece that can be taken, and calls those checkmate. It also says nothing about stalemate.

No legal moves at all; checkmate if the king is attacked, stalemate if notOur pick

Blocks and captures are legal moves, so they count, and stalemate needs no code of its own. The cost is finding every legal move after each move, which the next move needs anyway.

Undo

The game keeps every position it has been through, so undo drops the last one:

game/Game.javalines 71–80 of 133
    /** Takes back the last move, whoever made it. Empty if there is none. */    public Optional<Move> undo() {        if (moves.isEmpty()) {            return Optional.empty();        }        positions.remove(positions.size() - 1);        Move last = moves.remove(moves.size() - 1);        judge();        return Optional.of(last);    }

The earlier position already holds the right board, the right castling rights and the right en passant square, so undo restores all of them with no special cases. Undoing a castle puts the rook back, undoing en passant brings back the taken pawn, and undoing a promotion gives back the pawn. Undoing a checkmate reopens the game, because judge runs again on the earlier position.

Decision

Undo: reverse each move, or keep the positions?

Replay every move from the start

This needs only the start and the move list. But each undo then takes longer as the game gets longer.

Reverse the last move

It stores little. But each kind of move needs its own reverse: castling moves the rook back, en passant puts a pawn on a square the move never touched, and promotion turns a queen back into a pawn. A move must also remember what it captured, and the castling rights and en passant square before it.

Keep every position, and go back to the one beforeOur pick

A position is one 64-square board and three small fields, so a game of 200 moves keeps 200 small boards. Undo drops the last position, and that is right for every kind of move at once. Tic-tac-toe chose to reverse moves instead, because its board can hold 10,000 cells and a move changes one of them.

The final design

Game is the core. It owns the list of positions, the list of moves and the legal moves for the current position. Each Position owns its board and its castling rights, and reaches the way each piece moves only through the MoveRule its PieceType holds.

The design we built
The classes from the class diagram, in the same places, with names only. Amber badges number the decisions in the table below. Game carries 7 and 8. Position carries 3, 4 and 6. Board carries 1, PieceType carries 2, and CastlingRight carries 5. MoveRule carries a Strategy tag.The classes from the class diagram, in the same places, with names only. Amber badges number the decisions in the table below. Game carries 7 and 8. Position carries 3, 4 and 6. Board carries 1, PieceType carries 2, and CastlingRight carries 5. MoveRule carries a Strategy tag.
Each decision lands on one class. One interface carries a pattern. The classes from the class diagram, in the same places, with names only. Amber badges number the decisions in the table below. Game carries 7 and 8. Position carries 3, 4 and 6. Board carries 1, PieceType carries 2, and CastlingRight carries 5. MoveRule carries a Strategy tag.
S.No.The questionWhat we choseWhy
1Does a piece know its square?A square is a coordinate, and only the board knows what stands whereOne place says what stands where
2A class per piece, or a rule per piece type?A Piece record, and a MoveRule held by each PieceTypeRules list their moves directly, and three types share one rule
3Change one board in place, or make a new position for each move?A new Position for every moveTrying a move and undoing one never touch the live game
4How do we refuse a move that leaves the king in check?Every rule lists candidates; one filter tries each and drops any that leave the king attackedPins and checks come out of one test
5Where does the right to castle live?A set of castling rights on the position, lost when a move touches a home squareUndo restores the rights, and a FEN can state them
6How does the game know en passant is allowed?The position stores the square, set by a two-square step and empty after any other moveThe position alone answers every rule question
7How do we tell checkmate from stalemate?No legal moves at all; checkmate if the king is attacked, stalemate if notBlocks and captures count, and stalemate needs no code of its own
8Undo: reverse each move, or keep the positions?Keep every position, and go back to the one beforeDropping the last position is right for every kind of move

Here is white's en passant capture from the demo, end to end:

  1. The screen calls move(e5, d6) on its own thread. There is no lock, because the server hands this game one move at a time, and there is no outside call.
  2. move finds the game still on, a white pawn on e5 and white to move. It finds e5-d6 in legalMoves, where judge put it after black's d7-d5. PawnRule.candidates had offered it because d6 was the enPassantSquare, and keepsKingSafe had found the king safe.
  3. Position.apply copies the board, moves the pawn to d6 and clears d5. The new position has black to move and no en passant square.
  4. move adds the new position and the move to its lists, and judge works out black's legal moves and the status.
  5. The caller gets MoveResult(MOVED, NORMAL). A later undo removes that position, and the d5 pawn and the en passant chance come back.

A refused move takes the first steps of this path and stops before apply, so nothing in the game changes. Undo runs the path backwards: it removes the last position and the last move, then judge runs on the position before, so the status and the legal moves match the board again.

The complete code

Here is the whole project. Click any class name to jump to its file, or use Find a file to search. Badges in the tree show what each file is: a class, an interface, an enum or a record.

gameGame.java
package game; import java.util.ArrayList;import java.util.List;import java.util.Objects;import java.util.Optional; import board.Color;import board.Square;import piece.Piece;import piece.PieceType; /** * One game of chess. Players are not objects here: a move arrives as a call to * move(), from a screen or a server. The game keeps every position it has been * through, so undo goes back to the one before. * Not thread-safe: a server hands each game its moves one at a time. */public final class Game {    private final List<Position> positions = new ArrayList<>();    private final List<Move> moves = new ArrayList<>();    private List<Move> legalMoves;    private Status status;     public Game() {        this(Position.start());    }     public Game(Position start) {        positions.add(Objects.requireNonNull(start, "start"));        judge();    }     public MoveResult move(Square from, Square to) {        return play(from, to, null);    }     public MoveResult move(Square from, Square to, PieceType promotion) {        return play(from, to, Objects.requireNonNull(promotion, "promotion"));    }     private MoveResult play(Square from, Square to, PieceType promotion) {        Objects.requireNonNull(from, "from");        Objects.requireNonNull(to, "to");        Position position = position();        if (status.isOver()) {            return refuse(Outcome.GAME_OVER);        }        Optional<Piece> piece = position.board().pieceAt(from);        if (piece.isEmpty()) {            return refuse(Outcome.NO_PIECE);        }        if (piece.get().color() != position.sideToMove()) {            return refuse(Outcome.NOT_YOUR_TURN);        }        List<Move> legal = matching(legalMoves, from, to);        if (legal.isEmpty()) {            boolean ruleAllows = !matching(position.candidatesFrom(from), from, to).isEmpty();            return refuse(ruleAllows ? Outcome.KING_UNSAFE : Outcome.CANNOT_MOVE_THERE);        }        Optional<Move> chosen = choose(legal, promotion);        if (chosen.isEmpty()) {            return refuse(promotion == null ? Outcome.CHOOSE_PROMOTION : Outcome.BAD_PROMOTION);        }        positions.add(position.apply(chosen.get()));        moves.add(chosen.get());        judge();        return new MoveResult(Outcome.MOVED, status);    }     /** Takes back the last move, whoever made it. Empty if there is none. */    public Optional<Move> undo() {        if (moves.isEmpty()) {            return Optional.empty();        }        positions.remove(positions.size() - 1);        Move last = moves.remove(moves.size() - 1);        judge();        return Optional.of(last);    }     /** Every move the side to move may make, for a screen that shows them. */    public List<Move> legalMoves() {        return legalMoves;    }     public Position position() {        return positions.get(positions.size() - 1);    }     public Status status() {        return status;    }     /** The winner, once the game has ended in checkmate. */    public Optional<Color> winner() {        return status == Status.CHECKMATE ? Optional.of(position().sideToMove().opponent()) : Optional.empty();    }     public List<Move> moves() {        return List.copyOf(moves);    }     /** Works out the moves and the status of the position the game is now in. */    private void judge() {        Position position = position();        legalMoves = List.copyOf(position.legalMoves());        boolean inCheck = position.inCheck(position.sideToMove());        if (legalMoves.isEmpty()) {            status = inCheck ? Status.CHECKMATE : Status.STALEMATE;        } else {            status = inCheck ? Status.CHECK : Status.NORMAL;        }    }     private static List<Move> matching(List<Move> candidates, Square from, Square to) {        return candidates.stream().filter(move -> move.from().equals(from) && move.to().equals(to)).toList();    }     /** All moves here share from and to; they differ only in the piece a pawn becomes. */    private static Optional<Move> choose(List<Move> legal, PieceType promotion) {        for (Move move : legal) {            if (move.promotion() == promotion) {                return Optional.of(move);            }        }        return Optional.empty();    }     private MoveResult refuse(Outcome outcome) {        return new MoveResult(outcome, status);    }}
Click a class name in the code to open its fileJava · 133 lines · 1195 in the project

demo/Main.java plays six short scenes: a quick checkmate and its undo, a pinned bishop, castling, en passant, promotion, and a checkmate set beside a stalemate.

$ java demo.Main
1. A quick checkmate, and undo
  e2-e4    MOVED               NORMAL
  e7-e5    MOVED               NORMAL
  c1-e3    CANNOT_MOVE_THERE   NORMAL
  f1-c4    MOVED               NORMAL
  d7-d6    MOVED               NORMAL
  b8-c6    NOT_YOUR_TURN       NORMAL
  d1-h5    MOVED               NORMAL
  g8-f6    MOVED               NORMAL
  h5-f7    MOVED               CHECKMATE
  e8-f7    GAME_OVER           CHECKMATE
  undo     h5-f7               NORMAL
  f7 holds black pawn

2. A pinned bishop
  e2-d3    KING_UNSAFE         NORMAL
  e2-e4    CANNOT_MOVE_THERE   NORMAL

3. Castling
  e1-g1    KING_UNSAFE         NORMAL
  e1-c1    MOVED               NORMAL
  e8-g8    MOVED               NORMAL
8 r....rk.
7 ........
6 b.......
5 ........
4 ........
3 n.......
2 ........
1 ..KR...R
  abcdefgh

4. En passant, now or never
  e2-e4    MOVED               NORMAL
  a7-a6    MOVED               NORMAL
  e4-e5    MOVED               NORMAL
  d7-d5    MOVED               NORMAL
  h2-h3    MOVED               NORMAL
  h7-h6    MOVED               NORMAL
  e5-d6    CANNOT_MOVE_THERE   NORMAL
  undo     h7-h6               NORMAL
  undo     h2-h3               NORMAL
  e5-d6    MOVED               NORMAL
  d5 holds nothing

5. Promotion
  a7-a8    CHOOSE_PROMOTION    NORMAL
  a7-a8=K  BAD_PROMOTION       NORMAL
  a7-a8=N  MOVED               CHECK

6. Checkmate or stalemate
  g1-g6    MOVED               STALEMATE
  undo     g1-g6               NORMAL
  g1-g7    MOVED               CHECKMATE
  winner: WHITE

Notice four things in the output:

  • Two refusals of one bishop give two reasons. In scene 2, e2-d3 is KING_UNSAFE, because the bishop's rule allows it and only the pin stops it. Then e2-e4 is CANNOT_MOVE_THERE, because a bishop never moves straight.
  • An attack on b1 does not stop castling. In scene 3, white cannot castle kingside, because the bishop on a6 attacks f1. White can castle queenside, though the knight on a3 attacks b1. The board printed after it shows both sides castled.
  • Undo brings back the en passant chance. In scene 4, e5-d6 is refused after h2-h3 and h7-h6. Two undos open the chance again, and the same move then succeeds and clears d5.
  • One queen gives stalemate on g6 and checkmate on g7. Both leave black with no legal move, and only the check on g7 tells them apart.

Follow-up questions

The interviewer asksWhat changesWhat does not
Draw by threefold repetition?Game counts how often the current Position appears in its list, using the equals it already has. equals compares the en passant square even when no pawn can use it, so a strict count clears such a square first. Status gains a value for the drawThe pieces, the rules
The 50-move rule?Position gains a count of moves since the last capture or pawn move, which apply resets or adds to. Fen reads it from the fifth field, and Position.equals leaves it out, or a repeated position would never match. judge checks it, and Status gains a value for the drawThe piece rules
Resignation and draw offers?Game gains resign(color) and an agreed draw, and Status gains values for themPosition, the rules
Chess clocks?Game takes a java.time.Clock and each side's time left. Running out of time loses the game, so Status gains a loss on time, and Game needs a time check that runs without a move, such as a checkTime() the server calls on a timerPosition, the rules
A computer player?A MoveChooser outside Game, as in tic-tac-toe, that searches legalMoves(). A deep search would want one board changed in place instead of a new Position per moveGame's methods and its callers
Chess960, with a shuffled back rank?CastlingRight becomes a class built from the start position, because the king's and rooks' home squares change from game to game. Position.start builds a shuffled rank, and Fen reads the castling letters that name a rook's file. Position.apply must lift the king and rook before placing either, because the king can land on the rook's start square. Game.move names a castle as the king moving onto its own rook, because a one-square castle looks like a king stepSlidingRule, StepRule, PawnRule
A new piece that moves like a bishop or a knight?A new PieceType constant with a rule that joins the two lists, and a FEN letterPosition, Game
Write moves in chess notation, such as Nf3?A writer that turns a Move and its Position into text. It uses the legal list to tell apart two knights that can reach one square. The + and # marks need the position after the move, so the writer goes through Game, or apply becomes publicThe rules
Two players on two phones, moves on two threads?A private lock around each public method of Game, as in tic-tac-toePosition and the rules, which hold nothing that changes

Most rows add a class or a field and leave the piece rules alone. The 50-move rule and Chess960 reach into Position, CastlingRight and Fen, because they change what a position has to remember. Chess960 also changes how Game.move reads a castle. Saying that in the interview, with the class named, is the point of the follow-up.

What the interviewer looks for

Mid-level

A mid-level candidate builds a board, pieces that move by their rules, turns, and refusals for illegal moves. They know that a move must not leave the king in check, even if their test for it is narrow, such as one that checks only king moves.

Senior

A senior candidate puts each piece's movement behind one interface and shares the sliding code between the rook, the bishop and the queen. They enforce king safety with one test after the move, keep castling rights and the en passant square on the position instead of flags on pieces, and tell checkmate from stalemate by counting legal moves.

Staff+

A staff candidate explains why positions never change and what that buys: a safety test that cannot corrupt the game, and undo with no special cases. They name the cost, a board copy for every move tried, and say when it stops being acceptable. They also point out the cases a narrow design gets wrong, such as en passant that opens a rank to the king.

Common mistakes

  • A canMove(from, to) per piece and no list of moves. Checkmate and stalemate need to know whether any legal move exists at all, and asking each piece about 64 squares repeats work.
  • King safety inside each piece's rule. Pins, uncovered checks and en passant along a rank then need code in several places, and one gets missed.
  • A hasMoved flag for castling. Undo must restore it, and a puzzle cannot state it. A rook taken at home never moved, so its flag alone still says it can castle.
  • Checking only where the castling king lands. The king may not castle out of check or through an attacked square either, but an attack on b1 does not matter.
  • Keeping the en passant chance for more than one move. It belongs to the next move only.
  • Calling every position with no moves checkmate. A side with no moves and no check is stalemated, and that is a draw.
  • Making a queen without asking. The player chooses the piece, and a knight is sometimes the better one.

Summary

  • A Position holds the board and the three facts the board cannot show: whose move it is, the castling rights left, and the en passant square.
  • Each PieceType holds a MoveRule, and the rook, bishop and queen share SlidingRule with different directions.
  • Rules list candidates, and one filter applies each and drops any that leave the king attacked. Pins and checks need no code of their own.
  • Castling keeps its squares as data in CastlingRight, and a right is lost when any move touches its king's or rook's home square.
  • A two-square pawn step sets the en passant square, and the next position built leaves it empty.
  • No legal moves means checkmate if the king is attacked, and stalemate if not.
  • Positions never change, so undo goes back to the previous one and restores everything at once.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.