Chess: Random Play and Alpha–Beta Search

An adversarial search companion to Lecture 22

Author

Marcel Turcotte

This optional self-study notebook accompanies Lecture 22. We compare a random player with depth-limited alpha–beta search, using weighted piece counting to evaluate unfinished positions. We then investigate move ordering, search depth, an optional time budget, and a limitation of the material heuristic, in that order.

The Lecture 16 companion used chess movement rules for a one-sided puzzle: White moved repeatedly, and Black never replied. Here, both players choose moves, kings are present, and ordinary legal chess moves apply. The opponent’s possible replies are part of the search.

By the end, we will be able to:

The chess ideas we need

The library supplies the legal moves and identifies game endings. The experiments use a few chess terms:

Term Meaning
Capture Remove an opponent’s piece by making a legal move.
Material The pieces a player still has, counted using their weights.
Check A king is under attack.
Checkmate A king is under attack and there is no legal way to save it. The other player wins.
Stalemate A player has no legal move, but their king is not under attack. The game is drawn.

White takes the first turn, followed by Black. The algorithms can play either colour. Squares are named by column (a to h) and row (1 to 8), as marked on the boards. For example, d8 identifies one square.

Setup

The notebook runs independently of the lecture notebook. In your own Python environment, install the dependencies once, then select that environment’s kernel. The package named chess provides the python-chess library.

python -m pip install chess resvg-py ipykernel
from dataclasses import dataclass
from itertools import combinations
import math
import random
from time import perf_counter

import chess
import chess.svg
import resvg_py
from IPython.display import Image, display

SEED = 4106
Chessboard and compact table display helpers
def board_image(position, size=360, lastmove=None):
    """Return a PNG chessboard, as in the Lecture 16 companion."""
    svg = chess.svg.board(board=position, size=size, lastmove=lastmove)
    png = resvg_py.svg_to_bytes(svg_string=svg)
    return Image(data=png, width=size)


def boards_image(positions, size=240, gap=12):
    """Display labelled boards together in one compact PNG."""
    width = len(positions) * (size + gap) - gap
    parts = [
        f'<svg xmlns="http://www.w3.org/2000/svg" '
        f'width="{width}" height="{size + 32}">',
        '<rect width="100%" height="100%" fill="white"/>',
    ]
    for index, (name, position) in enumerate(positions.items()):
        x = index * (size + gap)
        parts.append(
            f'<text x="{x + size / 2}" y="21" '
            f'font-family="sans-serif" font-size="17" '
            f'text-anchor="middle">{name}</text>'
        )
        board_svg = chess.svg.board(board=position, size=size)
        parts.append(
            board_svg.replace('<svg ', f'<svg x="{x}" y="32" ', 1)
        )
    parts.append('</svg>')
    png = resvg_py.svg_to_bytes(svg_string="".join(parts))
    return Image(data=png, width=width)


def describe_move(position, move):
    """Name the piece and squares without requiring chess notation."""
    piece = position.piece_at(move.from_square)
    name = chess.piece_name(piece.piece_type)
    start = chess.square_name(move.from_square)
    end = chess.square_name(move.to_square)
    action = "captures" if position.is_capture(move) else "to"
    description = f"{name} {start} {action} {end}"
    if move.promotion:
        description += f", promotes to {chess.piece_name(move.promotion)}"
    return description


def print_table(rows, columns):
    """Print a small table that also survives notebook and PDF export."""
    widths = [len(column) for column in columns]
    for row in rows:
        for index, column in enumerate(columns):
            widths[index] = max(widths[index], len(str(row[column])))

    def line(values):
        return " | ".join(
            str(value).ljust(width)
            for value, width in zip(values, widths)
        )

    print(line(columns))
    print("-+-".join("-" * width for width in widths))
    for row in rows:
        print(line([row[column] for column in columns]))

What should the search evaluate?

All scores use White’s perspective: White maximizes and Black minimizes. This corresponds to the fixed X perspective in Lecture 22.

For nonterminal positions, count each side’s material using conventional, approximate piece values. Scores are expressed in pawn units: one pawn has weight 1.

Piece Pawn Knight Bishop Rook Queen
Weight 1 3 3 5 9

If N_W(p,s) and N_B(p,s) count pieces of type p, our heuristic is

h_W(s)=\sum_p w_p\bigl(N_W(p,s)-N_B(p,s)\bigr).

These weights are a simple baseline, not an exact measure of a position’s strength. Kings are omitted: they cannot be captured in legal chess, and checkmate is handled as a terminal outcome.

PIECE_VALUES = {
    chess.PAWN: 1,
    chess.KNIGHT: 3,
    chess.BISHOP: 3,
    chess.ROOK: 5,
    chess.QUEEN: 9,
}


def material_score(position):
    """Weighted White material minus weighted Black material."""
    return sum(
        weight * (
            len(position.pieces(piece_type, chess.WHITE))
            - len(position.pieces(piece_type, chess.BLACK))
        )
        for piece_type, weight in PIECE_VALUES.items()
    )


assert material_score(chess.Board()) == 0

Can material alone distinguish an active piece from an inactive one? What about two positions with the same pieces but different king safety? Keep these limitations in mind when interpreting the games.

A nonterminal score of zero means equal weighted material, not a drawn game. A score of +9 means White is ahead by nine pawn units, not that White is certain to win. Terminal outcomes are handled separately below.

Terminal utility and the depth limit

A ply is one player’s move. Depth 2 considers our move and the opponent’s reply. It does not mean two moves by each player.

Where the search stops Score returned, from White’s perspective
White wins +1000
Black wins -1000
Draw 0
Nonterminal depth cutoff Weighted material, h_W(s)

The win/loss scores dominate every possible material score. Their magnitude is a utility convention, not a prediction of how many pieces will be won. Test for a terminal outcome before applying the depth cutoff. A checkmate at the horizon is still a checkmate.

We use position.outcome() to ask the library whether a game has ended. The same game-ending rules apply in searches and matches. The appendix records the detailed draw rules.

The helper below supports three move orders: the library’s generated order, a seeded shuffle, and captures before non-captures. It changes which legal move is examined first, not which moves are allowed. We will compare these orders after the baseline tournament.

Generated, shuffled, and captures-first move orders
def ordered_moves(position, ordering, rng, shuffle=False):
    """Order legal moves without changing the position."""
    moves = list(position.legal_moves)
    if shuffle or ordering == "shuffled":
        rng.shuffle(moves)
    if ordering == "captures":
        moves.sort(key=position.is_capture, reverse=True)
    return moves
WIN_SCORE = 1000


@dataclass
class SearchStats:
    nodes: int = 0
    evaluations: int = 0


class SearchTimeout(Exception):
    """Stop an iteration while retaining its work counts."""
    def __init__(self, stats):
        super().__init__("The search time budget expired.")
        self.stats = stats


def alpha_beta(
    position, depth, alpha, beta, evaluate, stats,
    ordering="generated", rng=None, deadline=None,
):
    """Return a depth-limited value from White's perspective."""
    if deadline is not None and perf_counter() >= deadline:
        raise SearchTimeout(stats)
    stats.nodes += 1
    outcome = position.outcome()
    if outcome is not None:
        if outcome.winner is None:
            return 0
        return WIN_SCORE if outcome.winner == chess.WHITE else -WIN_SCORE

    if depth == 0:
        stats.evaluations += 1
        return evaluate(position)

    if position.turn == chess.WHITE:
        value = -math.inf
        for move in ordered_moves(position, ordering, rng):
            position.push(move)
            try:
                child_value = alpha_beta(
                    position, depth - 1, alpha, beta, evaluate, stats,
                    ordering, rng, deadline,
                )
            finally:
                position.pop()
            value = max(value, child_value)
            alpha = max(alpha, value)
            if alpha >= beta:
                break
        return value

    value = math.inf
    for move in ordered_moves(position, ordering, rng):
        position.push(move)
        try:
            child_value = alpha_beta(
                position, depth - 1, alpha, beta, evaluate, stats,
                ordering, rng, deadline,
            )
        finally:
            position.pop()
        value = min(value, child_value)
        beta = min(beta, value)
        if alpha >= beta:
            break
    return value

push() applies a move; the matching pop() restores the previous state. This avoids copying the board at every node and retains the history needed for repetition rules. The finally blocks restore the board even when a time limit interrupts the search. deadline=None leaves the fixed-depth examples untimed; the optional time-budget experiment uses this parameter. Unlike the one-sided puzzle, piece placement alone is not a complete state: the turn, castling rights, en-passant information, move counters, and relevant history can affect future play.

Alpha and beta are inherited by recursive calls. Only the root starts with an unbounded window. The selected move order is used throughout the tree. The search does not reuse results from earlier visits to a position or continue beyond the configured depth limit.

Two players, one move-selection interface

Both players implement select_move(position). It returns a move and a few statistics without changing the supplied position.

The random player samples uniformly from legal moves. The alpha–beta player evaluates every root move unless a later search proves some of its descendants irrelevant. In matches, it shuffles the root moves with its own seeded generator before applying the selected order. It keeps the first strictly best move. With captures-first ordering, the shuffle varies ties within the capture and non-capture groups. Controlled ordering comparisons disable this extra root shuffle.

Random and alpha–beta players
@dataclass
class MoveChoice:
    move: chess.Move
    value: float | None = None
    nodes: int = 0
    evaluations: int = 0


class RandomPlayer:
    def __init__(self, seed):
        self.rng = random.Random(seed)

    def select_move(self, position):
        """Choose a move without changing the nonterminal position."""
        moves = list(position.legal_moves)
        return MoveChoice(self.rng.choice(moves))


class AlphaBetaPlayer:
    def __init__(
        self, seed, depth=2, evaluate=material_score,
        ordering="generated", shuffle_root=True,
    ):
        if depth < 1:
            raise ValueError("Search depth must be at least one ply.")
        if ordering not in ("generated", "shuffled", "captures"):
            raise ValueError("Unknown move order.")
        self.rng = random.Random(seed)
        self.depth = depth
        self.evaluate = evaluate
        self.ordering = ordering
        self.shuffle_root = shuffle_root

    def select_move(self, position, deadline=None):
        """Search a nonterminal position without changing it."""
        moves = ordered_moves(
            position, self.ordering, self.rng, self.shuffle_root
        )
        maximizing = position.turn == chess.WHITE
        best_value = -math.inf if maximizing else math.inf
        best_move = None
        alpha, beta = -math.inf, math.inf
        stats = SearchStats(nodes=1)  # Include the root.

        for move in moves:
            position.push(move)
            try:
                value = alpha_beta(
                    position, self.depth - 1, alpha, beta,
                    self.evaluate, stats, self.ordering, self.rng,
                    deadline,
                )
            finally:
                position.pop()

            if (maximizing and value > best_value) or (
                not maximizing and value < best_value
            ):
                best_value, best_move = value, move

            if maximizing:
                alpha = max(alpha, best_value)
            else:
                beta = min(beta, best_value)

        return MoveChoice(
            best_move, best_value, stats.nodes, stats.evaluations
        )

The evaluate argument makes the cutoff heuristic replaceable. Terminal outcomes and alpha–beta’s decision rule remain separate from that choice.

Predict: should White capture the rook?

This position has four pieces: White’s queen on d1 and king on e1, and Black’s rook on d8 and king on e8. What will a one-ply search choose? Could looking one reply deeper change that choice?

Build the four-piece position
trap = chess.Board("3rk3/8/8/8/8/8/8/3QK3 w - - 0 1")
display(board_image(trap))

lookahead_results = []
for depth in (1, 2):
    player = AlphaBetaPlayer(seed=SEED, depth=depth)
    choice = player.select_move(trap)
    lookahead_results.append({
        "plies": depth,
        "move": describe_move(trap, choice.move),
        "value": choice.value,
        "nodes": choice.nodes,
    })

print_table(lookahead_results, ["plies", "move", "value", "nodes"])
plies | move                 | value | nodes
------+----------------------+-------+------
1     | queen d1 captures d8 | 9     | 21   
2     | queen d1 to a4       | 4     | 44   

At depth 1, White’s queen moves straight from d1 to d8 and captures Black’s rook. The remaining pieces give White an apparent advantage of 9. Looking one reply deeper reveals the problem: Black’s king can move from the neighbouring square e8 to d8 and capture White’s queen. Only the kings remain, and the library recognizes a draw. Keeping both the queen and rook on the board can instead retain White’s advantage of 9-5=4.

