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.
- 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
- 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.
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.
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.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.
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.
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.
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.
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.
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.
- 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.
- 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.
- 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.
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.
- 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.
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.
- 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.
- 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.
- 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.
- "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."