Monte Carlo Tree Search: Implementation and Experiments

CSI 4106 Introduction to Artificial Intelligence

Marcel Turcotte

Version: Nov 30, 2026 08:21

Preamble

Message of the Day

Learning objectives

  • Connect the four MCTS stages to one executable implementation.
  • Interpret node values, visit counts, and root recommendations.
  • Investigate simulation budgets and exploration using controlled comparisons.
  • Distinguish a fresh search from reuse of valid search statistics.
  • Explain how policy and value networks can guide search.

Retrieve the Four Stages

A rollout has just ended in an X win. What happens next?

  • Which stored nodes receive a visit?
  • Which nodes receive a positive return? A negative return?
  • Does the next simulation have to follow the same path?

Predict the Backup

The visited stored path is X root → O child → X leaf; each label names the player to move.

N counts visits; W sums returns from that player’s perspective. Before this simulation, (N,W) is root (6,2), child (4,-2), and leaf (2,0).

The rollout ends in an O win. What are the updated (N,W) values? What if it ends in a draw instead? Start each alternative from the same before-values.

Stored node After an O win After a draw
X root (7,1) (7,2)
O child (5,-1) (5,-2)
X leaf (3,-1) (3,0)

Python Reference

Framework Reference

The game rules, solvers, and runner are the same as in Lecture 22.

Imports used throughout this self-contained notebook
import math
import random
from base64 import b64encode
from functools import lru_cache
from time import perf_counter

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from graphviz import Digraph
from IPython.display import HTML, display
Game, TicTacToe, solvers, GameRunner, and exact minimax
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


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()


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


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 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)


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


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

Implementation

MCTSClassicSolver

The complete node-based MCTS solver
class MCTSClassicSolver(Solver):
    """Build a fresh node tree for each decision in a finite game.

    Node.W is a total from that node's player-to-move perspective.
    Rollouts return X's utility, as in the game framework.
    """

    class Node:
        def __init__(self, state, player, parent=None, moves=None):
            self.state = state
            self.player = player
            self.parent = parent
            self.children = {}
            self.untried_moves = list(moves) if moves is not None else []
            self.N = 0
            self.W = 0.0

    def __init__(
        self, num_simulations=500, exploration_c=math.sqrt(2), seed=None
    ):
        if num_simulations < 1:
            raise ValueError("Use at least one simulation per decision.")
        self.num_simulations = num_simulations
        self.exploration_c = exploration_c
        self.rng = random.Random(seed)
        self.game = None
        MCTSClassicSolver.reset(self)

    def reset(self):
        """Clear game-local counters without restarting the random stream."""
        self.root = None
        self._tree_size = 0
        self.game_simulations = 0
        self.game_nodes = 0
        self.game_edges = 0
        self.game_rollout_moves = 0
        self.game_decisions = 0
        self.game_first_retained_visits = None
        self._start_decision()

    def _start_decision(self):
        self.decision_simulations = 0
        self.decision_nodes = 0
        self.decision_edges = 0
        self.decision_rollout_moves = 0
        self.retained_root_visits = 0

    def _finish_decision(self):
        if self.game_first_retained_visits is None:
            self.game_first_retained_visits = self.retained_root_visits
        self.game_simulations += self.decision_simulations
        self.game_nodes += self.decision_nodes
        self.game_edges += self.decision_edges
        self.game_rollout_moves += self.decision_rollout_moves
        self.game_decisions += 1

    @property
    def root_visits(self):
        return self.root.N if self.root is not None else 0

    @property
    def tree_size(self):
        return self._tree_size

    def get_name(self):
        return f"MCTS-fresh({self.num_simulations})"

    def select_move(self, game, state, player):
        """Return a move, leaving the supplied board unchanged."""
        self.game = game
        self._start_decision()
        self.root = self.Node(
            state.copy(), player, moves=game.get_valid_moves(state)
        )
        self._tree_size = 1
        self.decision_nodes = 1  # The fresh root is an explicit node.
        if game.is_terminal(state):
            self._finish_decision()
            return None

        for _ in range(self.num_simulations):
            self._run_simulation()
        self._finish_decision()

        # Visits decide; the parent's mean breaks visit ties.
        best_move, best_key = None, (-1, -math.inf)
        for move, child in self.root.children.items():
            key = (child.N, -child.W / child.N)
            if key > best_key:
                best_move, best_key = move, key
        return best_move

    def _run_simulation(self):
        node = self.root
        while True:
            if self.game.is_terminal(node.state):
                outcome = self.game.evaluate(node.state)
                break
            if node.untried_moves:
                move = self.rng.choice(node.untried_moves)
                node.untried_moves.remove(move)
                state = self.game.make_move(node.state, move, node.player)
                player = self.game.get_opponent(node.player)
                child = self.Node(
                    state, player, node,
                    self.game.get_valid_moves(state),
                )
                node.children[move] = child
                self.decision_nodes += 1
                self.decision_edges += 1
                self._tree_size += 1
                node = child
                outcome = self._rollout(node.state, node.player)
                break
            node = self._select_child(node)

        self._backpropagate(node, outcome)
        self.decision_simulations += 1

    def _select_child(self, node):
        best_child, best_score = None, -math.inf
        for child in node.children.values():
            if child.N == 0:
                score = math.inf
            else:
                # The child has the opposing player's perspective.
                mean = -child.W / child.N
                bonus = self.exploration_c * math.sqrt(
                    math.log(node.N) / child.N
                )
                score = mean + bonus
            if score > best_score:
                best_child, best_score = child, score
        return best_child

    def _rollout(self, state, player_to_move):
        """Sample a random continuation; return the result for X."""
        state = state.copy()
        player = player_to_move
        while not self.game.is_terminal(state):
            move = self.rng.choice(self.game.get_valid_moves(state))
            state = self.game.make_move(state, move, player)
            player = self.game.get_opponent(player)
            self.decision_rollout_moves += 1
        return self.game.evaluate(state)

    def _backpropagate(self, node, outcome):
        while node is not None:
            reward = outcome if node.player == "X" else -outcome
            node.N += 1
            node.W += reward
            node = node.parent

