This project demonstrates an AI agent playing TicTacToe against a human player using a magic square representation and the minimax algorithm. The AI plays optimally, making it impossible to beat—your best outcome is a draw!
For a full walk-through with code and 🎮 play online (no setup required), see the Jupyter Notebook:
- Interactive GUI: Click-based gameplay using ipywidgets with a visual grid
- Magic Square Logic: Uses a 3×3 magic square for efficient win detection (any winning line sums to 15)
- Minimax Algorithm: AI makes optimal moves by exploring all possible game states
- Visual Feedback: Color-coded moves (red for AI's ❌, blue for player's ⭕)
- Flexible Start: Choose whether you or the AI goes first
ipywidgets
IPython- Run all cells in the notebook
- Choose whether to play first (Y/n)
- Click on empty cells to place your ⭕
- The AI will respond with its ❌ move
- Try to achieve a draw—the AI won't let you win!
┌───┬───┬───┐
│ 8 │ 3 │ 4 │
├───┼───┼───┤
│ 1 │ 5 │ 9 │
├───┼───┼───┤
│ 6 │ 7 │ 2 │
└───┴───┴───┘
Each position maps to a magic square value, enabling quick win detection by checking if any three positions sum to 15.
- AI (X): Maximizes score (+1 for win)
- Human (O): Minimizes score (-1 for win)
- Draw: Score of 0
The minimax algorithm recursively evaluates all possible game states to select the optimal move.
- Magic square setup and mapping
- Board display functions with ipywidgets
- Game logic:
- Win detection, available moves
- Minimax algorithm implementation
- Interactive gameplay function
Since the AI plays perfectly using minimax, can you force a draw? Good luck! 🎮