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
- Player vs player and player vs computer
- Easy (random) and impossible (minimax) levels
- Win line highlight and score board
- Undo move
- Responsive board
What you will learn
- 2-D arrays / boards
- Recursion
- Minimax and game trees
- Alpha-beta pruning
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
- Connect Four with depth-limited minimax
- Online multiplayer with WebSockets
- Count positions searched with and without pruning
On your resume
- Implemented an unbeatable tic-tac-toe AI using minimax with alpha-beta pruning in JavaScript.