Node

class MCTSClassicSolver(Solver):
    
    class Node:

        def __init__(self, state, player, parent=None, moves=None):
            self.state = state            # board position (NumPy array)
            self.player = player          # player to move in this state
            self.parent = parent          # parent Node (None for root)
            self.children = {}            # move -> child Node
            self.untried_moves = list(moves) if moves is not None else []
            self.N = 0                    # visit count
            self.W = 0.0                  # total reward (this player's perspective)

__init__

    def __init__(self, num_simulations=500, exploration_c=math.sqrt(2), seed=None):

        self.num_simulations = num_simulations
        self.exploration_c = exploration_c
        self.rng = random.Random(seed)

        self.game = None
        self.root = None

Public Solver interface

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

        self.game = game
        self.root = None  # building a new tree for each call

        # Create the root node for the current position.
        root_state = state.copy()
        root_moves = self.game.get_valid_moves(root_state)
        self.root = self.Node(root_state, player, parent=None, moves=root_moves)

        # Run multiple simulations starting from the root.
        for _ in range(self.num_simulations):
            self._run_simulation()

        best_move, best_key = None, (-1, -math.inf)
        for move, child in self.root.children.items():
            key = (child.N, -child.W / child.N)
            if key > best_key:
                best_move, best_key = move, key

        return best_move

Public Solver interface

    def opponent_played(self, move):
        pass

_run_simulation

    def _run_simulation(self):

        node = self.root

        # 1. SELECTION: descend while fully expanded and non-terminal.
        while True:

            if self.game.is_terminal(node.state):
                # Terminal position: evaluate immediately.
                outcome = self.game.evaluate(node.state)  # from X's perspective
                self._backpropagate(node, outcome)
                return

            if node.untried_moves:

                # 2. EXPANSION: choose one untried move and create a child node.
                move = self.rng.choice(node.untried_moves)
                node.untried_moves.remove(move)

                next_state = self.game.make_move(node.state, move, node.player)
                next_player = self.game.get_opponent(node.player)
                next_moves = self.game.get_valid_moves(next_state)

                child = self.Node(next_state, next_player, parent=node, moves=next_moves)
                node.children[move] = child

                # 3. SIMULATION: rollout from the newly created child.
                outcome = self._rollout(child.state, child.player)

                # 4. BACKPROPAGATION: update all nodes on the path from child to root.
                self._backpropagate(child, outcome)

                return

            # Node is fully expanded and non-terminal → choose a child by UCT.
            node = self._select_child(node)