The deeper search has not changed the heuristic. It applies that heuristic after considering the opponent’s reply. A similar problem can occur at any fixed horizon when an important continuation lies just beyond it.

The folded checks also use a nine-piece position where one move wins by checkmate, in both colour orientations, and a three-piece stalemate. These are individual correctness checks, not tournament games.

Check score signs, terminal outcomes, and state restoration
assert material_score(trap) == 4
assert material_score(trap.mirror()) == -4
assert lookahead_results[0]["move"] == "queen d1 captures d8"
assert lookahead_results[0]["value"] == 9
assert lookahead_results[1]["value"] == 4

mate_in_one = chess.Board("6k1/5ppp/8/8/8/8/5PPP/3R2K1 w - - 0 1")
for position in (mate_in_one, mate_in_one.mirror()):
    initial_fen = position.fen()
    initial_history = list(position.move_stack)
    moving_colour = position.turn
    choice = AlphaBetaPlayer(seed=SEED, depth=1).select_move(position)
    assert position.fen() == initial_fen
    assert position.move_stack == initial_history
    position.push(choice.move)
    assert position.outcome().winner == moving_colour
    expected = WIN_SCORE if moving_colour == chess.WHITE else -WIN_SCORE
    assert alpha_beta(
        position, 0, -math.inf, math.inf, material_score, SearchStats()
    ) == expected

stalemate = chess.Board("7k/5K2/6Q1/8/8/8/8/8 b - - 0 1")
assert material_score(stalemate) == 9
assert alpha_beta(
    stalemate, 0, -math.inf, math.inf, material_score, SearchStats()
) == 0
print("Search checks passed.")
Search checks passed.

Playing a game

The runner alternates turns and stops at an automatic game outcome or at max_plies additional plies after the starting position. Reaching this experimental limit produces an unfinished game, recorded as *. A material advantage at that point is not a chess victory.

We count recursive search calls, including roots, terminal positions, and repeated states. Heuristic evaluations count only nonterminal cutoff states. The random player performs no recursive search, so its search counters are zero.

Alternate moves and record the outcome and computational effort
def play_game(start, white, black, max_plies=120):
    position = start.copy()  # Keep any opening history.
    players = {chess.WHITE: white, chess.BLACK: black}
    totals = {
        colour: {
            "moves": 0, "nodes": 0,
            "evaluations": 0, "seconds": 0.0,
        }
        for colour in players
    }
    plies = 0
    for _ in range(max_plies):
        if position.outcome() is not None:
            break
        colour = position.turn
        before = perf_counter()
        choice = players[colour].select_move(position)
        totals[colour]["seconds"] += perf_counter() - before
        totals[colour]["moves"] += 1
        totals[colour]["nodes"] += choice.nodes
        totals[colour]["evaluations"] += choice.evaluations
        assert choice.move in position.legal_moves
        position.push(choice.move)
        plies += 1

    outcome = position.outcome()
    record = {
        "result": outcome.result() if outcome else "*",
        "reason": (
            outcome.termination.name.lower().replace("_", " ")
            if outcome else "move limit"
        ),
        "winner": outcome.winner if outcome else None,
        "plies": plies,
        "white_moves": totals[chess.WHITE]["moves"],
        "black_moves": totals[chess.BLACK]["moves"],
        "white_nodes": totals[chess.WHITE]["nodes"],
        "black_nodes": totals[chess.BLACK]["nodes"],
        "white_evaluations": totals[chess.WHITE]["evaluations"],
        "black_evaluations": totals[chess.BLACK]["evaluations"],
        "white_seconds": totals[chess.WHITE]["seconds"],
        "black_seconds": totals[chess.BLACK]["seconds"],
        "start_fen": start.fen(),
    }
    return record, position

A small tournament

Predict: will looking ahead always beat random moves? Is having more valuable pieces remaining enough to win by checkmate?

We compare two computer players. Random chooses an allowed move at random. AB-material uses alpha–beta search and weighted piece counting. At depth 2, it considers its candidate move and the opponent’s possible reply on every turn.

We use three starting boards, each with all 32 pieces. Each board is used twice, with the algorithms exchanging colours. White moves first; the colours identify roles in the game, not particular algorithms.

Starting board Random is White; alpha–beta is Black Alpha–beta is White; Random is Black
Initial Game 1 Game 2
Open game Game 3 Game 4
Queen’s pawn Game 5 Game 6

This produces six games, with one game for each board/colour assignment. There are no additional repetitions in this first experiment. The three boards provide variety; they are not a representative sample of chess.

Setting Meaning
SEARCH_DEPTH = 2 Consider one candidate move and one opponent reply.
MAX_PLIES = 120 Allow at most 120 additional individual moves in total, counting both players.

Each game creates fresh players with fixed, independent random seeds. The seeds control the random player’s choices and the searching player’s tie-breaking. Rerunning the same configuration reproduces the same six games and search counts; elapsed times vary.

SEARCH_DEPTH = 2
MAX_PLIES = 120

The folded setup creates the starting boards and the functions used to create fresh players. The opening sequences simply prepare the boards shown below; the algorithms choose the subsequent moves.

Starting positions and functions that create fresh players
OPENINGS = {
    "Initial": (),
    "Open game": ("e2e4", "e7e5", "g1f3", "b8c6"),
    "Queen's pawn": ("d2d4", "d7d5", "c2c4", "e7e6"),
}

PLAYER_FACTORIES = {
    "Random": RandomPlayer,
    "AB-material": lambda seed: AlphaBetaPlayer(
        seed=seed, depth=SEARCH_DEPTH, evaluate=material_score
    ),
}

Our three starting boards

All three boards have 32 pieces, and White moves next. In the last two boards, each side has already made two predetermined moves. No pieces have been captured. The computer players take over from these positions.

Build and display the three tournament starting boards
starting_positions = {}
for name, opening_moves in OPENINGS.items():
    position = chess.Board()
    for move in opening_moves:
        position.push_uci(move)
    assert len(position.piece_map()) == 32
    assert position.turn == chess.WHITE
    starting_positions[name] = position

