Solving Tic-Tac-Toe with R data.tree

In this post, we do a brute force solution of Tic-Tac-Toe, the well-known 3*3 game. You’ll learn how data.tree can be used to build a tree of game history, and how the resulting data.tree structure can be used to analyse the game.

This post is based on data.tree 0.2.1, which you can get from CRAN.

We want to set up the problem in a way such that each Node is a move of a player, and each path describes the entire history of a game.

We number the fields from 1 to 9. Additionally, for easy readability, we label the Nodes  in an Excel-like manner, such that field 9, say, is ‘c3’:

To speed up things a bit, we consider rotation, so that, say, the first move in a3 and a1 are considered equal, because they could be achieved with a 90 degree rotation of the board. This leaves us with only a3, b3, and b2 for the first move of player 1:

Game play

Now we traverse the tree recursively, and add possible moves to the leaves along the way, growing it to eventually hold all possible games. To do this, we define a method which, based on a Node’s path, adds possible moves as children.

Note that we store additional info along the way. For example, in the line  child$player <- ifelse(node$player == 1, 2, 1) , the player is deferred from the parent Node , and set as an attribute in the Node .

Exit Criteria

Our algorithm stops whenever either player has won, or when all 9 fields are taken. Whether a player has won is determined by this function:

Tree creation

The following code plays all possible games. Depending on your computer, this might take a few minutes:


What is the total number of games?

How many nodes (moves) does our tree have?

What is the average length of a game?

What is the average branching factor?

How many games were won by each player?

We can, for example, look at any Node , using the PrintBoard  function. This function prints the game history:

The first number denotes the move (1 to 9). The second number is the player:

We could now move on to define a minimax optimisation criteria, or a heuristic search.

Exercise: Do the same for Chess!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.