Projects · 12 / 19 Exercise Hard

Tic-tac-toe with AI

Objective

Program the move of an automatic player in tic-tac-toe. The strategy is simple but effective: win if it can, block if the opponent is about to win and, otherwise, take the best free cell.

Instructions

  • The first line is the AI piece (X or O) and it is its turn. Then 3 lines with the board, using X, O and . for free cells. There is always at least one free cell.
  • Choose the cell in this order: 1) complete one of its own lines that has two pieces, 2) block an opponent line with two pieces, 3) the center, 4) a free corner in the order top-left, top-right, bottom-left, bottom-right, 5) any free side in the order top, left, right, bottom.
  • Show Move: r c (row and column from 1), the resulting board and finally X wins, Draw or The game goes on.
Input
O
XX.
O..
...
Output
Move: 1 3
XXO
O..
...
The game goes on

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise