CSI 4106 Introduction to Artificial Intelligence
Version: Nov 30, 2026 08:21
A rollout has just ended in an X win. What happens next?
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) |
The game rules, solvers, and runner are the same as in Lecture 22.
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_moveclass 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.parentNodeclass 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 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_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)_backpropagatevisualize_treefrom 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>'
))num_simulations=10)num_simulations=500)exploration_c=math.sqrt(2)/2)exploration_c=1e-09)exploration_c=1000)num_simulations=500)num_simulations=10)num_simulations=50)num_simulations=250)num_simulations=500)num_sims=1000)num_simulationsdef 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)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_plotdef 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_Oclass MCTSSolver(MCTSClassicSolver):
"""Reuse state/action statistics across decisions when reuse=True.
States are keyed by (board, player to move). Repeated positions can
have several parents. Each parent-action edge therefore keeps its own
N and W, with W expressed from the parent's perspective. UCT and the
final action rule use these edge counts, not a child's global visits.
reuse=False clears the same implementation before each decision.
Reuse is valid only while the game rules and evaluation stay fixed.
"""
def __init__(
self, num_simulations=500, exploration_c=math.sqrt(2),
seed=None, reuse=True,
):
super().__init__(num_simulations, exploration_c, seed)
self.reuse = reuse
self.tree = {}
self.root_key = None
def reset(self):
"""Start a game, retaining valid analysis and the random stream."""
super().reset()
self.root_key = None
if not self.reuse:
self.clear_cache()
def clear_cache(self):
"""Discard retained analysis if rules or evaluation change."""
self.tree.clear()
self.root_key = None
@property
def root_visits(self):
if self.root_key is None:
return 0
return self.tree[self.root_key]["N"]
@property
def tree_size(self):
return len(self.tree)
def get_name(self):
mode = "retained" if self.reuse else "fresh"
return f"MCTS-state-{mode}({self.num_simulations})"
def select_move(self, game, state, player):
"""Synchronize from the actual board, then add new simulations."""
if game is not self.game or not self.reuse:
self.clear_cache()
self.game = game
self._start_decision()
self.root_key = (canonical(state), player)
node = self._get_or_create_node(self.root_key)
self.retained_root_visits = node["N"]
if game.is_terminal(state):
self._finish_decision()
return None
for _ in range(self.num_simulations):
self._run_simulation()
self._finish_decision()
best_move, best_key = None, (-1, -math.inf)
for move, edge in node["children"].items():
key = (edge["N"], edge["W"] / edge["N"])
if key > best_key:
best_move, best_key = move, key
return best_move
def opponent_played(self, move):
"""The next select_move receives the actual board; no guess needed."""
pass
def _get_or_create_node(self, key):
if key not in self.tree:
board, player = key
self.tree[key] = {
"player": player, "N": 0, "W": 0.0,
"children": {},
"untried_moves": list(
self.game.get_valid_moves(np.array(board))
),
}
self.decision_nodes += 1
return self.tree[key]
def _run_simulation(self):
key = self.root_key
nodes, edges = [], []
while True:
node = self.tree[key]
nodes.append(key)
state = np.array(key[0])
if self.game.is_terminal(state):
outcome = self.game.evaluate(state)
break
if node["untried_moves"]:
move = self.rng.choice(node["untried_moves"])
node["untried_moves"].remove(move)
state = self.game.make_move(state, move, node["player"])
player = self.game.get_opponent(node["player"])
child_key = (canonical(state), player)
self._get_or_create_node(child_key)
node["children"][move] = {
"child": child_key, "N": 0, "W": 0.0,
}
self.decision_edges += 1
edges.append((key, move))
nodes.append(child_key)
outcome = self._rollout(state, player)
break
move, edge = self._select_edge(node)
edges.append((key, move))
key = edge["child"]
self._backpropagate_graph(nodes, edges, outcome)
self.decision_simulations += 1
def _select_edge(self, node):
best_move, best_edge, best_score = None, None, -math.inf
for move, edge in node["children"].items():
if edge["N"] == 0:
score = math.inf
else:
# Edge rewards already use this parent's perspective.
mean = edge["W"] / edge["N"]
bonus = self.exploration_c * math.sqrt(
math.log(node["N"]) / edge["N"]
)
score = mean + bonus
if score > best_score:
best_move, best_edge, best_score = move, edge, score
return best_move, best_edge
def _backpropagate_graph(self, nodes, edges, outcome):
for key in nodes:
node = self.tree[key]
reward = outcome if node["player"] == "X" else -outcome
node["N"] += 1
node["W"] += reward
for key, move in edges:
node = self.tree[key]
edge = node["children"][move]
reward = outcome if node["player"] == "X" else -outcome
edge["N"] += 1
edge["W"] += reward10 new simulations per decision for each player.
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.
Where we are now: plain MCTS
Goal: give MCTS a better idea of which moves to explore first.
New component: policy network
Usage inside MCTS:
Goal: avoid long random rollouts and get a direct estimate of how good a position is.
New component: value network
Usage inside MCTS:
Putting it together (AlphaGo-style “AlphaTicTacToe”):
Marcel Turcotte
School of Electrical Engineering and Computer Science (EECS)
University of Ottawa