← The Engines

How Tic-tac-toe’s computer never loses

A companion to the game: every game in one tree, a search that scores it from the end, and a level that misses on purpose

Download PDFPlay Tic-tac-toe

Tic-tac-toe is small enough that the computer searches every game it could still play, every time it moves. This companion is the first of the arcade’s four, so it starts from the beginning. It defines a position, a ply and a game tree, and shows why a game like this one has a perfect player at all. It then runs the search, minimax, step by step on a position near the end of a game. It explains why the computer prefers quick wins and slow losses, and how one search plays both marks on one board. It counts what a full search costs and shows why this game needs none of the shortcuts the later companions explain. It ends with what perfect play looks like and how the Easy level plays badly on purpose.

1 Positions, moves and the game tree

What is the computer searching through?
The board has nine squares. This companion numbers them 1 to 9, row by row from the top left. X moves first, then the players take turns, each putting their mark on an empty square. The game ends when one of them has three in a line or the board is full. A line is a row, a column or a diagonal.

A position is everything that decides how the game can go on. In tic-tac-toe that is the marks on the board. Whose turn it is follows from the marks. When it is O’s turn, X has one more mark than O, and when it is X’s turn, both have the same number. A move takes the game from one position to the next. One player’s move is a ply. In everyday speech “a move” can mean one player’s turn or a pair of turns, so the arcade’s companions count plies. When a square below reads “wins in 3”, that means three plies: the winner’s move, the opponent’s reply and the winner’s move again.

Figure 1: The top of the game tree, with the empty board, X’s nine first moves, and O’s eight replies to the first of them. Every node is a position and every line is a move. A ring marks the square just played.

Drawing every position the game can reach, with a line for every move, gives the game tree. Its root is the empty board. Each position branches into one child per legal move, and a branch stops at a leaf, which is a finished game. A path from the root to a leaf is one complete game.

Definition 1 (Position, ply, game tree). A position is a board 𝑏 with the player 𝑝 to move. A ply is one player’s move, and 𝑑 counts the plies played since some starting position. The game tree below a position has that position as its root. The children of a node are the positions after each legal move from it. Its leaves are the finished games, which end in a line of three or a full board.
In wordsIn symbols
the squares, numbered row by row1,2,…,9
a position: the board and the player to move(𝑏,𝑝)
the position after 𝑝 plays square 𝑠𝑏+𝑠
one player’s movea ply
plies played since the search began𝑑

2 The whole game

How many ways can a game of tic-tac-toe go?
X has nine first moves, O eight replies, and so on, but many games stop early when someone completes a line. Following every game to its end gives 255,168 games through 5,478 different positions. X wins 131,184 of them and O wins 77,904. The shading shows something else. With good play from both sides, every first square ends in a draw.

If no game ended early, there would be 9!=362,880 games, one for each order of filling the nine squares. Lines of three cut that to 255,168. The shortest games end after five plies, when X completes a line with its third mark. The table counts the tree level by level.

Table 1: The game tree level by level. “Positions in the tree” counts a board once for every way of reaching it, and “different boards” counts it once. The last three columns are the games that end at that level.
Plies playedPositions in the treeDifferent boardsX wins hereO wins hereDraws here
011000
199000
27272000
3504252000
43,024756000
515,1201,2601,44000
654,7201,52005,3280
7148,1761,14047,95200
8200,448390072,5760
9127,8727881,792046,080

Compare two columns of Table 1. At three plies the tree has 504 positions but only 252 different boards. X can play its two squares in either order, so each board with two X’s and one O appears twice. Further down the gap grows, until at 8 plies the tree holds 200,448 positions that are only 390 different boards. Section 8 comes back to what that costs a search.

255,168 games
Every way a game can be played to its end, from the empty board.
5,478 positions
The different boards those games pass through.
549,946 searched
What a full search from the empty board visits, in 136 ms. The search visits a board once for each order of moves that reaches it.

3 Why a perfect player exists

How can anyone know the best move without trying every opponent?

Tic-tac-toe has three properties that make a perfect player possible. It is finite, because every game ends within nine plies. It has perfect information, because both players see the whole board. It has no chance, because nothing is rolled or dealt. In such a game every position has a definite result under best play. Backward induction finds that result by working backwards from the end.

