This is a short description and example of the 'A.I.' (Artificial intelligence) in my implementation of the Tic-tac-toe game, which you'll find on this site. You can see the A.I. in action in the game by enabling the "Watch AI" option from the menu and including at least one A.I. player.

Each time the AI player makes a move it makes a 2-stage evaluation of the current grid. The first stage evaluates each line and makes a count of how many "X" and "O"'s are on the line. From this three further properties for each line are evaluated; Friend, Block and Full.
If there are any friendly plays on the line but no enemy plays then the Friend count is the number of friendly plays on the line, otherwise it's 0 (Can't make a win on this line).
Block is calculated in much the same way as Friend however in this case it's based on there being no friendly plays but at least one enemy play.
The Full property is simply to check to see if the line is full or not as there's no point in checking full lines.
In this way we can work out which lines are the best chance for a good move. At this point the routine looks for an easy move which is either a win or a block, this being if one of the lines has a Friend or Block count of 2 respectively.
If no easy move it detected then it passes over to a second more exhaustive check of the board to see which squares represent the best plays. Each line is evaluated to see if it's worth playing there to either help score a win or help block the opponent. As the board has already been evaluated by the first half of the routine, this data is used again rather than having to re-profile the grid and a Block + Friend priority map is created. Based on how much of a priority each square is (The higher the value the higher the priority, 0 means none at all) a play can then be made, if necessary choosing one square at random if more than one contain the same priority.
Finally if no squares have any priority (End of a game with a draw situation) the routine resorts to "dumb" mode and just plays and square it can.

By adding a small amount of 'random' behaviour to the A.I., it allows the opponent to remain logical but not predictable.

These example games demonstrate the "Smart" A.I. players, the "Dumb" A.I. players simply make moves at random:

Game 1 · Game 2

Back to turorials