display(boards_image(starting_positions))

Three labelled chessboards, each with all 32 pieces.

  • Initial: the normal starting position; no moves have been played.
  • Open game: a standard King’s Knight Opening position. Each side has advanced one pawn and moved one knight. Lichess opening classification.
  • Queen’s pawn: the Queen’s Gambit Declined. Each side has advanced two pawns. Lichess opening classification.

The opening names are labels for these starting boards. The comparisons require no knowledge of opening theory.

The runner below plays each colour-swapped pair. A player-creation function returns a new player with its own seed for each game.

Play each pairing in both colours from each starting position
def run_tournament(openings, factories, seed, max_plies):
    records, final_positions = [], []
    for opening_index, opening_name in enumerate(openings):
        start = chess.Board()
        for move in openings[opening_name]:
            start.push_uci(move)

        pairings = combinations(factories, 2)
        for pair_index, (first, second) in enumerate(pairings):
            for leg, (white_name, black_name) in enumerate(
                ((first, second), (second, first))
            ):
                game_seed = (
                    seed + 1000 * opening_index + 10 * pair_index + leg
                )
                white = factories[white_name](seed=2 * game_seed)
                black = factories[black_name](seed=2 * game_seed + 1)
                record, final_position = play_game(
                    start, white, black, max_plies
                )
                record.update({
                    "opening": opening_name,
                    "white": white_name,
                    "black": black_name,
                    "seed": game_seed,
                })
                records.append(record)
                final_positions.append(final_position)

    return records, final_positions

Reading the results

Result codes refer to White and Black, not to algorithm names:

Result Meaning
1-0 White won.
0-1 Black won.
1/2-1/2 The game was drawn.
* The experiment stopped before the game ended.

For example, if White is Random, Black is AB-material, and the result is 0-1, alpha–beta won. A reason of move limit means the game reached our experimental limit; it is unfinished, not a draw.

before = perf_counter()
records, final_positions = run_tournament(
    OPENINGS, PLAYER_FACTORIES, seed=SEED, max_plies=MAX_PLIES
)
print_table(
    records, ["opening", "white", "black", "result", "reason", "plies"]
)
print(f"\nTournament elapsed time: {perf_counter() - before:.2f} seconds")
opening      | white       | black       | result | reason    | plies
-------------+-------------+-------------+--------+-----------+------
Initial      | Random      | AB-material | 0-1    | checkmate | 36   
Initial      | AB-material | Random      | 1-0    | checkmate | 57   
Open game    | Random      | AB-material | 0-1    | checkmate | 30   
Open game    | AB-material | Random      | 1-0    | checkmate | 69   
Queen's pawn | Random      | AB-material | 0-1    | checkmate | 118  
Queen's pawn | AB-material | Random      | 1-0    | checkmate | 41   

Tournament elapsed time: 0.44 seconds

Outcomes and search work

An unfinished game is counted separately and contributes no completed-game points. Among completed games, a win earns one point and a draw half a point. Compare the number of completed games as well as the points.

Summarize outcomes and per-player search effort
def summarize_tournament(records, names):
    """Keep completed outcomes, truncations, and search cost separate."""
    standings, effort = [], []
    for name in names:
        row = {
            "player": name, "wins": 0, "draws": 0,
            "losses": 0, "unfinished": 0,
        }
        moves, nodes, evaluations, seconds = 0, 0, 0, 0.0
        for record in records:
            if name not in (record["white"], record["black"]):
                continue
            side = "white" if record["white"] == name else "black"
            colour = chess.WHITE if side == "white" else chess.BLACK
            moves += record[f"{side}_moves"]
            nodes += record[f"{side}_nodes"]
            evaluations += record[f"{side}_evaluations"]
            seconds += record[f"{side}_seconds"]
            if record["result"] == "*":
                row["unfinished"] += 1
            elif record["winner"] is None:
                row["draws"] += 1
            elif record["winner"] == colour:
                row["wins"] += 1
            else:
                row["losses"] += 1
        row["points"] = row["wins"] + 0.5 * row["draws"]
        standings.append(row)
        effort.append({
            "player": name,
            "moves": moves,
            "nodes": nodes,
            "evals": evaluations,
            "seconds": round(seconds, 3),
            "ms/move": round(1000 * seconds / moves, 3) if moves else 0,
        })
    return standings, effort
standings, effort = summarize_tournament(records, PLAYER_FACTORIES)
print_table(
    standings,
    ["player", "wins", "draws", "losses", "unfinished", "points"],
)
print()
print_table(
    effort,
    ["player", "moves", "nodes", "evals", "seconds", "ms/move"],
)
player      | wins | draws | losses | unfinished | points
------------+------+-------+--------+------------+-------
Random      | 0    | 0     | 6      | 0          | 0.0   
AB-material | 6    | 0     | 0      | 0          | 6.0   

player      | moves | nodes | evals | seconds | ms/move
------------+-------+-------+-------+---------+--------
Random      | 174   | 0     | 0     | 0.003   | 0.018  
AB-material | 177   | 29729 | 23189 | 0.436   | 2.461  

Here, nodes counts recursive search calls and evals counts nonterminal cutoff evaluations. ms/move is mean move-selection time in milliseconds.

These are observations from a small, fixed experiment, not an Elo estimate or a guarantee against every opponent. The search totals describe decisions made in these games, where the players encountered different positions. They are not a controlled measurement of pruning efficiency.

Inspect the first game

We display the starting and final boards of the first scheduled game, regardless of its outcome. This reuses a recorded game; it does not play another one. Compare which pieces remain and read the reported outcome. The appendix retains its full move record for readers who want to inspect individual moves.

Display the first game’s starting and final boards
example = records[0]
final_position = final_positions[0]
print(f"White: {example['white']}; Black: {example['black']}")
print("Starting position:")
display(board_image(chess.Board(example["start_fen"])))
print(f"Final position: {example['result']} ({example['reason']})")
last_move = final_position.peek() if final_position.move_stack else None
display(board_image(final_position, lastmove=last_move))
White: Random; Black: AB-material
Starting position:

Final position: 0-1 (checkmate)

Does move ordering change the answer or the work?

We now hold the position, depth, and evaluation function fixed while changing the order in which alpha–beta examines moves.

