Contents
Figure 1: Monte Carlo Tree Search Explained with a Connect Four Example — a board awaiting its first move, which is exactly the position where random playouts must rediscover strategy on their own
Minimax needs two things: a game you can search deeply and a way to score positions that aren't finished. Many games give you neither. Monte Carlo Tree Search (MCTS) sidesteps both: it learns which moves look promising by playing thousands of random games and steering its attention toward the winners. I'll explain the four steps, build an MCTS player for Connect Four in Python, and run experiments that show what the algorithm does well and where it struggles. Every number below comes from code I ran.
Why MCTS?
Minimax with alpha-beta pruning works beautifully on tic-tac-toe — I walked through that engine in Minimax and Alpha-Beta Pruning Explained. For harder games, it leans on a hand-built evaluation function, and writing a good one takes expertise. MCTS needs only the rules of the game: which moves are legal, and who won. It builds a search tree incrementally through random simulation, which is where the "Monte Carlo" in the name comes from, and it spends more effort on branches that look promising.
MCTS also works as an anytime algorithm: you can stop it after any number of iterations and ask for its best move, and more iterations give better answers. The method gained attention after its breakthrough performance in Go, and AlphaZero-style systems use a modified version of it. If the overall landscape of search is new to you, the classical AI for beginners guide sets the context before you dive into the tree.
The Four Steps
Every MCTS iteration runs the same four phases:
- Selection: Starting at the root, walk down the tree by repeatedly choosing the child that looks best, until you reach a node with unexplored moves.
- Expansion: Add one new child node for an untried move.
- Simulation (rollout): From the new node, play random moves until the game ends.
- Backpropagation: Send the result back up the path, updating visit counts and win totals.
Repeat thousands of times. After the last iteration, pick the root's best move.
Choosing Which Child to Visit: UCB1
Selection has to balance two goals: exploit moves that have won often, and explore moves you haven't tried much. The standard rule is UCT, which applies the UCB1 bandit formula to trees:
score(child) = wins / visits + C * sqrt( ln(parent visits) / visits )
The first term rewards a high win rate. The second grows for rarely visited children, which forces occasional exploration. The constant C sets the balance. The UCT paper by Kocsis and Szepesvári shows that C = √2 is necessary for asymptotic convergence when rewards lie between 0 and 1, though it can be tuned for each domain [2], building on the UCB1 bound from Auer, Cesa-Bianchi and Fischer [3].
Be aware that sources write the formula in different forms, with factors of 2 in different places, so compare conventions before copying a constant. In my code, C = 1.4 approximates √2.
Build Connect Four
Connect Four is a good test: seven possible moves per turn, games lasting 20 or so plies, and no trivial solution a human can see at a glance. I stored the board as a flat tuple of 42 cells, with column heights tracked separately, and checked for a win only around the piece just played:
ROWS, COLS = 6, 7
DIRS = ((0, 1), (1, 0), (1, 1), (1, -1))
def wins_at(board, r, c, p):
for dr, dc in DIRS:
n = 1
for sgn in (1, -1):
rr, cc = r + sgn*dr, c + sgn*dc
while 0 <= rr < ROWS and 0 <= cc < COLS and board[rr*COLS + cc] == p:
n += 1; rr += sgn*dr; cc += sgn*dc
if n >= 4: return True
return False
Checking only the last piece keeps the win test cheap, and that matters because a simulation calls it at every ply. A State class holds the board, the column heights, whose turn it is, and the winner (0 for none, 1 or 2 for a player, 3 for a draw). Its play(col) method returns a new state, so the tree never mutates a position it might revisit.
The MCTS Loop
Here's the core, trimmed for the article. The full version has a Node class tracking visits, accumulated value, and untried moves:
def mcts(root_state, iterations, rng, C=1.4):
root = Node(root_state)
for _ in range(iterations):
node = root
# 1. selection
while not node.untried and node.children:
lnN = math.log(node.visits)
node = max(node.children,
key=lambda ch: ch.value / ch.visits + C * math.sqrt(lnN / ch.visits))
# 2. expansion
if node.untried:
m = node.untried.pop(rng.randrange(len(node.untried)))
child = Node(node.state.play(m), node, m)
node.children.append(child); node = child
# 3. simulation
result = rollout(node.state, rng)
# 4. backpropagation
while node is not None:
node.visits += 1
node.value += 1.0 if result == node.mover else (0.5 if result == DRAW else 0.0)
node = node.parent
return max(root.children, key=lambda ch: ch.visits).move
Two details deserve attention:
- Perspective: each node stores the value from the viewpoint of the player who made the move into that node (
node.mover). That's why selecting the child with the highest win rate always favors the player choosing at the parent. Getting this wrong is the classic MCTS bug, and it produces a bot that plays for the opponent. - Final choice: the algorithm returns the child with the most visits, not the highest win rate. A child with a few lucky visits can show a high win rate, while heavy visiting means the search repeatedly judged the move worth examining. That's a common convention, though I'm stating it from general knowledge.
Watching It Think
I ran 2,000 iterations from the empty board and printed the root's statistics:
column visits win rate
0 252 0.54
1 258 0.54
2 200 0.51
3 624 0.63 <- center
4 266 0.55
5 188 0.50
6 212 0.52
The search poured 31% of its visits into the center column, where simulated games won most often. Center control is well known as the strongest opening in Connect Four, and MCTS rediscovered it from random playouts alone, with no strategy coded in. FYI, a purely random game from the empty board favors the first player, who won 55% of my random games.
Experiments
All matches used fixed random seeds, and each agent played both colors. Sample sizes are small (30 to 40 games), so treat the numbers as indications, not proof.
1. Does It Beat Random Play?
MCTS(200 iterations) vs random: 40 wins, 0 losses
MCTS(20 iterations) vs random: 38 wins, 2 losses
Even 20 iterations per move crush random play, which says something about how weak random play actually is.
2. Does It See Immediate Tactics?
I built two positions: one where the player to move can win at once, and one where the player must block an opponent's winning move. I ran 50 trials at each iteration count:
iterations finds the winning move blocks the threat
20 30/50 23/50
100 50/50 49/50
500 50/50 50/50
2000 50/50 50/50
At 20 iterations the search is noisy: blind guessing would choose the right column about 14% of the time, so 20 iterations helps but isn't reliable. By 100 iterations, the tactics become nearly perfect.
3. How Much Does Thinking Time Help?
MCTS(1000) vs MCTS(100): 35 wins, 3 losses, 2 draws (score 0.90)
MCTS(5000) vs MCTS(1000): 19 wins, 10 losses, 1 draw (score 0.65)
A tenfold increase from 100 to 1,000 iterations gives a big advantage, while a fivefold increase from 1,000 to 5,000 helps less and shows more noise. That pattern of diminishing returns fits my general expectation of MCTS, though 30 games can't pin down the exact curve.
4. What About the Exploration Constant?
Each variant played against the default C = 1.4, all at 1,000 iterations:
C = 0.0 vs C = 1.4: 0 wins, 40 losses (score 0.00)
C = 0.3 vs C = 1.4: 17 wins, 21 losses, 2 draws (score 0.45)
C = 4.0 vs C = 1.4: 10 wins, 30 losses (score 0.25)
Zero exploration lost every game: with C = 0, the search commits to whichever move looked good first and never reconsiders. Too much exploration (C = 4.0) also lost, since the search wastes iterations on weak moves. A modest value near the default performed about the same as 0.3, so the lesson is that C has a wide flat optimum but two bad extremes.
5. Do Smarter Rollouts Help?
Random rollouts are cheap but ignore tactics. I added a simple rule to the rollout policy: take an immediate win if one exists, otherwise block an immediate loss, otherwise play randomly.
smart rollouts(200) vs vanilla(200): 21 wins, 9 losses (score 0.70)
smart rollouts(200) vs vanilla(4000) [similar time]: 9 wins, 20 losses, 1 draw (score 0.32)
At equal iteration counts, the smarter rollouts clearly won. But my smarter rollouts ran about 22 times slower per iteration, so at roughly equal time the plain version won. My implementation is unoptimized — it re-scans every column for threats at every ply — so a well-engineered version would narrow that gap. The honest takeaway: better rollouts improve the quality of each simulation, but you pay for it in simulation count, and the tradeoff depends on implementation speed.
Strengths and Weaknesses
Strengths:
- No evaluation function needed: just rules and simulation.
- Anytime: more time gives better moves, and you can stop whenever you like.
- Asymmetric growth: the tree deepens where results look promising.
- Handles large branching factors better than brute-force search.
Weaknesses:
- Random rollouts miss deep tactical traps. A move that loses to a single precise reply can still look good if most random replies fail to find it. That is from general knowledge, and it is why strong engines add domain knowledge or neural networks.
- Variance: results depend on random sampling, so the same position can give different moves.
- Cost: you need many simulations per move.
- Tuning: the exploration constant and rollout policy matter, and good values vary by domain.
Tuning Tips
- Start with C ≈ √2, then test a few values against each other.
- Reuse the tree between moves: after the opponent moves, keep the matching subtree instead of starting over. That is a common technique from my general knowledge.
- Improve rollouts cautiously: add cheap rules first, and measure the speed cost.
- Use robust move selection: pick by visit count.
- Parallelize: run several searches or simulations at once, then combine the visit statistics.
- Test with many games and fixed seeds, and report results with their sample sizes.
Common Mistakes
- Mixing up whose turn the value represents: this produces a bot that plays for the opponent.
- Choosing the final move by raw win rate: low-visit children can look deceptively good.
- Forgetting terminal nodes: a node that ends the game must never expand.
- Setting C to zero: the search gets stuck on early impressions.
- Judging from a handful of games: variance hides real differences :/
- Skipping legality checks: a full column must not offer a move.
- Assuming more iterations always help linearly: returns diminish.
Best Book to Read
| Cover | Book | Description | Get it |
|---|---|---|---|
![]() |
Deep Learning and the Game of Go | it builds a Go engine from scratch, introduces MCTS and UCT in code, and then shows exactly how a neural network replaces random rollouts in an AlphaZero-style agent. | View on Amazon |
As an Amazon Associate I earn from qualifying purchases. Links on this page are affiliate links, and I may earn a commission at no extra cost to you.
Read it after your Connect Four bot already plays. The book's MCTS chapters land harder once you have watched visit counts flow toward the center column on your own board and wondered why.
Wrapping Up
MCTS builds a game tree through repeated selection, expansion, random simulation, and backpropagation, balancing exploration and exploitation with UCB1. In my Connect Four tests it beat random play almost every time, found tactical wins and blocks reliably by 100 iterations, rediscovered center control on its own, and improved with more thinking time at a diminishing rate. Exploration settings mattered: none lost every game, and too much lost too.
Copy the code, run it for 1,000 iterations against yourself, and watch the root statistics change as the position changes. Then try your own rollout rule and measure it fairly — same seeds, both colors, and enough games to see past the noise. What game will you give MCTS next?
Frequently Asked Questions
What is Monte Carlo Tree Search in simple terms?
MCTS builds a game tree by playing thousands of random games from promising positions. Each iteration selects a path down the tree, expands one new move, simulates the rest of the game with random moves, and sends the win or loss back up the path. It needs only the game rules, not a hand-written evaluation function.
What is the difference between MCTS and minimax?
Minimax searches the full game tree and needs an evaluation function to score unfinished positions. MCTS grows the tree incrementally through random simulation, so it needs only the rules of the game. Minimax is exact but explodes on large branching factors; MCTS trades exactness for anytime, sampling-based effort.
Why is UCB1 used for selection in MCTS?
UCB1 balances exploitation and exploration. It scores each child by win rate plus an exploration bonus that grows for rarely visited children, so the search follows strong moves without abandoning the ones it has not tried. The constant C sets the balance, and the UCT paper shows C equals the square root of 2 gives asymptotic convergence when rewards lie between 0 and 1.
How many iterations does MCTS need per move?
It depends on the game and the implementation. In my Connect Four tests, 20 iterations per move already beat random play, but finding an immediate win or block reliably took about 100 iterations, and 500 to 2,000 made the tactics essentially perfect. More iterations give better moves, at a diminishing rate of return.
Does MCTS need a neural network?
No. Plain MCTS uses random rollouts and the game rules alone. Neural networks are an optional upgrade: AlphaZero-style systems replace random rollouts and the search policy with a trained network, which makes each simulation count for far more. The core loop of selection, expansion, simulation and backpropagation is unchanged.
Sources
[1]Browne et al., A Survey of Monte Carlo Tree Search Methods (2012) - the standard survey of the four phases, UCT, rollout policies and application domains: ieeexplore.ieee.org[2]Kocsis and Szepesvári, Bandit Based Monte-Carlo Planning (2006) - introduces UCT and shows the exploration constant for asymptotic convergence: link.springer.com[3]Auer, Cesa-Bianchi and Fischer, Finite-time Analysis of the Multiarmed Bandit Problem (2002) - the UCB1 bound that UCT applies to trees: link.springer.com[4]Silver et al., Mastering the Game of Go with Deep Neural Networks and Tree Search (2016) - AlphaGo, the system that paired MCTS with a neural network: nature.com[5]Russell and Norvig, Artificial Intelligence: A Modern Approach (4th edition) - Monte Carlo tree search, bandit problems and game playing in one chapter: aima.cs.berkeley.edu
