How does AI play games? It looks ahead.
Think about how you play tic-tac-toe. Before you put down an X, you ask yourself: "If I go here, where will my friend go? Can they block me? Can they win?" You are looking ahead. A game-playing AI does the same thing. It is just much faster and much more careful.
To look ahead, a computer needs two ideas:
- A state is a snapshot of the game at one moment: where every piece is and whose turn it is. A tic-tac-toe state is just the 9 squares plus "X's turn" or "O's turn."
- A move is an action that changes one state into a new state. Putting an O in the corner is a move.
Games like tic-tac-toe, checkers, chess, and Go are a perfect fit for this. Both players can see the whole board, there is no luck, and players take turns. Computer scientists call these two-player, perfect-information games. If a computer knows the rules, it can figure out every move that is allowed from any state.
What is a game tree?
Now imagine writing down every move you could make, and under each one, every reply your opponent could make, and so on until the game ends. The drawing you get looks like an upside-down tree, so it is called a game tree.
- The root (top) is the board right now.
- Each branch is one move.
- Each node is the board after that move.
- The leaves (bottom) are finished games: a win, a loss, or a draw.
The number of choices at each turn is called the branching factor. In tic-tac-toe, the first player has 9 choices. The second player then has 8. That is already 9 × 8 = 72 different ways the first two moves can go.
Keep going and the tree explodes. Counting every way a game can be played to the end:
For comparison, scientists estimate there are only about 1080 atoms in the whole observable universe. Keep that in mind. It is the reason chess AI needs some clever tricks, which you will see in section 7.
Scoring the end of the game
A tree full of boards is not useful until the computer knows which endings are good. So it gives every leaf a number called a score (or utility). On this page the AI plays O, so we score from O's point of view:
That is the whole scoring system. The AI wants the score to be as high as possible. You, its opponent, want it to be as low as possible. One score, two players pulling in opposite directions. That is why games like this are called zero-sum: whatever is good for one player is bad for the other.
Leaves are easy to score because the game is over. The hard part is scoring a move now, many turns before the end. That is exactly what minimax solves.
What is the minimax algorithm?
Minimax is a recipe for choosing a move. In one sentence:
"I pick my best move, assuming you will pick your best move."
The AI does not hope you make a mistake. It plans for the strongest possible opponent. Here is how the scores travel from the leaves up to the top:
- On the AI's turn, the node is a MAX node (drawn as ▲). It takes the biggest score below it, because the AI will pick its best move.
- On your turn, the node is a MIN node (drawn as ▼). It takes the smallest score below it, because a smart opponent will pick the move that is worst for the AI.
- The levels take turns, MAX, MIN, MAX, MIN, just like the players do. Scores bubble up from the bottom until the root knows which move is best.
Step through it yourself. The leaves have point scores (bigger is better for the AI). Press Step to fill in one node at a time.
Lab 1 · Watch scores bubble up
Minimax stepperPress Step. The AI starts at the bottom and works its way up.
Leaves checked: 0 of 8
Notice that the root does not just grab the biggest leaf. The biggest leaf is often a trap: the opponent would never let the game go there. Minimax finds the best score the AI can guarantee, no matter what the opponent does. Try New scores a few times and predict the root before you press Solve all.
Play tic-tac-toe against a minimax AI
This AI runs full minimax before every move. You are X and the AI is O. With Show the AI's thinking on, you will see the score it worked out for every empty square before it moves: +1 means "I can force a win," 0 means "best case is a draw," and −1 means "you can beat me if I go here."
Lab 2 · Can you beat it?
Minimax tic-tac-toeYour move. Pick any square.
Score
AI's last decision
The AI has not moved yet.
Things to try:
- On Unbeatable, the best you can do is a draw. If you play perfectly too, every game ends 0. That means tic-tac-toe is solved: we know the result of perfect play.
- Switch to Looks 2 moves ahead. This AI only sees its move and your reply, then treats everything after that as a "?" worth 0. Set up a fork (two ways to win at once) and it will not see it coming.
- Turn on AI starts and look at the counter. On an empty board, the AI checks over half a million positions before its first move.
Minimax in code
Here is minimax written in Python-style code. The AI plays O. The function gives back the best score O can guarantee from a board.
def minimax(board, ai_turn): # 1. Is the game over? Then just score it. if wins(board, "O"): return +1 # the AI won if wins(board, "X"): return -1 # you won if is_full(board): return 0 # draw # 2. Try every move and score what happens next. scores = [] for square in empty_squares(board): if ai_turn: board[square] = "O" else: board[square] = "X" scores.append(minimax(board, not ai_turn)) board[square] = " " # undo the move # 3. MAX on my turn, MIN on yours. if ai_turn: return max(scores) # I pick my best else: return min(scores) # you pick your best (my worst)
- Base case. If the game is over, there is nothing left to imagine. Return +1, −1, or 0.
- Try every move. For each empty square, place a piece, then ask minimax to score the new board with the other player's turn. Then undo the move so the board is clean for the next try.
- Pick. On the AI's turn return the biggest score. On your turn return the smallest.
Did you spot the trick? minimax calls itself. A function that calls itself is called recursion, and it is a natural fit for trees: to score a node, score its children first. To choose the actual move, the AI runs minimax on the board after each possible move and plays the one with the highest score. If you want to practice recursion first, try the basic recursion tutorial.
Why can't AI search all of chess?
Minimax is perfect for tic-tac-toe because the whole tree fits in a computer. Chess has about 35 legal moves per turn and games often last 80 turns or more (40 moves each). Drag the slider to see how fast the tree grows as the AI looks further ahead.
Lab 3 · How big is the tree?
Branching explorerBars use a stretched scale: each step of length means "times 10." A move here means one player's turn.
Chess at 1 billion positions per second
That's like
Even the fastest computer in the world could never finish. So real chess programs use three tricks.
Trick 1: Stop early (depth limit)
Instead of searching to the end of the game, the AI searches only a few moves ahead, say 10 or 20. This is called a depth limit. The "Looks 2 moves ahead" AI in Lab 2 uses a tiny depth limit of 2.
Trick 2: Guess the score (evaluation function)
When the search stops in the middle of a game, the board is not finished, so it cannot be scored +1, 0, or −1. Instead the AI uses an evaluation function: a formula that guesses how good a board is. A classic beginner version for chess counts up the pieces:
- pawn = 1, knight = 3, bishop = 3, rook = 5, queen = 9
- score = (my pieces) − (your pieces)
If the AI has a rook more than you, the guess is about +5. Real engines add much more, like how safe the king is and how much of the board each side controls. A better evaluation function makes a smarter AI, even with the same search.
Trick 3: Skip useless branches (alpha-beta pruning)
Alpha-beta pruning skips parts of the tree that cannot change the decision. Here is an everyday version. A friend offers you two bags of candy. You get to pick the bag, but your friend picks which candy from that bag you get, and they always give you the worst one.
Bag A
You look at every candy. The worst is 5, so Bag A guarantees you a 5.
Bag B
The first candy is a 2. Your friend will give you a 2 or worse, which is already worse than 5. Stop looking. Pick Bag A.
You got the same answer without checking two candies. Minimax with alpha-beta does exactly this, and it can let an AI search about twice as deep in the same amount of time. Go back to Lab 1, check Skip useless branches, and watch some leaves get crossed out.
From Deep Blue to AlphaGo
Game-playing AI has been a test for computer science for more than 70 years.
- 1928
The minimax idea
Mathematician John von Neumann proved the minimax theorem about the best strategy in two-player, zero-sum games.
- 1950
Shannon plans a chess computer
Claude Shannon described how a computer could play chess with minimax, a depth limit, and an evaluation function. He also estimated the 10120 number of possible games.
- 1980
Pac-Man's ghosts
Video game "AI" is often a set of simple rules, not search. Each Pac-Man ghost follows its own chase rule, which is enough to give them different personalities. Game designers want enemies that are fun, not unbeatable.
- 1997
Deep Blue beats Kasparov
IBM's Deep Blue beat world chess champion Garry Kasparov in a six-game match. It used minimax-style search with alpha-beta pruning, a hand-built evaluation function, and special chips that checked about 200 million positions per second.
- 2007
Checkers is solved
After 18 years of computing, the Chinook team proved that perfect checkers play by both sides always ends in a draw, just like tic-tac-toe.
- 2016
AlphaGo beats Lee Sedol
Go was thought to be decades away. DeepMind's AlphaGo used neural networks that first studied human expert games, then improved by playing millions of games against itself. Learning from rewards like this is called reinforcement learning. AlphaGo won 4 games to 1.
- 2017
AlphaZero learns from scratch
AlphaGo Zero and AlphaZero learned using only the rules and self-play, with no human games at all. AlphaZero taught itself chess, shogi, and Go, and beat the top programs of the time.
AlphaGo did not throw away search. It still built a game tree, but its neural networks acted like a super-powered evaluation function: one guessed which moves were worth exploring, and another guessed who was winning. That let it search a tiny, smart slice of an impossibly big tree.
The same ideas show up far beyond board games. Route planners, puzzle solvers, and robots also search through states and moves. See hill climbing and search for more.
Frequently asked questions
How does AI play games?
Most board-game AI looks ahead. It imagines each move it could make, then each reply you could make, and so on, building a game tree. It gives each imagined ending a score, like +1 for a win, 0 for a draw, and -1 for a loss, and picks the move that leads to the best score it can guarantee. Newer AIs like AlphaGo also use neural networks that learned from millions of practice games to guess which moves and positions are good.
What is the minimax algorithm?
Minimax is a way to pick a move in a two-player game. The AI assumes it will always pick the move with the highest score (MAX) and that you will always pick the move that gives it the lowest score (MIN). Starting from the end of the game, scores bubble up the game tree, alternating max and min, until the AI knows the best move it can make against a perfect opponent.
What is a game tree?
A game tree is a map of every way a game could go. The top is the current board. Each branch is a move, and each node below it is the board after that move. The bottom nodes, called leaves, are finished games. Tic-tac-toe has 255,168 possible games, while chess has so many that nobody could ever list them all.
Can you beat a minimax tic-tac-toe AI?
No. A full minimax tic-tac-toe AI searches every possible game, so it never makes a mistake. If you also play perfectly, every game ends in a draw. That is the best result either player can get in tic-tac-toe.
How many possible games of chess are there?
In 1950, Claude Shannon estimated about 10^120 possible chess games, a 1 followed by 120 zeros. This is called the Shannon number. It is far more than the roughly 10^80 atoms in the observable universe, so no computer can search all of chess. Chess programs search a few moves ahead and estimate the rest.
How did AlphaGo beat the best Go players?
Go has too many moves for plain minimax. AlphaGo, made by DeepMind, used neural networks that first studied human expert games and then got stronger by playing millions of games against itself, which is called reinforcement learning. The networks guessed promising moves and judged positions, so its search only had to explore the best-looking branches. In 2016 it beat champion Lee Sedol 4 games to 1.
What is alpha-beta pruning?
Alpha-beta pruning is a shortcut for minimax. When the AI sees that a branch is already worse than a move it has found, it stops exploring that branch, because the opponent would never let it end up better there. It gets the exact same answer as full minimax while looking at far fewer positions, so it can search deeper in the same time.
Quick quiz
1. In a game tree, what is a leaf?
2. A MIN node has three children with scores 4, −2, and 7. What score does it get?
3. Why does the minimax AI in Lab 2 never lose?
4. A chess AI stops searching after 12 moves. How does it score a board that is not finished?
5. What does alpha-beta pruning do?
6. How did AlphaGo get strong enough to beat a Go champion?
Keep learning
You just learned how a computer can plan ahead and play a perfect game. Next, see other ways AI makes decisions, or build your own game AI in a CodeHS course.