Adversarial Search

CSI 4106 Introduction to Artificial Intelligence

Marcel Turcotte

Version: Dec 3, 2026 11:38

Preamble

Message of the Day

Learning objectives

  • Identify the assumptions and utility convention of a two-player game.
  • Predict minimax choices and explain their worst-case guarantee.
  • Trace alpha–beta bounds and justify when a branch can be skipped.
  • Compare search effort on the same position, with the same move ordering.
  • Explain why larger games require limited search and state evaluation.

Core Game Framework

Motivation

Tic-tac-toe lets us compare random play, minimax, and alpha–beta pruning in a game we can solve completely. The next lecture uses the same interface for Monte Carlo Tree Search (MCTS).

  • Game: the rules, legal moves, transitions, and outcome.
  • Solver: the choice of a move.
  • GameRunner: alternating turns and recording the outcome.

Game

Code
class Game:

    """
    Abstract interface for a deterministic, 2-player, zero-sum,
    turn-taking game.

    Conventions (used by Tic-Tac-Toe and the solvers below):
    - Players are identified by strings "X" and "O".
    - evaluate(state) returns:
        > 0  if the position is good for "X"
        < 0  if the position is good for "O"
        == 0 for a draw or non-terminal equal position
    """

    def initial_state(self):

        """Return an object representing the starting position of the game."""

        raise NotImplementedError

    def get_valid_moves(self, state):

        """
        Given a state, return an iterable of legal moves.
        The type of 'move' is game-dependent (e.g., (row, col) for Tic-Tac-Toe).
        """

        raise NotImplementedError

    def make_move(self, state, move, player):

        """
        Return the successor state obtained by applying 'move' for 'player'
        to 'state'. The original state should not be modified in-place.
        """

        raise NotImplementedError

    def get_opponent(self, player):

        """Return the opponent of 'player'."""

        raise NotImplementedError

    def is_terminal(self, state):

        """
        Return True if 'state' is a terminal position (win, loss, or draw),
        False otherwise.
        """

        raise NotImplementedError

    def evaluate(self, state):

        """
        Return a scalar evaluation of 'state':
            +1 for X win, -1 for O win, 0 otherwise (for Tic-Tac-Toe).
        For other games this may be generalized, but here we keep it simple.
        """

        raise NotImplementedError

    def display(self, state):

        """Print a human-readable representation of 'state' (for debugging)."""

        raise NotImplementedError

Game

class Game:

    def initial_state(self):
        raise NotImplementedError

    def get_valid_moves(self, state):
        raise NotImplementedError

    def make_move(self, state, move, player):
        raise NotImplementedError

    def get_opponent(self, player):
        raise NotImplementedError

    def is_terminal(self, state):
        raise NotImplementedError

    def evaluate(self, state):
        raise NotImplementedError

    def display(self, state):
        raise NotImplementedError

Required Libraries

import math
import random
import numpy as np
import matplotlib.pyplot as plt

TicTacToe

Code
class TicTacToe(Game):

    """
    Classic 3x3 Tic-Tac-Toe implementation using a NumPy array of strings.
    Empty squares are represented by " ".
    Player "X" is assumed to be the maximizing player.
    """

    def __init__(self):
        self.size = 3

    def initial_state(self):

        """Return an empty 3x3 board."""

        return np.full((self.size, self.size), " ")

    def get_valid_moves(self, state):

        """All (i, j) pairs where the board cell is empty."""

        return [
            (i, j)
            for i in range(self.size)
            for j in range(self.size)
            if state[i, j] == " "
        ]

    def make_move(self, state, move, player):

        """
        Return a new board with 'player' placed at 'move' (row, col).
        The original state is not modified.
        """

        new_state = state.copy()
        new_state[move] = player
        return new_state

    def get_opponent(self, player):

        """Swap player labels between 'X' and 'O'."""

        return "O" if player == "X" else "X"

    def is_terminal(self, state):

        """
        A state is terminal if:
        - Either player has a 3-in-a-row (evaluate != 0), or
        - There are no empty squares left (draw).
        """

        if self.evaluate(state) != 0:
            return True
        return " " not in state

    def evaluate(self, state):

        """
        Return +1 if X has three in a row, -1 if O has three in a row,
        and 0 otherwise (including non-terminal states and draws).

        This is a "game-theoretic" evaluation at terminal states; for
        non-terminal positions we simply return 0.
        """

        lines = []

        # Rows and columns
        for i in range(self.size):
            lines.append(state[i, :])   # row i
            lines.append(state[:, i])   # column i

        # Main diagonals
        lines.append(np.diag(state))
        lines.append(np.diag(np.fliplr(state)))

        # Check each line for a win
        for line in lines:
            if np.all(line == "X"):
                return 1
            if np.all(line == "O"):
                return -1
        return 0

    def display(self, state):

        """
        Visualize a Tic-Tac-Toe board using matplotlib.

        Parameters
        ----------
        state : np.ndarray of shape (size, size)
            Board containing ' ', 'X', or 'O'.
        """

        size = self.size

        fig, ax = plt.subplots()
        ax.set_aspect('equal')
        ax.set_xlim(0, size)
        ax.set_ylim(0, size)

        # Draw grid lines
        for i in range(1, size):
            ax.axhline(i, color='black')
            ax.axvline(i, color='black')

        # Hide axes completely
        ax.axis('off')

        # Draw X and O symbols
        for i in range(size):
            for j in range(size):
                cx = j + 0.5
                cy = size - i - 0.5     # invert y-axis for correct row orientation

                symbol = state[i, j]

                if symbol == "X":
                    ax.plot(cx, cy, marker='x',
                            markersize=40 * (3/size),
                            color='blue',
                            markeredgewidth=3)
                elif symbol == "O":
                    circle = plt.Circle((cx, cy),
                                        radius=0.30 * (3/size),
                                        fill=False,
                                        color='red',
                                        linewidth=3)
                    ax.add_patch(circle)

        plt.show()