Predict: which quantities should agree: the value, the selected move, the number of visited nodes, and the elapsed time?

The three orders are:

  • generated: the library’s legal-move order;
  • shuffled: a seeded shuffle at every expanded node; and
  • captures: captures before non-captures, preserving the library’s order within each group.

A shuffled search order still uses alpha–beta to choose a move. It is different from the random player, which selects a legal move without search. For this comparison, shuffle_root=False disables the additional root shuffle used in matches, so each named order also applies at the root.

Same positions, same depth

Initial has all 32 pieces in their normal starting squares. Centre also has all 32 pieces, after each side advances a pawn and moves a knight and bishop. Trap reuses the four-piece queen-and-rook example. Each table row is one search, not a played game or an average over repeated searches.

centre = chess.Board()
for uci in ("e2e4", "e7e5", "g1f3", "b8c6", "f1c4", "f8c5"):
    centre.push_uci(uci)

ORDERING_POSITIONS = {
    "Initial": chess.Board(),
    "Centre": centre,
    "Trap": trap.copy(),
}
ORDERING_DEPTH = 3
Compare three move orders on the same positions
ordering_rows = []
for name, position in ORDERING_POSITIONS.items():
    values = []
    for ordering in ("generated", "shuffled", "captures"):
        player = AlphaBetaPlayer(
            seed=SEED, depth=ORDERING_DEPTH,
            ordering=ordering, shuffle_root=False,
        )
        before = perf_counter()
        choice = player.select_move(position)
        elapsed = perf_counter() - before
        values.append(choice.value)
        ordering_rows.append({
            "position": name,
            "order": ordering,
            "move": describe_move(position, choice.move),
            "value": choice.value,
            "nodes": choice.nodes,
            "evals": choice.evaluations,
            "ms": round(1000 * elapsed, 2),
        })
    assert len(set(values)) == 1

print_table(
    ordering_rows,
    ["position", "order", "move", "value", "nodes", "evals", "ms"],
)
position | order     | move            | value | nodes | evals | ms   
---------+-----------+-----------------+-------+-------+-------+------
Initial  | generated | knight g1 to h3 | 0     | 581   | 519   | 7.28 
Initial  | shuffled  | pawn b2 to b3   | 0     | 545   | 484   | 6.96 
Initial  | captures  | knight g1 to h3 | 0     | 581   | 519   | 6.97 
Centre   | generated | bishop c4 to d5 | 1     | 2500  | 2288  | 33.63
Centre   | shuffled  | king e1 to f1   | 1     | 2432  | 2285  | 31.11
Centre   | captures  | bishop c4 to d5 | 1     | 1495  | 1354  | 21.11
Trap     | generated | queen d1 to h5  | 4     | 913   | 816   | 12.07
Trap     | shuffled  | queen d1 to a4  | 4     | 706   | 648   | 9.32 
Trap     | captures  | queen d1 to h5  | 4     | 316   | 270   | 4.36 

The backed-up value agrees across the three orders at each position. Different moves can tie for that value, so the first best move returned may change. Search effort can change because earlier alternatives establish bounds that permit different cutoffs.

Captures-first is a cheap ordering heuristic, not a guarantee of fewer nodes on every position. Compare elapsed time as well as counts: ordering itself has a computational cost. At a fixed depth, ordering aims to save work while preserving the minimax value. Under a fixed time budget, those savings could allow a deeper search.

Does looking farther improve play?

Move ordering changes how much work is needed for a fixed-depth value. We now change the depth itself, keeping weighted material evaluation and captures-first ordering fixed.

Predict: will a deeper search choose the same move? Must its reported value increase? How much more computation will it require?

Inspect one decision at several depths

The next table performs one search at each of depths 2, 3, and 4 from each of our three starting positions. These are nine individual move searches, not nine games. All three positions retain the full 32-piece set, with White to move.

depth_rows = []
for name, opening_moves in OPENINGS.items():
    position = chess.Board()
    for move in opening_moves:
        position.push_uci(move)
    for depth in (2, 3, 4):
        player = AlphaBetaPlayer(
            seed=SEED, depth=depth, ordering="captures"
        )
        before = perf_counter()
        choice = player.select_move(position)
        seconds = perf_counter() - before
        depth_rows.append({
            "position": name,
            "plies": depth,
            "move": describe_move(position, choice.move),
            "value": choice.value,
            "nodes": choice.nodes,
            "evals": choice.evaluations,
            "ms": round(1000 * seconds, 1),
        })

print_table(
    depth_rows,
    ["position", "plies", "move", "value", "nodes", "evals", "ms"],
)
position     | plies | move                | value | nodes | evals | ms   
-------------+-------+---------------------+-------+-------+-------+------
Initial      | 2     | pawn b2 to b3       | 0     | 60    | 39    | 1.1  
Initial      | 3     | pawn b2 to b3       | 0     | 581   | 519   | 7.2  
Initial      | 4     | pawn b2 to b3       | 0     | 1470  | 944   | 24.4 
Open game    | 2     | pawn d2 to d3       | 0     | 116   | 88    | 2.0  
Open game    | 3     | pawn g2 to g3       | 1     | 1149  | 986   | 16.2 
Open game    | 4     | bishop f1 to b5     | 0     | 6283  | 4697  | 102.8
Queen's pawn | 2     | pawn c4 captures d5 | 0     | 95    | 64    | 1.9  
Queen's pawn | 3     | queen d1 to a4      | 1     | 1109  | 1005  | 14.4 
Queen's pawn | 4     | pawn e2 to e3       | -1    | 5006  | 3743  | 89.0 

Each depth evaluates a different truncated tree. Its reported value is not an accuracy score for the player. Increasing depth can expose a threat or remove an apparent opportunity, so neither the value nor playing strength is guaranteed to improve monotonically with an imperfect cutoff heuristic.

There is also an odd/even horizon effect. From the current player’s perspective, depth 2 stops after the opponent’s reply, while depth 3 can stop after our next capture but before the opponent’s recapture. Compare the values across depths before interpreting a one-ply increase as progress. Depths 2 and 4 both finish after an opponent reply.

Depth 2 against depth 3

The random player is a useful baseline, but it offers little discrimination once the searching player wins most games. We now compare two searching players, using the same heuristic and move-ordering rule.