_select_child

    def _select_child(self, node):

        parent_visits = node.N
        best_score = -math.inf
        best_child = None

        for move, child in node.children.items():
            if child.N == 0:
                score = math.inf  # always explore unvisited children at least once
            else:
                # Average reward from the child's own perspective.
                avg_child = child.W / child.N

                # Parent and child players alternate; reward from parent perspective
                # is the negative of the child's perspective.
                reward_parent = -avg_child

                exploration = self.exploration_c * math.sqrt(
                    math.log(parent_visits) / child.N
                )

                score = reward_parent + exploration

            if score > best_score:
                best_score = score
                best_child = child

        return best_child

_rollout

    def _rollout(self, state, player_to_move):

        current_state = state.copy()
        current_player = player_to_move

        while not self.game.is_terminal(current_state):
            moves = self.game.get_valid_moves(current_state)
            move = self.rng.choice(moves)
            current_state = self.game.make_move(current_state, move, current_player)
            current_player = self.game.get_opponent(current_player)

        return self.game.evaluate(current_state)

_backpropagate

    def _backpropagate(self, node, outcome):

        current = node
        while current is not None:
            if current.player == "X":
                reward = outcome
            else:
                reward = -outcome

            current.N += 1
            current.W += reward

            current = current.parent

visualize_tree

Code
from graphviz import Digraph

def visualize_tree(root, max_depth=3, show_mcts_stats=True, show_edge_labels=True):

    """
    Visualize a game tree rooted at `root` using Graphviz.

    Assumes:
      - `root` is a Node with attributes:
          state, player, children: dict[move -> Node], N, W.
      - This matches the Node used in MCTSClassicSolver.

    Parameters
    ----------
    root : Node
        Root of the (sub)tree to visualize.
    max_depth : int
        Maximum depth to recurse (root at depth 0).
    show_mcts_stats : bool
        If True, include N and V for each node (compact vertical layout).
    show_edge_labels : bool
        If True, label edges with the move (e.g., (row, col)).
    """

    dot = Digraph(format="svg")

    dot.edge_attr.update(
        fontsize="8",
        fontname="Helvetica"
    )

    # Make the tree compact

    dot.graph_attr.update(
        rankdir="TB",   # top-to-bottom
        nodesep="0.15", # horizontal spacing
        ranksep="0.50", # vertical spacing
    )
    dot.node_attr.update(
        shape="box",
        fontsize="9",
        fontname="Helvetica",
        margin="0.02,0.02",
    )

    def add_node(node, node_id, depth):
        if depth > max_depth:
            return

        # Build compact label
        if show_mcts_stats and node.N > 0:
            V = node.W / node.N
            # player on top, then N, then V (vertical)
            label = f"{node.player}\\nN={node.N}\\nV={V:.2f}"
        else:
            label = f"{node.player}"

        dot.node(node_id, label=label)

        # Recurse on children
        if depth == max_depth:
            return

        for move, child in node.children.items():
            child_id = f"{id(child)}"
            if show_edge_labels:
                dot.edge(node_id, child_id, label=str(move))
            else:
                dot.edge(node_id, child_id)
            add_node(child, child_id, depth + 1)

    add_node(root, "root", depth=0)

    return dot


def display_tree(dot):
    """Preserve the vector tree in HTML, notebook, and PDF exports."""
    svg = dot.pipe(format="svg")
    encoded = b64encode(svg).decode("ascii")
    source = f"data:image/svg+xml;base64,{encoded}"
    display(HTML(
        f'<a class="lightbox" href="{source}" data-type="image">'
        '<img alt="MCTS tree with visit counts and node values" '
        f'src="{source}" '
        'style="max-width:100%;height:auto;"/>'
        '</a>'
    ))

Search Tree (num_simulations=10)

Code
game = TicTacToe()
state = game.initial_state()
player = "X"

solver = MCTSClassicSolver(num_simulations=10, seed=4)

move = solver.select_move(game, state, player)

dot = visualize_tree(solver.root, 9, True)
print(move)
display_tree(dot)
(1, 0)
MCTS tree with visit counts and node values

Search Tree (num_simulations=500)

Code
game = TicTacToe()
state = game.initial_state()
player = "X"