TicTacToe

class TicTacToe(Game):

    """
    Classic 3x3 Tic-Tac-Toe implementation using a NumPy array of strings.
    Empty squares are represented by " ".
    Player "X" is assumed to be the maximizing player.
    """

    def __init__(self):
        self.size = 3

initial_state

    def initial_state(self):

        """Return an empty 3x3 board."""

        return np.full((self.size, self.size), " ")

get_valid_moves

    def get_valid_moves(self, state):

        """All (i, j) pairs where the board cell is empty."""

        return [
            (i, j)
            for i in range(self.size)
            for j in range(self.size)
            if state[i, j] == " "
        ]

make_move

    def make_move(self, state, move, player):

        """
        Return a new board with 'player' placed at 'move' (row, col).
        The original state is not modified.
        """

        new_state = state.copy()
        new_state[move] = player

        return new_state

get_opponent

    def get_opponent(self, player):

        """Swap player labels between 'X' and 'O'."""

        return "O" if player == "X" else "X"

evaluate


    def evaluate(self, state):

        lines = []

        # Rows and columns
        for i in range(self.size):
            lines.append(state[i, :])   # row i
            lines.append(state[:, i])   # column i

        # Main diagonals
        lines.append(np.diag(state))
        lines.append(np.diag(np.fliplr(state)))

        # Check each line for a win
        for line in lines:
            if np.all(line == "X"):
                return 1
            if np.all(line == "O"):
                return -1
        return 0

is_terminal

    def is_terminal(self, state):

        """
        A state is terminal if:
        - Either player has a 3-in-a-row (evaluate != 0), or
        - There are no empty squares left (draw).
        """

        if self.evaluate(state) != 0:
            return True
        return " " not in state

display

    def display(self, state):

        """
        Visualize a Tic-Tac-Toe board using matplotlib.

        Parameters
        ----------
        state : np.ndarray of shape (size, size)
            Board containing ' ', 'X', or 'O'.
        """

        size = self.size

        fig, ax = plt.subplots()
        ax.set_aspect('equal')
        ax.set_xlim(0, size)
        ax.set_ylim(0, size)

        # Draw grid lines
        for i in range(1, size):
            ax.axhline(i, color='black')
            ax.axvline(i, color='black')

        # Hide axes completely
        ax.axis('off')

        # Draw X and O symbols
        for i in range(size):
            for j in range(size):
                cx = j + 0.5
                cy = size - i - 0.5     # invert y-axis for correct row orientation

                symbol = state[i, j]

                if symbol == "X":
                    ax.plot(cx, cy, marker='x',
                            markersize=40 * (3/size),
                            color='blue',
                            markeredgewidth=3)
                elif symbol == "O":
                    circle = plt.Circle((cx, cy),
                                        radius=0.30 * (3/size),
                                        fill=False,
                                        color='red',
                                        linewidth=3)
                    ax.add_patch(circle)

        plt.show()

Solver

Code
class Solver:

    """
    Base class for all solvers (Random, Minimax, AlphaBeta, MCTS, etc.).

    Solvers must implement:
        - select_move(game, state, player)

    Solvers may optionally implement:
        - reset()           : called at the start of each game
        - opponent_played() : used by persistent solvers (e.g., MCTS)

    Notes
    -----
    - Solvers may retain analysis across moves within one game.
    - GameRunner calls reset() before every match.
    - A reset clears game-local state. Reusable exact analysis and random
      generator state may remain when this is intentional and valid.
    """

    def select_move(self, game, state, player):

        """
        Must be implemented by subclasses.
        Returns a legal move for the given player.
        """

        raise NotImplementedError

    def get_name(self):

        """
        Return the solver's name for reporting, logging, or tournament results.

        The default returns the class name, but solvers may override
        to include parameters (e.g., "MCTS(num_simulations=500)"").
        """
        
        return self.__class__.__name__

    def opponent_played(self, move):
        """
        Optional. Called after the opponent moves.
        Useful for stateful solvers like MCTS.
        Stateless solvers can ignore it.
        """
        pass

    def reset(self):

        """
        Called by GameRunner at the beginning of each game.
        Override to clear game-local state, such as search counters or a
        game-specific tree. Preserve reusable analysis or the random stream
        only when the solver deliberately supports that reuse.
        """

        pass

Solver

class Solver:

    def select_move(self, game, state, player):
        raise NotImplementedError

    def opponent_played(self, move):
        pass

    def reset(self):
        pass

    def get_name(self):
        return self.__class__.__name__

RandomSolver

