Game evaluation functions: know what the score means
博弈估值函数
Audit terminal utilities, heuristic features, perspective and action errors against a completely solved subtraction game.
game-evaluation-functionsA score can choose the right move for the wrong reason
There are four stones on a table. Two players alternate removing one or two stones; whoever takes the last stone wins. Max moves first. Removing one stone leaves three for Min, which is a winning plan for Max. Removing two leaves two for Min, who immediately takes both and wins.
An evaluation function is a guess about a position whose consequences the search has not fully explored. Our deliberately imperfect evaluator likes odd pile sizes for the player to move. A one-ply search with it removes two stones and loses. Looking two plies ahead chooses the winning move, even though its estimated value is still negative. Move quality and value accuracy are related, but they are different measurements.
This chapter audits the numbers supplied to a game search: whose payoff they describe, what their scale means, and whether their errors can change the chosen action. The minimax chapter explains the search recurrence itself. Berkeley’s evaluation-function section introduces replacing unfinished search leaves with estimates and combining state features with weights. CS188, section 3.2.2
Use one perspective and a stated utility scale
A state is : stones remain, and means Max moves next while means Min does. The game is deterministic, alternating, zero-sum and fully observable. Every action removes one or two available stones, so a game starting with stones ends within plies. A ply is one player’s action, not a pair of turns. There are no draws.
All values in the search use Max’s perspective. A win for Max has utility +1; a loss has utility −1. At , the player now due to move has already lost:
The terminal rule is exact. A depth cutoff is a different event and must not overwrite it. For a nonterminal state, define an odd-pile feature equal to +1 for odd and −1 for even , and a closeness feature . The original toy evaluator is
Multiplying by converts the features’ player-to-move perspective into Max’s perspective. The default weights are and . They are an authored baseline, not fitted coefficients or a theorem about good play. Oddness is the wrong pattern for this game, and being near the end can mean winning or losing. Clipping limits the range; it does not create calibration, certainty, or a probability of winning.
The exact result is easy to establish independently. Zero stones is losing for the player to move. From a positive multiple of three, both legal moves leave a nonmultiple. From any other positive pile, a player can remove one or two to leave a multiple of three. Induction therefore gives
The formula includes . It solves this specific subtraction game; it is not the general multi-pile Nim rule. The program below computes a complete finite table without using the remainder formula, allowing the two methods to check each other.
What does a leaf-value error imply? Fix a finite deterministic game tree, its Max/Min labels, and a particular depth cutoff. At each unfinished frontier node , compare its estimate with its exact continuation value . Assume a uniform bound over every such node, and exact utilities at terminal leaves. For two child-value vectors ,
For the maximum, each is at most , so their maximum is at most ; swapping the vectors proves the other direction. The minimum follows by negation. Repeating this argument toward the root shows that its backed-up error is at most , without multiplying by depth. This proof has no added transition rewards, random outcomes, selective omissions, or changing frontier.
At a Max decision, let be an action’s exact continuation value. If the best action is unique and its gap to the next action is , estimates satisfying those bounds cannot change the winner:
For a Min decision, negate the values before comparing. Equality at permits a tie and does not guarantee the same choice. Mean error on a collection of positions is not a uniform frontier bound. The proof also does not show that increasing depth always helps: a new cutoff produces a new set of leaf errors.
Audit the heuristic against a solved small game
This complete standard-library program uses rational arithmetic. Pile sizes and depths must be integers; turn must be +1 or −1. Booleans are rejected. Feature weights and queried evaluator outputs must be integers or Fraction objects, so decimal weights should be written as Fraction(1, 2), for example. The built-in evaluator clips nonterminal values; limited_value also permits other rational evaluators so their scale errors can be tested.
Terminal checks precede depth checks. Depth zero returns a value estimate, while choosing a move requires depth at least one. Max chooses the highest backed-up Max-value and Min the lowest. Ties choose the smaller removal. The exact solver uses a bottom-up table; the bounded search visits a tree without caching. No random opponent or learned policy supplies its reference values.
from fractions import Fraction
def check_state(n, turn):
if type(n) is not int or n < 0:
raise ValueError('pile size must be a nonnegative integer')
if type(turn) is not int or turn not in (-1, 1):
raise ValueError('turn must be -1 or 1')
def make_evaluator(parity=Fraction(1, 2), near=Fraction(1, 4)):
# Exact rational arithmetic keeps this small audit free of roundoff.
if any(type(w) not in (int, Fraction) for w in (parity, near)):
raise ValueError('weights must be integers or Fractions')
def evaluate(n, turn):
check_state(n, turn)
if n == 0:
return Fraction(-turn) # The player who must move has lost.
odd = 1 if n % 2 else -1
raw = parity * odd + near * Fraction(1, n+1)
return turn * max(Fraction(-1), min(Fraction(1), raw))
return evaluate
def exact_values(max_pile):
check_state(max_pile, 1)
values = {(0, turn): Fraction(-turn) for turn in (-1, 1)}
for n in range(1, max_pile+1):
for turn in (-1, 1):
children = [values[n-take, -turn] for take in (1, 2) if take <= n]
values[n, turn] = (max if turn == 1 else min)(children)
return values
def limited_value(n, turn, depth, evaluate):
check_state(n, turn)
if type(depth) is not int or depth < 0:
raise ValueError('depth must be a nonnegative integer')
def visit(pile, player, remaining):
if pile == 0:
return Fraction(-player) # Terminal test precedes depth cutoff.
if remaining == 0:
result = evaluate(pile, player)
if type(result) not in (int, Fraction):
raise ValueError('evaluator must return an integer or Fraction')
return result
children = [visit(pile-take, -player, remaining-1)
for take in (1, 2) if take <= pile]
return (max if player == 1 else min)(children)
return visit(n, turn, depth)
def choose(n, turn, depth, evaluate):
check_state(n, turn)
if type(depth) is not int or depth < 1:
raise ValueError('choosing a move requires positive integer depth')
if n == 0:
return None, {}
scores = {take: limited_value(n-take, -turn, depth-1, evaluate)
for take in (1, 2) if take <= n}
# Min prefers smaller Max-utility; exact ties choose the smaller removal.
action = min(scores, key=lambda take: (-turn*scores[take], take))
return action, scores
def audit(piles, depth, evaluate):
piles = tuple(piles)
if not piles or any(type(n) is not int or n < 1 for n in piles):
raise ValueError('audit needs positive pile sizes')
if len(set(piles)) != len(piles):
raise ValueError('audit pile sizes must be distinct')
exact = exact_values(max(piles))
errors, regrets = [], []
for n in piles:
for turn in (-1, 1):
estimate = evaluate(n, turn)
if type(estimate) not in (int, Fraction):
raise ValueError('evaluator must return an integer or Fraction')
errors.append(abs(estimate-exact[n, turn]))
action, _ = choose(n, turn, depth, evaluate)
regrets.append(turn*(exact[n, turn]-exact[n-action, -turn]))
return {'states': len(errors), 'mean_abs_error': sum(errors)/len(errors),
'max_abs_error': max(errors), 'blunders': sum(r > 0 for r in regrets),
'mean_regret': sum(regrets)/len(regrets)}
evaluate = make_evaluator()
assert limited_value(0, 1, 0, lambda *_: 999) == -1
assert evaluate(4, 1) == -evaluate(4, -1)
assert choose(4, 1, 1, evaluate)[0] == 2
assert choose(4, 1, 2, evaluate)[0] == 1
exact = exact_values(18)
assert exact[3, 1] == -1 and exact[4, 1] == 1
for depth in (1, 2, 3, 18):
print(depth, choose(4, 1, depth, evaluate),
audit(range(13, 19), depth, evaluate))
For Max facing four stones, “Take 1” and “Take 2” show the returned action values. “Choice” is the number removed; “Outcome” is the exact result under subsequent optimal play:
| Depth | Take 1 | Take 2 | Choice | Outcome |
|---|---|---|---|---|
| 1 | 2 | Max loses | ||
| 2 | 1 | Max wins | ||
| 3 | 1 | Max wins |
At depth 1, the search stops at two stones with Min to move and assigns from the flawed feature rule. One more ply exposes Min’s immediate win. At depth 2, the good action is ranked correctly but still has an estimated value below zero. The sign of a rough evaluator is not automatically a correct win/loss label.
The same program supplies an executed counterexample to monotonic improvement with depth. With eight stones and Max to move, depth 2 removes two and preserves a forced win; depth 3 removes one and loses against exact play. More computation can expose different misleading frontier states. Searching at least plies resolves the whole subtraction game and avoids the heuristic entirely.
For a maximum pile , the exact table contains states, each examining at most two actions: time and storage under unit-cost arithmetic. The uncached depth- search has at most binary branching, so visits is a conservative bound, with stack depth. Rational numerators and denominators add arithmetic costs. Large depth can exceed Python’s recursion limit even when the mathematical game is finite; these functions are intended for small audits. The exact table is an oracle here, not an efficiency claim about large board games.
Check what happens at the boundary of the search
A horizon effect occurs when a relevant consequence lies beyond the search cutoff; a move may even push an unavoidable loss beyond that boundary. The four-stone example is a small cutoff error. In chess, a material evaluator used halfway through an exchange may count a temporary gain before the opponent recaptures. Shannon discusses that problem and recommends examining forcing continuations until the position is more stable, subject to limits. Shannon, sections 4 and 6
Quiescence search develops this idea by extending selected tactical continuations rather than always evaluating at a fixed ply. A chess implementation must define which positions and moves qualify, how to handle check, and how to bound extensions. It does not mean every forcing line has been solved, nor that the old uniform-error bound automatically applies after changing the frontier. The subtraction code does not implement a chess quiescence engine.
Score units matter too. For a fixed deterministic Max/Min tree, applying the same positive affine transform , with , to every leaf value, including terminal utilities, preserves the action ordering: max and min commute with that transform. Scaling only the heuristic while leaving terminal wins at +1 can change the move. For two stones, assigning the unfinished one-stone child +3/4 lets Max prefer taking both and receiving +1. Doubling only that estimate to +3/2 makes Max choose the unfinished child instead and lose. Feature normalization should therefore be accompanied by a consistent utility convention and renewed checks of terminal comparisons.
Validation needs game structure. A board layout alone may omit the player to move, legal rights, repetition history or the rule version. In this game, forgetting turn merges two states with opposite Max-values. Opposite-perspective copies are also dependent examples, not twice as many independently sampled positions.
The following evaluation slice fixes the authored weights and considers piles 13 through 18 with both players to move. It compares static estimates with exact values, then tests whether the searched action preserves the exact game value. A blunder means choosing an action whose exact value is worse for the moving player. Regret uses that player’s utility; it is 2 for a lost forced win and 0 otherwise.
| Depth | States | Static mean absolute error | Blunders | Mean regret |
|---|---|---|---|---|
| 1 | 12 | 0.994277… | 4 | |
| 2 | 12 | 0.994277… | 4 | |
| 3 | 12 | 0.994277… | 4 | |
| 18 | 12 | 0.994277… | 0 | 0 |
The static maximum error is . Static error does not change with search depth because it measures the same evaluator at the same starting states. Full search fixes the decisions without changing those predictions. These are exhaustive counts on six specified piles and their sign counterparts, not evidence about a population of unseen games.
If weights are fitted, declare development, validation and final evaluation groups before fitting. One teaching split is pile sizes 1–8, 9–12 and 13–18; keep both turns of the same pile in one group. For recorded board games, group by game and check for repeated positions, symmetries and transpositions across groups. A split by starting game alone can still share states. Also record which opponent or solver produced labels and distinguish game outcomes under that opponent from exact minimax values. Tune on development/validation groups and use the final group once to report value error, move regret and failure cases. No weight fitting was performed for the table above.
Separate a bad estimate from a bad decision
- At three stones with Max to move, what are the terminal-game value and the default static estimate? What changes when Min moves next?
- Reproduce the four-stone table. Why can depth 2 choose correctly while assigning the chosen action a negative value? Does the eight-stone depth counterexample contradict the uniform-error proof?
- Two actions have exact values 1 and 0.4. Every estimated action value has error at most 0.2. Is the better action stable? What changes when the bound is 0.3?
- A dataset contains
(n,+1)and(n,-1)for each pile. Explain why assigning each row independently to training or test can mislead. Propose a check that measures move quality separately from average value error.
Worked answers
- Three is a multiple of three, so . The features return , the wrong sign. With Min to move, the exact Max-value is +1 while the estimate is . Both values reverse sign; the pile size alone is insufficient.
- At depth 2, removing one is estimated at , which is greater than the alternative’s exact loss value . Ranking them correctly does not require an exact prediction. With eight stones, changing depth changes the frontier. The error proof compares two evaluations on one fixed tree and cutoff, so it promises no monotonic relationship between those different searches.
- The exact gap is 0.6, greater than twice 0.2, so the better action remains strictly preferred. At error bound 0.3, the estimates can both be 0.7. The strict guarantee is gone; a tie rule can choose the worse action.
- The two rows share the same game structure and have opposite labels. Keep them together, and check for other state duplicates. For each test state, compare the exact value after the chosen action with its exact starting value from the mover’s perspective. Count lost winning positions and report mean regret alongside static prediction error. Retain cases with large errors and surprising ties for inspection.
Make evaluation claims falsifiable
Shannon’s 1950 paper separates approximate positional scores from exact win/draw/loss values and presents illustrative feature coefficients. Their historical role does not make them ground-truth chess utilities. This chapter uses an original subtraction-game evaluator precisely because every sign, terminal case and choice can be checked against a complete finite solution. Shannon, section 3
The accompanying tests compare the exact table with an independent Boolean winning-state construction and the proved remainder rule. They exercise terminal precedence, perspective reversal, fixed-frontier error bounds, the strict action-gap condition, scaling errors and the published small tables. Such finite checks support this teaching model; they do not establish a universal error bound for a learned evaluator, reproduce a chess engine, or supply independent human peer review.
Make a prediction, then check
In a fixed game tree, two actions have exact values1 and0.4, each with estimation error at most0.2. Will Max still prefer the better action?
Learning objectives
- Separate terminal utility from frontier estimates, reconcile mover and Max perspectives, and audit feature weights and score units.
- Verify value error, move regret and fixed-frontier stability in a solved finite game, and organize held-out validation by game state.
Prerequisites & connections
Explore related knowledge →References
- CS188 — 3.2 Minimax
University of California, Berkeley; CS188 course staff - Programming a Computer for Playing Chess
Claude E. Shannon · 1950
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable examples, independent finite-game oracles, bilingual review and a second Codex agent cross-check; not independent human peer review.
- Codex technical check: independently reread the migrated bilingual articles, confirming five display equations, identical complete Python code, six anchors and four answers. Verified nonexpansion of uniform error under fixed-frontier max/min backups, the strictly-greater-than-2ε action-gap condition, and the distinction between mean error and a uniform frontier bound.
- Eight checks passed using the published source paths: 61 pile sizes and both turns against independent Boolean winning states and the modulo-3 rule; terminal priority, features and perspective, four/eight-stone counterexamples, uniform errors, strict gaps, all-leaf affine transforms, inconsistent scales, evaluation tables and invalid inputs. Tests now extract code only from the repository article paths, without a draft fallback.
- Separately recomputed the 13–18-pile slice from modulo-3 values: static MAE 38846497/39070080, maximum 97/64; depths 1/2/3 each have four blunders and mean regret 2/3, while depth 18 has zero for both. At eight stones, depth-2 action values are −13/28 and −9/20, choosing two; depth-3 values are 9/20 and 5/12, choosing one and losing a forced win.
- Both repository MDX articles compiled individually with the current compiler and remark-math. Initial compilation exposed a paragraph-closing error from details/summary tags sharing one line; split those opening tags in both languages while preserving every answer, then reran all eight checks successfully. Stock-phrase scan passed and stale draft-test wording was removed.
- Articles and tests were migrated to their repository directories; original drafts remain intact and frontmatter stays review:written. Shared registries, counters and review records were not changed, and whole-site check/build were not run. This is an AI technical check, not independent human peer review.
- Migration exposed an MDX compilation error from adjacent details/summary opening tags on one line. Split them in both languages, preserving code, formulas and answer content; recompilation and topic checks passed.
- A second AI agent reread Shannon 1950 sections 3, 4, 6 and its first page, independently recomputing the 12-state MAE as 38846497/39070080 and maximum error 97/64. Another cross-check covered 1,296 leaf perturbations. Root reread the English fixed-frontier error conditions and score-scale counterexample.
- All 79 search checks, 105 article Python programs and the prose scan passed. Migration-stage written-status notes describe that earlier phase; this record registers the checked files after source review and binds their current hashes. All reviews are AI technical checks, not independent human peer review.
- An actual 390px screenshot showed long first-table headers compressed into single-character columns. Shortened both locales’ headers and explicitly defined action values, removal count and optimal-play outcomes immediately above. All numbers, formulas, code and exercises are unchanged; root reread before updating hashes.
Source locations checked:
- CS188 — 3.2 Minimax · Read section3.2.2 lines127–139: horizon estimates, loss of exact-play guarantee and linear feature construction; terminal definition at lines94–96. Original subtraction-game features and error proofs derived separately.
- Programming a Computer for Playing Chess · Read PDF pages5–7, sections3–4, for approximate versus categorical evaluation and unfinished-exchange caveat; PDF pages12–13, section6, for quasi-stability, forcing variations and depth caps. The teaching game is not general Nim; no original invention-priority claim or chess performance claim made. Migration review independently reopened the museum-hosted18-page PDF after local/tmp research lookup found only unrelated1938 material; rechecked page1 metadata, pages5–7 (§3–4), pages12–13 (§6), and the explicit extension cap at PDF13 lines467–468. Source text, figures and code were not copied.
Related topics