solver = MCTSClassicSolver(num_simulations=500, seed=4)

move = solver.select_move(game, state, player)

dot = visualize_tree(solver.root, 9, True)
print(move)
display_tree(dot)
(1, 1)
MCTS tree with visit counts and node values

Search Tree (exploration_c=math.sqrt(2)/2)

(2, 2)
MCTS tree with visit counts and node values

Search Tree (exploration_c=1e-09)

Code
game = TicTacToe()
state = game.initial_state()
player = "X"

solver = MCTSClassicSolver(num_simulations=500, exploration_c=1e-09, seed=4)

move = solver.select_move(game, state, player)

dot = visualize_tree(solver.root, 9, True)
print(move)
display_tree(dot)
(2, 2)
MCTS tree with visit counts and node values

Search Tree (exploration_c=1000)

Code
game = TicTacToe()
state = game.initial_state()
player = "X"

solver = MCTSClassicSolver(num_simulations=500, exploration_c=1000, seed=4)

move = solver.select_move(game, state, player)

dot = visualize_tree(solver.root, 9, True)
print(move)
display_tree(dot)
(2, 2)
MCTS tree with visit counts and node values

Search Tree (num_simulations=500)

Code
game = TicTacToe()
state = game.initial_state()
player = "X"

solver = MCTSClassicSolver(num_simulations=500, seed=4)

move = solver.select_move(game, state, player)

dot = visualize_tree(solver.root, 2, True)
print(move)
display_tree(dot)
(1, 1)
MCTS tree with visit counts and node values

Search Tree (num_simulations=10)

Code
game = TicTacToe()
state = game.initial_state()
player = "X"

solver = MCTSClassicSolver(num_simulations=10, seed=4)
move = solver.select_move(game, state, player)
dot = visualize_tree(solver.root, 1, True)
print(move)
display_tree(dot)
(1, 0)
MCTS tree with visit counts and node values

Search Tree (num_simulations=50)

Code
game = TicTacToe()
state = game.initial_state()
player = "X"

solver = MCTSClassicSolver(num_simulations=50, seed=4)
move = solver.select_move(game, state, player)
dot = visualize_tree(solver.root, 1, True)
print(move)
display_tree(dot)
(1, 0)
MCTS tree with visit counts and node values

Search Tree (num_simulations=250)

Code
game = TicTacToe()
state = game.initial_state()
player = "X"

solver = MCTSClassicSolver(num_simulations=250, seed=4)
move = solver.select_move(game, state, player)
dot = visualize_tree(solver.root, 1, True)
print(move)
display_tree(dot)
(1, 1)
MCTS tree with visit counts and node values

Search Tree (num_simulations=500)

Code
game = TicTacToe()
state = game.initial_state()
player = "X"

solver = MCTSClassicSolver(num_simulations=500, seed=4)
move = solver.select_move(game, state, player)
dot = visualize_tree(solver.root, 1, True)
print(move)
display_tree(dot)
(1, 1)
MCTS tree with visit counts and node values

Search Tree (num_sims=1000)

Code
game = TicTacToe()
state = game.initial_state()
player = "X"

solver = MCTSClassicSolver(num_simulations=1000, seed=4)
move = solver.select_move(game, state, player)
dot = visualize_tree(solver.root, 1, True)
print(move)
display_tree(dot)
(1, 1)
MCTS tree with visit counts and node values

Move Preference vs num_simulations