Code
class RandomSolver(Solver):

    """
    A simple baseline solver:
    - At each move, chooses uniformly at random among all legal moves.
    - Learns no strategy; its seeded random stream continues across games.
    """

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

    def select_move(self, game, state, player):

        """Return a random legal move for the current player."""

        moves = game.get_valid_moves(state)

        return self.rng.choice(moves)

    def opponent_played(self, move):

        """Random solver has no internal state to update."""

        pass
class RandomSolver(Solver):

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

    def select_move(self, game, state, player):
        moves = game.get_valid_moves(state)
        return self.rng.choice(moves)

GameRunner

Code
class GameRunner:

    """
    Utility to run a single game between two solvers on a given Game.

    This class is deliberately simple: it alternates moves between "X" and "O"
    until a terminal state is reached.
    """

    def __init__(self, game, verbose=False):
        self.game = game
        self.verbose = verbose
        self.final_state = None

    def play_game(self, solver_X, solver_O):

        """
        Play one full game:
        - solver_X controls player "X"
        - solver_O controls player "O"

        Returns
        -------
        result : int
            +1 if X wins, -1 if O wins, 0 for a draw.
        """

        solver_X.reset()
        solver_O.reset()
        state = self.game.initial_state()
        player = "X"
        solvers = {"X": solver_X, "O": solver_O}

        # Play until terminal position
        while not self.game.is_terminal(state):
            # Current player selects a move
            move = solvers[player].select_move(self.game, state, player)

            # Apply the move
            state = self.game.make_move(state, move, player)

            if self.verbose:
                self.game.display(state)

            # Notify the opponent (for persistent solvers like MCTS)
            opp = self.game.get_opponent(player)
            solvers[opp].opponent_played(move)

            # Switch active player
            player = opp

        if self.verbose:
            print(self.game.evaluate(state), "\n")

        # make_move returns new states, so retaining this final state is safe.
        self.final_state = state
        # Final evaluation from X's perspective
        return self.game.evaluate(state)

GameRunner

class GameRunner:

    def __init__(self, game):
        self.game = game

    def play_game(self, solver_X, solver_O):
        
        solver_X.reset()
        solver_O.reset()
        state = self.game.initial_state()
        player = "X"
        solvers = {"X": solver_X, "O": solver_O}

        while not self.game.is_terminal(state):
            move = solvers[player].select_move(self.game, state, player)
            state = self.game.make_move(state, move, player)
            opp = self.game.get_opponent(player)
            solvers[opp].opponent_played(move)
            player = opp

        self.final_state = state
        return self.game.evaluate(state)

Example

game = TicTacToe()
runner = GameRunner(game)

a = RandomSolver(123)
b = RandomSolver(456)

game.display(game.initial_state())
outcome = runner.play_game(a, b)
game.display(runner.final_state)
print("Outcome from X's perspective:", outcome)

Example

Outcome from X's perspective: -1

evaluate_solvers

Code
def evaluate_solvers(game, solver_X, solver_O, num_games, verbose=False):

    """
    Evaluate two solvers head-to-head on a given game.

    Parameters
    ----------
    game      : Game
        An instance of a Game (e.g., TicTacToe).
    solver_X  : Solver
        Solver controlling player "X" (the maximizing player).
    solver_O  : Solver
        Solver controlling player "O" (the minimizing player).
    num_games : int
        Number of games to play with these fixed roles.

    Notes
    -----
    - The same solver instances are reused across games, and GameRunner
      calls their reset() hooks at the start of each match. Each solver
      decides which game-local state to clear and which valid analysis to reuse.
    - RandomSolver retains its random stream, so repeated matches do not
      restart the same seeded game.
    - Outcomes are interpreted from X's perspective:
        +1 -> X wins
        -1 -> O wins
         0 -> draw
    """

    runner = GameRunner(game)

    # Aggregate statistics over all games
    results = {
        "X_wins": 0,
        "O_wins": 0,
        "draws": 0,
    }

    for i in range(num_games):
        # Play one game with solver_X as "X" and solver_O as "O"
        outcome = runner.play_game(solver_X, solver_O)

        # Update counters based on outcome (+1, -1, or 0)
        if outcome == 1:
            results["X_wins"] += 1
            if verbose:
                print(f"Game {i + 1}: X wins") 
        elif outcome == -1:
            results["O_wins"] += 1
            if verbose:
                print(f"Game {i + 1}: O wins") 
        else:
            results["draws"] += 1
            if verbose:
                print(f"Game {i + 1}: Draw")

    # Print final summary
    if verbose:
        print(f"\nAfter {num_games} games:")
        print(f"  X ({solver_X.get_name()}) wins: {results['X_wins']}")
        print(f"  O ({solver_O.get_name()}) wins: {results['O_wins']}")
        print(f"  Draws: {results['draws']}")

    return results

Can You Guess the Outcome?

game = TicTacToe()

a = RandomSolver(7)
b = RandomSolver(42)

results = evaluate_solvers(game, a, b, num_games=1000)

results

Can You Guess the Outcome?

{'X_wins': 581, 'O_wins': 290, 'draws': 129}

Introduction

Types of Games

  • Deterministic or stochastic transitions
  • One, two, or more players
  • Zero-sum or non-zero-sum utilities
  • Perfect or imperfect information

Zero-Sum Utilities

