Outline of a Computer Program to play Tic Tac Toe

Tic-tac-toe (American English), noughts and crosses (Commonwealth English and British English), or Xs and Os/“X’y O’sies” (Ireland), is a paper-and-pencil game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a diagonal, horizontal, or vertical row is the winner. It is a solved game with a forced draw assuming best play from both players.


The first player ‘X’ can force a win if the second player ‘O’ chooses an edge rather than a corner in response to X beginning with the middle square as shown below:

X then chooses the lower right box forcing O to choose upper-left box, which forces X to choose the lower right box. At that point O has to choose between the bottom edge or the top-left corner. In either case X wins by choosing the option O did not choose.

If O had chosen a corner rather than an edge then neither will loose simply by preventing the other from winning in the next move. If X has two boxes in a line with third empty than O prevents the X from winning just by taking the empty box. Likewise for X. If that situation does not arise then choose a corner and if none is available chose any.

These rules are easy to code and an implementation in C++ can be found here or here if you want Javascript. In both cases there is a function called ‘play’ where the magic happens. The function takes two parameters ‘state’ and ‘board’. ‘state’ is the number of turns taken by both players put together. ‘board’ is a 9-element array storing the current state of play. In the Javascript version ‘state’ is computed by counting the number of non-empty cells and hence only the ‘board’ parameter is required

About The Sunday Programmer

Joe is an experienced C++/C# developer on Windows. Currently looking out for an opening in C/C++ on Windows or Linux.
This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s