Code
def mcts_heatmaps(game, solver_class, simulations_list, player="X", seed=0):

    """
    Display heatmaps showing square visit frequencies
    for different MCTS simulation counts.

    Parameters
    ----------
    game : TicTacToe instance
    solver_class : a class such as MCTSClassicSolver
    simulations_list : list of ints (e.g. [50, 100, 200, 500, 1000])
    player : "X" or "O"
    """

    initial = game.initial_state()

    num_plots = len(simulations_list)
    fig, axes = plt.subplots(1, num_plots, figsize=(3 * num_plots, 3))

    if num_plots == 1:
        axes = [axes]  # normalize indexing

    for ax, sims in zip(axes, simulations_list):

        # ---------------------------------------------------------
        # Run MCTS
        # ---------------------------------------------------------

        solver = solver_class(num_simulations=sims, seed=seed)
        solver.reset()
        solver.select_move(game, initial, player)   # builds tree
        root = solver.root

        # ---------------------------------------------------------
        # Build a 3×3 matrix of visits
        # ---------------------------------------------------------

        visit_matrix = np.zeros((3, 3), dtype=float)

        for move, child in root.children.items():
            i, j = move
            visit_matrix[i, j] = child.N

        # ---------------------------------------------------------
        # Normalize (avoid division by zero)
        # ---------------------------------------------------------

        vmax = visit_matrix.max()
        if vmax > 0:
            heat = visit_matrix / vmax
        else:
            heat = visit_matrix

        # ---------------------------------------------------------
        # Plot heatmap
        # ---------------------------------------------------------

        im = ax.imshow(heat, cmap="viridis", vmin=0, vmax=1)
        ax.set_title(f"{sims} simulations")
        ax.set_xticks([])
        ax.set_yticks([])

    plt.tight_layout()
    plt.show()
    plt.close(fig)
Code
game = TicTacToe()

mcts_heatmaps(
    game,
    solver_class=MCTSClassicSolver,
    simulations_list=[50, 200, 500, 1000, 5000],
    player="X",
)

Tallies by X’s first move

Code
def tally_scores(game):
    """
    Enumerate all complete games of Tic-Tac-Toe from the initial position
    (X to move) and tally how many end in:

        - X win
        - draw
        - O win

    Returns
    -------
    overall : dict
        {'X': total_X_wins, 'draw': total_draws, 'O': total_O_wins}

    table : list[list[dict]]
        A 3x3 list of dicts. For each cell (i, j),
        table[i][j] = {'X': ..., 'draw': ..., 'O': ...}
        counts games where X's *first move* was at (i, j).
    """

    size = game.size  # should be 3 for standard Tic-Tac-Toe

    # Overall tallies for all games
    overall = {'X': 0, 'draw': 0, 'O': 0}

    # Per-first-move tallies as a 3x3 grid
    table = [
        [ {'X': 0, 'draw': 0, 'O': 0} for _ in range(size) ]
        for _ in range(size)
    ]

    def recurse(state, player, first_move):

        """
        Depth-first enumeration of all complete games.

        Parameters
        ----------
        state : board position (NumPy array)
        player : 'X' or 'O' (player to move)
        first_move : None, or (row, col) of X's very first move
        """

        # Base case: terminal state → classify outcome

        if game.is_terminal(state):
            v = game.evaluate(state)  # +1 (X win), -1 (O win), 0 (draw)

            if v > 0:
                outcome = 'X'
            elif v < 0:
                outcome = 'O'
            else:
                outcome = 'draw'

            # Update overall tally
            overall[outcome] += 1

            # If we know X's first move, update that cell's tally too
            if first_move is not None:
                i, j = first_move
                table[i][j][outcome] += 1

            return

        # Recursive case: expand all legal moves
        for move in game.get_valid_moves(state):
            next_state = game.make_move(state, move, player)
            next_player = game.get_opponent(player)

            # Record X's very first move
            if first_move is None and player == "X":
                fm = move  # this becomes the first_move for the rest of this branch
            else:
                fm = first_move

            recurse(next_state, next_player, fm)

    # Start from the empty board, X to move, and no first_move yet
    initial_state = game.initial_state()
    recurse(initial_state, player="X", first_move=None)

    return overall, table

def print_tally_table(table):

    """
    Print a 3x3 table of tallies.

    Each cell shows: X:<wins> D:<draws> O:<wins>
    where counts are restricted to games where X's first move
    was played in that cell.
    """

    size = len(table)
    for i in range(size):
        row_cells = []
        for j in range(size):
            stats = table[i][j]
            cell_str = f"X:{stats['X']} D:{stats['draw']} O:{stats['O']}"
            row_cells.append(cell_str)
        print(" | ".join(row_cells))
    print()

def print_tally_table_percentages(table):

    """
    Print a 3x3 table of tallies.

    Each cell shows: X:<wins> D:<draws> O:<wins>
    where counts are restricted to games where X's first move
    was played in that cell.
    """

    size = len(table)
    for i in range(size):
        row_cells = []
        for j in range(size):
            stats = table[i][j]
            cell_str = f"X:{stats['X']/255168:.2%} D:{stats['draw']/255168:.2%} O:{stats['O']/255168:.2%}"
            row_cells.append(cell_str)
        print(" | ".join(row_cells))
    print()


