Unbeatable tic-tac-toe (minimax)
Play tic-tac-toe against a computer that never loses, powered by the minimax algorithm.
What you'll learn
- โ2D arrays and game state
- โRecursion and backtracking
- โThe minimax algorithm (and alpha-beta pruning)
What you'll build
- โHuman vs human and human vs computer
- โComputer never loses
- โChoose who starts
- โScore board across games
Step-by-step guide
- 1
Represent the board
char[3][3] filled with ' '; print it with row and column numbers.
- 2
Detect a winner
Check 3 rows, 3 columns and 2 diagonals; a draw is a full board with no winner.
- 3
Human moves
Read row and column with Scanner, reject taken or out-of-range cells.
- 4
Minimax
score(board, isMax): if game over return +10 (AI wins), โ10 (human wins) or 0. Otherwise try every empty cell, recurse with !isMax, undo the move, and return the max or min.
- 5
Prefer quick wins
Subtract depth from wins (10 โ depth) so the AI wins in fewest moves and delays losses.
- 6
Best move
For each empty cell, place AI mark, compute minimax, undo; play the cell with the highest score.
- 7
Alpha-beta
Add alpha and beta parameters to skip branches that cannot change the result; count nodes visited before and after.
๐ Make it stand out
- +Swing GUI with clickable cells
- +Difficulty levels (random move some of the time)
- +Extend to 4ร4 with depth limits