Tic Tac Toe (noughts and crosses) is always such a nice example.

I was thinking about strategies and decided to implement a program that plays Tic Tac Toe according to John von Neumann's minimax. This is a kind of meta-strategy that can be used for playing any game: Always chose the move that will minimize the maximum damage that your opponent can do to you.

The algorithm works recursively by looking for the move that will let an optimally playing opponent inflict the least damage. The opponent's strategy is calculated by way of the same algorithm, and so on. This means that on the first move, the computer investigates the entire game tree - it considers every single possible Tic Tac Toe game and then choses randomly among the best (least dangerous) moves.

Have a go. Click on the playing field first, and then press S or C to begin. The computer should always achieve draw or win - otherwise there is a bug.

(Press H for hints when playing - the program will evaluate each possible move.)

Some observations from this:

 

(Jesper Juul, December 2003.)