game = TicTacToe()

overall, table = tally_scores(game)

print("Overall tally:")
print(overall)  # {'X': ..., 'draw': ..., 'O': ...}

print("\nTallies by X's first move (3x3 grid):")
print_tally_table(table)

print("\nTallies by X's first move (3x3 grid) as percentages:")
print_tally_table_percentages(table)

Overall tally:

{‘X’: 131184, ‘draw’: 46080, ‘O’: 77904}

{‘X’: 51.41%, ‘draw’: 18.06%, ‘O’: 30.53%}

Tallies by X’s first move (3x3 grid, X/draw/O):

14652/5184/7896 14232/5184/10176 14652/5184/7896
14232/5184/10176 15648/4608/5616 14232/5184/10176
14652/5184/7896 14232/5184/10176 14652/5184/7896

Tallies by X’s first move (3x3 grid, X/draw/O) as percentages:

5.74% / 2.03% / 3.09% 5.58% / 2.03% / 3.99% 5.74% / 2.03% / 3.09%
5.58% / 2.03% / 3.99% 6.13% / 1.81% / 2.20% 5.58% / 2.03% / 3.99%
5.74% / 2.03% / 3.09% 5.58% / 2.03% / 3.99% 5.74% / 2.03% / 3.09%

evaluate_solvers_with_plot

Code
def evaluate_solvers_with_plot(game, solver_X, solver_O, num_games):
    """
    Play 'num_games' games between solver_X (as 'X') and solver_O (as 'O'),
    track cumulative performance, and plot running average scores.

    Scoring is from X's perspective:
        outcome = +1  if X wins
        outcome = -1  if O wins
        outcome =  0  if draw

    The running average score for O is simply the negative of X's
    running average (zero-sum).
    """

    runner = GameRunner(game)

    # Counters for final summary
    results = {
        "X_wins": 0,
        "O_wins": 0,
        "draws": 0,
    }

    # For plotting: running average score as a function of game index
    avg_scores_X = []
    avg_scores_O = []

    cumulative_score_X = 0.0

    for i in range(num_games):
        outcome = runner.play_game(solver_X, solver_O)
        # Update win/draw counters
        if outcome == 1:
            results["X_wins"] += 1
        elif outcome == -1:
            results["O_wins"] += 1
        else:
            results["draws"] += 1

        # Update cumulative score (from X's perspective)
        cumulative_score_X += outcome
        avg_X = cumulative_score_X / (i + 1)
        avg_O = -avg_X  # zero-sum

        avg_scores_X.append(avg_X)
        avg_scores_O.append(avg_O)

    # Plot running average scores
    games = range(1, num_games + 1)
    plt.figure(figsize=(8, 4))
    plt.plot(games, avg_scores_X, label=f"X: {solver_X.get_name()}")
    plt.plot(games, avg_scores_O, label=f"O: {solver_O.get_name()}")
    plt.axhline(0.0, linestyle="--", linewidth=1)
    plt.xlabel("Game number")
    plt.ylabel("Average score")
    plt.title("Running average score (X perspective)")
    plt.legend()
    plt.tight_layout()
    plt.show()

    return results, avg_scores_X, avg_scores_O

Random vs MCTS

rand = RandomSolver(seed=0)
mcts = MCTSClassicSolver(num_simulations=10, seed=1)

results, avg_X, avg_O = evaluate_solvers_with_plot(game, rand,  mcts, num_games=100)
results

Random vs MCTS

{'X_wins': 21, 'O_wins': 68, 'draws': 11}

Random vs MCTS

rand = RandomSolver(seed=0)
mcts = MCTSClassicSolver(num_simulations=100, seed=1)

results, avg_X, avg_O = evaluate_solvers_with_plot(game, rand,  mcts, num_games=100)
results

Random vs MCTS

{'X_wins': 2, 'O_wins': 85, 'draws': 13}

MCTS vs Random

mcts = MCTSClassicSolver(num_simulations=10, seed=0)
rand = RandomSolver(seed=0)

results, avg_X, avg_O = evaluate_solvers_with_plot(game, mcts, rand, num_games=100)
results

MCTS vs Random

{'X_wins': 89, 'O_wins': 6, 'draws': 5}