One player’s gain is the other player’s loss: u_O(s)=-u_X(s).

Terminal outcome Utility for X Utility for O
X wins +1 -1
Draw 0 0
O wins -1 +1

A Game State Includes the Turn

  • A state records the information needed to determine legal moves and outcomes.
  • For tic-tac-toe, use the board and the player to move.
  • A legal action produces a successor state and changes the active player.

Policy or Transition?

  • The transition function describes the rules: T(s,a) is the successor after legal action a.
  • A policy chooses a legal action: \pi(s)\in A(s) when it is that player’s turn.

Does a policy prescribe one fixed path through the game?

It must respond to the states that the opponent’s choices can produce.

Can You Guarantee Never Losing?

Consider tic-tac-toe against an opponent whose moves you cannot predict.

  • Can you guarantee that you never lose?
  • Does the answer change if you play X or O?
  • Does a never-lose strategy guarantee a win?

Why Use Tic-Tac-Toe?

Each of nine squares has three possible contents: 3^9=19{,}683 raw boards.

Legal play reaches 5,478 positions and produces 255,168 complete move sequences.

Minimax

A Two-Move Game

Predict the Opponent’s Responses

Back Up the Opponent’s Choices

Maximize the Guaranteed Value

Video Walkthrough: Minimax

A Tic-Tac-Toe Game Tree

Minimax Backups

For a complete finite game tree, let V(s) be the value from X’s perspective:

V(s)= \begin{cases} u_X(s), & \text{if }s\text{ is terminal},\\ \max_{a\in A(s)} V(T(s,a)), & \text{if X moves},\\ \min_{a\in A(s)} V(T(s,a)), & \text{if O moves}. \end{cases}

  • X chooses a child with the largest value.
  • O chooses a child with the smallest value.
  • Terminal utilities are +1 for X winning, -1 for O winning, and 0 for a draw in Tic-Tac-Toe.

Exercise

Predict a Tic-Tac-Toe Move

X is to move. Dots denote empty squares.

Row / column 0 1 2
0 X X ·
1 O O ·
2 · · ·

Which move wins immediately, and what utility does it return?

Move (0, 2) completes X’s row and returns utility +1.

Executable Minimax Reference

Show the complete minimax solver and hashable-board helper
from functools import lru_cache
import pandas as pd


def canonical(state):
    """Make the board hashable; rotations and reflections are not merged."""
    return tuple(map(tuple, state))


class MinimaxSolver(Solver):
    """Full Tic-Tac-Toe minimax, with exact values cached for fixed rules."""

    def __init__(self):
        self.game = None

    def clear_cache(self):
        """Discard cached results if rules or evaluation are changed in place."""
        self._minimax.cache_clear()

    def select_move(self, game, state, player):
        """Choose an optimal move; X maximizes and O minimizes."""
        if self.game is not game:
            self.clear_cache()
            self.game = game
        _, move = self._minimax(canonical(state), player, player == "X")
        return move

    @lru_cache(maxsize=None)
    def _minimax(self, state_key, player, maximizing):
        state = np.array(state_key)
        if self.game.is_terminal(state):
            return self.game.evaluate(state), None

        best_value = -math.inf if maximizing else math.inf
        best_move = None
        for move in self.game.get_valid_moves(state):
            next_state = self.game.make_move(state, move, player)
            value, _ = self._minimax(
                canonical(next_state),
                self.game.get_opponent(player),
                not maximizing,
            )
            improves = value > best_value if maximizing else value < best_value
            if improves:
                best_value, best_move = value, move
        return best_value, best_move

From the Recurrence to the Loop

if game.is_terminal(state):
    return game.evaluate(state), None

for move in game.get_valid_moves(state):
    next_state = game.make_move(state, move, player)
    value, _ = minimax(next_state, game.get_opponent(player))
    # X retains the largest value; O retains the smallest.

Can You Guess the Outcomes?

All games start from an empty board. Predict the possible outcomes:

X O Can X win? Can O win? Can they draw?
Minimax Random ? ? ?
Random Minimax ? ? ?
Minimax Minimax ? ? ?

Minimax (X) vs Random (O)

What outcomes do you predict over 1,000 games?

Run Minimax as X against Random as O
game = TicTacToe()
result = evaluate_solvers(game, MinimaxSolver(), RandomSolver(7), num_games=1000)
print(pd.DataFrame([
    {"X": "Minimax", "O": "Random", "Games": 1000, **result}
]).to_string(index=False))
      X      O  Games  X_wins  O_wins  draws
Minimax Random   1000     998       0      2

What do you predict if we reverse the roles: Random (X) vs Minimax (O)? Will every game end in a draw?

Random (X) vs Minimax (O)

With the roles reversed, what outcomes do you predict over 1,000 games?

Run Random as X against Minimax as O
game = TicTacToe()
result = evaluate_solvers(game, RandomSolver(7), MinimaxSolver(), num_games=1000)
print(pd.DataFrame([
    {"X": "Random", "O": "Minimax", "Games": 1000, **result}
]).to_string(index=False))
     X       O  Games  X_wins  O_wins  draws
Random Minimax   1000       0     793    207

Minimax (X) vs Minimax (O)

What do you predict over 1,000 games? Will they all end in a draw?

