Noughts and Crosses

The script on this page uses a simple algorithm to play noughts and crosses.  It is based on the logic found on p137 of The Power of Computational Thinking by Paul Curzon and Peter W McOwan, which can be found at the bottom of the page.

There is also a Python version of the noughts and crosses, which contains only the code required to solve the problem and is thoroughly commented.

The computer usually goes first - tick here if you want to  

Click the Play button to start.

The Algorithm

I tweaked the algorithm slightly to allow either player to go first. The algorithm that appears in the book is as follows (and assumes that you are X and will go first).  It outlines the first five moves:

  1. Go in a corner.
  2. Go in the opposite corner (to move 1) if it is still available - if it's not then go in another free corner.
  3. If there are two Xs in a line then go between them if possible, otherwise if there are two Os in a row go between them if possible, otherwise go in a free corner.
  4. If there are two Xs in a line then go between them if possible, otherwise if there are two Os in a row go between them if possible, otherwise go in a free corner.
  5. Go in the free space.

If you want to see how this has been implemented, you can either view the source of this page or look at the Python version of the noughts and crosses program, which is fully commented.