MCTS vs Random

mcts = MCTSClassicSolver(num_simulations=100, seed=0)
rand = RandomSolver(seed=0)

results, avg_X, avg_O = evaluate_solvers_with_plot(game, mcts, rand, num_games=100)
results

MCTS vs Random

{'X_wins': 99, 'O_wins': 0, 'draws': 1}

Minimax vs MCTS

minimax = MinimaxSolver()
mcts = MCTSClassicSolver(num_simulations=10, seed=2)

results, avg_X, avg_O = evaluate_solvers_with_plot(game, minimax, mcts, num_games=100)
results

Minimax vs MCTS

{'X_wins': 94, 'O_wins': 0, 'draws': 6}

Minimax vs MCTS

minimax = MinimaxSolver()
mcts = MCTSClassicSolver(num_simulations=100, seed=2)

results, avg_X, avg_O = evaluate_solvers_with_plot(game, minimax, mcts, num_games=100)
results

Minimax vs MCTS

{'X_wins': 49, 'O_wins': 0, 'draws': 51}

Minimax vs MCTS

minimax = MinimaxSolver()
mcts = MCTSClassicSolver(num_simulations=500, seed=2)

results, avg_X, avg_O = evaluate_solvers_with_plot(game, minimax, mcts, num_games=100)
results

Minimax vs MCTS

{'X_wins': 13, 'O_wins': 0, 'draws': 87}

MCTS vs Minimax

mcts = MCTSClassicSolver(num_simulations=10, seed=2)
minimax = MinimaxSolver()

results, avg_X, avg_O = evaluate_solvers_with_plot(game, mcts, minimax, num_games=100)
results

MCTS vs Minimax

{'X_wins': 0, 'O_wins': 55, 'draws': 45}

MCTS vs Minimax

mcts = MCTSClassicSolver(num_simulations=100, seed=2)
minimax = MinimaxSolver()

results, avg_X, avg_O = evaluate_solvers_with_plot(game, mcts, minimax, num_games=100)
results

MCTS vs Minimax

{'X_wins': 0, 'O_wins': 1, 'draws': 99}

MCTS vs Minimax

mcts = MCTSClassicSolver(num_simulations=500, seed=2)
minimax = MinimaxSolver()

results, avg_X, avg_O = evaluate_solvers_with_plot(game, mcts, minimax, num_games=100)
results

MCTS vs Minimax

{'X_wins': 0, 'O_wins': 0, 'draws': 100}

MCTS (few sims) vs MCTS (few sims)

mcts_a = MCTSClassicSolver(num_simulations=10, seed=3)
mcts_b = MCTSClassicSolver(num_simulations=10, seed=4)

results, avg_X, avg_O = evaluate_solvers_with_plot(game, mcts_a, mcts_b, num_games=100)
results

MCTS (few sims) vs MCTS (few sims)

{'X_wins': 64, 'O_wins': 23, 'draws': 13}

MCTS (few sims) vs MCTS (many sims)

mcts_a = MCTSClassicSolver(num_simulations=10, seed=3)
mcts_b = MCTSClassicSolver(num_simulations=500, seed=4)

results, avg_X, avg_O = evaluate_solvers_with_plot(game, mcts_a, mcts_b, num_games=100)
results

MCTS (few sims) vs MCTS (many sims)

{'X_wins': 2, 'O_wins': 51, 'draws': 47}

Same Computational Budget

10 new simulations per decision for each player.

mcts_a = MCTSSolver(num_simulations=10, seed=3)
mcts_c = MCTSClassicSolver(num_simulations=10, seed=4)
results, _, _ = evaluate_solvers_with_plot(game, mcts_a, mcts_c, num_games=100)
results

Same Computational Budget

{'X_wins': 80, 'O_wins': 14, 'draws': 6}

Learner vs Thinker

a = MCTSSolver(num_simulations=10, seed=3)
b = MCTSClassicSolver(num_simulations=40, seed=4)

results, _, _ = evaluate_solvers_with_plot(game, a, b, num_games=375)
results

Learner vs Thinker

{'X_wins': 258, 'O_wins': 7, 'draws': 110}

Learner vs Minimax

a = MCTSSolver(num_simulations=10, seed=3)
b = MinimaxSolver()

results, _, _ = evaluate_solvers_with_plot(game, a, b, num_games=375)
results