Run Minimax against Minimax
game = TicTacToe()
result = evaluate_solvers(game, MinimaxSolver(), MinimaxSolver(), num_games=1000)
print(pd.DataFrame([
    {"X": "Minimax", "O": "Minimax", "Games": 1000, **result}
]).to_string(index=False))
      X       O  Games  X_wins  O_wins  draws
Minimax Minimax   1000       0       0   1000

What Have We Guaranteed?

  • Minimax chooses the move with the best worst-case utility.
  • The guarantee holds against any legal opponent play.
  • Equally valued moves can lead to different games and empirical win rates.
  • A successful outcome experiment illustrates the algorithm; it does not replace the minimax argument.

Why Does Full Search Become Expensive?

With branching factor b and search depth d, a full tree has approximately O(b^d) nodes.

Can we avoid examining a branch without changing the minimax value?

Alpha-Beta Pruning

Must We Examine Every Leaf?

Minimax backs up terminal utilities to choose a move.

Can an unfinished branch already contain enough information to rule it out?

Pruning Intuition in Detail

Pruning Intuition: Continued

Pruning Intuition: Continued

Pruning Intuition: Continued

Pruning Intuition: Continued

Pruning Intuition: Continued

Pruning Intuition: Continued

Pruning Intuition: Continued

Pruning Intuition: Continued

Pruning Intuition: Continued

Pruning Intuition: Continued

Pruning Intuition: Continued

Pruning Intuition: Continued

Pruning Intuition: Continued

Pruning Intuition: Continued

Pruning Intuition: Continued

A Search Window Passed Down the Tree

  • Alpha, \alpha: a threshold from the best alternative already available to MAX.
  • Beta, \beta: a threshold from the best alternative already available to MIN.
  • Initialize only the root with \alpha=-\infty and \beta=\infty.
  • Recursive calls inherit the current window; each node keeps its own local value.

Exercise

Walkthrough

Walkthrough

Walkthrough

Walkthrough

Walkthrough

Walkthrough

Walkthrough

Walkthrough

Walkthrough

Walkthrough

Walkthrough

Walkthrough

Two Cutoffs, One Principle

Current node Information obtained Why the remaining children can be skipped
MAX Local value \geq\beta A MIN ancestor already has an option worth at most \beta
MIN Local value \leq\alpha A MAX ancestor already has an option worth at least \alpha

Both use the stopping condition \alpha\geq\beta after updating the relevant threshold.

What Changes in the Code?

After each MAX child:

value = max(value, child_value)
alpha = max(alpha, value)
if alpha >= beta:
    break

After each MIN child, replace max by min and update beta.

Complete Search and Counting Helpers

The complete definitions keep the notebook independently executable. The counting version of alpha-beta reuses the same recursive algorithm.

Alpha-beta and the two instrumented solvers
class MinimaxAlphaBetaSolverV1(Solver):
    """Full Tic-Tac-Toe search with inherited alpha-beta bounds.

    Utilities are always from X's perspective. Equal values retain the first
    legal move in the game's move order. Depth 9 covers every remaining move;
    the zero returned for a nonterminal board is not a useful cutoff heuristic.
    """

    def select_move(self, game, state, player):
        self.game = game
        _, move = self._alphabeta(
            state, player, player == "X", 9, -math.inf, math.inf
        )
        return move

    def _alphabeta(self, state, player, maximizing, depth, alpha, beta):
        """Return a search value and move; a cutoff value may be a bound."""
        if self.game.is_terminal(state) or depth == 0:
            return self.game.evaluate(state), None

        best_move = None
        if maximizing:
            value = -math.inf
            for move in self.game.get_valid_moves(state):
                next_state = self.game.make_move(state, move, player)
                child_value, _ = self._alphabeta(
                    next_state, self.game.get_opponent(player), False,
                    depth - 1, alpha, beta
                )
                if child_value > value:
                    value, best_move = child_value, move
                alpha = max(alpha, value)
                if alpha >= beta:
                    break  # Skip the remaining children of this MAX node.
        else:
            value = math.inf
            for move in self.game.get_valid_moves(state):
                next_state = self.game.make_move(state, move, player)
                child_value, _ = self._alphabeta(
                    next_state, self.game.get_opponent(player), True,
                    depth - 1, alpha, beta
                )
                if child_value < value:
                    value, best_move = child_value, move
                beta = min(beta, value)
                if beta <= alpha:
                    break  # Skip the remaining children of this MIN node.
        return value, best_move


class MinimaxSolverV2(Solver):

    """
    A classic, exact Minimax solver for Tic-Tac-Toe — *instrumented version*.

    Differences from V1
    --------------------
    - Adds a counter `self.nodes_visited` that counts each recursive call.
    - Uses `reset()` so the GameRunner or TournamentRunner can correctly
      prepare the solver before each game.
    - Still performs a full game-tree search without memoization.

    Characteristics
    ---------------
    - Assumes "X" is the maximizing player.
    - Performs a complete minimax search (Tic-Tac-Toe is small enough).
    """

    def __init__(self):

        # Count how many nodes have been visited in the current run
        self.nodes_visited = 0

    # ------------------------------------------------------------
    # Solver interface
    # ------------------------------------------------------------
    
    def select_move(self, game, state, player):

        """
        Choose the optimal move for `player` using a full minimax search.
        """

        maximizing = (player == "X")
        value, move = self._minimax(game, state, player, maximizing)
        return move
        
    def reset(self):

        """
        Reset instrumentation counters at the start of a game (or tournament run).

        GameRunner / TournamentRunner should call solver.reset() before
        starting a new game.
        """

        self.nodes_visited = 0

    def get_name(self):

        """
        Name is inherited from Solver but solvers may override get_name()
        to display additional instrumentation info.
        """

        return f"{self.__class__.__name__} (nodes={self.nodes_visited})"

    # ------------------------------------------------------------
    # Core recursive minimax
    # ------------------------------------------------------------

    def _minimax(self, game, state, player, maximizing):

        """
        The core recursive minimax computation.

        Parameters
        ----------
        game       : TicTacToe instance
        state      : NumPy array of current board position
        player     : "X" or "O" — the player whose turn it is at this node
        maximizing : True if this node corresponds to X; False if O

        Returns
        -------
        (value, move)
            value : +1 for X win, -1 for O win, 0 otherwise
            move  : best move selected at this node
        """

        # Instrumentation
        self.nodes_visited += 1

        # ------------------------
        # TERMINAL NODE?
        # ------------------------
        if game.is_terminal(state):
            return game.evaluate(state), None

        # ------------------------
        # GENERATE ALL MOVES
        # ------------------------
        moves = game.get_valid_moves(state)

        # ------------------------
        # MAX NODE (X plays)
        # ------------------------
        if maximizing:
            best_value = -math.inf
            best_move = None

            for move in moves:
                next_state = game.make_move(state, move, player)
                val, _ = self._minimax(
                    game,
                    next_state,
                    game.get_opponent(player),
                    maximizing=False
                )
                if val > best_value:
                    best_value = val
                    best_move = move

            return best_value, best_move

        # ------------------------
        # MIN NODE (O plays)
        # ------------------------

        else:
            best_value = math.inf
            best_move = None

            for move in moves:
                next_state = game.make_move(state, move, player)
                val, _ = self._minimax(
                    game,
                    next_state,
                    game.get_opponent(player),
                    maximizing=True
                )
                if val < best_value:
                    best_value = val
                    best_move = move

            return best_value, best_move

class MinimaxAlphaBetaSolverV2(MinimaxAlphaBetaSolverV1):
    """The same alpha-beta search, counting every recursive call."""

    def __init__(self):
        self.nodes_visited = 0

    def reset(self):
        """Reset per-game counters while leaving the search algorithm unchanged."""
        self.nodes_visited = 0

    def _alphabeta(self, state, player, maximizing, depth, alpha, beta):
        self.nodes_visited += 1
        return super()._alphabeta(
            state, player, maximizing, depth, alpha, beta
        )

Does Pruning Change Optimal Play?

Predict: what happens when alpha-beta replaces either or both minimax players?

Code
sanity_game = TicTacToe()
sanity_matchups = [
    ("Alpha-beta vs minimax", MinimaxAlphaBetaSolverV1(), MinimaxSolver()),
    ("Minimax vs alpha-beta", MinimaxSolver(), MinimaxAlphaBetaSolverV1()),
    ("Alpha-beta vs alpha-beta", MinimaxAlphaBetaSolverV1(), MinimaxAlphaBetaSolverV1()),
]
sanity_rows = []
for matchup, solver_x, solver_o in sanity_matchups:
    result = evaluate_solvers(sanity_game, solver_x, solver_o, num_games=1)
    sanity_rows.append({"X vs O": matchup, **result})
print(pd.DataFrame(sanity_rows).to_string(index=False))

Does Pruning Change Optimal Play?

                  X vs O  X_wins  O_wins  draws
   Alpha-beta vs minimax       0       0      1
   Minimax vs alpha-beta       0       0      1
Alpha-beta vs alpha-beta       0       0      1

How Much Search Work Did We Save?

Predict: will the two searches return the same value? Will they visit the same number of nodes?

Hold fixed the starting board, player to move, legal-move order, and full-search horizon.

A Controlled Same-Position Comparison

Code
comparison_game = TicTacToe()
comparison_state = comparison_game.initial_state()
mm = MinimaxSolverV2()
ab = MinimaxAlphaBetaSolverV2()
mm.reset()
ab.reset()

# Direct calls expose both the root value and the selected move.
mm_value, mm_move = mm._minimax(comparison_game, comparison_state, "X", True)
ab.game = comparison_game
ab_value, ab_move = ab._alphabeta(
    comparison_state, "X", True, 9, -math.inf, math.inf
)
assert mm_value == ab_value == 0
assert mm_move == ab_move  # Same order and first-in-order tie convention.

print(pd.DataFrame([
    {"Search": "Minimax", "Root value": mm_value, "Move": mm_move,
     "Recursive calls": mm.nodes_visited},
    {"Search": "Alpha-beta", "Root value": ab_value, "Move": ab_move,
     "Recursive calls": ab.nodes_visited},
]).to_string(index=False))

A Controlled Same-Position Comparison

    Search  Root value   Move  Recursive calls
   Minimax           0 (0, 0)           549946
Alpha-beta           0 (0, 0)            18297

Does Move Order Matter?

  • What stays unchanged? The full-search minimax value.
  • What may change? The number of visited nodes and the first equally optimal move returned.
  • Promising moves considered early can produce earlier cutoffs.

