Interactive Tic-Tac-Toe: Minimax in Action

Hands-On Demo

Prerequisites

🎯 Learning Objectives

  • See minimax in action on a real game
  • Compare the number of nodes evaluated with and without alpha-beta pruning
  • Understand why the AI never loses at Tic-Tac-Toe

1. Play Against the AI

You are X (you move first). The AI plays O using the Minimax algorithm. Toggle alpha-beta pruning to see how it affects the number of nodes the AI evaluates.

Your turn (X)
Nodes evaluated by AI: 0
Total nodes this game: 0

2. How the AI Works

Minimax for Tic-Tac-Toe

The AI explores the entire remaining game tree from the current position. Since Tic-Tac-Toe is small enough (max ≈9! = 362,880 states), minimax can solve it completely without any cutoff depth. The AI plays perfectly and will never lose.

2.1 Node Counts to Observe

AI’s Move #Without Alpha-BetaWith Alpha-BetaReduction
1st (8 empty)~549,946~18,297~97%
2nd (6 empty)~7,920~900~89%
3rd (4 empty)~168~48~71%
4th (2 empty)~4~3~25%

Alpha-beta pruning is most impactful early in the game when the tree is largest.

2.2 Why the AI Never Loses

The minimax value of Tic-Tac-Toe from the initial state is 0 (draw). With perfect play by both sides, neither player can win. Since the AI always plays perfectly, the best you can achieve is a draw.

3. Experiments to Try

  • Experiment 1: Play with alpha-beta ON, note total nodes. Reset and play the same moves with alpha-beta OFF. Compare.
  • Experiment 2: Try to win! You’ll find the AI always blocks threats and forces a draw.
  • Experiment 3: Start in the corner vs. center vs. edge. Notice how the AI responds differently and the node counts change.

4. Algorithm Applied

Minimax for Tic-Tac-Toe (Simplified)
function bestMove(board, useAlphaBeta):
    bestScore ← −∞
    bestAction ← null
    for each empty cell c in board:
        board[c] ← 'O'  // AI move
        if useAlphaBeta:
            score ← alphabeta(board, false, −∞, +∞)
        else:
            score ← minimax(board, false)
        board[c] ← empty
        if score > bestScore:
            bestScore ← score
            bestAction ← c
    return bestAction

// Utility: X wins → −1, O wins → +1, Draw → 0