Learner vs Minimax

{'X_wins': 0, 'O_wins': 9, 'draws': 366}

Learner vs Minimax

a = MCTSSolver(num_simulations=20, seed=3)
b = MinimaxSolver()

results, _, _ = evaluate_solvers_with_plot(game, a, b, num_games=375)
results

Learner vs Minimax

{'X_wins': 0, 'O_wins': 1, 'draws': 374}

Learner vs Minimax

a = MCTSSolver(num_simulations=50, seed=3)
b = MinimaxSolver()

results, _, _ = evaluate_solvers_with_plot(game, a, b, num_games=375)
results

Learner vs Minimax

{'X_wins': 0, 'O_wins': 1, 'draws': 374}

Exploration

  • Incorporate heuristics to detect when a winning move is achievable in a single step.

  • Experiment with varying the number of iterations and the constant C.

Monte Carlo Tree Search

  • In our current code:
    • Selection: follow the tree (UCT) to promising nodes
    • Expansion: add a new child node
    • Rollout: play random moves to the end of the game
    • Backpropagation: send the final result back up the tree

Monte Carlo Tree Search

  • This works very well for Tic-Tac-Toe, but:
    • Random rollouts can be slow and noisy in larger games
    • The rules and terminal utilities are known, but a fresh tree estimates nonterminal values from simulations.

Add a Policy Network

Goal: give MCTS a better idea of which moves to explore first.

New component: policy network

  • Input: a board position
  • Output: a probability for each legal move
    • “In this position, move A looks 40%, move B 30%, move C 10%, …”

Add a Policy Network

Usage inside MCTS:

  • At a new node (when we expand a state):
    1. Call the policy network on the board
    2. Store the move probabilities as priors for this node
  • During selection:
    • MCTS still uses visit counts from the tree
    • But now it also uses the policy priors to prefer moves that look good according to the network

Add a Value Network

Goal: avoid long random rollouts and get a direct estimate of how good a position is.

New component: value network

  • Input: a board position
  • Output: a single number estimating X’s expected return:
    • Close to +1 if X is likely to win
    • Close to -1 if O is likely to win
    • Near 0 for a balanced expected return

Add a Value Network

Usage inside MCTS:

  • At a leaf node (frontier of the tree):
    • Instead of doing a random rollout:
      1. Call the value network on the board
      2. Use its output as the leaf value
      3. Backpropagate this value up the tree

AlphaTicTacToe

Putting it together (AlphaGo-style “AlphaTicTacToe”):

  • MCTS + policy network:
    • Guides which moves to explore
  • MCTS + value network:
    • Evaluates positions without random playouts
  • Over time, both networks can be trained from example games (e.g., self-play):
    • Policy network learns “good moves”
    • Value network learns “good positions”

Epilogue

Summary

  • MCTS allocates simulations using evolving estimates and exploration bonuses.
  • Node values require a stated player perspective.
  • The search-time UCT choice differs from the final root action rule.
  • A larger budget provides more evidence, without a finite-run guarantee.
  • Persistent search can reuse valid statistics; reset and cache policy must be explicit.
  • Policy and value models can guide the same search process.

Closing Questions

  • When would exact minimax be preferable? When would sampling be useful?
  • Which information in a search result is proved, estimated, or observed?
  • What does a fair computational comparison require?

References

Browne, Cameron B., Edward Powley, Daniel Whitehouse, et al. 2012. “A Survey of Monte Carlo Tree Search Methods.” IEEE Transactions on Computational Intelligence and AI in Games 4 (1): 1–43. https://doi.org/10.1109/TCIAIG.2012.2186810.
Russell, Stuart, and Peter Norvig. 2020. Artificial Intelligence: A Modern Approach. 4th ed. Pearson. http://aima.cs.berkeley.edu/.
Świechowski, Maciej, Konrad Godlewski, Bartosz Sawicki, and Jacek Mańdziuk. 2023. “Monte Carlo Tree Search: a review of recent modifications and applications.” Artificial Intelligence Review 56 (3): 2497–562. https://doi.org/10.1007/s10462-022-10228-y.

Appendix

Blending Logic and Learning

Further Exploration

Marcel Turcotte

[email protected]

School of Electrical Engineering and Computer Science (EECS)

University of Ottawa