Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Projects › Beginner

Tic-Tac-Toe with an Unbeatable AI

A browser tic-tac-toe where the computer never loses — your first real game-tree algorithm.

Level: Beginner · Time: 2–3 days · Tech stack: JavaScript, Minimax

Features to build

What you will learn

Step-by-step guide

1. Represent the board

An array of 9 cells: ['X', null, 'O', …]. Precompute the 8 winning lines [[0,1,2],[3,4,5],…].

2. Check the winner

const winner = (b) => LINES.find(([a, c, d]) => b[a] && b[a] === b[c] && b[a] === b[d]);

3. Minimax

The computer tries every move, assumes you also play perfectly, and picks the best score.

function minimax(board, isAi) {
  const w = winner(board);
  if (w) return board[w[0]] === 'O' ? 10 : -10;
  if (board.every(Boolean)) return 0;                   // draw
  const scores = board.map((cell, i) => {
    if (cell) return null;
    board[i] = isAi ? 'O' : 'X';
    const s = minimax(board, !isAi);
    board[i] = null;                                      // undo (backtracking)
    return s;
  }).filter(s => s !== null);
  return isAi ? Math.max(...scores) : Math.min(...scores);
}

4. Prefer faster wins

Subtract the depth from winning scores so the AI wins in fewer moves.

5. Alpha-beta pruning

Pass alpha and beta and stop exploring a branch once it can't change the result — the same answer, far fewer positions.

6. UI

Render the board as a 3×3 CSS grid of buttons; disable clicks while the AI "thinks" (add a 300 ms delay so it feels natural).

Level it up

On your resume

Learn on Codify