What Have We Preserved?

Alpha-beta returns the same minimax value and an optimal move while avoiding branches whose exact values cannot affect an ancestor’s choice.

What Happens in Larger Games?

For branching factor b and search depth d, a full game tree can grow as O(b^d).

  • Alpha–beta avoids branches that cannot affect the decision.
  • It can still be too expensive to search all the way to terminal states.
  • A depth limit stops the search earlier.

Terminal Utility or Cutoff Evaluation?

Where search stops Value returned
Terminal position Exact game utility, u_X(s)
Nonterminal depth cutoff Heuristic estimate, h_X(s)

Would returning zero at every cutoff give useful guidance?

The heuristic must distinguish promising and unfavorable nonterminal positions.

Epilogue

Summary

  • A policy must respond to the opponent’s possible actions.
  • Minimax maximizes the utility guaranteed against the opponent’s best responses.
  • Keep one utility perspective: X maximizes and O minimizes.
  • Alpha–beta inherits bounds and skips remaining children when an ancestor’s alternative makes them irrelevant.
  • Move ordering changes the work, while the minimax value is preserved.
  • Compare recursive calls from the same position, player, and move order.

Next Lecture

Lecture 23: Monte Carlo Tree Search examines how simulations and selective exploration can guide decisions when full search is impractical.

References

Russell, Stuart, and Peter Norvig. 2020. Artificial Intelligence: A Modern Approach. 4th ed. Pearson. http://aima.cs.berkeley.edu/.

Appendix

Textbook Minimax Pseudocode

Memoization and Repeated Positions

Different move histories can reach the same board and player to move. Under unchanged rules, their full-search minimax values are identical.

Uncached Minimax Reference

Show the uncached full-search minimax implementation
class MinimaxSolverV1(Solver):
    """Full minimax without memoization; scores are always from X's perspective."""

    def select_move(self, game, state, player):
        _, move = self._minimax(game, state, player, player == "X")
        return move

    def _minimax(self, game, state, player, maximizing):
        if game.is_terminal(state):
            return game.evaluate(state), None

        best_value = -math.inf if maximizing else math.inf
        best_move = None
        for move in game.get_valid_moves(state):
            next_state = game.make_move(state, move, player)
            value, _ = self._minimax(
                game, next_state, game.get_opponent(player), not maximizing
            )
            improves = value > best_value if maximizing else value < best_value
            if improves:
                best_value, best_move = value, move
        return best_value, best_move

Timing One Fixed Position

Compare uncached, cold-cache, and warm-cache calls
import time

timing_game = TicTacToe()
timing_state = np.array([
    ["X", "O", "X"],
    [" ", "O", " "],
    [" ", "X", " "],
])
cached_solver = MinimaxSolver()
timing_rows = []
for label, solver in [
    ("Uncached", MinimaxSolverV1()),
    ("Cached: first call", cached_solver),
    ("Cached: repeated call", cached_solver),
]:
    start = time.perf_counter()
    move = solver.select_move(timing_game, timing_state, "O")
    timing_rows.append({
        "Search": label, "Move": move,
        "Seconds": time.perf_counter() - start,
    })
print(pd.DataFrame(timing_rows).to_string(index=False))
               Search   Move  Seconds
             Uncached (1, 0) 0.001782
   Cached: first call (1, 0) 0.002613
Cached: repeated call (1, 0) 0.000003

Counting Complete Games

There are 255,168 complete legal move sequences from an empty Tic-Tac-Toe board. Play stops as soon as a player wins or the board is full.

Count terminal histories while reusing counts for repeated positions
def count_valid_sequences(game, state, player):
    """Count complete histories from this position, ending at the first terminal state."""
    @lru_cache(maxsize=None)
    def count(state_key, player):
        board = np.array(state_key)
        if game.is_terminal(board):
            return 1
        opponent = game.get_opponent(player)
        return sum(
            count(canonical(game.make_move(board, move, player)), opponent)
            for move in game.get_valid_moves(board)
        )

    return count(canonical(state), player)


counting_game = TicTacToe()
total_sequences = count_valid_sequences(
    counting_game, counting_game.initial_state(), "X"
)
print(f"Complete legal move sequences: {total_sequences:,}")
Complete legal move sequences: 255,168

Symmetry: Specify What Is Being Counted

The square has eight symmetries: four rotations, and a reflection combined with each rotation.

Object and equivalence convention Count
Reachable legal boards 5,478
Reachable boards identified by rotation/reflection 765
Paths after merging symmetric child boards at every position 26,830

Verify the Symmetry-Reduced Counts

Count paths after deduplicating symmetric successors at each position
def symmetry_key(board):
    """Return the smallest board key among its eight square symmetries."""
    images = []
    for turns in range(4):
        images.append(canonical(np.rot90(board, turns)))
        images.append(canonical(np.rot90(np.fliplr(board), turns)))
    return min(images)


def count_symmetry_reduced_paths(game):
    """Return path and position counts in the symmetry-reduced state graph."""
    @lru_cache(maxsize=None)
    def count(state_key, player):
        board = np.array(state_key)
        if game.is_terminal(board):
            return 1
        child_keys = {
            symmetry_key(game.make_move(board, move, player))
            for move in game.get_valid_moves(board)
        }
        opponent = game.get_opponent(player)
        return sum(count(key, opponent) for key in child_keys)

    paths = count(symmetry_key(game.initial_state()), "X")
    return paths, count.cache_info().currsize