The leaves are easy, because a finished game’s result is on the board. One level up, the player to move has a few moves. Each leads to a leaf with a known result, and the player takes the best one. Now every position on that level has a known result, and the same step repeats level by level up to the root. Figure 2 shows the tree below a position near the end of a game, with the result of every node. The heavy lines are the moves each player takes.

Figure 2: Backward induction on a position near the end. Finished games get their score from the board, and each level takes its values from the level below, from 0 empty squares up to 3.
Definition 2 (Value). Score a finished game +1 if O has won, −1 if X has, and 0 for a draw. The value of an unfinished position is the largest value among its children if O is to move there, and the smallest if X is to move.

Scoring from O’s side alone is a convention. O wants large values and X wants small ones, so one number works for both players. Section 5 refines the score, and nothing in this section depends on the details.

Theorem 1 (Backward induction). Every position 𝑏 has a value 𝑣(𝑏). From 𝑏, O has a way of playing that ends with a score of at least 𝑣(𝑏) whatever X does, and X has one that ends with at most 𝑣(𝑏) whatever O does. So 𝑣(𝑏) is the result of 𝑏 when both sides play perfectly.
Proof. By induction on the number 𝑘 of empty squares. With 𝑘=0 the board is full, the game is over, and its score is its value; there is nothing to play. Suppose the statement holds for every position with fewer than 𝑘 empty squares, and take one with 𝑘. If it is finished, the same holds. Otherwise each of its children has 𝑘−1 empty squares, so each has a value, and 𝑣(𝑏) is defined. Say O is to move. The case of X is the mirror image. O plays to a child whose value is 𝑣(𝑏), the largest, and from there, by the induction hypothesis, can reach at least 𝑣(𝑏). Whatever O plays, X can answer. Every child has value at most 𝑣(𝑏), and from any child X can hold the score to at most that value. ∎

The result is Zermelo’s theorem (1913), the oldest theorem of game theory. It needs all three properties. The second companion, Chopsticks, has finitely many positions, but its games can return to a position and go on forever, so there is no last level to start from. In the fourth, Chowka Bhara, players throw cowrie shells, so a position’s value is an average over the throws.

4 Searching from the end

How does the computer choose a square?
Algorithm 1: Minimax, the function minimax in src/games/tic-tac-toe/game.ts.
Require: a board 𝑏 and the player 𝑝 to move; 𝑑, the moves played since the search began
Ensure: the value of 𝑏 for O: 10−𝑑′ if O wins after 𝑑′ moves in all, 𝑑′−10 if X does, 0 for a draw
1if the game is over then return its value
2for each empty square 𝑠
3play 𝑝 on 𝑠; 𝑣𝑠← minimax(the board, the other player, 𝑑+1)
4clear 𝑠 againone board serves the whole search
5if 𝑝 is O then return max𝑠𝑣𝑠 else return min𝑠𝑣𝑠each side picks its best

Minimax is backward induction written as a program. It scores the finished games, then works backwards. A position is worth what its best move is worth, for whichever player is to move. Every value is from O’s side, so O picks the largest and X picks the smallest. The name records this alternation, a minimum of maxima of minima. The computer plays the square whose value is best for its own mark.

In wordsIn symbols
O wins after 𝑑 plies10−𝑑
X wins after 𝑑 plies𝑑−10
a draw0
a position, O to movemax𝑠𝑣(𝑏+𝑠)
a position, X to movemin𝑠𝑣(𝑏+𝑠)

The function calls itself. To score a position it scores each child, and each child scores its own children, down to finished games. A recursive search like this one goes depth first. It follows one line of play to the end before it tries the next square. Each call stays open until all the calls under it have returned.

