A chess engine picks a move by looking ahead: try each move, try each reply, and keep the line that ends best for the side that is choosing. This lesson is that search. It pairs with the "Algorithms Explained" video on minimax and alpha-beta pruning by Sebastian Lague, linked under Watch & read. You build negamax, then alpha-beta pruning that returns the same answer after visiting far fewer positions, and you check both against exhaustive minimax.
The search never touches chess rules. It works on any game object with three methods: moves(state) lists the legal moves, play(state, move) returns the next state and leaves the old one alone, and score(state) rates a state from the point of view of the side to move, where larger is better for that side. A state with no moves is over, and score says how it ended. With an interface this small you can test the search on tiny trees and on Nim long before it meets a board.
Minimax says one player takes the largest score and the other takes the smallest. Negamax uses the fact that the game is zero-sum: what is good for the opponent is exactly as bad for you. So the value of a state for the side to move is the best of the negated values of its children, and one function with one sign flip replaces two. At depth 0, or in a state with no moves, the search returns score(state). It also counts every state it visits, because the count is how you measure pruning. When two moves tie, keep the first.
Walk through the figure. After branch A the root is guaranteed 3. In branch B the opponent can answer with the leaf worth 2, so B is worth 2 or less to the root, whatever the other leaf says. The 9 cannot change the decision. Negamax visits all 7 states; skipping the 9 gives 6.
Alpha-beta turns that argument into two numbers. Alpha is the best value the side to move is already sure of. Beta is the value at which the opponent would refuse to enter this line, because it has something at least as good elsewhere. When you search a child, the two sides swap roles and the signs flip, so the child gets the window (-beta, -alpha). After each move you raise alpha to the best value so far, and once alpha >= beta the remaining moves cannot matter and the loop stops.
from math import inf
def search(tree, d, alpha=-inf, beta=inf):
value, kids = tree
if d == 0 or not kids:
return value, 1
best, nodes = -inf, 1
for kid in kids:
v, n = search(kid, d - 1, -beta, -alpha)
nodes += n
best = max(best, -v)
alpha = max(alpha, best)
if alpha >= beta:
break
return best, nodes
a = (0, [(0, [(3, []), (5, [])]), (0, [(2, []), (9, [])])])
b = (0, [(0, [(2, []), (9, [])]), (0, [(3, []), (5, [])])])
print(search(a, 2), search(b, 2))The second tree is the first with its branches swapped, and it costs 7 nodes instead of 6. Pruning depends on the order in which moves are tried: a strong move first raises alpha early, and every later branch is cut sooner. With the best move first everywhere, alpha-beta visits roughly the square root of what negamax visits, which lets an engine search about twice as deep for the same effort. Engines therefore sort moves with a cheap guess, such as captures first. order_moves(moves, key) does the sorting: best first, higher key first, equal keys left in their original order.
Nim makes a good test game, because its answer is known without any search: with heaps a, b and c, the player to move wins exactly when a xor b xor c is not zero. A player who cannot move has lost, so that state scores -1.
from math import inf
class Nim:
def moves(self, s):
return [(i, k) for i, h in enumerate(s) for k in range(1, h + 1)]
def play(self, s, m):
heaps = list(s)
heaps[m[0]] -= m[1]
return tuple(heaps)
def score(self, s):
return -1 if sum(s) == 0 else 0
def negamax(g, s, d):
moves = g.moves(s)
if d == 0 or not moves:
return g.score(s), 1
best, nodes = -inf, 1
for m in moves:
v, n = negamax(g, g.play(s, m), d - 1)
best, nodes = max(best, -v), nodes + n
return best, nodes
def alpha_beta(g, s, d, alpha=-inf, beta=inf):
moves = g.moves(s)
if d == 0 or not moves:
return g.score(s), 1
best, nodes = -inf, 1
for m in moves:
v, n = alpha_beta(g, g.play(s, m), d - 1, -beta, -alpha)
best, nodes = max(best, -v), nodes + n
alpha = max(alpha, best)
if alpha >= beta:
break
return best, nodes
print(negamax(Nim(), (1, 2, 3), 6), alpha_beta(Nim(), (1, 2, 3), 6), 1 ^ 2 ^ 3)The heaps (1, 2, 3) xor to zero, so the player to move loses: the value is -1 in both searches, with 447 nodes against 249.
Three mistakes account for most broken searches. The first is forgetting to negate the child's score. The code reads naturally and the engine still plays moves, but it picks the move that is best for the opponent. The second is passing the child the same window, or the negated window with the two bounds not swapped: the cutoffs then fire at the wrong moments and good moves are discarded. The third is a sorting slip in the ordering step. Python's sorted(..., reverse=True) keeps tied elements in their original order, while reversing a finished ascending list does not, and a changed tie order changes which of several equal moves the engine plays.
The tests compare your functions with an exhaustive minimax that shares no code with them, on random trees with many ties, on every small Nim position, and on tic-tac-toe, which must come out a draw. They also compare node counts with the known minimum for perfectly ordered trees. This shows that pruning never changes the root's answer. It does not show that the score is any good: a search is only as wise as its score function, and a fixed depth can stop in the middle of an exchange of pieces. Those limits belong to the evaluation, which later lessons return to.