♟️ Game Trees
🔍 Searching in games
In the previous chapters we saw how search algorithms help solve puzzles and problems, such as finding a way out of a maze, solving the Tower of Hanoi puzzle or finding the fastest route through a city. These problems all have something in common: there is only one "player", who decides which actions are needed to reach a solution.
But what if you are dealing with games in which several players compete against each other? Then everything becomes a lot more complex. Your opponent is neither passive nor under your control: they actively try to beat you and seize every chance to thwart your plans. That calls for a different approach than the search algorithms you have seen so far in this course. Can you beat the AI opponent below at Connect Four (external link)? You take turns dropping a disc into a column, where it always lands in the lowest free cell of that column: so you choose the column, but not the height.
How can a computer play this game automatically? To win, you have to get four in a row. So a position is good when you are close to four in a row and your opponent is not. A simple measure to estimate this is the number of threats: the empty cells where one more disc would give a player four in a row. The more threats you have and the fewer your opponent has, the better your position. We sum that up in a single number: the number of threats of 🔵blue minus the number of threats of 🔴red. Blue wants that number as high as possible, red as low as possible.
A simple strategy for the computer is then: try every possible move, count both players' threats after each move, and pick the move with the best difference. Play a move below: the search tree that the AI (🔴red) used to choose its reply then appears next to the board. It looks only one turn ahead. Under each possible move is the difference in threats after that move (🔵blue minus 🔴red), labeled . Red picks the move with the lowest number. That move gets a green outline; moves with a black outline were just as good but were not chosen. When there is a tie, the AI picks the column closest to the middle. The colored dots on the board show the threats: on those cells blue or red would get four in a row, even if the cell cannot be reached yet.
But this is not the smartest strategy, because you look only one step into the future. What if your move happens to make the very cell reachable where your opponent wins?
In the game position below, on a smaller board with six columns, it is red's turn. If red drops a disc into the third column, two red threats appear at once: a vertical one and a diagonal one. Looking only one step deep, that is the best move: a greedy move. But that disc lifts the next blue disc to exactly the cell above it, where blue completes a diagonal of four. Look in the search tree to see which move the AI wants to play, then click the arrow below the board to see that move and blue's reply.
Had the AI looked one move further, it would have avoided the third column. Greedy moves can be harmful in the longer run. To avoid them, the AI has to look several moves ahead at the game positions that may follow. That turns it into a search problem.
🚫 The problem with ordinary search algorithms
Now you might think: "Why not just use the familiar search algorithms from the previous chapters to compute optimal paths to victory?" The problem is that you do not know which move your opponent will make, and you cannot decide that yourself either.
If you model the problem as a search problem and use an ordinary search algorithm, the algorithm always picks the opponent's moves that are as favorable as possible for you. It effectively assumes that your opponent is the worst player ever: someone who deliberately makes the moves that suit you perfectly, so that you win. That is of course not realistic.
In the real world you want to assume the opposite: that you are playing against the strongest possible opponent. You want to choose a move that keeps your score as high as possible in the worst case. How can you generalize the solution method to learn to play this kind of game optimally? You do that with minimax game trees, which take into account that the opponent also wants to play optimally for themselves.
🌲 Minimax game trees
A minimax game tree represents the search space of a competitive game with alternating turns between two players who each have different interests. The tree contains the game states from a given turn up to a given number of turns deep.
You can draw such a game tree for any two-player game: Connect Four, tic-tac-toe, chess, and so on. The specific rules of the game only determine how you get from one game state to the possible next game states. The reasoning of minimax always stays the same.
A game state describes the complete status of a game at a given moment: the board configuration, whose turn it is, and all other information needed to continue playing from that state. It plays the same role as a state in search algorithms, applied to the context of a game.
One player tries to make a certain game score as high as possible (MAX), the other as low as possible (MIN). Since the outcome of a game is usually only known at the end (in Connect Four you only know who wins once four discs actually lie in a row), a minimax game tree uses a heuristic to estimate which player a given game state favors.
A single score is enough for both players because Connect Four, chess and most other board games are zero-sum games.
A zero-sum game is a game in which one player's gain is exactly the other player's loss. If you give a win point, a loss and a draw , the outcomes of the two players always add up to zero. What is good for MAX is therefore equally bad for MIN.
🧩 Abstract form
Below is a game tree that looks two turns deep. The red MIN and blue MAX on the left show whose turn it is in each row. Depending on that, that player tries to make the score of the board as low as possible (MIN) or as high as possible (MAX).
You build such a tree from the top down. At the top is the current game state, in which it is the blue MAX player's turn. The row below it contains every game state MAX can reach in one move; in each of them it is the red MIN player's turn. The bottom row contains, for each of those states, every game state MIN can turn it into with one move. That is where the tree stops: those bottom game states (the leaves of the tree) were given a score by a heuristic.
Once the tree is built and the leaves have a score, you work your way back up from the bottom to find the best next move for MAX.
Minimax assumes that the MIN opponent always picks the move that makes the score as low as possible. So in the left branch MIN picks the game state with score 3, in the middle branch -2, and in the right branch the game state with score -8.
The MAX player in turn now picks the game state with the highest score, given that the MIN player plays optimally. Out of the three possible next moves, MAX therefore picks the left one, with score 3. That way the MAX player is sure to get a score of at least 3 even in the worst case, whatever the MIN player does.
You can repeat this pattern to build deeper game trees that think even more moves ahead. When you want to use a minimax algorithm for a game, you first decide how many turns deep you want to look. The deeper you look, the smarter the algorithm plays, but the longer it takes to compute the best move. The minimax search tree then works out every move up to that depth and computes a score for each of those game states with an evaluation function, to estimate who has the best chance of winning.
🔭 Looking further ahead in Connect Four
We can now do the same in Connect Four by looking two turns ahead with a minimax game tree. Only for the game states at the leaves (the ends of the tree) does the AI compute a score, with the same evaluation as before: the difference in threats, labeled (e.g. for one more threat for blue). A won position gets an extreme score: if blue has four in a row, if red wins. That way a win always outweighs any number of threats. The other game states always get the minimum or maximum score of the possible next moves (the propagated minimax value, labeled ).
Because the algorithm now thinks two turns ahead, it sees the trap from before. Under the greedy move in the third column it now says : blue wins there on the next turn, and for red that is the worst possible outcome. Red therefore picks another column, where blue cannot win on the next turn.
Click through to the next moves and try to understand how the minimax game tree computes the best moves for both players. Under some game states you can unfold hidden branches to see which other moves are possible; the default view leaves them out to show the optimal path.
💥 Large search space
Why do we stop at two turns deep? Why not always build complete game trees? That is often impossible, because a complete game tree grows exponentially. Below, for example, is a game tree four moves deep on the regular board with seven columns. By default the tree only shows the best path in full: click a collapsed branch to unfold it, or show the whole tree with the button at the top right.
In Connect Four there are at most seven possible moves each turn, one per column. Each extra turn therefore multiplies the number of game positions in the tree by seven:
- 1 move deep: 7 positions
- 2 moves deep: positions
- 3 moves deep: positions
- 4 moves deep: positions
In chess it is even more extreme. Each turn there are roughly 35 possible moves (external link). As a result, the number of possible positions in the game tree explodes quickly:
- 2 moves deep: positions
- 3 moves deep: positions
- 4 moves deep: positions
The total number of possible chess games, also known as the Shannon number (external link), is about . That is more than the number of atoms in the observable universe. For games such as Go (external link) it is far more extreme still, with about 250 different moves per turn. This explains why building and searching a complete game tree is impossible in practice for complex games.
🌡️ Game-state evaluation function
To estimate which move is best, you need a way to judge how good a given game state is without playing the game to the end. We call this a game-state evaluation function. For an intermediate game state, this function estimates who is winning.
A game-state evaluation function (or evaluation function for short) is a function that assigns a given game state a numerical value estimating how favorable that state is for a player. A higher value means that the position is more favorable for the MAX player, a lower value that it is more favorable for the MIN player.
An evaluation function for game states resembles the heuristics you saw in heuristic search. One difference from the heuristic in the A* search algorithm is that here it does not have to underestimate the true value. Ideally it estimates the chance of winning as accurately as possible, whether that means overestimating or underestimating.
Each game typically has its own heuristic. When you play a game yourself, you soon discover rules of thumb that help you judge whether you are doing well or badly. A few examples of heuristics for game states:
- 🔴 Connect Four: count each player's threats (the cells where one more disc would give that player four in a row).
- 🔵 Reversi (external link): look at the difference in the number of discs of each color.
- ♟️ Chess: look at the difference in material, where each piece has its own value (e.g. a ♙ pawn is worth 1 point and a ♕ queen 9).
Simple evaluations like these compute a numerical value that estimates, at any moment in the game, who has the upper hand.
🤖 The minimax algorithm
We can now describe the minimax algorithm in full. The idea is simple: prepare for the worst-case scenario. It assumes that you maximize your score and your opponent minimizes it. With that assumption you can compute, for every possible move, what happens if your opponent also responds optimally, and then choose the move that makes the best of the worst-case scenario.
The minimax algorithm works in the following steps:
-
Build a game tree up to a certain depth (for example moves ahead).
-
Evaluate all leaves of the game tree (the game states after moves, at the ends of the game tree) with your evaluation function.
-
Propagate values one level up according to the minimax rule, for every position whose next moves (the level below it) all have a value already:
- 🔵 MAX positions (your turn): take the highest value of all child nodes. After all, you play optimally, so you choose the move that gives you the highest score.
- 🔴 MIN positions (your opponent's turn): take the lowest value of all child nodes. After all, your opponent plays optimally too, and chooses the move that gives you the lowest score.
-
Repeat step 3 until you reach your current game position at the top of the game tree.
-
Choose the move with the highest value in the top node: that is the move you should play now.
This process guarantees that you always choose the move that gives you the best guarantee of the least bad score for yourself, even if your opponent plays perfectly.
In the simulator below you can watch the algorithm at work on a few game trees. Each step of the simulator is a step of the algorithm above: first all leaves get their score, then the values move up level by level to the top node.
📏 Quality of the evaluation function
We want the best evaluation function we can get, that is, a function that approximates the true chances of winning from a game state as closely as possible. After all, that function is the weak link: minimax is only as good as the evaluation function it uses to judge game states. A poor assessment of game positions leads to poor decisions, however perfectly the algorithm itself works. The evaluation should not take too long either: otherwise you might as well spend that time searching deeper in the game tree.
For Connect Four, so far we have only counted threats. But if you play the game more often, you soon notice that more things matter:
- Center: a disc in the middle column is part of many more possible lines of four than a disc at the edge. Whoever controls the center gets more chances later on.
- Open twos: two of your own discs in a line of four whose other two cells are still empty are tomorrow's threats.
You can then extend the evaluation function for a game state with such factors, each multiplied by a weight that sets how important that factor is:
Each factor is the difference between blue and red, and you can set the weights to yourself based on experience, or through machine learning (ML). Different weights give a different playing style: more weight on the center, for example, makes the AI more patient in the opening, while more weight on threats makes it more aggressive.
In the demo below, the AI plays with an extended evaluation function that counts the three factors (threats, open twos and center discs) with weights 8, 2 and 1. Play a few games and compare with the simple version from before: change the weights (for example center high and the rest at zero) and see how the values and the chosen moves change.
The same approach (start with a rough count and refine it with positional factors) works for many games. Chess shows it particularly well, because not every piece is worth the same.
In chess, human players typically use a few rules of thumb that are quick to compute to judge whether a game state favors white or black. A well-known simple heuristic looks at the advantage in "material": the chess pieces still on the board. Unlike Connect Four, where there is only one kind of disc, chess experts assign the following values to the pieces:
- ♙ Pawn: 1 point
- ♘ Knight: 3 points
- ♗ Bishop: 3 points
- ♖ Rook: 5 points
- ♕ Queen: 9 points
- ♔ King: irrelevant (0 points), since it is never captured
On the board below, the players have:
- ◼️ Black: 3♙ + 1♕ + 1♔ = 12 material points
- ◻️ White: 2♙ + 1♗ + 1♘ + 1♖ + 1♔ = 2 + 3 + 3 + 5 + 0 = 13 material points
The difference is therefore +1 point in white's favor.

But is white really better off? After all, the queen can move to h4 and give check right away, and so try to win a rook, and white's pawns are not very well placed. Sometimes such a simple heuristic misjudges the chances of winning, because some pieces stand on poor squares (far from the center, pawns in front of each other, and so on). That is why you can refine the heuristic with positional factors, such as:
- Central control: +0.2 per controlled central square (the four middle squares)
- Pawn structure:
- +0.3 per connected pawn (a pawn with a neighbor on an adjacent file).
- −0.4 per isolated pawn.
- −0.5 per doubled pawn (pawns directly behind each other on the same file).
- King safety:
- −0.4 per open/half-open file around the king.
- −0.5 if an enemy queen/rook can give check in one move.
Each factor is counted as white minus black, so an advantage for black enters as a negative number. Applied to the position above, the score per factor becomes:
- Material: see the calculation above: +1.0
- Central control: black controls two central squares with ♛ (d4 and e4) and white two with ♖ (e4 and e5) → 0.0
- Pawn structure:
- White: b3–b4 = doubled pawn (−0.5) and both isolated (−0.8) → −1.3.
- Black: a7-b6-c7 are connected (+0.3 per pawn) → +0.9 for black, so −0.9 for white.
- Total: −1.3 − 0.9 = −2.2.
- King safety:
- White: 2 open files around the king → −0.8; ♛ can give check → −0.5 → together −1.3.
- Black: king is safe → 0.
- Total: −1.3
In total, this new evaluation function therefore scores this position as , in black's favor. That is a better estimate than the material difference alone. It is also closer to what a chess engine such as Stockfish (external link) gives for this position (external link) with white to move (around −2.5 when searching to depth 25).
So it often pays off to design a better heuristic that takes more factors into account. Ideally the heuristic approximates the true chances of winning as closely as possible, but in practice it is always a compromise between accuracy and speed of computation.
🧠 Neural heuristics
So far we have mostly used handcrafted evaluation functions with explicit rules that people came up with themselves. In practice, these are increasingly replaced or complemented by learned evaluation functions based on neural networks, which discover patterns themselves from a very large number of played games.
For most games, neural networks perform better as evaluation functions than the traditional handcrafted heuristics. The neural network learns to recognize abstract patterns from millions of played games (against humans, against itself or against other AI models), so that it can estimate the chances of winning from each game state more accurately.
Chess analysis often relies on engines such as Stockfish (external link) for this, which today combines classic search techniques with a neural evaluation function called NNUE (external link). The evaluation function even appears as an "eval bar" next to live chess boards during chess tournaments. That lets the audience follow how well a player is doing and when they make a mistake, as you can see in the video below:
https://www.youtube.com/watch?v=EEIyWNHjf8c
🎲 Dealing with chance
Minimax assumes that every branch in the game tree is chosen by a player: by you or by your opponent. In many games, however, the players are not the only ones deciding what happens. In Monopoly a dice roll determines which moves are possible, and in card games the order of the deck determines which cards you get. This randomness is neither hostile nor friendly: it simply follows a probability distribution that you usually know exactly (a fair die shows each of its six faces with probability ).
Expectiminimax extends minimax with a third kind of node for exactly those moments.
A chance node is a node in a game tree where chance, not a player, decides which branch is followed. Each branch below it is a possible outcome with a known probability, and the probabilities of all branches add up to 1.
An expectiminimax tree therefore has three kinds of levels that alternate: MAX (your turn), CHANCE (chance decides, for example a dice roll) and MIN (your opponent's turn), with typically a CHANCE level between every MIN and MAX.
🧮 The value of a chance node
At a MAX node you take the maximum and at a MIN node the minimum, but at a chance node there is nothing to choose. After all, you do not know in advance which outcome you will get, only how likely each outcome is. So there you take the weighted average of the values below it, where each outcome counts in proportion to the probability that it occurs.
The expected value of a chance node with outcomes that occur with probabilities is:
It is the score you would get on average if you played this situation very many times.
Suppose, for example, that you take a gamble with three possible outcomes: a 60% chance of a score of 4, a 30% chance of 1 and a 10% chance of . The expected value of that gamble is then:
In the demo below, that gamble is on the right. On the left is a safe move: a 50% chance of 2 and a 50% chance of 1, so an expected value of . Nothing bad can ever happen there, but on average the gamble yields more (2.1). Chance nodes are the orange squares with a die; each branch below one shows the probability of that outcome. Step through it and watch how the expected value is built up outcome by outcome, until MAX at the top picks the better of the two.
In a real game, chance does not decide just once, but again and again. Choose the tree "Chance after every move" at the top left: there every move, yours and your opponent's, is followed by a chance node with two equally likely outcomes.
📏 The scale of your evaluation function now matters
In ordinary minimax only the order of the scores matters. Whether your leaves are 1, 2 and 3 or 1, 2 and 300: MIN picks the lowest and MAX the highest, so the chosen move stays the same. With expectiminimax that is no longer true, because you now actually add the values together.
Suppose that in the tree above you make only the worst outcome more dramatic, from to . The order of the leaves does not change, but the expected value of the gamble does: . Now MAX picks the safe move on the left: it is still worth 1.5, while the gamble yields on average. So for a game with chance nodes it is not enough for your evaluation function to put positions in the right order: the numbers themselves have to be in proportion to the true chances of winning.
✂️ Alpha-beta pruning
The search time of minimax grows exponentially with the search depth, and that limits how far ahead the algorithm can look. For a game with branching factor (the average number of moves you can play in a position) and search depth , the algorithm has to examine about game states. For Connect Four, with , each extra move of depth therefore costs seven times as much work: looking eight moves ahead already costs about million positions.
A well-known optimization is alpha-beta pruning. This technique lets you skip entire branches of the game tree, and yet the algorithm is guaranteed to end up with the same move as plain minimax. So you lose nothing in quality: you only save computation.
🌟 The intuition
Look at the small game tree below. It is your turn (MAX) and you have two possible moves, and after each move your opponent (MIN) picks from three replies.
You first work out the left branch completely. There MIN picks the lowest of 4, 6 and 5, so that branch is worth 4. That already tells you something important about the root: you get at least 4 no matter what, because that left move is available.
Then you start on the right branch, and the first leaf you see there is a 3. Under that branch MIN picks the minimum, so the branch is worth at most 3: the two leaves you have not seen yet can only pull that value down, never up. At most 3 is worse than the 4 you already have for sure, so you will never play that right move. Whatever else is below it no longer matters: you can skip those two leaves without looking at them.
Step through it in the demo below. The skipped nodes get a red cross, and below the tree you see how many nodes the algorithm visited in the end.
🛠️ How it works
To automate that reasoning, the algorithm keeps track of two bounds on its way down:
- Alpha (): the best value MAX can already be sure of on the path from the root to here, through a branch that has already been worked out. It is a lower bound for MAX: MAX never chooses a branch that yields less.
- Beta (): the best value MIN can already force for sure on the path from the root to here (that is, the lowest score), through a branch that has already been worked out. It is an upper bound for MIN: MIN never allows a branch that yields more.
The two bounds start at and and move toward each other as the algorithm finishes branches: a MAX node pushes up, a MIN node pushes down. As long as , there is room between the two: a value in between is good enough for MAX and is also allowed by MIN, so the branch you are in can still change the choice at the top.
As soon as , that room is gone. An upper bound that drops below a lower bound looks like a contradiction, but the two bounds do not come from the same branch: is what MAX is already sure of elsewhere, is what MIN can force in this branch. In the example above, thanks to the left branch, and in the right branch already drops to 3 at the first leaf: MAX wants at least 4, but gets at most 3 here. So that branch can never be chosen any more, and you can skip the remaining child nodes without looking at them. Skipping branches like this is called pruning.
The same condition also works for MIN, with the roles reversed. If the value of a MAX node rises to or higher, then MIN can already force at most elsewhere while this branch yields at least , so you can prune in that case too.
Pruning never changes the move the algorithm ends up choosing: you skip exactly the branches you already know neither player would choose. What you do give up is the exact value of the pruned branches: for those you only know a bound, because you stopped computing as soon as they could no longer win.
Now try it on a larger tree. Switch "Alpha-beta pruning" on and off on the left, and watch how the counter below the tree changes along with it. Each pruning step also says which player never picks that branch: in the "Basic" tree that is MAX three times and MIN once.
🌿 Effectiveness of pruning
How much you can prune depends entirely on the order in which you examine the branches. If you come across the best move first, is high right away and all later branches drop out quickly. If you only come across it last, you never have a useful lower bound and you examine the whole tree. In the demo above, compare the "Basic" tree with "Basic (sorted)": the trees are the same size, but with the sorted order the algorithm visits fewer nodes.
That is why real game-tree algorithms order their moves before they descend. In chess, the search algorithm often tries the moves that capture a piece first, then the moves that threaten a piece, then forward moves, and only after that backward moves.
That order also determines how much you can gain in theory:
- In the worst case (the worst possible order), alpha-beta prunes nothing and you stay at nodes.
- In the best case (the perfect order), about are enough.
That last number is exactly why you can search "twice as deep". Searching to depth with perfect pruning costs nodes, which is exactly what searching to depth without pruning costs. For the same amount of computation, you therefore look twice as far ahead. In Connect Four (), looking eight moves ahead without pruning costs about million positions; with a perfect move order, of them remain, as many as looking four moves ahead without pruning.
In practice you never achieve that perfect order, so the real gain lies somewhere between the two extremes. It is still large enough to search noticeably deeper in the same computing time, and that is exactly what makes an AI stronger.
Below you see the same effect on a real board: the same position as earlier in this chapter, but now with a pruning switch. Below the tree you see how many positions the AI explored. Turn pruning on and off, then increase the depth to see how the difference grows along with it.
🤝 Assumptions and behavior of minimax
🎯 Assuming a perfect opponent
Minimax guarantees the best move if you assume that the opponent also plays perfectly, and if you compute the game tree all the way to the end states. For Connect Four we actually know that outcome: the game is completely solved (external link), and the player who moves first always wins with perfect play. So we could build a perfect solver for it. For chess or Go that is infeasible because there are too many possible states, so minimax cuts the tree off at a certain depth and uses an evaluation function to score the intermediate states. With such a depth-limited tree, the guarantee no longer holds: the quality of the chosen move then depends on how well the evaluation function approximates the true value of a position. So minimax is ideal for competitive games in which both players aim to play flawlessly, but it can feel conservative against human players who make the occasional mistake.
🛡️ Defensive playing style
Because minimax always accounts for the worst-case scenario, it naturally plays defensively. It has no notion of risk versus reward: it avoids risky moves that work out well in most cases but can be catastrophic if the opponent finds the right response. It always prefers safe moves over risky but potentially brilliant opportunities. Human players can sometimes take a risk and win; minimax avoids that same move if it could fail somewhere down the line.
The left move probably brings a big gain, but minimax chooses the right move because it gives a better score in the worst case.
🧭 When to use minimax?
Minimax is ideal for:
- ✅ Perfect information: two-player games with perfect information (both players know everything about the board position, there are no hidden pieces)
- ⚖️ Zero-sum game: what one player wins, the other loses, so that your opponent, by playing as well as possible for themselves, really does make your score as low as possible
- 🛡️ Defensive play: situations where you want to play defensively
- 🌲 Limited branching factor: games of manageable size (with not too many possible moves per game state)
- 🌡️ Good evaluation function: when you have a good game-state evaluation function
Minimax is less suitable when:
- 🎲 Randomness: chance plays a large role
- 💀 Risky play: you want to use aggressive, risky strategies
- 💥 Large branching factor: the game tree is gigantic (as in Go)
- 🤪 Imperfect opponent: the opponent will probably make mistakes you want to exploit
🕹️ Demos
Experiment further with the full simulators and demos featured above.
🗣️ Feedback
Just like machine learning algorithms, we also love learning from your feedback to improve the course.
Let us know how informative and how difficult you found this chapter, and where it could be better.