1Score the finished gamesAlgorithm 1
Require: a board 𝑏 and the player 𝑝 to move; 𝑑, the moves played since the search began
Ensure: the value of 𝑏 for O: 10−𝑑′ if O wins after 𝑑′ moves in all, 𝑑′−10 if X does, 0 for a draw
1if the game is over then return its value
2for each empty square 𝑠
3play 𝑝 on 𝑠; 𝑣𝑠← minimax(the board, the other player, 𝑑+1)
4clear 𝑠 again
5if 𝑝 is O then return max𝑠𝑣𝑠 else return min𝑠𝑣𝑠
X is to move with three squares left. The search plays each branch out to its end and gives each finished game its value: −9 when X wins at once, 0 for a draw, +8 when O wins on the second move.
2Back the values upAlgorithm 1
Require: a board 𝑏 and the player 𝑝 to move; 𝑑, the moves played since the search began
Ensure: the value of 𝑏 for O: 10−𝑑′ if O wins after 𝑑′ moves in all, 𝑑′−10 if X does, 0 for a draw
1if the game is over then return its value
2for each empty square 𝑠
3play 𝑝 on 𝑠; 𝑣𝑠← minimax(the board, the other player, 𝑑+1)
4clear 𝑠 again
5if 𝑝 is O then return max𝑠𝑣𝑠 else return min𝑠𝑣𝑠
Every position takes the value of its best move for the player to move there. Where O is to move it takes the largest, so the branch that lets O win is worth +8 to O.
Require: a board 𝑏 and the player 𝑝 to move; 𝑑, the moves played since the search began
Ensure: the value of 𝑏 for O: 10−𝑑′ if O wins after 𝑑′ moves in all, 𝑑′−10 if X does, 0 for a draw
1if the game is over then return its value
2for each empty square 𝑠
3play 𝑝 on 𝑠; 𝑣𝑠← minimax(the board, the other player, 𝑑+1)
4clear 𝑠 again
5if 𝑝 is O then return max𝑠𝑣𝑠 else return min𝑠𝑣𝑠
At the top X takes the smallest value, −9, which is the square that wins at once. The heavy lines are the moves each player takes. The draw is worth 0, and the third square loses.

The storyboard shows the values level by level, as Theorem 1 builds them. The search itself reaches them in a different order. It goes depth first: it follows the leftmost branch to its end, comes back up, then takes the next branch. The live figure runs the engine’s search on the same tree one step at a time and highlights each line of Algorithm 1 as it runs.

Figure 3: The engine’s minimax on the example, one step at a time. The tree fills in the order the search visits it. Each position shows its value once the search has finished with it. The board on the right is the one board the search plays on.

5 Quick wins, slow losses

Why does the score depend on how long the game takes?

A win is worth 10−𝑑, so a win now beats a win later, and a loss later beats a loss now. Without the 𝑑 in the score, every winning line has the same value. A computer that can win at once may then play a slower win. A computer that has lost plays any losing square, even one that lets the opponent win on the next ply, instead of making the opponent find the win.

Figure 4: Two positions. The left column scores only win, draw or loss, and the right column counts plies. The ringed square is the one each scoring plays.

The four boards show two positions, each scored both ways. In the top row, X can win at once on square 7. A search that scores only win, draw or loss sees five winning squares. It takes the first of equals, as the computer does, and plays square 5, a win three plies away. In the bottom row O loses whatever it plays. The search that scores only win, draw or loss plays square 3, and X wins on the next ply. The search that counts plies blocks on square 9 and makes X find a second win. Against a perfect opponent the result is the same. Against a person, the block gives them a chance to go wrong.

Proposition 1 (The score that counts plies). Let a finished game after 𝑑 plies score 10−𝑑 for an O win, 𝑑−10 for an X win and 0 for a draw. Since 𝑑≤9, every win scores at least 1 and every loss at most −1. So the scores keep the order of Definition 2, where any win beats any draw and any draw beats any loss. Among wins, fewer plies score higher. Among losses, more plies score higher.
Proof. 1≤𝑑≤9 gives 1≤10−𝑑≤9 and −9≤𝑑−10≤−1. Taking maxima and minima keeps the signs, so a position’s value with plies counted has the sign of its value in Definition 2. Among positive values, the largest is the shortest win. ∎

Any constant above 9 would work in place of 10, because it only has to keep every win positive. A square’s value is from the side of the player who plays it. The square itself counts as the first ply, so a win “in 1” means the square completes a line.

After X takes a corner, every square but one loses for O. The centre draws, and any other square lets X force a win six plies later. The values are O’s, so the computer playing O takes the centre.

With X in opposite corners and O in the centre, a corner is the mistake for O. It loses four plies later, and an edge draws. Minimax needs no rule for this. It finds the trap by playing the corner out to the end.

Figure 5: Every empty square’s value for the player to move, here O. Play either side to see the values change. The computer plays the best square.

