Tic-Tac-Toe
Play Tic-Tac-Toe against an easy or unbeatable computer.
Overview
Tic-Tac-Toe is the ageless three-in-a-row game on a 3x3 grid. Two players alternate placing X and O marks; the first to align three of their marks horizontally, vertically, or diagonally wins. If all nine cells fill with no line, the game is a draw. This version lets you play X against either an easy or an unbeatable computer opponent.
The easy mode plays random legal moves, which is fine for kids or for warming up. The unbeatable mode runs a complete game-tree search, so it never loses — the best you can manage is a draw. That mirrors the well-known mathematical result: Tic-Tac-Toe is a solved game, and with perfect play from both sides it always ends in a draw.
How it works
The game tree of Tic-Tac-Toe has at most 9! = 362 880 leaves, small enough to enumerate exhaustively at the start of every move. The unbeatable AI runs a minimax search to terminal positions, scoring wins for the AI as +1, losses as -1, and draws as 0. It picks the move with the highest minimax value, breaking ties by preferring shorter wins and longer losses to make play feel decisive.
The easy AI samples a legal move uniformly without any look-ahead. This usually loses to a thoughtful human, since most random move sequences walk into a setup the player can capitalise on within a few turns. The unbeatable AI's main responsibility is to find forks — positions where two winning lines threaten simultaneously and the opponent cannot block both.
Examples
- Centre opening (X plays cell 5): the strongest opening — the centre participates in 4 of 8 winning lines.
- Corner opening: also strong; encourages a fork later.
- Edge opening: weakest, often leads to draws against any competent opponent.
- A famous fork: X plays centre, O plays edge, X plays opposite corner, threatening two wins at once.
FAQ
Is Tic-Tac-Toe always a draw with perfect play?
Yes. Both sides can force at least a draw, and neither can force a win.
Can I beat the unbeatable AI?
No. It plays a complete game-tree search; the best result is a draw.
Why does the easy AI sometimes win?
Random play occasionally stumbles into the right move, especially if the human makes an early mistake.
What's the best opening?
The centre cell is the strongest opening because it appears in four of the eight possible winning lines.
Does the game end early if a win is unreachable?
This version plays out every move until a win or a full board. Some implementations call a draw early when no win is possible.