We use all three 32-piece starting boards, swap colours, and repeat with distinct seeds. With the default two repeats, this gives twelve games. Each player searches to its configured depth on every turn. Increase DEPTH_REPEATS for a larger experiment; rerunning the same configuration reproduces the same games.

DEPTH_REPEATS = 2
Run colour-swapped depth comparisons with distinct seeds
def compare_depths(shallow_depth, deep_depth, repeats):
    factories = {
        f"AB-d{shallow_depth}": lambda seed: AlphaBetaPlayer(
            seed=seed, depth=shallow_depth, ordering="captures"
        ),
        f"AB-d{deep_depth}": lambda seed: AlphaBetaPlayer(
            seed=seed, depth=deep_depth, ordering="captures"
        ),
    }
    match_records = []
    for repeat in range(repeats):
        repeat_seed = SEED + 10000 * (repeat + 1)
        batch, _ = run_tournament(
            OPENINGS, factories, seed=repeat_seed,
            max_plies=MAX_PLIES,
        )
        for record in batch:
            record["repeat"] = repeat + 1
        match_records.extend(batch)
    return match_records, factories
depth_records, depth_factories = compare_depths(2, 3, DEPTH_REPEATS)
print_table(
    depth_records,
    ["repeat", "opening", "white", "black", "result", "reason", "plies"],
)
depth_standings, depth_effort = summarize_tournament(
    depth_records, depth_factories
)
print()
print_table(
    depth_standings,
    ["player", "wins", "draws", "losses", "unfinished", "points"],
)
print()
print_table(
    depth_effort,
    [
        "player", "moves", "nodes", "evals", "seconds", "ms/move",
    ],
)
repeat | opening      | white | black | result | reason     | plies
-------+--------------+-------+-------+--------+------------+------
1      | Initial      | AB-d2 | AB-d3 | *      | move limit | 120  
1      | Initial      | AB-d3 | AB-d2 | *      | move limit | 120  
1      | Open game    | AB-d2 | AB-d3 | 0-1    | checkmate  | 40   
1      | Open game    | AB-d3 | AB-d2 | 1-0    | checkmate  | 55   
1      | Queen's pawn | AB-d2 | AB-d3 | 0-1    | checkmate  | 118  
1      | Queen's pawn | AB-d3 | AB-d2 | 1-0    | checkmate  | 49   
2      | Initial      | AB-d2 | AB-d3 | 0-1    | checkmate  | 112  
2      | Initial      | AB-d3 | AB-d2 | *      | move limit | 120  
2      | Open game    | AB-d2 | AB-d3 | 0-1    | checkmate  | 68   
2      | Open game    | AB-d3 | AB-d2 | 1-0    | checkmate  | 89   
2      | Queen's pawn | AB-d2 | AB-d3 | 0-1    | checkmate  | 54   
2      | Queen's pawn | AB-d3 | AB-d2 | 1-0    | checkmate  | 53   

player | wins | draws | losses | unfinished | points
-------+------+-------+--------+------------+-------
AB-d2  | 0    | 0     | 9      | 3          | 0.0   
AB-d3  | 9    | 0     | 0      | 3          | 9.0   

player | moves | nodes  | evals  | seconds | ms/move
-------+-------+--------+--------+---------+--------
AB-d2  | 497   | 46797  | 37206  | 0.825   | 1.66   
AB-d3  | 501   | 903958 | 820543 | 13.126  | 26.2   

The deeper player receives a larger search horizon, generally requiring more computation. Interpret outcomes alongside search work and elapsed time. An unfinished game remains unfinished, even if one side has won material. These few games illustrate the trade-off; they do not establish an Elo rating or guarantee that the deeper player will always win.

Further experiment: depth 2 against depth 4

The switch below controls this longer comparison. Set RUN_DEPTH_FOUR to True to include it, or False to skip it. Depths 2 and 4 both finish after an opponent reply. The experiment’s complete code remains available below.

Enable the depth-two versus depth-four experiment
RUN_DEPTH_FOUR = True

if RUN_DEPTH_FOUR:
    deeper_records, deeper_factories = compare_depths(
        2, 4, DEPTH_REPEATS
    )
    print_table(
        deeper_records,
        [
            "repeat", "opening", "white", "black",
            "result", "reason", "plies",
        ],
    )
    deeper_standings, deeper_effort = summarize_tournament(
        deeper_records, deeper_factories
    )
    print()
    print_table(
        deeper_standings,
        ["player", "wins", "draws", "losses", "unfinished", "points"],
    )
    print()
    print_table(
        deeper_effort,
        [
            "player", "moves", "nodes", "evals", "seconds", "ms/move",
        ],
    )
else:
    print("Depth 2 versus depth 4 is available but was not run.")
repeat | opening      | white | black | result | reason     | plies
-------+--------------+-------+-------+--------+------------+------
1      | Initial      | AB-d2 | AB-d4 | 0-1    | checkmate  | 80   
1      | Initial      | AB-d4 | AB-d2 | *      | move limit | 120  
1      | Open game    | AB-d2 | AB-d4 | *      | move limit | 120  
1      | Open game    | AB-d4 | AB-d2 | 1-0    | checkmate  | 99   
1      | Queen's pawn | AB-d2 | AB-d4 | 0-1    | checkmate  | 68   
1      | Queen's pawn | AB-d4 | AB-d2 | *      | move limit | 120  
2      | Initial      | AB-d2 | AB-d4 | *      | move limit | 120  
2      | Initial      | AB-d4 | AB-d2 | *      | move limit | 120  
2      | Open game    | AB-d2 | AB-d4 | *      | move limit | 120  
2      | Open game    | AB-d4 | AB-d2 | 1-0    | checkmate  | 25   
2      | Queen's pawn | AB-d2 | AB-d4 | 0-1    | checkmate  | 88   
2      | Queen's pawn | AB-d4 | AB-d2 | 1-0    | checkmate  | 59   

player | wins | draws | losses | unfinished | points
-------+------+-------+--------+------------+-------
AB-d2  | 0    | 0     | 6      | 6          | 0.0   
AB-d4  | 6    | 0     | 0      | 6          | 6.0   

player | moves | nodes   | evals   | seconds | ms/move
-------+-------+---------+---------+---------+--------
AB-d2  | 568   | 49292   | 38726   | 0.881   | 1.552  
AB-d4  | 571   | 3055395 | 1986283 | 58.527  | 102.499

Further experiment: how deep can we search in 20 seconds?

Instead of choosing a depth in advance, suppose we allow 20 seconds to choose one move. How far can the same search look ahead? Will it reach the same depth from each starting board?

We use iterative deepening: search to depth 1, then 2, then 3, and so on. Keep the decision from the last fully completed iteration. If time expires during the next iteration, discard its partial result: some root moves may not have been examined. The earlier complete decision remains available. If even depth 1 does not finish, we report no completed decision.

The budget covers all iterations together, not 20 seconds at each depth. It is a budget per move decision, not a clock for an entire game. For an example of a chess interface with a time-per-move limit, see the python-chess engine documentation.

Predict: how much more time will each extra ply require? Could better move ordering allow a greater depth within the same budget?

The implementation below reuses our alpha–beta search. Its optional deadline is checked at each recursive call. A SearchTimeout exception stops the unfinished iteration; finally restores every pushed move as the calls return. Checking time only between depths could overrun the budget by the duration of an entire deeper search. Our checks allow a small overrun while the current operation finishes and the calls return.

Keep the last complete search before the deadline
def iterative_deepening(position, seconds):
    """Search a nonterminal board within one shared time budget."""
    if seconds <= 0:
        raise ValueError("The time budget must be positive.")
    started = perf_counter()
    deadline = started + seconds
    best_choice = None
    iterations = []

    while True:
        depth = len(iterations) + 1
        player = AlphaBetaPlayer(
            seed=SEED, depth=depth, ordering="captures",
            shuffle_root=False,
        )
        before = perf_counter()
        status = "complete"
        try:
            work = player.select_move(position, deadline=deadline)
            best_choice = work
        except SearchTimeout as timeout:
            status = "interrupted"
            work = timeout.stats

        iterations.append({
            "depth": depth,
            "status": status,
            "nodes": work.nodes,
            "evals": work.evaluations,
            "seconds": round(perf_counter() - before, 3),
        })
        if status == "interrupted":
            return best_choice, iterations, perf_counter() - started

The switch below enables three individual move searches, not three games: one from each of our 32-piece starting boards, with White to move. At 20 seconds per board, allow about one minute. Set RUN_TIME_BUDGET to True to include this experiment, or False to skip it and shorten the notebook run. The time budget remains visible when the helper code is folded.

RUN_TIME_BUDGET = True
BUDGET_SECONDS = 20
Measure completed depths under a per-position time limit
if RUN_TIME_BUDGET:
    budget_rows = []
    for name, position in starting_positions.items():
        choice, iterations, elapsed = iterative_deepening(
            position, BUDGET_SECONDS
        )
        print(f"\n{name}: {BUDGET_SECONDS} seconds for one decision")
        print_table(
            iterations, ["depth", "status", "nodes", "evals", "seconds"]
        )
        if choice is None:
            print("No depth completed; no move is reported.")
        else:
            print("Selected move:", describe_move(position, choice.move))
            print("Value from White's perspective:", choice.value)
        budget_rows.append({
            "position": name,
            "depth": len(iterations) - 1,
            "seconds": round(elapsed, 3),
            "nodes": sum(row["nodes"] for row in iterations),
            "evals": sum(row["evals"] for row in iterations),
        })

    print("\nLast complete depth; total work includes interruption:")
    print_table(
        budget_rows, ["position", "depth", "seconds", "nodes", "evals"]
    )
else:
    print("Set RUN_TIME_BUDGET = True to run the 20-second searches.")

Initial: 20 seconds for one decision
depth | status      | nodes  | evals  | seconds
------+-------------+--------+--------+--------
1     | complete    | 21     | 20     | 0.0    
2     | complete    | 60     | 39     | 0.001  
3     | complete    | 581    | 519    | 0.007  
4     | complete    | 1495   | 966    | 0.026  
5     | complete    | 21060  | 17978  | 0.286  
6     | complete    | 208037 | 158634 | 3.12   
7     | complete    | 797710 | 683105 | 10.816 
8     | interrupted | 392757 | 309691 | 5.743  
Selected move: knight g1 to f3
Value from White's perspective: 1

Open game: 20 seconds for one decision
depth | status      | nodes   | evals  | seconds
------+-------------+---------+--------+--------
1     | complete    | 28      | 27     | 0.0    
2     | complete    | 116     | 88     | 0.002  
3     | complete    | 1143    | 980    | 0.016  
4     | complete    | 4842    | 3726   | 0.076  
5     | complete    | 33619   | 28353  | 0.483  
6     | complete    | 250999  | 188519 | 4.166  
7     | interrupted | 1005966 | 824142 | 15.257 
Selected move: knight f3 to g1
Value from White's perspective: -1

Queen's pawn: 20 seconds for one decision
depth | status      | nodes   | evals   | seconds
------+-------------+---------+---------+--------
1     | complete    | 31      | 30      | 0.0    
2     | complete    | 95      | 64      | 0.002  
3     | complete    | 1109    | 1005    | 0.015  
4     | complete    | 5431    | 4130    | 0.095  
5     | complete    | 46547   | 42502   | 0.608  
6     | complete    | 159041  | 106706  | 3.271  
7     | interrupted | 1146800 | 1011482 | 16.008 
Selected move: pawn c4 captures d5
Value from White's perspective: -1

Last complete depth; total work includes interruption:
position     | depth | seconds | nodes   | evals  
-------------+-------+---------+---------+--------
Initial      | 7     | 20.0    | 1421721 | 1170952
Open game    | 6     | 20.0    | 1296713 | 1045835
Queen's pawn | 6     | 20.0    | 1359054 | 1165919

Each detailed row describes one attempted depth; the final row is interrupted. In the summary, depth is the last complete depth (0 means none completed). Total work includes the earlier completed searches and the discarded work from the interrupted iteration. We deliberately keep captures-first ordering fixed and disable root shuffling. This simple version starts each iteration afresh; it does not reuse earlier results to order later searches.

There is no single maximum reasonable depth. The result depends on the position, move ordering, evaluation cost, hardware, and other work running on the computer. A fixed seed cannot make a time-limited result identical across machines or even across runs. Also, completing depth d here does not show that a single search to depth d+1 from scratch could never fit the budget: iterative deepening spent some time on shallower searches.

Limits of this notebook. This is a readable teaching implementation, not an optimized chess engine. Python recursion, board operations, and repeated evaluation contribute overhead. The design also matters: we use one search thread, simple captures-first ordering, and no cache of earlier search results. Optimized engines combine efficient implementation with additional search techniques and stronger evaluation. Their reported depths can involve branches searched to different depths, so they should not be compared directly with our fixed-depth iterations; see Stockfish’s explanation of depth. Our timing results characterize this implementation on these boards; they are not a limit on alpha–beta search or a benchmark of Python alone. More time also does not remove every weakness of the material heuristic.

What does material fail to distinguish?

This final example uses three pieces: White’s king and queen, and Black’s king. There are no pawns or other pieces. White has a material advantage of 9.

Predict: can the material heuristic distinguish a move that restricts Black’s king from one that leaves it more freedom?

Build the three-piece ending
endgame = chess.Board("4k3/8/8/8/8/8/8/3QK3 w - - 0 1")
display(board_image(endgame))

Compare three legal, non-capturing moves. None gives check or ends the game. Because Black has only its king, its number of legal replies measures the king’s immediate freedom to move.

endgame_rows = []
for uci in ("d1c2", "d1d5", "e1e2"):
    move = chess.Move.from_uci(uci)
    name = describe_move(endgame, move)
    endgame.push(move)
    endgame_rows.append({
        "White move": name,
        "material": material_score(endgame),
        "Black replies": endgame.legal_moves.count(),
    })
    endgame.pop()

print_table(endgame_rows, ["White move", "material", "Black replies"])
White move     | material | Black replies
---------------+----------+--------------
queen d1 to c2 | 9        | 5            
queen d1 to d5 | 9        | 2            
king e1 to e2  | 9        | 3            

All three positions receive the same material score, although Black has different choices. The reply count is a diagnostic shown for discussion; it is not part of our evaluator. Fewer replies are not automatically better: zero legal replies without check would be stalemate, a draw.

Terminal utility still distinguishes checkmate from stalemate. Search can find a mate within its horizon, but material provides little guidance for making progress when the mate lies beyond that horizon.

A short continuation

Predict: will depth-two search win by checkmate within 24 individual moves? Use the same seed as before and play one short continuation, not a tournament.

Play one capped continuation from the three-piece ending
endgame_record, endgame_final = play_game(
    endgame,
    AlphaBetaPlayer(seed=SEED, depth=2, ordering="captures"),
    RandomPlayer(seed=SEED + 1),
    max_plies=24,
)
print_table(
    [endgame_record], ["result", "reason", "plies"]
)
print("Final material score:", material_score(endgame_final))
result | reason     | plies
-------+------------+------
*      | move limit | 24   
Final material score: 9

With these settings, the continuation is unfinished at the limit, even though White retains its material advantage. This is one reproducible observation; another seed or a deeper search may produce a different continuation.

What additional information could help the player recognize useful progress? Possible suggestions include how the pieces cooperate and how much space the opposing king can use. A richer evaluator, including a learned correction, can express preferences that material alone cannot.

Interpret and experiment

  1. Does the tournament support your prediction? Separate wins, draws, and unfinished games before drawing a conclusion.
  2. In the ordering comparison, which quantities stayed fixed and which changed? Did fewer visited nodes always translate into less elapsed time?
  3. Compare the values at depths 2, 3, and 4. Locate a possible capture and recapture. Why is a larger reported value not evidence of greater accuracy?
  4. Repeat the depth comparison with new seeds. Does the observed advantage persist? Keep the starting positions and other settings unchanged.
  5. In the optional time-budget experiment, does the last complete depth agree across the three boards? Try generated instead of captures ordering in the helper, holding the position and budget fixed.
  6. In the three-piece ending, what information could distinguish progress beyond material? A different evaluator can be passed to AlphaBetaPlayer without changing the search or tournament runner.

A material advantage does not tell the player how to coordinate its pieces, make progress when few pieces remain, or avoid every tactical trap beyond the cutoff. The experiment connects the lecture’s exact pruning argument with the practical limits of a depth-limited, heuristic-guided player.

Appendix

Complete game record

This is the first tournament game already shown above, not an additional game. PGN (Portable Game Notation) stores the complete move sequence. It is useful for replaying or exporting a game, but is unnecessary for interpreting the board displays and experiment tables.

The record includes the predetermined opening moves. The tournament’s move count starts after those moves. The result codes have the same meaning as in the main tables.

Export the first recorded game as PGN
import chess.pgn

pgn = chess.pgn.Game.from_board(final_positions[0])
pgn.headers["White"] = records[0]["white"]
pgn.headers["Black"] = records[0]["black"]
pgn.headers["Result"] = records[0]["result"]
pgn.headers["Termination"] = (
    "unterminated" if records[0]["result"] == "*" else "normal"
)
print(pgn)
[Event "?"]
[Site "?"]
[Date "????.??.??"]
[Round "?"]
[White "Random"]
[Black "AB-material"]
[Result "0-1"]
[Termination "normal"]

1. e3 c6 2. h3 d6 3. f3 b6 4. Na3 a5 5. Bb5 cxb5 6. d4 b4 7. Nb1 Bf5 8. a3 bxa3 9. c4 axb2 10. Qc2 bxa1=Q 11. Qd1 Bxb1 12. Qb3 Bf5 13. c5 Qxc1+ 14. Ke2 dxc5 15. Qa2 cxd4 16. Qa3 Qxa3 17. Kf1 dxe3 18. Ne2 Qd1# 0-1

Game-ending rules

position.outcome() recognizes automatic endings, including checkmate, stalemate, insufficient material, fivefold repetition, and the 75-move rule. The last two prevent some games from continuing indefinitely through repeated positions or long sequences without pawn moves or captures.

The players do not request optional threefold-repetition or 50-move draw claims. This is the same policy in searches and matches; it uses the library’s default claim_draw=False. See the python-chess outcome documentation.