CodeRigor

LESSON

Capstone: a chess engine that finds mates

Combine evaluation, move ordering, quiescence and iterative deepening with mate scores into a small engine, and test it against brute-force mate searches.

This lesson ties the course together. You already generate legal moves and know how a search prunes, so here you decide what a position is worth, which moves to look at first, when to stop looking, and how to report a forced mate. This lesson pairs with Coding Adventure: Making a Better Chess Bot by Sebastian Lague, linked under Watch & read. The video is a long build of improvements to a chess bot, with chapters on move ordering, search extensions, transposition troubles and testing; you build the smallest version of those ideas that can find a mate. The move generator is supplied. You write evaluate, move_order, quiesce, search and choose_move.

Start with the score. evaluate adds up piece values (pawn 100, knight 320, bishop 330, rook 500, queen 900, in centipawns) and a small bonus from a piece-square table, then returns the total from the side to move's point of view. Black reads the table from its own end of the board, so a position and its colour-flipped copy must score the same. That one property catches most sign and rank mistakes.

Five functions, one call chain
start / 4
choose_move calls search for every root move. search ends in quiesce, which ends in evaluate. move_order feeds both searches.
Five functions, one call chain
choose_move calls search for every root move. search ends in quiesce, which ends in evaluate. move_order feeds both searches.

Alpha-beta prunes more when good moves come first. move_order scores a capture as 10 × (victim + 1) − attacker, where each piece is its index in "pnbrqk", and adds 100 for a promotion. A pawn taking a queen goes ahead of a queen taking a pawn, and quiet moves come last in their original order.

Python
ORDER = "pnbrqk"


def key(victim, attacker):
    return 10 * (ORDER.index(victim) + 1) - ORDER.index(attacker)


print(key("q", "p"), key("q", "r"), key("p", "q"))

At depth 0 the search must not score a position in the middle of an exchange. quiesce keeps searching captures until none are left. It begins by standing pat: the side to move is not forced to capture, so the static score is a floor. If that floor already reaches beta, return beta. Otherwise raise alpha to it and try the captures. Leave the floor out and a position whose only capture loses the queen is scored as if the queen had to be thrown away.

Now the end of the game. A position with no legal moves is stalemate (score 0) or checkmate. Mate is scored −(MATE − ply) for the side that is mated, with ply counted from the root. The sign flips on the way up, so a mate in one is worth MATE − 1 at the root and a mate in two is worth MATE − 3. If every mate scored −MATE, the engine would have no reason to choose the quicker one.

A mate in two, with the scores each node returns
start / 2
White rook on d5, kings on f6 and g8. Rd5-h5 takes away the h-file, Black's only move is Kf8, and Rh5-h8 mates. MATE is 100000.
A mate in two, with the scores each node returns
White rook on d5, kings on f6 and g8. Rd5-h5 takes away the h-file, Black's only move is Kf8, and Rh5-h8 mates. MATE is 100000.

choose_move runs the whole thing with iterative deepening. It searches depth 1, then 2, then 3, keeping the best move of each finished depth and trying it first next time. A node budget is counted inside search and quiesce, and an exception unwinds the recursion when it is spent. An unfinished depth is thrown away, because it has compared only some of the root moves. If not even depth 1 finished, the engine still returns the first ordered move.

Python
MATE = 100_000
for moves_to_mate in (1, 2, 3):
    ply = 2 * moves_to_mate - 1
    print(moves_to_mate, MATE - ply)

Four mistakes cost real learners the most. Scoring mate as a flat −MATE makes all mates tie. Dropping stand pat, or using min where max belongs, makes quiescence return a bound instead of a score. Forgetting to negate and swap the window in a recursive call turns the search into a maximiser for both sides. And forgetting to lift the node limit after choose_move returns breaks the next search that runs.

The tests compare your search and quiesce with plain versions that never prune, and the mate-in-one and mate-in-two positions with a brute-force mate finder. When they agree, your pruning, mate scores and stalemate handling are consistent with an exhaustive search at the same depth. They do not show that the engine plays well: the evaluation is crude, there is no castling, en passant or underpromotion, and quiescence does not look for mates or checks, so a mate hidden behind a capture sequence can be missed.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

A long build that improves an existing chess bot: move ordering, search extensions, transposition troubles, killer moves, and testing it against other bots. Watch it for how the pieces of an engine fit together, then build a small one here.

A chess engine from the board up, with chapters on generating moves, search and evaluation, easy endgames and the transposition table. Use the search and evaluation chapters beside this lesson's evaluate and search.