๐ŸŽ™ Free live masterclass ยท Sun, 29 Nov, 7:00 pm IST ยท Java Full Stack roadmap Register free โ†’
Skills101

Unbeatable tic-tac-toe (minimax)

Play tic-tac-toe against a computer that never loses, powered by the minimax algorithm.

Intermediateโฑ 5โ€“8 hours๐Ÿชœ 7 stepsJavaRecursionGame AI

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. 1

    Represent the board

    char[3][3] filled with ' '; print it with row and column numbers.

  2. 2

    Detect a winner

    Check 3 rows, 3 columns and 2 diagonals; a draw is a full board with no winner.

  3. 3

    Human moves

    Read row and column with Scanner, reject taken or out-of-range cells.

  4. 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. 5

    Prefer quick wins

    Subtract depth from wins (10 โˆ’ depth) so the AI wins in fewest moves and delays losses.

  6. 6

    Best move

    For each empty cell, place AI mark, compute minimax, undo; play the cell with the highest score.

  7. 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