6 One search for both marks

Minimax scores from O’s side. How does the computer play X?

The computer usually plays O, but not always. In a Play with friends room it takes the seat of a player who leaves, which may be X. The live figures here also let it play either side. The engine has no second search that scores from X’s side. It swaps the marks instead. Every X on the board becomes an O and every O becomes an X, and the computer, now holding O, runs the usual search.

Figure 6: A position with X to move, and the same position with the marks swapped. X’s values on the first board equal O’s values on the second, square by square.

On the left, figures.ts searches each of X’s squares directly. X plays the square, minimax scores the rest from O’s side, and flipping the sign gives X’s value. On the right is the board the engine searches, with the marks swapped and O to move. The values agree square by square, and figures.ts checks that they agree before drawing either board.

Lemma 1 (Swapping the marks). Let swap(𝑏) be 𝑏 with every X replaced by O and every O by X. Then for every empty square 𝑠, the value of 𝑠 for X on 𝑏 equals the value of 𝑠 for O on swap(𝑏), plies included.
Proof. Swapping is a one-to-one map from games to games. A sequence of plays from 𝑏 becomes the same sequence of squares from swap(𝑏) with the marks exchanged. A line of X’s becomes a line of O’s, and a full board stays full. The rules treat both marks alike except that X moves first. The search never uses who moved first, because its caller passes it the player to move. So each game from 𝑏 that X wins after 𝑑 plies corresponds to a game from swap(𝑏) that O wins after 𝑑 plies, and the best play of one is the best play of the other. ∎
Algorithm 2: Each square’s value for either mark, from squareValues in src/games/tic-tac-toe/game.ts.
Require: a board 𝑏 and the computer’s mark 𝑚
Ensure: each empty square’s value for 𝑚
1if 𝑚 is X then 𝑏←swap(𝑏)now the computer holds O
2for each empty square 𝑠: 𝑣𝑠← minimax(𝑏+𝑠 with O on 𝑠, X, 1)

The search starts at depth 1 because the square being scored is the first ply.

7 One board, filled and cleared

The search visits half a million positions. Does it copy the board for each?

No. The whole search uses one board. To try a square, minimax writes the mark into it, calls itself, and erases the mark again when the call returns. Lines 3 and 4 of Algorithm 1 do this. The strip below shows the first steps of the search in Section 4 on that one board.

Figure 7: The first steps of the search on the example, on the one board it plays on. The search fills a square on the way down and clears it on the way back up.
Invariant 1 (The board comes back as it went in). When a call to minimax returns, the board holds exactly the marks it held when the call began.
Proof. On a finished position, minimax returns without touching the board. Otherwise line 4 clears every square that line 3 filled before the loop moves on. The call made in between returns the board as it found it, by the same argument one level down. Formally, this is induction on the number of empty squares. ∎

Copying would cost an allocation of nine squares at each of the half a million positions. Filling and clearing costs two writes. In return the code must keep Invariant 1. A search that returned early from inside the loop, before line 4, would leave a stray mark behind. The engine’s loop scores a square, clears it, and only then moves on, so it never leaves one. Callers also get their own board back untouched for a second reason. squareValues makes one copy of the board per call, with the marks swapped as in Section 6 when the computer holds X, and searches that copy.

8 What a full search costs

How much work is one move, and could the search be made cheaper?

Figure 8 counts the positions Hard’s search visits for each ply of a game between two Hard computers. The first move, on the empty board, costs the most: 549,945 positions, in about 136 ms. Each later ply has one empty square fewer and costs several times less. The searches for the last few plies visit only a handful of positions.

Figure 8: Positions Hard’s search visits for each ply of the game in Figure 9, on a logarithmic scale.

Table 1 shows that the tree holds many more positions than there are boards. Players can reach a board by playing the same squares in different orders. The search follows moves only, so it scores the board once for every order. Two orders that reach the same position are called a transposition.

In one order, X takes square 1, O takes the centre, and X takes square 9. In the other, X takes square 9 first and square 1 last. Either way the board is the same, so its future and its value are the same too. The search scores it twice.
Proposition 2 (Orders of moves). An unfinished position with 𝑘 X’s and 𝑗 O’s is reached from the empty board by exactly 𝑘!⋅𝑗! orders of moves.
Proof. X placed its marks on X’s turns, in some order, and O placed its marks on O’s turns. That gives 𝑘! orders for X and 𝑗! for O, and any pair of them is a sequence of legal moves. None of these sequences stops early, because every earlier board is a subset of the final one, and a line of three in a subset would be a line in the final board. ∎

