Case study: Chess
What you will learn on this page
Section titled “What you will learn on this page”- How to model a board and its pieces as plain values: a piece is a
colour and a kind from a closed
enum, and the board is 64 cells that each may hold a piece. You will compare this honestly with a class hierarchy and with astd::variant, and see when each one fits. - How to find legal moves the simple way: generate the moves each piece could make, try each one on a copy of the position, and keep the ones that do not leave the mover’s own king attacked. You will see what that costs and why the cost is fine here.
- How castling, en passant, and promotion fit into the same move generator, and how a refusal names the exact rule a move broke.
- How checkmate, stalemate, and the fifty-move rule become a small
state machine, the
GameState. - How a move record, one plain value that holds everything needed to reverse a move, gives undo and redo. It is the Command idea without a class hierarchy, and you will see when a Command class would earn its place.
- How perft, a count of positions reachable in a few moves, serves as a test oracle, and what a matching count proves and does not.
- How a later change, chess clocks and PGN export, lands: a clock that reads time from an injected source, an undo policy for timed games, and algebraic notation that tells pieces apart using legal moves only.
This page assumes the Command and Memento pages, and State machines. The order of work follows How to approach a case study.
The request
Section titled “The request”“We run a small chess club and want our own game program for the club laptops: two people at one screen, or one person checking a line of play. It has to know the rules properly, including the odd ones. Last year we tried a free program that let a pinned bishop move and would not let anyone castle after their rook came back home. And people keep asking for a take-back button.”
Two complaints, and both are about rules that depend on more than the piece that moves. A pinned bishop may move like a bishop, but not if moving it exposes its own king. Castling depends on whether the king or the rook has ever moved, which the board alone cannot show. A take-back has to put back things that a picture of the board does not show either. The design has to decide where that hidden information lives.
Clarifying questions
Section titled “Clarifying questions”Each question is here because its answer changes the design.
| Question | Answer (from the club) | What it changes |
|---|---|---|
| Which rules? Standard chess, or a variant? | Standard chess, the FIDE rules, every move. | Six kinds of piece, fixed for ever: a closed set. Castling, en passant, and promotion are part of move generation. |
| How do people enter a move? | Typing it. Two squares, like e2e4, is fine; the screen shows a letter grid. |
Coordinate notation in, with a promotion letter (e7e8q). A parser that refuses anything else with a hint. |
| What should happen with a move that is not allowed? | Say why. “Illegal move” teaches nobody anything. | A Refusal enum, one value per rule, and a text that names the squares. |
| Which endings must it detect? | Checkmate and stalemate. The fifty-move rule would be nice. We do not need repetition for now. | A GameState with wins and draws. Threefold repetition is out of scope, and the page says so. |
| Can people set up a position, say from a puzzle book? | Yes. Our puzzle files use FEN. | Reading and writing FEN, and refusing a FEN that is not a position chess can reach (two kings on one side, and so on). |
| How far back can a take-back go? | All the way to the start, and forward again if they change their mind. | Undo and redo through a history of move records, not one level. |
| Does it need to play against people? | No. Two humans, or one person looking at lines. | No engine, no search, no evaluation. Move generation only has to be fast enough for one person’s clicks and for the tests. |
| Will it run on a server, or one laptop? | One laptop, one window. | Single process, single thread, stated. |
Two answers decide the shape. “Every move, the FIDE rules” means the set
of piece kinds is closed and well known, so a value with an enum is a
fair model and a class per piece is not needed. “All the way to the
start” means each move must leave behind enough to reverse it, including
the castling rights and the en passant square, which nothing on the
board shows.
Confirmed:
- The standard starting position, or any position given as FEN.
- Every legal move: normal moves and captures, the pawn’s double step, castling on both sides, en passant, and promotion to any of the four pieces.
- Refusing a move with the rule it breaks, and changing nothing.
- Check, checkmate, stalemate, and the fifty-move rule.
- Undo to the start and redo, and FEN out at any time.
Assumed:
- Two players at one screen. Whoever types the move is the side to move.
- Moves come in coordinate notation. A friendlier input (clicking, or
Nf3) can be built on top of the sameGame. - The fifty-move rule ends the game by itself after 100 half-moves without a capture or a pawn move. Under the FIDE rules a player must claim this draw, and only the 75-move rule ends the game without a claim; the club accepted the simpler rule for now.
Out of scope:
- Threefold repetition, and draws for insufficient material (a king against a king, say). The Exercise adds repetition.
- Draw offers and resignation.
- A computer opponent, analysis, and opening books.
- Networked play, saving games to disk, and more than one game at a time.
Requirements
Section titled “Requirements”Functional requirements.
- FR-1 Positions. The program can start from the standard position or from a FEN string, and can write the current position as FEN. A FEN that describes an impossible position is refused with a reason.
- FR-2 Legal moves. The program knows every legal move in a position, including castling, en passant, and promotion, and no move that would leave the mover’s own king attacked.
- FR-3 Refusals. A move that is not legal is refused with the rule it breaks, and the game is unchanged.
- FR-4 The end of the game. The program detects checkmate (a win), stalemate (a draw), and the fifty-move rule (a draw), and accepts no move afterwards.
- FR-5 Take-backs. Any number of moves can be taken back, back to the start, and played again in order. A new move after a take-back forgets the moves that were taken back.
- FR-6 Input. Moves are typed in coordinate notation: two squares, and a letter for a promotion. Anything else is refused with an example of the format.
Non-functional requirements.
- NFR-1 Correct by count. The number of positions reachable in a few moves from well-known test positions matches the published perft counts.
- NFR-2 Testable without a screen. The rules live in a library with no input or output. The demo program is a thin layer over it.
- NFR-3 Positions are values. A position can be copied and compared, and owns nothing on the heap, so a test can save one and check that undo gets back exactly the same thing.
- NFR-4 Single-threaded. One game is used by one thread at a time. This is stated in the code, not enforced.
- NFR-5 Fast enough for people and tests. Finding the legal moves
of one position takes far less time than a person notices. As a
rough measure, counting the 197,281 positions four moves deep from
the start took 59 to 61 ms in three runs on one machine (g++ 11.4,
-O2, an AMD EPYC 7H12 server). That figure is specific to that machine and is not a benchmark.
Use cases and acceptance criteria
Section titled “Use cases and acceptance criteria”The tests are named after these criteria. See Use cases, user stories, and acceptance criteria.
UC-1 Set up and read a position.
- AC-1.1 The start position has every piece at home, White to move, all four castling rights, and no en passant square.
- AC-1.2 FEN read and written again gives the same string, and a FEN that is malformed or impossible is refused.
- AC-1.3 Coordinate notation is parsed (
e2e4,e7e8q) and anything else is refused.
UC-2 Move by the rules.
- AC-2.1 to AC-2.4 Perft counts match the published counts for the start position, Kiwipete, a rook-and-pawn endgame with en passant pins, and two positions full of promotions.
- AC-2.5 Castling moves the king two squares and the rook to the other side of it, on both sides.
- AC-2.6 Castling is refused once the king or that rook has moved, or the rook was captured.
- AC-2.7 Castling is refused when a square between the king and the rook is occupied.
- AC-2.8 Castling is refused out of check, through an attacked square, or onto one.
- AC-2.9 En passant removes the pawn beside, not a pawn on the square the capturer lands on.
- AC-2.10 En passant is allowed only on the move straight after the double step.
- AC-2.11 En passant is refused when removing both pawns from a rank would expose the king to a rook or queen on that rank.
- AC-2.12 A pawn promotes to the piece chosen, including a knight.
- AC-2.13 A promotion needs a letter, and only a promotion may have one.
UC-3 Refuse a move.
- AC-3.1 Each refusal names the rule broken.
- AC-3.2 A move that leaves the mover’s king attacked is refused, whether by a pin, a king step, or ignoring a check.
- AC-3.3 A refused move changes nothing.
UC-4 End the game.
- AC-4.1 Scholar’s mate is a win for White.
- AC-4.2 Fool’s mate is a win for Black.
- AC-4.3 No legal move without check is stalemate (tested with a well-known ten-move stalemate attributed to Sam Loyd).
- AC-4.4 After 100 half-moves without a capture or a pawn move the game is drawn, unless the last move was mate.
- AC-4.5 No move is accepted once the game is over.
- AC-4.6 A check that can be answered is not mate.
UC-5 Take back and play again.
- AC-5.1 Undo restores the exact position after every kind of move.
- AC-5.2 Redo plays the move again; a new move forgets the moves that could have been redone.
- AC-5.3 Undo and redo with nothing to do are refused.
- AC-5.4 Undoing a mate reopens the game.
- AC-5.5 In random games, undo and redo pass through exactly the same positions as the game did.
Invariants
Section titled “Invariants”Each invariant names the code that keeps it. See Invariants.
- INV-1 One king each. Every position has exactly one white and one
black king. Kept by
Position::from_fen, which refuses anything else, and by INV-2: a king is never left where it could be taken, so no move ever captures one. - INV-2 The side that just moved is not in check. Kept by
Position::legal_moves, which tries every move on a copy and drops the ones that leave the mover’s king attacked, and byfrom_fen, which refuses a position where the side not to move is in check. - INV-3 Undo is exact.
unmake(make(move))gives back a position equal, member by member, to the one before. Kept byMoveRecord, which stores everythingmakechanges that cannot be worked out again. - INV-4 Castling rights only shrink, and are true. A castling right
is never gained back, and a right means the king and that rook are on
their home squares. Kept by
from_fen, which checks the pieces, and bymake, which removes rights whenever a move starts or ends on a king’s or rook’s home square. - INV-5 An en passant square is fresh. It is set only by a pawn’s
double step, to the square the pawn passed over, and cleared by the
next move. Kept by
make, and checked byfrom_fen. - INV-6 A refused move changes nothing. Kept by
Game::check, which isconst, and byGame::play, which changes the position only aftercheckaccepts. - INV-7 The state matches the position.
Game::state()is always what the rules say about the current position. Kept byupdate_state, which runs after the constructor, after every move, and after every undo.
Entities and relationships
Section titled “Entities and relationships”Start with the nouns in the request and the answers: a game, a board, pieces, squares, moves, the side to move, a take-back. Then ask which of them have an identity that matters over time, and which are only values. See Entities, values, and services.
- Square is a value: a number from 0 to 63, with a file (a to h) and a rank (1 to 8).
- Piece is a value: a colour and a kind. Two white knights are interchangeable. Nothing in the rules asks “which knight”, only “a knight on g1”.
- Move is a value: two squares, and a kind for a promotion.
- Position is a value: the board, the side to move, the castling rights, the en passant square, and two counters. It is everything the rules need to know about “now”. Two positions with the same contents are the same position.
- MoveRecord is a value: a move plus what it destroyed, so that it can be reversed.
- Game is the one entity. It has a history, it changes over time, and it decides whether a request is allowed.
Text description of the diagram
A Game is the only entity. It holds the current Position, a history of MoveRecord values (oldest first), and a list of Move values that can be played again. A Position holds 64 cells, each empty or holding one Piece (a colour and a kind), and possibly an en passant Square. A MoveRecord holds the Move that was made and the Piece it captured, if any, with the square it stood on. A Move holds two Squares.
Diagram source (Mermaid)
flowchart LR
Game["Game (entity)"] -->|"current"| Position["Position (value)"]
Game -->|"history, oldest first"| Record["MoveRecord (value)"]
Game -->|"moves to play again"| Move["Move (value)"]
Position -->|"64 cells, each empty or one"| Piece["Piece (value): colour and kind"]
Position -->|"en passant square, if any"| Square["Square (value)"]
Record -->|"the move made"| Move
Record -->|"what it took, and from where"| Piece
Move -->|"from and to"| SquareNotice what is not an entity: the pieces. A beginner’s first sketch
often gives each piece an object with an identity, a position, and a
move method. The rules never need that identity, and the
Pieces: enum, hierarchy, or variant?
section shows what it costs.
Text description of the diagram
Game owns, by value, a Position, a vector of MoveRecord values (the history), a vector of Move values (the moves that can be redone), and a GameState. It offers check, play, undo, redo, legal_moves, and state; check, play, undo, and redo return a Verdict, which holds a Refusal and a text and says whether the request was accepted. Position owns 64 optional Piece cells, the side to move, the castling rights, an optional en passant square, the half-move clock, and the move number. It offers start and from_fen (both static), to_fen, pseudo_legal_moves, legal_moves, is_legal, in_check, make (which returns a MoveRecord), and unmake. MoveRecord holds the Move, its MoveKind, the piece that moved, the captured piece if any and the square it stood on, and the castling rights, en passant square, and half-move clock from before the move. Move holds two squares and an optional promotion kind. Piece holds a colour and a kind.
Diagram source (Mermaid)
classDiagram
class Game {
-Position position_
-vector~MoveRecord~ history_
-vector~Move~ redo_
-GameState state_
+check(move) Verdict
+play(move) Verdict
+undo() Verdict
+redo() Verdict
+legal_moves() vector~Move~
+state() GameState
}
class Position {
-optional~Piece~ board_[64]
-Color to_move_
-CastlingRights castling_
-optional~Square~ en_passant_
-int halfmove_clock_
-int fullmove_number_
+start()$ Position
+from_fen(text)$ Position
+to_fen() string
+pseudo_legal_moves() vector~Move~
+legal_moves() vector~Move~
+is_legal(move) bool
+in_check(color) bool
+make(move) MoveRecord
+unmake(record)
}
class MoveRecord {
+Move move
+MoveKind kind
+Piece moved
+optional~Piece~ captured
+Square captured_on
+CastlingRights castling_before
+optional~Square~ en_passant_before
+int halfmove_clock_before
}
class Move {
+Square from
+Square to
+optional~Kind~ promotion
}
class Piece {
+Color color
+Kind kind
}
class Verdict {
+Refusal refusal
+string text
+accepted() bool
}
Game *-- Position
Game *-- MoveRecord : history
Position *-- Piece : 64 cells
MoveRecord *-- Move
Game ..> Verdict : returnsOwnership is the simplest it can be: everything is held by value.
There is no pointer, no new, and no shared state anywhere in step 1.
A Game can be copied, and the copy is a separate game. A Position
is 792 bytes (measured with g++ 11.4; the exact size depends on the
compiler) and copying it is a memcpy-sized job, which matters in a
moment, when legality is tested on copies.
Class design
Section titled “Class design”The code is in examples/case-studies/chess/step-1. Each block below
comes from it, and the text after each block explains what to notice.
Squares and pieces
Section titled “Squares and pieces”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One of the 64 squares, stored as an index: 0 is a1, 1 is b1, ... 7 is// h1, 8 is a2, ... 63 is h8. So index = rank * 8 + file, where file 0..7// means a..h and rank 0..7 means the ranks 1..8 printed on a board.// A value type: two ints' worth of meaning in one, copied freely.struct Square { int index = 0;
[[nodiscard]] constexpr int file() const { return index % 8; } [[nodiscard]] constexpr int rank() const { return index / 8; } friend constexpr bool operator==(Square, Square) = default;};
// The square on file 0..7 and rank 0..7 (both checked by the caller).[[nodiscard]] constexpr Square square_at(int file, int rank) { return Square{rank * 8 + file}; }
// The square reached from `from` by moving file_step files right and// rank_step ranks up (negative steps go left and down), or empty if that// leaves the board. Working on file and rank, not on the index, is what// stops a step right from h4 wrapping round to a5.[[nodiscard]] constexpr std::optional<Square> step(Square from, int file_step, int rank_step) { const int file = from.file() + file_step; const int rank = from.rank() + rank_step; if (file < 0 || file > 7 || rank < 0 || rank > 7) return std::nullopt; return square_at(file, rank);}A Square is an index from 0 to 63, rank * 8 + file, so a1 is 0, h1
is 7, a2 is 8, and h8 is 63. The square e5 is file 4, rank 4, so it is
36. A plain number makes the board an ordinary array, and moving “one
rank up” is adding 8. The file() and rank() helpers keep that
arithmetic in one place, so the rest of the code says what it means.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The two sides. White moves first.enum class Color { white, black };
[[nodiscard]] constexpr Color opposite(Color color) { return color == Color::white ? Color::black : Color::white;}
// The six kinds of piece. The rules of chess fix this set, so it is a// closed enum, and every rule that depends on the kind (how it moves,// what a pawn may become, its letter in notation) is a switch over it.//// Why an enum and not a class hierarchy (a Piece base with a virtual// moves() in Knight, Bishop, ...):// - A move depends on more than the piece: on the whole board, the side// to move, castling rights, and the en passant square. A Knight object// would need all of that passed in, so the rules would live in// Position anyway.// - Promotion turns a pawn into a queen. With values that is one// assignment; with objects it is deleting one and allocating another.// - A board of values copies with one assignment. Trying a move on a copy// (the legality test), undo, and the tests all rely on that.// A hierarchy fits when the set of kinds is open: a variant-chess program// that loads fairy pieces from plugins, where adding a kind must not mean// editing every switch. std::variant<Pawn, Knight, ...> sits between the// two: values, but one type per kind. It pays off when kinds carry// different data; here none does.enum class Kind { pawn, knight, bishop, rook, queen, king };
// A piece is just a colour and a kind: a small value, copied freely.// There is no "has moved" flag: the only rules that need one (castling// and the pawn's double step) are kept by Position as castling rights and// by the pawn's rank.struct Piece { Color color = Color::white; Kind kind = Kind::pawn; friend constexpr bool operator==(Piece, Piece) = default;};A piece is two small enums. Kind is a closed set: chess has had
these six kinds for centuries, and a club program will not grow a
seventh. The comment in the code gives the reasoning, and the
Pieces: enum, hierarchy, or variant?
section compares the alternatives. Piece compares with ==, which
the castling code uses to ask “is that cell my rook?”.
Moves and coordinate notation
Section titled “Moves and coordinate notation”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A move as a player asks for it: from one square to another, and, only// when a pawn reaches the last rank, what it becomes. Castling is the// king's move (e1g1), and en passant is the pawn's move to the empty// square behind the pawn it takes (e5d6); Position works out the rest.// A Move says nothing about whether it is legal: Game checks that.struct Move { Square from; Square to; std::optional<Kind> promotion; // queen, rook, bishop, or knight
friend bool operator==(const Move&, const Move&) = default;};A Move is only a request: two squares and a promotion kind. It does
not say whether it is legal, and it does not know what is on the
board. That is deliberate. The same Move value comes from the parser,
from the move generator, and from the redo list, and only the position
can decide what it means.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Reads coordinate notation: four characters for the two squares ("e2e4")// and, for a promotion, a fifth: q, r, b, or n ("e7e8q"). Returns empty// for anything else: the wrong length, a square off the board, capitals,// or another letter (a pawn may not become a king or stay a pawn).// Whether the move is legal is not checked here.[[nodiscard]] inline std::optional<Move> parse_move(std::string_view text) { if (text.size() != 4 && text.size() != 5) return std::nullopt; const std::optional<Square> from = parse_square(text.substr(0, 2)); const std::optional<Square> to = parse_square(text.substr(2, 2)); if (!from || !to) return std::nullopt; Move move{*from, *to, std::nullopt}; if (text.size() == 5) { switch (text[4]) { case 'q': move.promotion = Kind::queen; break; case 'r': move.promotion = Kind::rook; break; case 'b': move.promotion = Kind::bishop; break; case 'n': move.promotion = Kind::knight; break; default: return std::nullopt; } } return move;}parse_move returns std::optional<Move>: either a move or nothing,
with no exception. Bad typing is an ordinary event at a keyboard, not
an error in the program. It checks only the shape (two squares on the
board, and at most one promotion letter from qrbn); whether the move is
allowed is a question for Game::check. So e2e4q parses, because
its shape is right, and check then refuses it with “only a pawn
reaching the last rank can promote”. check also refuses a Move
built in code with a king or pawn as the promotion, which the parser
can never produce.
The position
Section titled “The position”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The whole state of a game that the rules need: where every piece is,// whose turn it is, the castling rights, the en passant square, and the// two counters FEN records. It is a value: copying it copies the game at// that moment, and two positions compare equal only if all of that is// equal.//// It knows the rules of movement: which moves are legal, whether a square// is attacked, and how to make and unmake a move. It does not know about// turns being refused, game results, or history: that is Game's job.class Position {public: // The standard starting position, White to move. [[nodiscard]] static Position start();
// Reads Forsyth-Edwards Notation, the usual one-line text for a // position, e.g. the start is // "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" // (ranks 8 down to 1, side to move, castling rights, en passant // square, half-moves since a capture or pawn move, move number). // The last two fields may be left out. Throws std::invalid_argument // for text that is malformed or for a position the rules cannot reach // in the ways this class depends on: not exactly one king a side, a // pawn on the first or last rank, the side not to move in check, or a // castling right without its king and rook at home. [[nodiscard]] static Position from_fen(std::string_view fen); [[nodiscard]] std::string to_fen() const;
[[nodiscard]] std::optional<Piece> at(Square square) const { return board_[static_cast<std::size_t>(square.index)]; } [[nodiscard]] Color to_move() const { return to_move_; } [[nodiscard]] const CastlingRights& castling() const { return castling_; } // The square a pawn may capture onto en passant: the one a pawn just // passed over with its double step. Empty after any other move. [[nodiscard]] std::optional<Square> en_passant() const { return en_passant_; } [[nodiscard]] int halfmove_clock() const { return halfmove_clock_; } [[nodiscard]] int fullmove_number() const { return fullmove_number_; }
// True if a piece of colour `by` attacks `square` (whether or not // anything stands there, and whether or not that piece is pinned). [[nodiscard]] bool attacked(Square square, Color by) const; [[nodiscard]] Square king_square(Color color) const; [[nodiscard]] bool in_check(Color color) const;
// Every move the side to move could make if leaving its own king in // check were allowed ("pseudo-legal"). Castling is included only when // the rights, the empty squares, and "not out of or through check" // all hold; "not into check" is left to legal_moves like any move. [[nodiscard]] std::vector<Move> pseudo_legal_moves() const; // The pseudo-legal moves that do not leave the mover's king attacked. [[nodiscard]] std::vector<Move> legal_moves() const; // True if `move` is a pseudo-legal move here and leaves the mover's // king safe. Promotions must name the piece. [[nodiscard]] bool is_legal(const Move& move) const;
// Plays `move`, which must be pseudo-legal here (unchecked: Game // checks first), and returns the record that unmake needs. MoveRecord make(const Move& move); // Takes back the last move made: `record` must be the one make // returned for it, and moves must be unmade in reverse order. void unmake(const MoveRecord& record);
friend bool operator==(const Position&, const Position&) = default;
private: Position() = default; // an empty board; start and from_fen fill it
std::optional<Piece>& cell(Square square) { return board_[static_cast<std::size_t>(square.index)]; } void add_target(Square from, Square to, std::vector<Move>& moves) const; void add_pawn_moves(Square from, std::vector<Move>& moves) const; void add_castling(Square from, std::vector<Move>& moves) const;
std::array<std::optional<Piece>, 64> board_{}; // empty squares hold nullopt Color to_move_ = Color::white; CastlingRights castling_; std::optional<Square> en_passant_; int halfmove_clock_ = 0; int fullmove_number_ = 1;};The board is std::array<std::optional<Piece>, 64>: 64 cells, each
empty (std::nullopt) or holding a piece. The array lives inside the
Position object, so a copy of a position is a copy of the board, and
nothing points anywhere else. See
Value and reference semantics
for why that matters.
The rest of the members are the facts the board cannot show:
| Member | Why the board alone is not enough |
|---|---|
to_move_ |
The same arrangement of pieces is a different position with the other side to move. |
castling_ |
A king and rook at home may have moved away and back, which takes the right away for good. |
en_passant_ |
A pawn beside an enemy pawn may capture it en passant only straight after that pawn’s double step. |
halfmove_clock_ |
The fifty-move rule counts half-moves since the last capture or pawn move. |
fullmove_number_ |
FEN and, later, PGN number the moves. |
These are exactly the six fields of a FEN string, which is no accident: FEN was designed to hold everything needed to continue a game from a position, apart from the history needed for repetition.
Position declares a defaulted operator==, so two positions compare
member by member. The tests lean on this: “undo restores the position”
becomes one comparison.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
Position Position::from_fen(std::string_view fen) { // A small helper that builds the exception to throw. [fen] copies the // view into the lambda, so every message can quote the input. const auto fail = [fen](const std::string& why) { return std::invalid_argument("bad FEN \"" + std::string(fen) + "\": " + why); }; // Split at single spaces into the four or six fields. std::vector<std::string_view> fields; // find gives npos (the largest size_t) when no space is left, and // std::min turns that into the end of the text: the last field. for (std::size_t begin = 0; begin <= fen.size();) { const std::size_t end = std::min(fen.find(' ', begin), fen.size()); fields.push_back(fen.substr(begin, end - begin)); begin = end + 1; } if (fields.size() != 4 && fields.size() != 6) throw fail("expected 4 or 6 fields");
Position position; position.castling_ = CastlingRights{{false, false}, {false, false}}; // only those listed
// Field 1: the ranks from 8 down to 1, split by '/'. A digit stands for // that many empty squares; a letter for a piece. int rank = 7; int file = 0; for (const char c : fields[0]) { if (c == '/') { if (file != 8 || rank == 0) throw fail("each rank needs exactly 8 squares"); --rank; file = 0; } else if (c >= '1' && c <= '8') { file += c - '0'; if (file > 8) throw fail("a rank is longer than 8 squares"); } else { const std::optional<Piece> piece = piece_from_letter(c); if (!piece) throw fail(std::string("unknown piece letter '") + c + "'"); if (file > 7) throw fail("a rank is longer than 8 squares"); position.cell(square_at(file, rank)) = piece; ++file; } } if (rank != 0 || file != 8) throw fail("expected 8 ranks of 8 squares");
// Field 2: whose turn it is. if (fields[1] == "w") { position.to_move_ = Color::white; } else if (fields[1] == "b") { position.to_move_ = Color::black; } else { throw fail("side to move must be w or b"); }
// Field 3: castling rights, "-" or some of KQkq. An empty field (two // spaces in a row) is refused, not read as "no rights". if (fields[2].empty()) throw fail("castling rights must be - or letters from KQkq"); if (fields[2] != "-") { for (const char c : fields[2]) { switch (c) { case 'K': position.castling_.white.king_side = true; break; case 'Q': position.castling_.white.queen_side = true; break; case 'k': position.castling_.black.king_side = true; break; case 'q': position.castling_.black.queen_side = true; break; default: throw fail("castling rights must be - or letters from KQkq"); } } }
// Field 4: the en passant square, which lies behind a pawn the other // side just moved two squares: on rank 6 when White is to move, with a // black pawn just below it and the square it came from empty. if (fields[3] != "-") { const std::optional<Square> square = parse_square(fields[3]); const Color mover = opposite(position.to_move_); // the side that made the double step const int expected_rank = mover == Color::black ? 5 : 2; if (!square || square->rank() != expected_rank) throw fail("bad en passant square"); const int f = square->file(); const int r = square->rank(); const int ahead = forward(mover); // the direction that pawn was moving if (position.at(*square) || position.at(square_at(f, r - ahead)) || position.at(square_at(f, r + ahead)) != Piece{mover, Kind::pawn}) { throw fail("no pawn has just made a double step past the en passant square"); } position.en_passant_ = square; }
// Fields 5 and 6, if present: the half-move clock and the move number. if (fields.size() == 6) { const std::optional<int> halfmoves = parse_count(fields[4]); const std::optional<int> number = parse_count(fields[5]); if (!halfmoves || !number || *number < 1) throw fail("bad move counters"); position.halfmove_clock_ = *halfmoves; position.fullmove_number_ = *number; }
// The checks the rest of the class relies on. std::count compares every // cell (an optional) with an optional holding this side's king. for (Color color : {Color::white, Color::black}) { const auto kings = std::count(position.board_.begin(), position.board_.end(), std::optional<Piece>(Piece{color, Kind::king})); if (kings != 1) throw fail("each side needs exactly one king"); const int home = home_rank(color); const SideRights rights = position.castling_.of(color); const bool king_home = position.at(square_at(4, home)) == Piece{color, Kind::king}; if (rights.king_side && (!king_home || position.at(square_at(7, home)) != Piece{color, Kind::rook})) { throw fail("a king-side castling right needs the king and rook at home"); } if (rights.queen_side && (!king_home || position.at(square_at(0, home)) != Piece{color, Kind::rook})) { throw fail("a queen-side castling right needs the king and rook at home"); } } for (int f = 0; f < 8; ++f) { for (int edge : {0, 7}) { const std::optional<Piece> piece = position.at(square_at(f, edge)); if (piece && piece->kind == Kind::pawn) throw fail("no pawn may stand on rank 1 or 8"); } } if (position.in_check(opposite(position.to_move_))) { throw fail("the side that just moved is in check"); } return position;}from_fen throws std::invalid_argument with a reason, because a bad
FEN is a programming or data error, found once when a puzzle is
loaded, not a move typed at the keyboard. It checks more than the
format. A position with two white kings, a pawn on the first or last
rank, a castling right without the king and rook at home, an en
passant square with no pawn that just made a double step, or the side
not to move in check, cannot happen in a game, and accepting it
would break INV-1, INV-2, INV-4, or INV-5 for every function after it.
See Errors and contracts for when to
throw and when to return.
Generating moves
Section titled “Generating moves”Move generation has two stages. The first finds pseudo-legal moves: moves that follow how each piece moves, ignoring whether the mover’s own king ends up attacked. The second keeps the legal ones.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The idea: look outwards from the square, as if it held each kind of// piece in turn. A knight standing a knight's jump away attacks it; so// does a rook or queen that is the first piece met along a rank or file;// and so on. That is 8 + 8 + 8 short looks, not a scan of the whole board.bool Position::attacked(Square square, Color by) const { // A pawn attacks the two squares diagonally ahead of it, so the // attacking pawn would stand one rank behind (from its own side's // point of view) and one file to either side. for (int side : {-1, 1}) { const std::optional<Square> from = step(square, side, -forward(by)); if (from && at(*from) == Piece{by, Kind::pawn}) return true; } for (const Offset jump : knight_jumps) { const std::optional<Square> from = step(square, jump.file, jump.rank); if (from && at(*from) == Piece{by, Kind::knight}) return true; } for (const Offset one : king_steps) { const std::optional<Square> from = step(square, one.file, one.rank); if (from && at(*from) == Piece{by, Kind::king}) return true; } // Sliding pieces: walk each direction until the first piece (or the // edge). That piece attacks the square if it slides this way: `kind` // (rook on straight lines, bishop on diagonals) or a queen. The // parameter is `const auto&`, so the one lambda takes either array. const auto first_piece_slides = [&](const auto& directions, Kind kind) { for (const Offset dir : directions) { std::optional<Square> from = step(square, dir.file, dir.rank); while (from && !at(*from)) from = step(*from, dir.file, dir.rank); if (!from) continue; // reached the edge: nothing on this line const std::optional<Piece> piece = at(*from); if (piece == Piece{by, kind} || piece == Piece{by, Kind::queen}) return true; } return false; }; return first_piece_slides(straight, Kind::rook) || first_piece_slides(diagonal, Kind::bishop);}attacked(square, by) answers “could a piece of colour by capture on
this square?”. It looks outwards from the square: along the diagonals
for a bishop or queen, along files and ranks for a rook or queen, a
knight’s jump away, one step for a king, and the two squares a pawn
would capture from. Looking outwards from one square is cheaper than
generating every enemy move, and it is the question that check,
castling, and legality all ask.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
void Position::add_pawn_moves(Square from, std::vector<Move>& moves) const { const int ahead = forward(to_move_); const int last_rank = home_rank(opposite(to_move_)); // rank 8 for White // Adds a move to `to`, or all four promotions if `to` is on the last rank. const auto add = [&](Square to) { if (to.rank() != last_rank) { moves.push_back(Move{from, to, std::nullopt}); return; } for (Kind kind : {Kind::queen, Kind::rook, Kind::bishop, Kind::knight}) { moves.push_back(Move{from, to, kind}); } }; // Straight ahead only onto an empty square; two squares only from the // starting rank and only if both squares are empty. const std::optional<Square> one = step(from, 0, ahead); if (one && !at(*one)) { add(*one); const int start_rank = home_rank(to_move_) + ahead; // rank 2 for White, 7 for Black const std::optional<Square> two = step(from, 0, 2 * ahead); if (from.rank() == start_rank && two && !at(*two)) add(*two); } // Diagonally ahead only to capture: an enemy piece there, or the en // passant square (empty, with the pawn to take beside this one). for (int side : {-1, 1}) { const std::optional<Square> to = step(from, side, ahead); if (!to) continue; const std::optional<Piece> target = at(*to); if (target) { if (target->color != to_move_) add(*to); } else if (en_passant_ == to) { add(*to); } }}Pawns have the most rules of any piece: one step forward onto an empty square, two from the home rank if both squares are empty, diagonal captures, en passant onto the stored square, and four promotion moves instead of one when the pawn reaches the last rank. The generator emits a promotion as four separate moves (queen, rook, bishop, knight), so perft counts and the legal move list see four choices, as the rules do.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Castling is the king's move two squares towards a rook; make() moves// the rook. It is offered only if every condition holds:// - the right still exists (neither the king nor that rook has moved, and// the rook was not captured), and the rook is in its corner;// - every square between the king and the rook is empty;// - the king is not in check now, and the square it passes over is not// attacked. The square it lands on is tested by legal_moves, as for any// king move ("not into check").void Position::add_castling(Square from, std::vector<Move>& moves) const { const Color us = to_move_; const Color them = opposite(us); const int rank = home_rank(us); if (from != square_at(4, rank) || in_check(us)) return; const SideRights rights = castling_.of(us); const auto empty = [&](int file) { return !at(square_at(file, rank)); }; // An optional, so that it compares directly with what at() returns. const std::optional<Piece> own_rook = Piece{us, Kind::rook}; if (rights.king_side && at(square_at(7, rank)) == own_rook && empty(5) && empty(6) && !attacked(square_at(5, rank), them)) { moves.push_back(Move{from, square_at(6, rank), std::nullopt}); } // The queen side has three squares between; b1 must be empty but may // be attacked, because the king does not cross it. if (rights.queen_side && at(square_at(0, rank)) == own_rook && empty(1) && empty(2) && empty(3) && !attacked(square_at(3, rank), them)) { moves.push_back(Move{from, square_at(2, rank), std::nullopt}); }}The generator offers castling only when every condition that can be seen before the move holds: the king on its home square and not in check, the right still held, that rook on its corner, the squares between empty, and the square the king crosses not attacked. The last condition, that the king does not land on an attacked square, is left to the legality test, which checks every move the same way.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A pseudo-legal move is legal if, once made, the mover's own king is not// attacked. Trying it on a copy keeps this function const and keeps the// test simple: it covers pins, moving into check, a king walking along a// checking line, and an en passant capture that uncovers a rank, all with// the same one question.std::vector<Move> Position::legal_moves() const { std::vector<Move> legal; for (const Move& move : pseudo_legal_moves()) { Position after = *this; after.make(move); if (!after.in_check(to_move_)) legal.push_back(move); } return legal;}This is the whole legality rule in six lines: copy the position, make the move on the copy, and keep the move if the mover’s king is not attacked afterwards. One test covers every way a move can be illegal because of the king: a pinned piece that moves off the line, a king that steps onto an attacked square, a move that ignores a check, a castling king that lands on an attacked square, and the rare en passant capture that removes two pawns from one rank and opens it to a rook. There is no separate pin-finding code to get wrong.
How this code works: What trying each move on a copy costs
Take the position after scholar’s mate, with Black to move (the step 1 demo reaches it). These numbers come from running the step 1 code on it for this page:
| Step | Value |
|---|---|
| Pseudo-legal moves for Black | 30 |
| Copies of the position made | 30, one per candidate, about 792 bytes each |
| Of those, the king is not attacked | 0, so legal_moves() is empty |
| King moves among the 30 | e8e7 (onto a square the queen attacks) and e8f7 (taking the queen, but the bishop on c4 guards f7) |
What update_state concludes |
no legal move, and Black is in check: checkmate, White wins |
The copy costs one 792-byte copy and one make per candidate, then
one attacked look from the king. For one position that is
microseconds. The same approach counted the 197,281 positions four
moves deep from the start in about 60 ms at -O2, and about 700 ms
at -O0 (three runs each on one server, g++ 11.4; other machines will
differ). People type one move every few seconds, and the perft tests
reach about 426,000 leaf positions in each test program, so this is
fast enough by a wide margin.
When would it not be? A chess engine searches millions of positions
per second, and there the copy, and the vector each legal_moves call
allocates, would matter. Engines make and unmake in place, track pins
directly, and use bitboards (64-bit masks) instead of an array of
cells. That is a different program with a different main requirement.
For this one, the simplest rule that is obviously right wins.
Making and unmaking a move
Section titled “Making and unmaking a move”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Everything needed to put the position back exactly as it was before one// move. Position::make returns it and Position::unmake takes it back.// This is the Command idea (a request that can be undone) as a plain// value. A Command class hierarchy (a MoveCommand base with virtual// execute and undo, one subclass per kind of move) would buy nothing here:// the four kinds are fixed by the rules and differ by a few lines in// make and unmake, while a record is copyable and comparable, sits in a// std::vector with no allocation per move, and can be replayed (step 2// writes PGN from it). A hierarchy fits when the set of commands is open,// as in an editor whose plugins add their own.struct MoveRecord { Move move; MoveKind kind = MoveKind::normal; Piece moved; // as it stood on move.from: a pawn when promoting std::optional<Piece> captured; // the piece taken, if any Square captured_on; // where it stood: move.to, except for en passant CastlingRights castling_before; // rights before the move (it may lose some) std::optional<Square> en_passant_before; int halfmove_clock_before = 0;
friend bool operator==(const MoveRecord&, const MoveRecord&) = default;};A MoveRecord holds what make cannot work out again afterwards. The
move itself says where the piece went. The record adds the kind of
move, the piece that moved (a pawn, even if a queen now stands there),
the captured piece and the square it stood on (which differs from the
move’s target for en passant), and the castling rights, en passant
square, and half-move clock from before. The move number and the side
to move are not stored: undoing a move by moved.color tells both.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
MoveRecord Position::make(const Move& move) { // First, record everything this move may change. MoveRecord record; record.move = move; record.moved = *at(move.from); // a pseudo-legal move starts on one of the mover's pieces record.captured = at(move.to); record.captured_on = move.to; record.castling_before = castling_; record.en_passant_before = en_passant_; record.halfmove_clock_before = halfmove_clock_;
// Then work out which kind of move it is. const Piece piece = record.moved; const int file_change = move.to.file() - move.from.file(); if (piece.kind == Kind::king && std::abs(file_change) == 2) { record.kind = MoveKind::castle; // only castling moves a king two files } else if (piece.kind == Kind::pawn && file_change != 0 && !record.captured) { // A pawn moving diagonally onto an empty square: en passant. The // pawn it takes stands beside it, on the rank it came from. record.kind = MoveKind::en_passant; record.captured_on = square_at(move.to.file(), move.from.rank()); record.captured = at(record.captured_on); } else if (move.promotion) { record.kind = MoveKind::promotion; }
// Move the pieces. The captured square is cleared first because, for // en passant, it is not the square the pawn lands on. cell(record.captured_on).reset(); cell(move.to) = move.promotion ? Piece{piece.color, *move.promotion} : piece; cell(move.from).reset(); if (record.kind == MoveKind::castle) { const RookHop rook = castling_rook(move); cell(rook.to) = cell(rook.from); cell(rook.from).reset(); }
// Then the rest of the state. Only a double step leaves an en passant // square: the one the pawn passed over, halfway between from and to. en_passant_.reset(); if (piece.kind == Kind::pawn && std::abs(move.to.rank() - move.from.rank()) == 2) { en_passant_ = square_at(move.from.file(), (move.from.rank() + move.to.rank()) / 2); } // The fifty-move rule counts half-moves since the last capture or pawn move. halfmove_clock_ = (piece.kind == Kind::pawn || record.captured) ? 0 : halfmove_clock_ + 1; lose_rights(castling_, move.from); lose_rights(castling_, move.to); if (piece.color == Color::black) ++fullmove_number_; // a move number covers both sides to_move_ = opposite(to_move_); return record;}make fills the record first, while the old values are still
there, then changes the position. Castling is recognised as “a king
moving two files”, en passant as “a pawn moving sideways onto an empty
square”, and promotion by the move’s letter. The rook’s hop for
castling comes from castling_rook, one small function shared with
unmake.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The reverse of make, in the reverse order, using only the record: no// searching, and no guessing what was captured or which rights there were.void Position::unmake(const MoveRecord& record) { const Move& move = record.move; to_move_ = record.moved.color; if (record.moved.color == Color::black) --fullmove_number_; cell(move.from) = record.moved; // a pawn again, if it had promoted cell(move.to).reset(); cell(record.captured_on) = record.captured; // nullopt when nothing was taken if (record.kind == MoveKind::castle) { const RookHop rook = castling_rook(move); cell(rook.from) = cell(rook.to); cell(rook.to).reset(); } castling_ = record.castling_before; en_passant_ = record.en_passant_before; halfmove_clock_ = record.halfmove_clock_before;}unmake is make backwards, using only the record: the piece goes
back as the piece that moved, the target empties, the captured piece
(or std::nullopt) goes back to captured_on, the rook hops back,
and the three stored facts are put back as they were.
How this code works: The demo's en passant, e5d6, through make and unmake
The step 1 demo starts its special moves from
r3k2r/1P6/8/3pP3/8/8/8/R3K2R w KQkq d6 0 1: Black’s pawn has just
gone from d7 to d5, past d6, and White’s pawn stands on e5. These
values come from running the step 1 code on this move for this page.
Step in make |
Value |
|---|---|
record.moved |
white pawn |
record.captured at first |
at(d6): empty |
file_change |
3 minus 4 = -1, a pawn moving sideways onto an empty square |
record.kind |
MoveKind::en_passant |
record.captured_on |
file of d6, rank of e5: d5 (square 35) |
record.captured |
the black pawn on d5 |
castling_before, en_passant_before, halfmove_clock_before |
KQkq, d6, 0 |
| Cells changed | d5 emptied, d6 gets the white pawn, e5 emptied |
| After | en passant square cleared; half-move clock 0 (a pawn moved); Black to move |
| FEN after | r3k2r/1P6/3P4/8/8/8/8/R3K2R b KQkq - 0 1 |
unmake with this record puts White to move again, puts the white
pawn back on e5, empties d6, puts the black pawn back on d5, and
restores KQkq, d6, and 0. The result compares equal to the starting
position with ==. A record that kept only “from e5 to d6” could not
have done this: nothing in those two squares says that a pawn on d5
disappeared.
The game
Section titled “The game”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Where the game stands. Checkmate is a win for the side that gave it;// stalemate (no legal move, not in check) is a draw. The fifty-move rule// is applied automatically here, as soon as fifty moves by each side pass// with no capture and no pawn move; under FIDE rules a player must claim// it (and only the seventy-five-move rule is automatic). Left out on// purpose: threefold repetition, draws by insufficient material, draws by// agreement, and resignation.enum class GameState { in_progress, white_wins, black_wins, draw_by_stalemate, draw_by_fifty_moves };VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Why a request was refused. The enum is for code (tests, a UI choosing a// message); the text in Verdict is for people.enum class Refusal { none, // accepted bad_notation, // not coordinate notation such as e2e4 or e7e8q game_over, // the game has ended: undo is still allowed empty_square, // nothing stands on the from-square not_your_piece, // the piece belongs to the side not to move illegal_for_piece, // that piece cannot move that way from there promotion_required, // a pawn reaching the last rank must name a piece promotion_not_allowed, // a letter given for a move that is not a promotion castle_rights_lost, // the king or that rook has moved, or the rook is gone castle_path_blocked, // a square between the king and the rook is occupied castle_out_of_check, // the king is in check castle_through_check, // the square the king crosses is attacked leaves_king_in_check, // the mover's king would be attacked afterwards nothing_to_undo, nothing_to_redo,};
// The answer to every request that may be refused: accepted, or refused// with a reason and an explanation.struct Verdict { Refusal refusal = Refusal::none; std::string text;
[[nodiscard]] bool accepted() const { return refusal == Refusal::none; }};GameState is the result so far, and Refusal is one value per rule a
request can break. A test checks the enum value (Refusal::castle_through_check),
and a person reads the text that comes with it. The two are separate
so that a test does not break when the wording improves, and so that a
caller (a future clickable board, say) can react to the kind of refusal
without parsing English.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// One game: the position, the moves made (for undo), the moves undone (for// redo), and the result. It owns all of these by value; nothing is shared.//// Rules live in two places. Position knows how pieces move. Game decides// whether a request is allowed, says why not, keeps the history, and// works out the result after every change.class Game {public: // A game from the standard start. Game(); // A game from any position (a puzzle, a test, an adjourned game). explicit Game(Position start);
[[nodiscard]] const Position& position() const { return position_; } [[nodiscard]] GameState state() const { return state_; } // The legal moves of the side to move; none once the game is over. [[nodiscard]] std::vector<Move> legal_moves() const; // The moves made so far, oldest first. [[nodiscard]] const std::vector<MoveRecord>& history() const { return history_; }
// Whether `move` would be accepted now, and if not, why. Changes nothing. [[nodiscard]] Verdict check(const Move& move) const; // Plays the move if check() accepts it. Playing a move forgets // anything that could have been redone. Verdict play(const Move& move); // The same, from coordinate notation such as "e2e4" or "e7e8q". Verdict play(std::string_view coordinates);
// Takes back the last move (allowed after the game has ended, which // reopens it). Refused when no move has been made. Verdict undo(); // Plays again the move undo took back most recently. Refused when // nothing has been undone since the last new move. Verdict redo();
private: void apply(const Move& move); // make it, record it, update the state void update_state();
Position position_; std::vector<MoveRecord> history_; std::vector<Move> redo_; // the last one is redone first GameState state_ = GameState::in_progress;};Game is the only class with a rule about requests rather than
positions: whose turn it is, whether the game is over, and what a
take-back means. It holds the position, the history of records, and
the moves that can be redone.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The checks run from the cheapest and most general to the most specific,// so each refusal names the first rule broken. The idea for the last one// is "try it and look": make the move on a copy and see if the king is// attacked.Verdict Game::check(const Move& move) const { const std::string what = to_string(move) + ": "; if (state_ != GameState::in_progress) { return refuse(Refusal::game_over, what + "the game is over (" + to_string(state_) + ")"); } const std::optional<Piece> piece = position_.at(move.from); if (!piece) { return refuse(Refusal::empty_square, what + "there is no piece on " + to_string(move.from)); } const Color us = position_.to_move(); if (piece->color != us) { return refuse(Refusal::not_your_piece, what + "it is " + to_string(us) + "'s turn"); }
// A king moving two files along its home rank from its starting square // is trying to castle. Each condition gets its own reason, in the order // a player would check them. const int home = us == Color::white ? 0 : 7; const bool castling = piece->kind == Kind::king && move.from == square_at(4, home) && move.to.rank() == home && std::abs(move.to.file() - 4) == 2; if (castling) { const bool king_side = move.to.file() == 6; const std::string side = king_side ? "king side" : "queen side"; const SideRights rights = position_.castling().of(us); const int rook_file = king_side ? 7 : 0; if (!(king_side ? rights.king_side : rights.queen_side) || position_.at(square_at(rook_file, home)) != Piece{us, Kind::rook}) { return refuse(Refusal::castle_rights_lost, what + to_string(us) + " can no longer castle on the " + side + ": the king or that rook has moved, or the rook was captured"); } // The files strictly between the king (file 4) and the rook. for (int file = std::min(4, rook_file) + 1; file < std::max(4, rook_file); ++file) { if (position_.at(square_at(file, home))) { return refuse(Refusal::castle_path_blocked, what + "cannot castle: " + to_string(square_at(file, home)) + " is between the king and the rook and is not empty"); } } if (position_.in_check(us)) { return refuse(Refusal::castle_out_of_check, what + "cannot castle while in check"); } const Square crossed = square_at(king_side ? 5 : 3, home); if (position_.attacked(crossed, opposite(us))) { return refuse(Refusal::castle_through_check, what + "cannot castle: the king would cross " + to_string(crossed) + ", which is attacked"); } }
// Is there a pseudo-legal move from this square to that one? The // promotion letter is ignored here so that a missing or wrong letter // gets its own reason below. const std::vector<Move> candidates = position_.pseudo_legal_moves(); const bool reachable = std::any_of(candidates.begin(), candidates.end(), [&](const Move& m) { return m.from == move.from && m.to == move.to; }); if (!reachable) { return refuse(Refusal::illegal_for_piece, what + "a " + to_string(piece->kind) + " cannot move from " + to_string(move.from) + " to " + to_string(move.to) + " here"); } const bool promoting = piece->kind == Kind::pawn && move.to.rank() == 7 - home; if (promoting && !move.promotion) { return refuse(Refusal::promotion_required, what + "a pawn reaching the last rank must become a queen, rook, bishop, or " "knight: add q, r, b, or n"); } if (!promoting && move.promotion) { return refuse(Refusal::promotion_not_allowed, what + "only a pawn reaching the last rank can promote"); } if (promoting && (*move.promotion == Kind::king || *move.promotion == Kind::pawn)) { return refuse(Refusal::promotion_not_allowed, what + "a pawn may become a queen, rook, bishop, or knight"); } if (!position_.is_legal(move)) { return refuse(Refusal::leaves_king_in_check, castling ? what + "cannot castle: the king would land on " + to_string(move.to) + ", which is attacked" : what + "that would leave " + to_string(us) + "'s king in check"); } return Verdict{};}check is const, so it cannot change the game, and its order is the
order a person would want to hear about mistakes: the game is over;
there is nothing on that square; it is not your piece; then each
castling condition by name; then “that piece cannot move like that”;
then the promotion letter; and last, “that would leave your king in
check”. Each step is a cheap test, and only the last one uses the copy.
Castling gets its own refusals before the general test because
“the king or that rook has moved” teaches a club player something that
“a king cannot move from e1 to g1” does not. Those tests repeat what
the generator checks, on purpose: the generator decides whether,
check explains why not, and AC-2.6 to AC-2.8 test both together.
How this code works: Where check stops each refusal in the step 1 demo
The demo’s refusals, and the line of check (or play) that stops
each one. The texts are from expected_output.txt.
| Request | Position | Stopped by | Refusal and text |
|---|---|---|---|
"e2x4" |
start | parse_move returns nothing, in play(string_view) |
bad_notation: “give two squares such as e2e4, …” |
e7e5 |
start | the piece on e7 is Black’s and White is to move | not_your_piece: “it is White’s turn” |
e2e5 |
start | no pseudo-legal move goes from e2 to e5 | illegal_for_piece: “a pawn cannot move from e2 to e5 here” |
g1g3 |
start | no pseudo-legal move goes from g1 to g3 | illegal_for_piece: “a knight cannot move from g1 to g3 here” |
e1g1 |
start | castling: the right is held, but f1 is the first square between and is occupied | castle_path_blocked: “f1 is between the king and the rook and is not empty” |
e8c8 |
after e5d6 |
castling passes every early test (d8 is not attacked), the generator offers it, and the copy finds c8 attacked by the pawn on b7 | leaves_king_in_check: “the king would land on c8, which is attacked” |
b7b8 |
after e8g8 |
a pawn reaching the last rank with no letter | promotion_required |
In every row, the position afterwards is the position before:
check is const and play returns as soon as check refuses.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
Verdict Game::play(const Move& move) { Verdict verdict = check(move); if (!verdict.accepted()) return verdict; // refused: nothing has changed apply(move); redo_.clear(); // a new move starts a new line: the old one cannot be redone verdict.text = "played " + to_string(move); if (state_ != GameState::in_progress) verdict.text += std::string(": ") + to_string(state_); return verdict;}
Verdict Game::play(std::string_view coordinates) { const std::optional<Move> move = parse_move(coordinates); if (!move) { return refuse(Refusal::bad_notation, "\"" + std::string(coordinates) + "\" is not coordinate notation: give two squares such as e2e4, and q, " "r, b, or n for a promotion (e7e8q)"); } return play(*move);}
void Game::apply(const Move& move) { history_.push_back(position_.make(move)); update_state();}play is three steps: check, apply, forget the redo list. Forgetting
the redo list is FR-5: once a player takes a move back and plays a
different one, the old line is a different game.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Undo unmakes the last record and keeps its move for redo. Redo plays// that move again without checking it: the position is exactly the one in// which it was legal, because unmake restored everything.Verdict Game::undo() { if (history_.empty()) return refuse(Refusal::nothing_to_undo, "no move to take back"); const MoveRecord record = history_.back(); history_.pop_back(); position_.unmake(record); redo_.push_back(record.move); update_state(); // undoing a mate reopens the game return Verdict{Refusal::none, "took back " + to_string(record.move)};}
Verdict Game::redo() { if (redo_.empty()) return refuse(Refusal::nothing_to_redo, "no move to play again"); const Move move = redo_.back(); redo_.pop_back(); apply(move); return Verdict{Refusal::none, "played again " + to_string(move)};}undo pops the last record, unmakes it, and pushes its move onto the
redo list. redo plays that move again through apply, without
check: the move was legal in exactly this position a moment ago, and
INV-3 says the position is exactly the same. Both call update_state,
so undoing a mate reopens the game (AC-5.4).
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Run after every change. No legal move means the game is over: checkmate// if the side to move is in check, stalemate if not. Checkmate wins even on// the hundredth half-move, so the fifty-move rule is looked at last.void Game::update_state() { const Color us = position_.to_move(); if (position_.legal_moves().empty()) { if (!position_.in_check(us)) { state_ = GameState::draw_by_stalemate; } else { state_ = us == Color::white ? GameState::black_wins : GameState::white_wins; } } else if (position_.halfmove_clock() >= 100) { state_ = GameState::draw_by_fifty_moves; // 100 half-moves: fifty by each side } else { state_ = GameState::in_progress; }}The order of tests encodes a rule: a move that mates on the hundredth half-move is still mate. So “no legal move” comes first, and the fifty-move count last.
The state of the game
Section titled “The state of the game”Text description of the diagram
The game starts in progress (or already over, if a FEN with no legal move is loaded; update_state runs in the constructor). From in progress: if the side to move has no legal move and is in check, the other side wins (white wins when Black is mated, black wins when White is mated); with no legal move and no check, the game is drawn by stalemate; with 100 half-moves since the last capture or pawn move, it is drawn by the fifty-move rule. Every ending goes back to in progress on undo. A move, undo, or redo that ends nothing stays in progress. No move is accepted in any ending.
Diagram source (Mermaid)
stateDiagram-v2
[*] --> in_progress : start, or a FEN with a legal move
in_progress --> white_wins : Black to move, in check, no legal move
in_progress --> black_wins : White to move, in check, no legal move
in_progress --> draw_by_stalemate : not in check, no legal move
in_progress --> draw_by_fifty_moves : 100 half-moves, no capture or pawn move
white_wins --> in_progress : undo
black_wins --> in_progress : undo
draw_by_stalemate --> in_progress : undo
draw_by_fifty_moves --> in_progress : undo
in_progress --> in_progress : a move, undo, or redo that ends nothingGameState is an enum, not a set of state classes. The states hold
no data of their own and behave the same way (each refuses moves and
allows undo), so the
State pattern would add
six classes to say what one if says. Compare the ATM case study,
where each state holds different data and a variant earns its place;
State machines covers both.
Where each rule lives
Section titled “Where each rule lives”| Rule | Where it is decided |
|---|---|
| How each piece moves | Position::pseudo_legal_moves and its helpers |
| Is a square attacked | Position::attacked |
| A move may not leave the own king attacked | Position::legal_moves and is_legal, on a copy |
| Castling conditions | add_castling (whether); Game::check (why not) |
| En passant and promotion effects | Position::make |
| Castling rights lost | lose_rights, called by make |
| Whose turn it is, and the game is over | Game::check |
| Checkmate, stalemate, fifty moves | Game::update_state |
| What undo restores | MoveRecord, filled by make, used by unmake |
| A new move forgets the redo list | Game::play |
| A position chess can reach | Position::from_fen |
Verification trace
Section titled “Verification trace”Take the last move of the scholar’s mate in the step 1 demo: White’s queen takes on f7. These values come from running the step 1 code on this position for this page.
Text description of the diagram
The demo calls play with “h5f7”. Game parses it into a move from h5 to f7, asks the position what stands on h5 (a white queen) and whose turn it is (White’s), and asks for the pseudo-legal moves (43, including h5f7). It asks whether h5f7 is legal; the position makes the move on a copy and finds White’s king not attacked. Game then makes the move on the real position, which returns a MoveRecord saying a black pawn was taken on f7 and the half-move clock had been 4, and pushes it onto the history. To update the state, Game asks for Black’s legal moves; the position tries all 30 pseudo-legal moves on copies, and in every one Black’s king is attacked. With no legal move and Black in check, the state becomes white wins. The redo list is cleared, and the demo is told “played h5f7: checkmate, White wins”.
Diagram source (Mermaid)
sequenceDiagram
participant Demo
participant Game
participant Position
participant Copy as Position copy
Demo->>Game: play("h5f7")
Game->>Game: parse_move gives h5 to f7
Game->>Position: at(h5), to_move()
Position-->>Game: white queen, White
Game->>Position: pseudo_legal_moves()
Position-->>Game: 43 moves, h5f7 among them
Game->>Position: is_legal(h5f7)
Position->>Copy: copy, make(h5f7), in_check(White)?
Copy-->>Position: no
Position-->>Game: legal
Game->>Position: make(h5f7)
Position-->>Game: MoveRecord (took a pawn on f7, clock was 4)
Game->>Game: history_.push_back(record)
Game->>Position: legal_moves() for Black
Position->>Copy: 30 copies, each make, in_check(Black)?
Copy-->>Position: yes, all 30
Position-->>Game: no legal move
Game->>Position: in_check(Black)?
Position-->>Game: yes
Game->>Game: state_ = white_wins, redo_.clear()
Game-->>Demo: accepted, "played h5f7: checkmate, White wins"- Parse.
"h5f7"becomesMove{h5, f7, nullopt}. - Check. The game is in progress, h5 holds a white queen, and it is White’s turn. The move is not castling. It is among White’s 43 pseudo-legal moves, it is not a promotion, and on a copy White’s king on e1 is not attacked afterwards.
- Make. The record stores the queen as
moved, the black pawn ascapturedon f7,KQkq, no en passant square, and a half-move clock of 4 (Bc4,Nc6,Qh5, andNf6since the last pawn move). The clock becomes 0, because this is a capture. The move number stays 4, because White moved. - Update. Black has 30 pseudo-legal moves and 0 legal ones, and
is in check:
white_wins. - Afterwards.
a7a6is refused with “the game is over (checkmate, White wins)”, andundogives back the position with a pawn on f7, a clock of 4, and the game in progress, which is what the demo prints next.
Architecture and patterns
Section titled “Architecture and patterns”Pieces: enum, hierarchy, or variant?
Section titled “Pieces: enum, hierarchy, or variant?”This is the question most chess designs in interviews start with, and the one where a pattern is most often forced onto the problem.
A std::variant is the third option, and it is worth seeing, because it
is the right choice in a nearby problem.
IllustrativeA fragment for explanation; not compiled on its own.
// One empty struct per kind of piece, and a variant that holds one of them.struct Pawn {};struct Knight {};struct Bishop {};struct Rook {};struct Queen {};struct King {};using KindOf = std::variant<Pawn, Knight, Bishop, Rook, Queen, King>;
// std::visit calls the lambda with whichever struct the variant holds. The// `if constexpr` tests are decided by the compiler for each type.int points_of(const KindOf& kind) { return std::visit( [](const auto& piece) { using P = std::decay_t<decltype(piece)>; // the struct's type, without const& if constexpr (std::is_same_v<P, Knight> || std::is_same_v<P, Bishop>) return 3; else if constexpr (std::is_same_v<P, Rook>) return 5; else if constexpr (std::is_same_v<P, Queen>) return 9; else if constexpr (std::is_same_v<P, King>) return 0; // never traded else return 1; // only Pawn is left }, kind);}With empty structs, this is an enum with more ceremony: every
question about a piece becomes a visit. The variant pays off when the
alternatives carry different data. In chess they do not: a knight
and a rook need exactly the same facts, a colour and a square. In the
ATM case study, the session states do carry
different data (a card, a bank session, an amount), and there a variant
is the better fit. See
Templates and polymorphism and
Inheritance and interfaces.
Legal means legal after the move
Section titled “Legal means legal after the move”What undo has to remember
Section titled “What undo has to remember”The Command idea, without a Command class
Section titled “The Command idea, without a Command class”The Command pattern turns a request into an
object that can be stored, executed, and undone. MoveRecord is that
idea: a stored request (the move) with what it needs to reverse it.
What is missing is the class hierarchy, a Command base with virtual
execute and undo, and nothing here needs it. Every undoable action
in this program is a move, and every move is reversed by the same
unmake. A base class with one subclass is indirection with no
choice behind it.
Refusals are values, not exceptions
Section titled “Refusals are values, not exceptions”An illegal move is the most ordinary thing that can happen at a chess
board, so Game::play returns a Verdict instead of throwing. A
bool would lose the reason, and an exception would make a mistyped
square look like a broken program. The Refusal enum gives tests and
callers something exact to compare, and the text gives a person
something to read. Position::from_fen does throw, because a broken
FEN is bad data, found once, and an object that refuses to exist is
better than a position that breaks the invariants.
What is not here, and why
Section titled “What is not here, and why”- No
Boardclass apart fromPosition. A board without the side to move, the castling rights, and the en passant square cannot answer any rule question, so it would only be passed around next to the rest. - No piece objects, no identity for pieces. See above.
- No bitboards and no incremental attack tables. They make an engine fast and a teaching example hard to check. NFR-5 is met without them.
- No observer or event for a screen. The demo prints after each call; a UI can do the same. Add one when something needs to react to a game it did not call.
- No threefold repetition and no insufficient-material draw. Both were out of scope. Repetition needs the history of positions, which the Exercise adds.
Building it step by step
Section titled “Building it step by step”The order the code was written in, each stage tested before the next:
Square,Piece,Move, andparse_move, with their tests (AC-1.3).Positionwith FEN in and out (AC-1.1, AC-1.2). Every later test sets up positions with FEN, so this came first.attackedand the pseudo-legal generator, thenlegal_moveson a copy, thenmakeandunmakewith the record.perft, checked against the published counts (AC-2.1 to AC-2.4). This is where move-generation bugs show up, and why perft came before the game.Game:checkwith every refusal,play, andupdate_state(UC-3, UC-4).- Undo and redo, and the random test (UC-5).
- The demo, a thin
mainthat only callsGame.
Scenarios
Section titled “Scenarios”The step 1 demo
Section titled “The step 1 demo”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
Game game; // the standard start, White to movestd::cout << "Refused requests:\n";play(game, {"e2x4", "e7e5", "e2e5", "g1g3", "e1g1"});
std::cout << "\nScholar's mate:\n";play(game, {"e2e4", "e7e5", "f1c4", "b8c6", "d1h5", "g8f6", "h5f7", "a7a6"});std::cout << diagram(game.position());
std::cout << "\nUndo and redo:\n";const Verdict undone = game.undo(); // takes back the mate: the game is open againstd::cout << " " << undone.text << " -> " << to_string(game.state()) << "\n";const Verdict redone = game.redo();std::cout << " " << redone.text << " -> " << to_string(game.state()) << "\n";std::cout << " " << game.redo().text << "\n"; // refused: nothing left to redo
std::cout << "\nSpecial moves:\n";Game special(Position::from_fen("r3k2r/1P6/8/3pP3/8/8/8/R3K2R w KQkq d6 0 1"));play(special, {"e5d6", "e8c8", "e8g8", "b7b8", "b7a8q", "f8a8", "e1g1"});std::cout << " " << special.position().to_fen() << "\n";while (special.undo().accepted()) {} // undo everything, back to the position the game started fromstd::cout << " after undoing all: " << special.position().to_fen() << "\n";Refused requests: refused: "e2x4" is not coordinate notation: give two squares such as e2e4, and q, r, b, or n for a promotion (e7e8q) refused: e7e5: it is White's turn refused: e2e5: a pawn cannot move from e2 to e5 here refused: g1g3: a knight cannot move from g1 to g3 here refused: e1g1: cannot castle: f1 is between the king and the rook and is not empty
Scholar's mate: ok: played e2e4 ok: played e7e5 ok: played f1c4 ok: played b8c6 ok: played d1h5 ok: played g8f6 ok: played h5f7: checkmate, White wins refused: a7a6: the game is over (checkmate, White wins)8 r . b q k b . r7 p p p p . Q p p6 . . n . . n . .5 . . . . p . . .4 . . B . P . . .3 . . . . . . . .2 P P P P . P P P1 R N B . K . N R a b c d e f g h
Undo and redo: took back h5f7 -> in progress played again h5f7 -> checkmate, White wins no move to play again
Special moves: ok: played e5d6 refused: e8c8: cannot castle: the king would land on c8, which is attacked ok: played e8g8 refused: b7b8: a pawn reaching the last rank must become a queen, rook, bishop, or knight: add q, r, b, or n ok: played b7a8q ok: played f8a8 ok: played e1g1 r5k1/8/3P4/8/8/8/8/R4RK1 b - - 1 3 after undoing all: r3k2r/1P6/8/3pP3/8/8/8/R3K2R w KQkq d6 0 1Reading the output:
- Refused requests. A typing mistake that never reaches
check, then four requests thatcheckstops: a piece of the wrong side, a pawn and a knight asked to move in ways they cannot, and a castling with a piece in the way. Each text names the squares and the rule. - Scholar’s mate. Seven accepted moves; the seventh ends the game, and the eighth request is refused because the game is over. The board is printed from White’s side.
- Undo and redo. Undoing the mate reopens the game, redoing it ends it again, and a second redo has nothing to play.
- Special moves. En passant, a castling refused because the king would land on an attacked square, castling on the other side, a promotion refused for a missing letter, promotion with a capture, a rook move, and White castling. Undoing all five accepted moves gives back the starting FEN, character for character.
The tests are named after the acceptance criteria and use FEN to set up each position. Perft carries most of the weight for move generation.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
std::uint64_t perft(Position& position, int depth) { if (depth <= 0) return 1; // a leaf: this position itself std::uint64_t leaves = 0; for (const Move& move : position.legal_moves()) { const MoveRecord record = position.make(move); leaves += perft(position, depth - 1); position.unmake(record); } return leaves;}perft(position, depth) counts the positions at the end of every
sequence of depth legal moves, by making each move, counting below
it, and unmaking it. From the start, there are 20 first moves, 400
two-move sequences, 8,902 for three, and 197,281 for four. These
numbers have been computed by many independent programs and are
published on the Chess Programming Wiki’s “Perft Results” page.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
LLD_TEST(ac_2_1_perft_from_the_start_matches_published_counts) { LLD_CHECK_EQ(perft_of(start_fen, 1), std::uint64_t{20}); LLD_CHECK_EQ(perft_of(start_fen, 2), std::uint64_t{400}); LLD_CHECK_EQ(perft_of(start_fen, 3), std::uint64_t{8902}); LLD_CHECK_EQ(perft_of(start_fen, 4), std::uint64_t{197281});}
LLD_TEST(ac_2_2_perft_kiwipete_matches_published_counts) { // Castling both ways for both sides, pins, en passant, and promotions. const std::string_view kiwipete = "r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1"; LLD_CHECK_EQ(perft_of(kiwipete, 1), std::uint64_t{48}); LLD_CHECK_EQ(perft_of(kiwipete, 2), std::uint64_t{2039}); LLD_CHECK_EQ(perft_of(kiwipete, 3), std::uint64_t{97862});}
LLD_TEST(ac_2_3_perft_endgame_with_en_passant_pins_matches_published_counts) { const std::string_view position3 = "8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 1"; LLD_CHECK_EQ(perft_of(position3, 1), std::uint64_t{14}); LLD_CHECK_EQ(perft_of(position3, 2), std::uint64_t{191}); LLD_CHECK_EQ(perft_of(position3, 3), std::uint64_t{2812}); LLD_CHECK_EQ(perft_of(position3, 4), std::uint64_t{43238});}
LLD_TEST(ac_2_4_perft_promotion_heavy_positions_match_published_counts) { const std::string_view position4 = "r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1"; LLD_CHECK_EQ(perft_of(position4, 1), std::uint64_t{6}); LLD_CHECK_EQ(perft_of(position4, 2), std::uint64_t{264}); LLD_CHECK_EQ(perft_of(position4, 3), std::uint64_t{9467}); const std::string_view position5 = "rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8"; LLD_CHECK_EQ(perft_of(position5, 1), std::uint64_t{44}); LLD_CHECK_EQ(perft_of(position5, 2), std::uint64_t{1486}); LLD_CHECK_EQ(perft_of(position5, 3), std::uint64_t{62379});}The five positions are the standard set from that page: the start (depth 4), “Kiwipete” (depth 3: 48, 2,039, 97,862), a sparse endgame built to catch en passant and pin bugs (depth 4: 14, 191, 2,812, 43,238), and two positions full of promotions (position 4 to depth 3: 6, 264, 9,467; position 5 to depth 3: 44, 1,486, 62,379).
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
LLD_TEST(ac_2_8_castling_is_refused_out_of_through_or_into_check) { Game in_check = from_fen("r3k2r/8/8/8/8/8/4r3/R3K2R w KQkq - 0 1"); LLD_CHECK_EQ(in_check.play("e1g1").refusal, Refusal::castle_out_of_check); LLD_CHECK_EQ(in_check.play("e1c1").refusal, Refusal::castle_out_of_check);
Game through = from_fen("4kr2/8/8/8/8/8/8/R3K2R w KQ - 0 1"); // f1 is attacked LLD_CHECK_EQ(through.play("e1g1").refusal, Refusal::castle_through_check); LLD_CHECK(through.play("e1c1").accepted());
Game into = from_fen("4k1r1/8/8/8/8/8/8/R3K2R w KQ - 0 1"); // g1 is attacked const Verdict verdict = into.play("e1g1"); LLD_CHECK_EQ(verdict.refusal, Refusal::leaves_king_in_check); LLD_CHECK(verdict.text.find("land on g1") != std::string::npos);
// On the queen side only d1 and c1 matter: an attacked b1 is fine. Game b_file = from_fen("1r2k3/8/8/8/8/8/8/R3K2R w KQ - 0 1"); LLD_CHECK(b_file.play("e1c1").accepted());}AC-2.8 covers the three castling conditions about attacks: out of
check, through an attacked square, and onto one. The first two are
stopped by check’s castling tests, the last by the copy, so the test
checks the Refusal value in each case, not only that the move was
refused. The last game checks the one square that is easy to get
wrong: on the queen side the king crosses d1 and lands on c1, so an
attack on b1, which only the rook crosses, does not stop castling.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
LLD_TEST(ac_5_5_random_games_undo_and_redo_through_exactly_the_same_positions) { std::mt19937 random(20261128); // fixed seed: the same games every run int seen[4] = {0, 0, 0, 0}; // how often each MoveKind was played std::uniform_int_distribution<int> coin(0, 1); for (int round = 0; round < 20; ++round) { Game game; std::vector<Position> positions{game.position()}; while (game.state() == GameState::in_progress && game.history().size() < 150) { const std::vector<Move> moves = game.legal_moves(); std::vector<Move> specials; for (const Move& m : moves) { if (special(game.position(), m)) specials.push_back(m); } // Half the time, if there is one, play a special move. const bool prefer_special = !specials.empty() && coin(random) == 1; const std::vector<Move>& choices = prefer_special ? specials : moves; // pick(random) gives an index from 0 to size - 1, every one equally likely. std::uniform_int_distribution<std::size_t> pick(0, choices.size() - 1); LLD_CHECK(game.play(choices[pick(random)]).accepted()); // The enum's value (0 to 3) as an index: count this kind of move. ++seen[static_cast<int>(game.history().back().kind)]; positions.push_back(game.position()); } // Back to the start, one position at a time, then forward again. for (std::size_t i = positions.size() - 1; i > 0; --i) { LLD_CHECK(game.undo().accepted()); LLD_CHECK(game.position() == positions[i - 1]); } LLD_CHECK_EQ(game.undo().refusal, Refusal::nothing_to_undo); for (std::size_t i = 1; i < positions.size(); ++i) { LLD_CHECK(game.redo().accepted()); LLD_CHECK(game.position() == positions[i]); } } // The games covered every kind of move, so undo was tested on each. for (int count : seen) LLD_CHECK(count > 0);}How this code works: The random undo test
- A repeatable dice.
std::mt19937 random(20261128)is a pseudo-random generator with a fixed seed, so every run plays the same 20 games, and a failure can be replayed exactly. - Steering towards rare moves. Castling, en passant, and
promotion are rare in random play. When at least one is legal, a
coin decides whether to choose among those only.
seencounts theMoveKindof each move played, and the last line checks that every kind came up at least once, so the test cannot pass by never reaching the hard cases. - Remember every position. Each game runs until it ends or
reaches 150 half-moves, and
positionskeeps a copy of the position after every move, which is cheap becausePositionis a value. - Back, then forward. Undo each move and compare with the saved
position before it, using the defaulted
==, which compares every member. One more undo must be refused. Then redo each move and compare again.
The code agent that wrote the example reported a mutation check on a scratch copy: 25 deliberate small bugs, of which the tests caught 24; it then added a test for the survivor, a line-wrapping bug in step 2 (AC-7.10). That check was not run again for this page.
When the requirements change
Section titled “When the requirements change”“The club loved it. Two things for the next season. We play blitz on it now, so we need chess clocks: three minutes each with two seconds added per move, say. And we want to send our games to the league, which takes PGN files.”
Two new rules:
- FR-7 Clocks. A game may have a time control: a base time for each side and an increment added after each move. Only the side to move’s clock runs. When a side’s time reaches zero, that side loses, unless the opponent has no material that could mate, in which case the game is drawn.
- FR-8 PGN export. A game can be written as PGN: the standard tags, the moves in standard algebraic notation (SAN), and the result, in lines short enough for any reader.
Two questions came back from the club, and their answers became rules:
- What does a take-back do to the clocks? “Nobody gets thinking time back. But the two seconds for the move that was taken back should go.” And a result on time cannot be taken back at all: the flag has fallen.
- How exactly is “could mate” judged? “By what is on the board: a bare king, or a king and one bishop or knight, cannot mate. That is what our arbiters use for blitz.” The FIDE rule is stricter: a fallen flag is a draw if the opponent cannot mate by any series of legal moves, which depends on the position, not only the material. Two bishops that stand on squares of one colour cannot mate, and neither can a side whose pieces are locked behind pawns, yet this code counts both as able to. The simplification is stated in the code and here.
“Only the side to move’s clock runs” decides most of the design. The clock belongs to the game, because only the game knows when a move was accepted, and it reads time from an injected source, because a test cannot wait three minutes.
Use cases for the change
Section titled “Use cases for the change”UC-6 Play with a clock.
- AC-6.1 Both sides start with the base time, and only the side to move’s clock runs.
- AC-6.2 A move charges the mover the time used and adds the increment.
- AC-6.3 The flag falls when the time reaches zero, not one millisecond later, and the opponent wins on time.
- AC-6.4 A move made after the flag fell is refused, even if nobody asked the clock in between.
- AC-6.5 A flag fall is a draw when the opponent cannot mate.
- AC-6.6 Undo takes back the undone move’s increment, but gives back no thinking time.
- AC-6.7 A result on time cannot be undone or redone.
- AC-6.8 The clocks stop at mate, and undoing the mate restarts the mover’s clock.
- AC-6.9 A refused move does not press the clock.
- AC-6.10 A base of zero or less, or a negative increment, is refused; a game without a time control has no clock.
UC-7 Export the game.
- AC-7.1 SAN is right for pawn and piece moves, captures, castling, and promotion.
- AC-7.2 SAN marks check with
+and mate with#. - AC-7.3 SAN tells two pieces apart by file, then by rank, then by both.
- AC-7.4 A pinned piece that cannot really make the move does not cause disambiguation.
- AC-7.5 The PGN of a finished game has the tags, the moves, and the result.
- AC-7.6 The result tag and the extra tags (time control, a set-up position, a loss on time) follow the game.
- AC-7.7 Movetext lines stay under 80 characters.
- AC-7.8 Moves that were taken back are left out.
- AC-7.9 In random games, every legal move in a position has its own SAN.
- AC-7.10 A line that would reach 80 characters is broken before the token, not after.
What moved
Section titled “What moved”| File | Change |
|---|---|
clock.hpp |
new: the Clock interface, SystemClock, and ManualClock for tests |
chess_clock.* |
new: TimeControl and ChessClock, a value holding both sides’ time |
game.* |
three GameState values for time; Refusal::result_on_time_is_final; an optional clock and a time source; check_flag; the start position is kept |
pgn.* |
new: to_san, PgnTags, and to_pgn |
position.* |
unchanged |
| tests | the step 1 tests run unchanged; twenty new tests for UC-6 and UC-7 |
Position did not change at all. Neither change is about the rules of
movement, and a design that had put the clock in the position (it is
“part of the game state”, after all) would have had to copy it on every
legality test.
The clock
Section titled “The clock”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Where a game gets the time. The game asks for "now" whenever a move,// an undo, or a flag check happens; it never sleeps or runs a timer. The// tests and the demo pass ManualClock and move time by hand, so a flag// fall is checked to the millisecond. A steady clock is used because it// never jumps backwards when the computer's wall clock is adjusted.using TimePoint = std::chrono::steady_clock::time_point;
class Clock {public: virtual ~Clock() = default; [[nodiscard]] virtual TimePoint now() const = 0;
protected: Clock() = default; Clock(const Clock&) = default; Clock& operator=(const Clock&) = default;};
class SystemClock final : public Clock {public: [[nodiscard]] TimePoint now() const override { return std::chrono::steady_clock::now(); }};
class ManualClock final : public Clock {public: [[nodiscard]] TimePoint now() const override { return now_; }
// Throws std::invalid_argument for a negative step. void advance(std::chrono::milliseconds step) { if (step.count() < 0) throw std::invalid_argument("time only moves forward here"); now_ += step; }
private: TimePoint now_{}; // starts at the clock's epoch; only differences matter};Clock has one function, now(). SystemClock reads
std::chrono::steady_clock, which never jumps backwards when the
computer’s time is corrected; ManualClock is the
test double, whose time
moves only when a test calls advance. This is the same
seam as the ATM’s timeout clock.
See Test doubles and seams.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The two clocks of a chess clock, at most one running. It is a value// that only does arithmetic on times it is given: it never reads a clock// itself, so Game decides what "now" is and the tests can check every// rule exactly.//// How it keeps time: left_ holds each side's time as it was when the// running side's turn began, and turn_started_ says when that was. Time// left now is left_ minus the time since turn_started_, for the running// side only. Nothing ticks.class ChessClock {public: // Starts `first`'s clock at `now`. Throws std::invalid_argument if the // base time is not positive or the increment is negative. ChessClock(TimeControl control, Color first, TimePoint now);
[[nodiscard]] TimeControl control() const { return control_; } // Whose clock is running; empty once stopped. [[nodiscard]] std::optional<Color> running() const { return running_; } // Time left for `color` at `now`, never below zero. [[nodiscard]] std::chrono::milliseconds remaining(Color color, TimePoint now) const; // True if the running side has no time left at `now` (reaching zero // exactly counts as out of time). [[nodiscard]] bool flag_fell(TimePoint now) const;
// The running side has moved: charge it the time used, add the // increment, and start the other side's clock. void press(TimePoint now); // Stops both clocks (the game has ended), charging the running side. void stop(TimePoint now); // For undoing a move made by `mover`: charge the running side (if any) // the time it has used, take back the increment that move earned, and // start `mover`'s clock again. Time already spent thinking is not // given back to either side. void take_back(Color mover, TimePoint now);
private: [[nodiscard]] static std::size_t slot(Color color) { return color == Color::white ? 0 : 1; } void charge_running(TimePoint now); // turns the running side's elapsed time into left_
// The clock's own unit (nanoseconds with the usual libraries), so that // no time is lost to rounding as turns add up. using Duration = TimePoint::duration;
TimeControl control_; std::array<Duration, 2> left_; // [0] White, [1] Black std::optional<Color> running_; TimePoint turn_started_;};ChessClock is a value: two remaining times, which side is running
(none, once stopped), and when that side’s turn started. It does not
hold a Clock. Every function that needs the time takes now as an
argument, so the clock is plain arithmetic and can be copied, and the
question “what time is it” is asked in one place, the Game.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
std::chrono::milliseconds ChessClock::remaining(Color color, TimePoint now) const { Duration left = left_[slot(color)]; if (running_ == color) left -= now - turn_started_; // only the running side's time moves left = std::max(left, Duration::zero()); // Whole milliseconds, rounded down: 1.9 ms left shows as 1 ms. return std::chrono::duration_cast<std::chrono::milliseconds>(left);}
bool ChessClock::flag_fell(TimePoint now) const { if (!running_) return false; // stopped clocks never run out return now - turn_started_ >= left_[slot(*running_)];}
void ChessClock::charge_running(TimePoint now) { if (!running_) return; Duration& left = left_[slot(*running_)]; left = std::max(left - (now - turn_started_), Duration::zero()); turn_started_ = now;}
void ChessClock::press(TimePoint now) { if (!running_) return; // nothing to press once stopped const Color mover = *running_; charge_running(now); left_[slot(mover)] += control_.increment; running_ = opposite(mover);}
void ChessClock::stop(TimePoint now) { charge_running(now); running_.reset();}
// The undo policy in one place: the increment earned by the undone move// is removed; thinking time already used stays used, for both sides.void ChessClock::take_back(Color mover, TimePoint now) { charge_running(now); Duration& left = left_[slot(mover)]; // Duration(...) turns the increment's seconds into the clock's unit; // std::max keeps the time from going below zero. left = std::max(left - Duration(control_.increment), Duration::zero()); running_ = mover; turn_started_ = now;}The stored times change only when a turn ends (charge_running). In
between, remaining works out the running side’s time from now
without changing anything, so asking the clock is free of side effects.
flag_fell uses >=: a side with exactly zero left has lost
(AC-6.3). take_back is the undo policy in one function: charge the
side that was thinking, remove the undone move’s increment from its
mover, and restart the mover’s clock from now.
How this code works: The step 2 demo's clocks, move by move
Three minutes each, two seconds’ increment. The demo advances a
ManualClock before each move. The values are from
expected_output.txt, except the last row, which the demo does not
print, and each follows from press:
| Event | Who was running | Time used | Arithmetic | White | Black |
|---|---|---|---|---|---|
| Start | White | 3:00.0 | 3:00.0 | ||
e4 |
White | 5 s | 3:00 − 5 + 2 | 2:57.0 | 3:00.0 |
e5 |
Black | 3 s | 3:00 − 3 + 2 | 2:57.0 | 2:59.0 |
Nf3 |
White | 12 s | 2:57 − 12 + 2 | 2:47.0 | 2:59.0 |
Nc6 |
Black | 4 s | 2:59 − 4 + 2 | 2:47.0 | 2:57.0 |
Bb5 |
White | 20 s | 2:47 − 20 + 2 | 2:29.0 | 2:57.0 |
a6 |
Black | 7 s | 2:57 − 7 + 2 | 2:29.0 | 2:52.0 |
undo a6 |
White | 2 s | White 2:29 − 2; Black 2:52 − 2 | 2:27.0 | 2:50.0 |
redo a6 |
Black | 1 s | 2:50 − 1 + 2 | 2:27.0 | 2:51.0 |
| White thinks 3 minutes | White | 180 s | 2:27 left, so the flag falls | 0:00.0 | 2:51.0 |
The undo row is the policy at work. White had been thinking for 2
seconds, and those are charged: thinking time stays used. Black’s
increment for a6 is removed, and Black’s clock runs again, because it
is Black’s move once more. The redo is then an ordinary move by Black,
1 second later, with a new increment. After the flag falls, Black has
plenty of material, so the result is “White’s time ran out, Black
wins”, and both the next move and an undo are refused.
Flag fall and mating material
Section titled “Flag fall and mating material”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Whether `side` could ever give mate, judged by material alone. A bare// king never can, and a king with one bishop or one knight cannot against// a bare king. Anything else counts as able to mate: with a single minor// piece against other material a mate can usually be built with the// help of the opponent's own pieces.// This is a simplification of the FIDE rule ("cannot checkmate by any// possible series of legal moves"): it ignores the position, so it calls// a win where only bishops on squares of one colour are left, or where// pawns are locked so that nothing can get through.bool could_mate(const Position& position, Color side) { int minor_pieces = 0; // side's knights and bishops bool other_material = false; // side's pawns, rooks, or queens bool opponent_material = false; // anything the opponent has besides the king for (int index = 0; index < 64; ++index) { const std::optional<Piece> piece = position.at(Square{index}); if (!piece || piece->kind == Kind::king) continue; if (piece->color != side) { opponent_material = true; } else if (piece->kind == Kind::knight || piece->kind == Kind::bishop) { ++minor_pieces; } else { other_material = true; } } if (other_material) return true; if (minor_pieces == 0) return false; // a bare king if (minor_pieces == 1 && !opponent_material) return false; // K+B or K+N against a bare king return true;}could_mate counts material: a bare king cannot mate, and neither can
a king with one bishop or one knight against a bare king. Against a
king with any other piece, even one knight can mate in a corner if the
other side’s own piece blocks the king’s escape, so the code counts
that as able to. As said above, this judges material, not the
position.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
GameState Game::check_flag() { if (!flag_fell_now()) return state_; const Color flagged = *clock_->running(); // only a running clock can fall clock_->stop(time_source_->now()); const Color opponent = opposite(flagged); if (!could_mate(position_, opponent)) { state_ = GameState::draw_on_time; } else { state_ = opponent == Color::white ? GameState::white_wins_on_time : GameState::black_wins_on_time; } return state_;}A flag falls between calls, while nobody is asking. So every request
that could change the game, play, undo, and redo, calls
check_flag first, and a move typed after the flag fell is refused
even if nothing looked at the clock in between (AC-6.4). check,
which is const, reports the fallen flag but cannot end the game; only
a non-const call records the result.
The undo policy
Section titled “The undo policy”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Undo unmakes the last record and keeps its move for redo. Redo plays// that move again without checking it: the position is exactly the one in// which it was legal, because unmake restored everything.//// With clocks (step 2) the policy is:// - a result on time is final: the time really ran out, so it cannot be// taken back;// - undo removes the increment the undone move earned and restarts the// mover's clock, but gives back no thinking time to either side;// - redo is like playing the move again now: the mover is charged for the// time since the undo and earns the increment again.Verdict Game::undo() { if (ended_on_time(check_flag())) { return refuse(Refusal::result_on_time_is_final, "the game was decided on time, which cannot be taken back"); } if (history_.empty()) return refuse(Refusal::nothing_to_undo, "no move to take back"); const MoveRecord record = history_.back(); history_.pop_back(); position_.unmake(record); redo_.push_back(record.move); if (clock_) clock_->take_back(record.moved.color, time_source_->now()); update_state(); // undoing a mate reopens the game return Verdict{Refusal::none, "took back " + to_string(record.move)};}
Verdict Game::redo() { if (check_flag() != GameState::in_progress) { return refuse(Refusal::game_over, std::string("the game is over (") + to_string(state_) + ")"); } if (redo_.empty()) return refuse(Refusal::nothing_to_redo, "no move to play again"); const Move move = redo_.back(); redo_.pop_back(); apply(move); return Verdict{Refusal::none, "played again " + to_string(move)};}Three rules, each in one line: a result on time is refused first; the
position is unmade as in step 1; and take_back removes the
increment. Redo is a new move “now”, charged and given a new increment,
because the time it took to decide to redo was real thinking time.
Text description of the diagram
Step 2 keeps the five states of step 1 and adds three results on time. From in progress, a fallen flag gives a win on time to the opponent if the opponent could mate (White wins on time when Black’s flag falls, Black wins on time when White’s falls), and a draw on time if the opponent could not. The four endings from step 1 still go back to in progress on undo, and the mover’s clock runs again. The three results on time are final: undo and redo are refused, and the clocks are stopped.
Diagram source (Mermaid)
stateDiagram-v2
[*] --> in_progress
in_progress --> white_wins : Black is mated
in_progress --> black_wins : White is mated
in_progress --> draw_by_stalemate : no legal move, no check
in_progress --> draw_by_fifty_moves : 100 half-moves
in_progress --> white_wins_on_time : Black's flag falls, White could mate
in_progress --> black_wins_on_time : White's flag falls, Black could mate
in_progress --> draw_on_time : a flag falls, the opponent could not mate
white_wins --> in_progress : undo, the mover's clock runs again
black_wins --> in_progress : undo
draw_by_stalemate --> in_progress : undo
draw_by_fifty_moves --> in_progress : undo
white_wins_on_time --> [*]
black_wins_on_time --> [*]
draw_on_time --> [*]SAN and PGN
Section titled “SAN and PGN”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
std::string to_san(const Position& before, const Move& move) { const Piece piece = *before.at(move.from); // a legal move starts on the mover's piece const int file_change = move.to.file() - move.from.file(); std::string san; if (piece.kind == Kind::king && std::abs(file_change) == 2) { san = file_change > 0 ? "O-O" : "O-O-O"; // castling has its own symbols } else { // En passant lands on an empty square but is still a capture. const bool capture = before.at(move.to).has_value() || (piece.kind == Kind::pawn && file_change != 0); if (piece.kind == Kind::pawn) { // A pawn has no letter; a capturing pawn names the file it left // (exd5), which is always enough to tell two pawns apart. if (capture) san += static_cast<char>('a' + move.from.file()); } else { san += letter(piece.kind); // Other pieces of the same kind and colour that could legally go // to the same square. Each promotion of one pawn is a separate // legal move, but pawns never get here. bool any_other = false; bool same_file = false; // one of them is on the mover's file bool same_rank = false; // one of them is on the mover's rank for (const Move& other : before.legal_moves()) { if (other.to != move.to || other.from == move.from) continue; if (before.at(other.from) != piece) continue; any_other = true; same_file = same_file || other.from.file() == move.from.file(); same_rank = same_rank || other.from.rank() == move.from.rank(); } // Prefer the file; use the rank if the file is shared; use both // if each is shared with some other piece. const std::string from = to_string(move.from); // e.g. "b1": file then rank if (any_other && !same_file) { san += from[0]; } else if (any_other && !same_rank) { san += from[1]; } else if (any_other) { san += from; } } if (capture) san += 'x'; san += to_string(move.to); if (move.promotion) { san += '='; san += letter(*move.promotion); } } // Check or mate: look at the position after the move. Position after = before; after.make(move); if (after.in_check(after.to_move())) san += after.legal_moves().empty() ? '#' : '+'; return san;}SAN writes a move from the reader’s point of view: the piece letter,
x for a capture, the target square, = and the new piece’s letter for a promotion (=N for a knight), and O-O
or O-O-O for castling. When two pieces of the same kind could reach
the target, it adds just enough of the starting square to tell them
apart: the file if that is enough, otherwise the rank, otherwise both.
The check mark comes from the position after the move: + if the
other king is attacked, # if it is also left with no legal move.
How this code works: Three queens and one square
Take 8/7k/8/8/8/Q7/8/Q1Q4K w - - 0 1: White queens on a1, a3, and
c1, and all three can reach b2. AC-7.3 checks these three moves, and
the step 2 code gives:
| Move | Other queens that can reach b2 | One on the mover’s file? | One on the mover’s rank? | SAN |
|---|---|---|---|---|
c1b2 |
a1, a3 | no (file c) | yes (a1 is on rank 1) | Qcb2 |
a3b2 |
a1, c1 | yes (a1 is on file a) | no (rank 3) | Q3b2 |
a1b2 |
a3, c1 | yes (a3) | yes (c1) | Qa1b2 |
“Other queens” means queens with a legal move to b2. The next section shows why that word matters.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
std::string to_pgn(const Game& game, const PgnTags& tags) { std::string out; // Writes one tag line. [&out] lets the lambda append to `out` itself, // not to a copy. const auto tag = [&out](const std::string& name, const std::string& value) { out += "[" + name + " \"" + escaped(value) + "\"]\n"; }; const std::string result = result_token(game.state()); // The Seven Tag Roster, in the order the standard fixes. tag("Event", tags.event); tag("Site", tags.site); tag("Date", tags.date); tag("Round", tags.round); tag("White", tags.white); tag("Black", tags.black); tag("Result", result); // An if with a declaration: `control` exists only inside, and the // branch runs only when it holds a value (a timed game). if (const std::optional<TimeControl> control = game.time_control()) { // Seconds, then "+" and the increment in seconds: "300+2". tag("TimeControl", std::to_string(control->base.count()) + "+" + std::to_string(control->increment.count())); } if (!(game.start_position() == Position::start())) { tag("SetUp", "1"); tag("FEN", game.start_position().to_fen()); } if (ended_on_time(game.state())) tag("Termination", "time forfeit"); out += "\n";
// The movetext as tokens: "1." before each White move, "N..." before a // Black move only if it comes first, each move in SAN, then the result. // SAN depends on the position before each move, so the history is // replayed from the start position. std::vector<std::string> tokens; Position replay = game.start_position(); for (const MoveRecord& record : game.history()) { const std::string number = std::to_string(replay.fullmove_number()); if (replay.to_move() == Color::white) { tokens.push_back(number + "."); } else if (tokens.empty()) { tokens.push_back(number + "..."); } tokens.push_back(to_san(replay, record.move)); replay.make(record.move); } tokens.push_back(result);
// Fill lines with tokens separated by single spaces, starting a new // line before any token that would make the line longer than 79. std::string line; for (const std::string& token : tokens) { if (!line.empty() && line.size() + 1 + token.size() > 79) { out += line + "\n"; line.clear(); } if (!line.empty()) line += ' '; line += token; } out += line + "\n"; return out;}to_pgn writes the seven required tags (Event, Site, Date, Round,
White, Black, Result) and then only the tags the game needs:
TimeControl in seconds, as 180+2; SetUp and FEN when the game
did not start from the standard position; and Termination for a
result on time. The moves are replayed from the start position, so SAN is
always written from the position before each move. Each move number
comes from that position, with 12... when the first move is Black’s.
Lines are filled word by word and broken before a token that would
take the line past 79 characters, so no line reaches 80 (AC-7.7).
AC-7.10 builds a line of exactly 77 characters, where the next token
9. with its space would make 80, and checks that it goes on the next
line.
to_pgn is a free function reading the game through its public
interface: history(), start_position(), state(), and
time_control(). Game does not know PGN exists, and a second format
would be a second function, not a change to Game. The
Visitor pattern exists for adding operations
over a class hierarchy; with no hierarchy here, a free function is the
whole answer.
Step 2 tests
Section titled “Step 2 tests”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
LLD_TEST(ac_6_3_the_flag_falls_at_zero_and_the_opponent_wins_on_time) { ManualClock clock; Game game({10s, 0s}, clock); // {10s, 0s} is a TimeControl: 10 s each, no increment clock.advance(9'999ms); // the ' only groups digits: 9,999 milliseconds LLD_CHECK_EQ(game.check_flag(), GameState::in_progress); play_all(game, {"e2e4"}); // with 1 ms to spare clock.advance(10s); // exactly all of Black's time LLD_CHECK_EQ(game.check_flag(), GameState::white_wins_on_time); LLD_CHECK_EQ(left(game, Color::black), std::int64_t{0}); LLD_CHECK_EQ(left(game, Color::white), std::int64_t{1}); const Verdict late = game.play("e7e5"); LLD_CHECK_EQ(late.refusal, Refusal::game_over); LLD_CHECK(game.legal_moves().empty()); clock.advance(60s); // stopped clocks stay as they are LLD_CHECK_EQ(left(game, Color::white), std::int64_t{1});}
LLD_TEST(ac_6_4_a_late_move_is_refused_even_if_nobody_looked_at_the_clock) { ManualClock clock; Game game({10s, 5s}, clock); clock.advance(10'001ms); // check() is const: it reports the flag but cannot end the game. LLD_CHECK_EQ(game.check(move("e2e4")).refusal, Refusal::game_over); LLD_CHECK_EQ(game.state(), GameState::in_progress); const Verdict verdict = game.play("e2e4"); LLD_CHECK_EQ(verdict.refusal, Refusal::game_over); LLD_CHECK_EQ(verdict.text, std::string("e2e4: the game is over (White's time ran out, Black wins)")); LLD_CHECK_EQ(game.state(), GameState::black_wins_on_time); LLD_CHECK(game.history().empty());}
LLD_TEST(ac_6_5_a_flag_fall_is_a_draw_when_the_opponent_cannot_mate) { struct Case { std::string_view fen; // White to move; White's flag falls GameState expected; }; for (const Case& c : { Case{"4k3/8/8/8/8/8/4P3/4K3 w - - 0 1", GameState::draw_on_time}, // bare king Case{"4k3/8/8/8/8/8/8/1n2K3 w - - 0 1", GameState::draw_on_time}, // K+N v K Case{"4k3/8/8/8/8/8/8/2b1K3 w - - 0 1", GameState::draw_on_time}, // K+B v K Case{"4k3/8/8/8/8/8/4P3/1n2K3 w - - 0 1", GameState::black_wins_on_time}, // K+N v K+P Case{"4k3/8/8/8/8/8/8/1nn1K3 w - - 0 1", GameState::black_wins_on_time}, // K+N+N Case{"r3k3/8/8/8/8/8/8/4K3 w - - 0 1", GameState::black_wins_on_time}, // K+R Case{"4k3/p7/8/8/8/8/8/4K3 w - - 0 1", GameState::black_wins_on_time}, // K+P }) { ManualClock clock; Game game(Position::from_fen(c.fen), {60s, 0s}, clock); clock.advance(61s); LLD_CHECK_EQ(game.check_flag(), c.expected); }}
LLD_TEST(ac_6_6_undo_takes_back_the_increment_but_gives_back_no_thinking_time) { ManualClock clock; Game game(blitz, clock); clock.advance(10s); play_all(game, {"e2e4"}); // White 292 s, Black running clock.advance(5s); LLD_CHECK(game.undo().accepted()); LLD_CHECK_EQ(left(game, Color::black), std::int64_t{295'000}); // its 5 s stay spent LLD_CHECK_EQ(left(game, Color::white), std::int64_t{290'000}); // the 2 s increment is gone clock.advance(3s); LLD_CHECK_EQ(left(game, Color::white), std::int64_t{287'000}); // White's clock runs again LLD_CHECK(game.redo().accepted()); // like playing e4 again now LLD_CHECK_EQ(left(game, Color::white), std::int64_t{289'000}); LLD_CHECK_EQ(left(game, Color::black), std::int64_t{295'000}); clock.advance(1s); LLD_CHECK_EQ(left(game, Color::black), std::int64_t{294'000});}
LLD_TEST(ac_6_7_a_result_on_time_cannot_be_undone_or_redone) { ManualClock clock; Game game({10s, 0s}, clock); play_all(game, {"e2e4"}); LLD_CHECK(game.undo().accepted()); clock.advance(10s); const Verdict undo = game.undo(); LLD_CHECK_EQ(undo.refusal, Refusal::result_on_time_is_final); LLD_CHECK_EQ(game.state(), GameState::black_wins_on_time); LLD_CHECK_EQ(game.redo().refusal, Refusal::game_over);}The clock tests move time by exact amounts. AC-6.3 leaves White 1 ms and Black exactly zero, and checks both the result and the stopped clocks 60 seconds later. AC-6.6 and AC-6.7 check the undo policy in both directions: the increment goes, the thinking time stays, and a result on time cannot be undone.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
LLD_TEST(ac_7_3_san_tells_pieces_apart_by_file_then_rank_then_both) { const std::string_view knights = "4k3/8/8/8/8/8/8/1N2KN2 w - - 0 1"; LLD_CHECK_EQ(san(knights, "b1d2"), std::string("Nbd2")); LLD_CHECK_EQ(san(knights, "f1d2"), std::string("Nfd2")); LLD_CHECK_EQ(san(knights, "b1c3"), std::string("Nc3")); // only one knight reaches c3 const std::string_view rooks = "4k3/8/8/R7/8/8/8/R3K3 w - - 0 1"; LLD_CHECK_EQ(san(rooks, "a1a3"), std::string("R1a3")); LLD_CHECK_EQ(san(rooks, "a5a3"), std::string("R5a3")); LLD_CHECK_EQ(san(rooks, "a1d1"), std::string("Rd1")); const std::string_view queens = "8/7k/8/8/8/Q7/8/Q1Q4K w - - 0 1"; LLD_CHECK_EQ(san(queens, "a1b2"), std::string("Qa1b2")); // shares a file and a rank LLD_CHECK_EQ(san(queens, "a3b2"), std::string("Q3b2")); // shares the a-file only LLD_CHECK_EQ(san(queens, "c1b2"), std::string("Qcb2")); // shares rank 1 only // Disambiguation goes before the capture mark. LLD_CHECK_EQ(san("4k3/8/8/8/8/8/K7/R2n3R w - - 0 1", "a1d1"), std::string("Raxd1"));}
LLD_TEST(ac_7_4_a_pinned_piece_does_not_cause_disambiguation) { // The knight on c3 could reach e2, but it is pinned by the bishop on a5. LLD_CHECK_EQ(san("4k3/8/8/b7/8/2N5/8/4K1N1 w - - 0 1", "g1e2"), std::string("Ne2")); LLD_CHECK_EQ(san("4k3/8/8/8/8/2N5/8/4K1N1 w - - 0 1", "g1e2"), std::string("Nge2"));}The step 2 demo
Section titled “The step 2 demo”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The clock is declared before the game, because the game keeps a// pointer to it and must not outlive it.ManualClock clock;Game game(TimeControl{180s, 2s}, clock); // 3 minutes, plus 2 seconds a movestd::cout << "Start:";show_clocks(game);play(game, clock, "e2e4", 5s);play(game, clock, "e7e5", 3s);play(game, clock, "g1f3", 12s);play(game, clock, "b8c6", 4s);play(game, clock, "f1b5", 20s);play(game, clock, "a7a6", 7s);
std::cout << "\nUndo after 2 s, redo after 1 s more:\n";clock.advance(2s);std::cout << " " << game.undo().text << ":";show_clocks(game); // White used 2 s; Black keeps its 7 s used and loses its 2 s incrementclock.advance(1s);std::cout << " " << game.redo().text << ":";show_clocks(game);
PgnTags tags;tags.event = "CS-13 demo";tags.date = "2026.11.28";tags.white = "Ann";tags.black = "Ben";std::cout << "\n" << to_pgn(game, tags);
std::cout << "\nWhite thinks for 3 minutes:\n";clock.advance(180s);std::cout << " " << to_string(game.check_flag()) << "\n";std::cout << " " << game.play("b5c6").text << "\n";std::cout << " " << game.undo().text << "\n";std::cout << "\n" << to_pgn(game, tags);Start: White 3:00.0, Black 3:00.0e4 after 5 s: White 2:57.0, Black 3:00.0e5 after 3 s: White 2:57.0, Black 2:59.0Nf3 after 12 s: White 2:47.0, Black 2:59.0Nc6 after 4 s: White 2:47.0, Black 2:57.0Bb5 after 20 s: White 2:29.0, Black 2:57.0a6 after 7 s: White 2:29.0, Black 2:52.0
Undo after 2 s, redo after 1 s more: took back a7a6: White 2:27.0, Black 2:50.0 played again a7a6: White 2:27.0, Black 2:51.0
[Event "CS-13 demo"][Site "?"][Date "2026.11.28"][Round "?"][White "Ann"][Black "Ben"][Result "*"][TimeControl "180+2"]
1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 *
White thinks for 3 minutes: White's time ran out, Black wins b5c6: the game is over (White's time ran out, Black wins) the game was decided on time, which cannot be taken back
[Event "CS-13 demo"][Site "?"][Date "2026.11.28"][Round "?"][White "Ann"][Black "Ben"][Result "0-1"][TimeControl "180+2"][Termination "time forfeit"]
1. e4 e5 2. Nf3 Nc6 3. Bb5 a6 0-1The first PGN is the game in progress (*); the second is the same
game after White’s flag fell, with 0-1 and Termination "time forfeit". The undone and replayed a6 appears once.
Presenting it in an interview
Section titled “Presenting it in an interview”A plan for 45 minutes, using the time boxes from The design workflow:
| Time | What to do | What to say |
|---|---|---|
| About 5 min | Ask which rules, how moves come in, which endings matter, whether there is an engine, and how far take-backs go. | “Is threefold repetition in scope? It needs the history of positions, not only the current one.” |
| 5 min | Sketch Piece, Position, Move, MoveRecord, and Game. Say that everything but the game is a value. |
“The set of pieces is closed and they carry the same data, so a kind enum, not a class per piece.” |
| 10–15 min | Write legal_moves on a copy, then make and the record. State INV-2 and INV-3. |
“Legal means the king is safe after the move. One test covers pins, checks, and castling into check.” |
| 10 min | Walk check and its refusals, then the game states, then undo through the record. Name perft as the test oracle. |
“A matching perft count is strong evidence; two bugs can still cancel.” |
| About 5 min | Take a change: clocks, or PGN. | “The clock reads an injected time source, and only the game decides when a move was accepted.” |
What is usually expected at each level
| Level | Usually expected |
|---|---|
| Junior | A board of 64 cells; pieces with a colour and a kind; moves for each kind; whose turn it is; detecting check; a few tests of single moves. |
| Mid-level | All of the above, plus: legality after the move, so pins and checks are handled; castling, en passant, and promotion with their conditions; checkmate and stalemate; refusals with reasons; undo through a record of what a move changed. |
| Senior | All of the above, plus: a justified choice between enum, hierarchy, and variant; positions as comparable values; perft as an oracle, and its limits; the cost of copy-based legality and when it would stop being fine; a clock behind a seam; SAN from legal moves only. |
These are this site’s judgement of common practice, as on How to approach a case study, not any company’s rubric.
Questions an interviewer may ask
Why not a Piece base class with a virtual moves()?
Because the rules are about the board, not the piece. A piece cannot
decide alone whether its move is legal: that depends on the squares
between, on the last move (en passant), and on where its own king is.
The set of kinds is closed and every kind has the same data, so a
Kind enum with the movement code in Position is simpler, and keeps
the position a copyable value. A hierarchy would fit an open set of
invented pieces, and even then check would stay in the position.
Copying the position for every candidate move sounds slow. Is it?
Measured for this page: four moves deep from the start, 197,281
positions, in about 60 ms at -O2 on one server (machine-specific,
not a benchmark). A person needs one
position’s moves at a time, so it is far below anything noticeable.
An engine searching millions of positions a second would make and
unmake in place and track pins directly; that is a different
requirement, and I would change the design only for it.
What exactly does undo need to store, and why not just the two squares?
Everything a move destroys or overwrites that cannot be worked out afterwards: the captured piece and the square it stood on (different for en passant), the piece that moved (it may have promoted), and the castling rights, en passant square, and half-move clock from before. The side to move and the move number follow from the colour of the piece that moved. The rook’s hop for castling follows from the move.
Is your move record the Command pattern?
It is the idea, a stored request that can be reversed, without the
class hierarchy. Every undoable action here is a move, reversed by the
same unmake, so a Command base class would have one subclass. I
would add one if the undo stack had to hold different kinds of action,
like comments or hand-placed pieces on an analysis board.
How do you know your move generator is right?
Perft: count the positions reachable in a few moves from well-known positions and compare with the published counts, which many independent programs agree on. A mismatch proves a bug, and splitting the count by first move finds it. A match is strong evidence, not proof: two bugs can cancel, and perft says nothing about notation, refusal texts, or game endings, which have their own tests.
How would you add threefold repetition?
It needs more than the current position: the game has to remember the positions it has passed through, and undo has to keep that memory in step with the history. The subtle part is deciding when two positions count as the same. The Exercise works it through.
Where does the clock live, and why not in the position?
In the game. The position is copied for every legality test and must
compare equal after undo; time does not belong in either. Only the
game knows when a move was accepted, so only the game presses the
clock, and it reads the time from an injected Clock so that tests
can move time exactly.
Production limitations
Section titled “Production limitations”- Not all the draw rules. Threefold and fivefold repetition, draws by insufficient material on the board, and draw offers are missing. The fifty-move rule is applied without a claim, where FIDE requires one (only the 75-move rule is automatic).
- Loss on time is judged by material alone. Two bishops on one colour, or a locked position, would be scored as a win on time where the FIDE rules give a draw.
- Copy-based legality. Simple and checked, but too slow for an
engine or for analysing many games in bulk. Each
legal_movescall also allocates a vector. - No engine, no analysis, no opening book.
- Single process, single thread. A
Gameis not safe to use from two threads, and there is no server, no network play, and no saving to disk. A PGN string is produced, but writing the file is the caller’s job. - No PGN import. Reading PGN means parsing SAN, which needs the same legal-move list in reverse, and handling comments and variations.
- Coordinate input only. SAN is written but not read.
- The clock has no delay modes (such as the “Bronstein” or simple delay used in some events), and it measures time only when the game is called. A real interface would also show the time ticking down.
Traceability
Section titled “Traceability”| Requirement | Design element | Code | Tests | Status |
|---|---|---|---|---|
| FR-1 positions | Position, start, from_fen, to_fen |
step 1 position.* |
ac_1_1_…, ac_1_2_… |
Tested |
| FR-2 legal moves | pseudo-legal generation, legal_moves on a copy, make |
step 1 position.cpp |
ac_2_1_… to ac_2_13_…, ac_3_2_… |
Tested |
| FR-3 refusals | Refusal, Verdict, Game::check |
step 1 game.* |
ac_3_1_… to ac_3_3_…, ac_2_6_… to ac_2_8_…, ac_2_13_… |
Tested |
| FR-4 the end of the game | GameState, update_state |
step 1 game.cpp |
ac_4_1_… to ac_4_6_… |
Tested |
| FR-5 take-backs | MoveRecord, unmake, undo, redo |
step 1 position.*, game.cpp |
ac_5_1_… to ac_5_5_… |
Tested |
| FR-6 input | parse_move, Refusal::bad_notation |
step 1 move.hpp, game.cpp |
ac_1_3_…, ac_3_1_… |
Tested |
| NFR-1 correct by count | perft |
step 1 position.cpp |
ac_2_1_… to ac_2_4_… |
Tested |
| NFR-2 testable without a screen | Game with no input or output; a thin main |
step 1 game.*, main.cpp |
every test | Tested |
| NFR-3 positions are values | std::array of std::optional<Piece>, defaulted == |
step 1 position.hpp |
ac_5_1_…, ac_5_5_… |
Tested |
| NFR-4 single-threaded | documented on Game |
step 1 game.hpp |
none: a statement, not a behaviour | Stated |
| NFR-5 fast enough | copy-based legality, perft depths chosen for test time | step 1 position.cpp |
measured once for this page, not a test | Measured |
| FR-7 clocks | Clock, ChessClock, check_flag, could_mate, take_back |
step 2 clock.hpp, chess_clock.*, game.* |
ac_6_1_… to ac_6_10_… |
Tested |
| FR-8 PGN export | to_san, to_pgn, PgnTags |
step 2 pgn.* |
ac_7_1_… to ac_7_10_… |
Tested |
Exercise
Section titled “Exercise”Exercise: Add threefold repetition
The club now wants the game drawn when the same position appears for the third time (they accept that it ends by itself, without a claim, as with the fifty-move rule). Two positions count as the same when the same pieces stand on the same squares, the same side is to move, the castling rights are the same, and the same en passant captures are possible. Work on step 1.
- What has to be stored, and where? What does undo have to do with it?
- Write the function that makes a “same position” key. Be careful with
the en passant square: after
e2e4, FEN always names e3, but if no black pawn can capture there, the position is the same as one without it. - Write three tests: knights out and back until the draw, undo after the draw, and an en passant square that does or does not make a position different.
Show the explained answer
What is stored. A key for every position of the game, in order,
kept by Game next to the history, starting with the first position:
std::vector<std::string> keys_. The constructor pushes the first key,
apply pushes a key after each make, and undo pops one, so the
keys always match the history. A new GameState::draw_by_repetition
(with its text in to_string) is set by update_state when the
current key appears three times. That test goes after the mate and
stalemate tests (a mate that repeats a position is still mate) and
before the fifty-move test.
The key. FEN already holds exactly the four facts, plus two counters that must be dropped:
IllustrativeA fragment for explanation; not compiled on its own.
// A position's identity for repetition: its FEN without the two counters,// and with the en passant square only if a capture there is really legal.std::string repetition_key(const Position& position) { std::string fen = position.to_fen(); fen.erase(fen.rfind(' ')); // drop the move number fen.erase(fen.rfind(' ')); // and the half-move clock if (const std::optional<Square> ep = position.en_passant()) { const std::vector<Move> moves = position.legal_moves(); // Can any pawn of the side to move legally take on that square? const bool can_take = std::any_of(moves.begin(), moves.end(), [&](const Move& m) { return m.to == *ep && position.at(m.from)->kind == Kind::pawn; }); // If not, write "-" as if there were no en passant square at all. if (!can_take) fen.replace(fen.rfind(' ') + 1, std::string::npos, "-"); } return fen;}IllustrativeA fragment for explanation; not compiled on its own.
// In update_state, after the mate and stalemate tests:} else if (std::count(keys_.begin(), keys_.end(), keys_.back()) >= 3) { state_ = GameState::draw_by_repetition; // the current position, a third time}Using legal_moves, not pseudo-legal moves, matters for the same
reason as in SAN: a pawn that is pinned cannot take en passant, so its
presence does not make the position different.
The tests. Knights out and back (g1f3, g8f6, f3g1, f6g8,
twice) bring the start position back for the third time on the eighth
half-move, and the game is drawn; undo reopens it, and redo draws it
again. After e2e4, the e3 square is set, but no black pawn can take
there, so that position counts the same as the later ones without it.
From 4k3/8/8/8/1p6/8/P7/4K1N1 w - - 0 1, after a2a4 the pawn on
b4 could take en passant, so that position is different from the same
pieces later, and the draw comes on the ninth half-move after a2a4. With the black
pawn on b3 instead, no capture is possible, and the same moves draw on
the eighth.
This answer was checked in a scratch copy of step 1, not in the example in the repository. With these changes, the new tests and the 30 existing step 1 tests passed under GCC and Clang, and under AddressSanitizer with UndefinedBehaviorSanitizer.
In step 2, result_token in pgn.cpp would also need the new state.
Its switch has no default, so -Wall warns until it is added.
Summary
Section titled “Summary”- Model pieces as values: a colour and a kind from a closed enum. The rules are about the whole board, so they live in the position, not in the pieces.
- Make the position a value that holds everything the rules need: the board, the side to move, the castling rights, the en passant square, and the counters. Copy it and compare it freely.
- Legal means safe after the move. Generate pseudo-legal moves, try each on a copy, and keep those that leave the mover’s king unattacked. Measure before calling it slow.
- A move record that stores everything a move destroyed gives exact undo. It is the Command idea; add a Command hierarchy only when the undo stack holds different kinds of action.
- Refuse with a reason: an enum for code, a text for people.
- Use perft counts as an oracle, and know that a match is evidence, not proof.
- Put the clock in the game, read time through an injected source, and write down the undo policy. Write SAN from legal moves only.