Search a game tree with negamax and alpha-beta pruning, counting visited leaves
Before learned value networks, game engines searched the tree with minimax and pruned branches that could not change the decision. Alpha-beta pruning gives the same answer as full minimax while visiting far fewer leaves.
A tree is either a number (a leaf, scored from the point of view of the player to move at that leaf) or a list of child trees. Use the negamax form: the value of an internal node is max over children of -value(child).
Write negamax_ab(tree) returning (value, leaves) where value is the root value for the player to move at the root, and leaves is how many leaf numbers were evaluated.
- Search children left to right with alpha-beta: start alpha = -inf, beta = +inf; a child is searched with window (-beta, -alpha); after each child set alpha = max(alpha, score); stop searching the remaining children as soon as alpha >= beta.
- An internal node with no children is not used.
def negamax_ab(tree)Example
negamax_ab([[3, 5], [2, 9]]) returns (3, 3). The first child is worth max(-3, -5) = -3, so the root scores 3 from it. In the second child the first leaf already scores -2 for that child, which is enough to prove it is worse for the root, so leaf 9 is never evaluated.
Understand the idea
Negamax writes minimax with one rule: a node's value for the player to move is the best of the negated child values, because the child's value is from the opponent's view. Alpha-beta pruning skips branches that cannot change the decision: alpha is the best score already guaranteed, beta is the most the opponent will allow. Worked example: tree [[4, 6], [2, 7], [5, 8]]. Child 1: max(-4, -6) = -4, so the root scores 4 from it and alpha = 4. Child 2 is searched with window (-inf, -4); its first leaf gives -2, and -2 >= -4 means this child is already good enough for the opponent, so leaf 7 is skipped; the root scores 2 from it. Child 3: leaves 5 and 8 give -5 and -8, child value -5, root scores 5, alpha = 5. Answer (5, 5): value 5, and 5 leaves evaluated instead of 6. Rule: at each internal node, for children left to right, score = -search(child, -beta, -alpha); alpha = max(alpha, score); stop once alpha >= beta; a leaf returns its number and counts as one evaluation. Classic chess and checkers engines are built on this search.