The example tree’s root has three X’s and three O’s, so 3!⋅3!=36 orders reach it. The figure script, figures.ts, counts the orders of every position in the game and checks the proposition on all of them. That multiplication accounts for the gap between 549,946 positions searched and 5,478 boards.

Two standard techniques make a search like this cheaper, and the engine uses neither.

A transposition table
A table from position to value. Before scoring a position, the search looks it up, and after scoring it, the search stores it. The search would then score every board once, making 5,478 scores instead of 549,946, 100 times fewer. It works here because a board’s depth from the root is the number of marks placed, which is the same along every path to it. So a stored value is right on every later visit.
Alpha-beta pruning
The search stops looking at a move as soon as one reply shows the move is no better than one the player already has. Say X has already found a square that wins at once, worth −9. The search can drop any other square as soon as it finds an O reply there that does not lose at once, because X will not choose that square, whatever O’s other replies are worth. The search keeps two numbers for this, 𝛼 and 𝛽, which hold the best score each player is already sure of.

Neither is worth its complexity here. The most expensive search takes about 136 ms, and it happens only when the computer opens the game as X. Four in a Row, the third companion, is different. Its board has trillions of positions. Its solver needs a transposition table, alpha-beta pruning and an opening book computed in advance to answer in time.

9 Breaking ties

When several squares are equally good, which does the computer play?

It plays the first one. computerSquare scans the empty squares from 1 to 9 and changes its choice only for a strictly better square, so among equals the lowest-numbered square wins. On the empty board every square is worth a draw, so Hard as X always opens on square 1, the top-left corner.

That makes Hard deterministic. From a given position it always plays the same square. So two Hard computers always play the same game, shown below. It is a draw, as Theorem 1 says a game between perfect players must be.

Figure 9: Hard against Hard, the only game two Hard computers ever play. It ends in a draw. Each player takes the first of its best squares.

Against a perfect opponent, every choice in Figure 9 is as good as any other square of the same value. Against a person, Hard is predictable. Someone who has seen this game knows every reply Hard will make. Chopsticks’ computer, in the next companion, breaks ties at random instead, so the same position can bring different replies. Both computers play perfectly. They differ only in how they choose among equally good moves.

10 What perfect play looks like

If both players are perfect, what happens, and where do people go wrong?

The empty board’s value is 0, so tic-tac-toe is a draw. Neither player can force a win, and each can force at least a draw. Holding the draw takes care, mostly from O, who moves second.

Figure 10: O’s replies to X’s three kinds of first move, a corner, an edge and the centre, each with its value for O.

After a corner, only the centre draws. After an edge, four replies draw. After the centre, the four corners draw and the four edges lose. Each losing reply loses the same way. X makes a fork, a move that leaves two lines each one mark from complete, and O can block only one of them.

Figure 11: The trap of Section 5 played out. With X in opposite corners, O takes a corner. X must block on square 7, and the block makes two threats at once. O stops one, and X completes the other.

Every one of these facts comes from the same search. None of them is a rule written into the engine.

11 Playing badly on purpose

How does Easy lose sometimes?

Hard always plays minimax’s choice, so it never loses, and against itself every game is a draw. Easy plays a random empty square 60% of the time and minimax’s choice otherwise. When Easy does search, it finds every win and every threat, but most of its moves skip the search.

In wordsIn symbols
Easy searcheswith probability 40%
Easy plays a random empty squarewith probability 60%
chance of a best square, 𝑤 of the 𝑘 empty squares best0.4+0.6⋅𝑤𝑘

In the example of Section 4, one of X’s three squares wins at once, so Easy takes it with probability 0.4+0.6⋅13=0.6. Easy draws a new random number every move, so a game of five Easy moves contains at least one random move 99% of the time.

The bars below show a thousand games of each pairing, with X’s wins, draws and O’s wins. Hard as O never loses to a player who picks squares at random. Easy as O loses to that player 343 times in a thousand.

Figure 12: A thousand games of each pairing. Choose the players and play more.