Skip to content
Tutorials Center
My learning

Topics

Lesson 90 of 96 ยท Projects

Project: Tic Tac Toe

Build tic tac toe in TypeScript - a fixed-size tuple board, win detection from constant lines, a discriminated game state, an unbeatable minimax AI and a click-driven UI binding.

Tic tac toe is small enough to finish in an afternoon yet rich enough to show how types can make illegal states impossible. A board is exactly nine cells, a move is an index from 0 to 8, and a game is in exactly one of three states: someone's turn, a win or a draw. TypeScript can express all of that, and then the compiler does the checking for you.

You will build the game in three stages: the board and rules (types, moves, win detection), the AI (a simple heuristic player and a perfect minimax player), and the UI binding, written against DOM-shaped interfaces so you can play it right here.

Stage 1: board, moves and win detection

A board is a tuple of nine cells. Unlike Cell[], a tuple has a fixed length, so board[9] is a compile error. Moves are indexes 0 | 1 | ... | 8, and the winning lines are a constant list of index triples.

TypeScript Stage 1: tuple board, lines and a discriminated game state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Study the types. LINES uses as const satisfies ...: as const keeps the exact numbers, and satisfies checks that every row is a triple of valid indexes without widening them (you met this operator in satisfies). GameState is a discriminated union, so a won state has a winner and a line while a playing state has a next player; no state can have a winner and a next player. Because the state is immutable (readonly everywhere), play returns a new state instead of changing the old one, which makes undo and AI search trivial.

The one cast in play, from map's Cell[] back to the 9-tuple Board, is the place where TypeScript cannot follow the logic (map preserves length, but the type loses it). It is contained in one line.

Stage 2: the AI

Two levels make a nice difficulty setting:

  • Heuristic player: win if you can, otherwise block the opponent's win, otherwise take the center, then a corner, then anything. Easy to read, and not perfect.
  • Minimax player: try every possible continuation of the game and choose the move that leads to the best outcome assuming the opponent also plays perfectly. Tic tac toe has fewer than 550,000 move sequences, so a full search is instant.
TypeScript Stage 2: heuristic and minimax players, tested against each other

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

A Strategy is just a function type, so players are interchangeable: the game loop does not care whether a move came from a human, a heuristic or a search. This is the same idea as the injected Clock in Project: Typing Speed Test, and it is why the tournament code is so short.

The numbers tell the story. Random play is chaotic. The heuristic beats a random opponent most of the time but can lose to a smart one. Minimax never loses: against random it wins or draws, and against itself it always draws, which is the known result of perfect tic tac toe. Scoring wins by how many empty squares remain is a small refinement so that the AI prefers a quick win to a slow one.

Minimax meets the same position many times, reached by different move orders. The cache map, keyed by the board plus whose turn it is, makes each position be scored once; without it, this demo would take seconds instead of milliseconds. That works because the score depends only on the position, not on the path (which is why the score uses the number of empty squares instead of a depth counter).

Stage 3: the UI binding

The final stage connects the game to nine buttons and a status line. The controller only needs three small things from the DOM: a status label, nine cell-like elements and a way to listen for clicks.

TypeScript Stage 3: clicking squares through DOM-shaped cells

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

In a browser, the setup is just selection and a call:

TypeScript
const squares = [...document.querySelectorAll<HTMLButtonElement>('#board button')];
const status = document.querySelector<HTMLElement>('#status');

if (status) {
  mount(squares, status);
}

A real HTMLButtonElement already has textContent, disabled and addEventListener('click', ...), so it satisfies SquareLike without adapters. The game logic and the page are connected only through the narrow interfaces, which is what made the logic runnable in this editor.

Ideas to extend it

  • Add a difficulty selector typed as 'easy' | 'medium' | 'hard' and a Record<Difficulty, Strategy> table.
  • Add undo by keeping an array of states (see the generic History<T> in Project: Pixel Art Maker).
  • Highlight the winning line with the line from the won state.
  • Generalize the board to N x N and K in a row, deriving the winning lines programmatically.
  • Add alpha-beta pruning to minimax and measure how many positions it skips.
  • Store a running scoreboard in a Record<Player | 'draw', number>.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is the board typed as a 9-element tuple instead of Cell[]?

    Cell[] has an unknown length. A nine-element tuple makes board[9] an error.
  2. 2. What does as const satisfies ReadonlyArray<readonly [Index, Index, Index]> achieve for LINES?

    as const preserves the literals; satisfies validates the shape without widening the types.
  3. 3. How does the GameState union prevent a won game from having a next player?

    With a discriminated union, the compiler allows only the fields declared for the member selected by status.
  4. 4. What does minimax assume about the opponent?

    At the opponent's turns it takes the minimum score for you, which is how it guards against the best replies.
  5. 5. Why can the game controller work with plain objects instead of real buttons?

    Structural typing lets any object with textContent, disabled and addEventListener be used.

Summary

  • Model the board as a fixed-length tuple and moves as a literal union of indexes to rule out out-of-range access at compile time.
  • Keep the winning lines as a constant checked with as const satisfies.
  • A discriminated GameState makes illegal combinations (winner plus next player) unrepresentable.
  • play is a pure function returning a MoveResult, which makes undo and AI search simple.
  • A Strategy function type makes players interchangeable; minimax searches every continuation and never loses at tic tac toe.
  • Bind to the page through narrow interfaces so the logic runs anywhere.

Next: Project: Canvas Animation