reduced_paths, unique_positions = count_symmetry_reduced_paths(counting_game)
print(f"Symmetry-reduced paths: {reduced_paths:,}")
print(f"Symmetry classes of reachable boards: {unique_positions:,}")
Symmetry-reduced paths: 26,830
Symmetry classes of reachable boards: 765

Large Game Trees

  • Chess: 35^{80} leaves in a simplified tree with branching factor 35 and depth 80 plies.
  • Go (19 \times 19 board): 361! placement orderings under the artificial rule that each of the 361 intersections is filled exactly once.
  • Neither expression is an exact count of legal games.

Explore Another Game

  • Implement Connect Four using the same game/solver interface.
  • Compare full search with a depth cutoff and a nonterminal evaluation function.
  • Investigate its vertical reflection symmetry, and distinguish symmetry reduction from memoization of identical positions.

Alpha-Beta Implementation Details

The complete MinimaxAlphaBetaSolverV1 definition is in the earlier reference cell. It keeps a local value, passes inherited bounds to children, and breaks only when the cutoff condition holds.

# MAX node: explanatory excerpt from the complete implementation.
value = -math.inf
for move in self.game.get_valid_moves(state):
    # Recursively evaluate the child with the current alpha and beta.
    value = max(value, child_value)
    alpha = max(alpha, value)
    if alpha >= beta:
        break

For MIN, initialize the local value to positive infinity, minimize it, and update beta. The best_move variable is updated only on a strict improvement, preserving the first equally good move in the given order.

Alpha-Beta with Memoization

A cutoff return can be a lower or upper bound rather than an exact value. This implementation keeps the search window in its cache key.

Window-specific memoization for alpha-beta
class AlphaBetaSolver(Solver):
    
    """
    A classical Minimax solver enhanced with Alpha-Beta pruning.

    - Assumes "X" is the maximizing player.
    - Uses memoization (lru_cache) to avoid recomputing states.
    - Performs a *full* search of Tic-Tac-Toe (depth=9).
    - Returns the optimal move for the current player.
    """

    # ------------------------------------------------------------
    # Solver interface
    # ------------------------------------------------------------

    def select_move(self, game, state, player):

        """
        Public interface required by Solver.
        Runs Alpha-Beta search from the current state.
        """

        self.game = game

        maximizing = (player == "X")   # X maximizes, O minimizes

        # Clear at each move; keys include the search window as well as the state
        self._alphabeta.cache_clear()

        value, move = self._alphabeta(
            canonical(state),
            player,
            maximizing,
            9,               # full-depth search
            -math.inf,       # alpha
            math.inf         # beta
        )
        return move

    # ------------------------------------------------------------
    # Internal alpha-beta with memoization
    # ------------------------------------------------------------

    @lru_cache(maxsize=None)
    def _alphabeta(self, state_key, player, maximizing, depth, alpha, beta):

        """
        Parameters
        ----------
        state_key : tuple-of-tuples board
        player    : player whose turn it is ('X' or 'O')
        maximizing: True if this node is a maximizing node for X
        depth     : remaining depth
        alpha     : inherited MAX alternative threshold
        beta      : inherited MIN alternative threshold
        """

        state = np.array(state_key)

        # Terminal or horizon case
        if self.game.is_terminal(state) or depth == 0:
            return self.game.evaluate(state), None

        moves = self.game.get_valid_moves(state)
        best_move = None

        # --------------------------------------------------------
        # MAX (X)
        # --------------------------------------------------------

        if maximizing:
            value = -math.inf

            for move in moves:
                st2 = self.game.make_move(state, move, player)

                child_val, _ = self._alphabeta(
                    canonical(st2),
                    self.game.get_opponent(player),
                    False,              # now minimizing
                    depth - 1,
                    alpha,
                    beta
                )

                if child_val > value:
                    value = child_val
                    best_move = move

                alpha = max(alpha, value)
                if beta <= alpha:
                    break  # β-cutoff

            return value, best_move

        # --------------------------------------------------------
        # MIN (O)
        # --------------------------------------------------------

        else:
            value = math.inf

            for move in moves:
                st2 = self.game.make_move(state, move, player)

                child_val, _ = self._alphabeta(
                    canonical(st2),
                    self.game.get_opponent(player),
                    True,               # now maximizing
                    depth - 1,
                    alpha,
                    beta
                )

                if child_val < value:
                    value = child_val
                    best_move = move

                beta = min(beta, value)
                if beta <= alpha:
                    break  # α-cutoff

            return value, best_move

Supplementary Alpha-Beta Video

Another View of Alpha-Beta

Further Alpha-Beta Experiments

  • Change only the legal-move order, then compare values and recursive-call counts from the same starting positions.
  • Implement Connect Four, then compare minimax and alpha-beta at the same depth with the same evaluation function.
  • Keep head-to-head outcomes separate from search-work comparisons. Swapping X and O changes which positions the algorithms examine.

Marcel Turcotte

[email protected]

School of Electrical Engineering and Computer Science (EECS)

University of Ottawa