A move generator that is wrong by one rule in one rare position poisons everything built on it. A search will happily play the illegal move, or never see the legal one that wins. This lesson makes the rules exact and then proves them by counting. It pairs with Coding Adventure: Chess and Coding Adventure: Making a Better Chess Bot by Sebastian Lague, linked under Watch & read; between them their chapters cover generating moves and testing and optimizing move generation. You build make_move, in_check, castling_moves, legal_moves and perft on top of a supplied board and a supplied generator of pseudo-legal moves.
Pseudo-legal means the piece rules allow it: a rook slides until it meets a piece, a pawn pushes, captures and promotes. The supplied pseudo_moves ignores check completely. A move is legal when, after you play it, your own king is not attacked. That gives the whole filter in three steps: play the move on a copy, look at your own king in the copy, keep the move or drop it. Testing after the move is the point. A pinned piece, a king stepping next to the other king and a move that opens a line to your king are all invisible before the move.
The board is a string of 64 characters with a1 as square 0, so square = 8 · rank + file (counting ranks and files from 0), h1 is 7 and a8 is 56. A move is a tuple (from, to, promotion). make_move copies the board into a list, moves the piece, flips the side to move and then repairs everything a plain move gets wrong:
- an en passant capture lands on an empty square, and the captured pawn stands one rank behind it, on a different square
- a promotion replaces the pawn with the named piece, in the mover's case
- castling is the king's two-square move, and the rook must jump to the other side of it
- the castling rights, the en passant square and both clocks change
def square(name):
return "abcdefgh".index(name[0]) + 8 * (int(name[1]) - 1)
print(square("e2"), square("e4"), (square("e2") + square("e4")) // 2)
target = square("d6") # White pawn on e5 takes en passant on d6
print(target, target - 8, square("d5"))The target square is 8 away from the victim, and which way depends on whose move it is. A double push sets the en passant square to the square it jumped over, here 20 for e2 to e4, and only a double push sets it.
Castling rights are the easiest thing to lose track of. A right dies when its king moves, when its rook leaves the corner, and when anything lands on the rook's corner, because the rook has been captured. Keeping one set of squares per right turns all three into the same test.
castle_squares = {"K": {4, 7}, "Q": {0, 4}, "k": {60, 63}, "q": {56, 60}}
def rights_after(rights, frm, to):
lost = {frm, to}
return "".join(c for c in rights if lost.isdisjoint(castle_squares[c]))
print(rights_after("KQkq", 4, 5)) # the white king steps from e1 to f1
print(rights_after("KQkq", 14, 7)) # a black bishop takes the rook on h1For in_check, look outward from the king instead of generating the other side's moves. Test the two squares a pawn could attack from, the knight and king squares, and then each of the eight rays to the first piece it meets. Square arithmetic wraps around the board edge, which is the usual trap with pawns.
king = 8 # a white king on a2
print([divmod(s, 8) for s in (king + 7, king + 9)]) # (rank, file) of the squares a black pawn would attack fromThe first pair is (rank 1, file 7), which is h2: it sits on the king's own rank and is not a square a pawn attacks from. Check the file before using an offset.
Castling needs four things: the right is still held, the squares between king and rook are empty, the king is not in check, and it neither passes through nor lands on an attacked square. Only the king's squares count. The rook may be attacked, and so may b1 when castling long.
Perft is how you prove all this. perft(pos, depth) counts the move sequences of exactly that many plies, and published counts exist for well-known positions. From the starting position the counts are 20, 400, 8902 and 197281 for depths 1 to 4. The count is a strong fingerprint: one wrong rule in one corner changes it. A count that is right at depth 2 and wrong at depth 3 points to a fault that needs two plies of setup, such as a right that should have been lost.
Four mistakes cause most of the wrong counts. The first is clearing rights for the piece that moves but not for the piece that is captured, so a rook taken on its corner leaves its right behind. The second is removing the en passant victim from the wrong square, or not at all, which shows up only a ply later. The third is asking about the king before the move instead of after. The fourth is wrapping a pawn or knight offset around the edge of the board.
Here is what the evidence covers. The public tests use the starting position and small positions you can check by hand. The hidden tests compare against published counts for four positions chosen to contain castling, pins, en passant and promotions, and check the rules that counts cannot isolate, such as which squares an en passant capture changes. A matching count shows that the sum over all positions is right, not that each move is right, since two errors can cancel. It also says nothing about draws by repetition or by the fifty-move rule, and it counts a position again every time a different move order reaches it.