THE CORE OF THE TIC-TAC-TOE PROGRAM
(OR WHAT IS INSIDE THE COMPUTER BRAIN)

The squares of the board are numbered from 0 to 8, line this:

012
345
678

The horizontal rows are (0, 1, 2), (3, 4, 5), and (6, 7, 8).
The vertical columns are (0, 3, 6), (1, 4, 7), and (2, 5, 8).
The diagonals are (0, 4, 8) and (2, 4, 6).
For brevity we will refer to a row, column, or diagonal as a triad.

The program keeps track of location of each square as well as a whether a square is empty, is occupied by the HUMAN player or the COMPUTER player. If the computer plays first, it plays on one of the four corners (0, 2, 6, 8) or the center (4). The choice is made by rolling (the equivalent of) a five-sided dice. If it plays second and the first human play is in one of the corners (0, 2, 6, 8), it plays on the opposite corner (8, 6, 2, 0). If not it proceeds to play according to the rules below. (This part is suppressed if the flag EASY has been set.)

When the user presses the left mouse button the program finds the square pointed by the user, fills it and then it takes the following steps.

  1. It checks if the human has completed a triad in which case it declares the human the winner and ends the game.

  2. It checks if the board is full and ends the game without a winner.

  3. It checks whether there is a triad with two elements filled by the same player and the third empty. The computer plays the empty element either blocking the human player or winning. Then it goes to step 7.  If there was no move the program continues to step 4.

  4. If the center square is empty the computer occupies it and goes to step 7. Otherwise it continues to step 5.

  5. The programs looks for an empty corner (0, 2, 6, 8) and if there is an empty space, it takes it and goes to step 7, otherwise it continues to step 6.

  6. The programs looks for an empty middle (1, 3, 5, 7) and if there is an empty space, it takes it.

  7. The program checks if the computer has won. If it has, the program ends the game.

  8. The program checks if the board is full, in which case it ends the game. Otherwise it waits for the human to play.

Download Program