Skip to content
Tutorials Center
My learning

Topics

Lesson 135 of 156 ยท Projects

Project: Tic-Tac-Toe and Rock-Paper-Scissors

Build Tic-Tac-Toe with win detection and an unbeatable minimax computer opponent, plus Rock-Paper-Scissors with a best-of-five match. Learn game state in JavaScript.

Games are the best way to learn state. Every game is the same loop: some data describes where things stand, the player does something, the rules change the data, and the screen is redrawn from it. If you can keep that loop clean in a game of Tic-Tac-Toe, you can keep it clean in a shopping cart or a spreadsheet.

In this project you'll build two classic games. Tic-Tac-Toe comes first: you'll write the rules as plain functions, play it against a friend, then add a computer opponent with three difficulty levels, the hardest of which is unbeatable thanks to an algorithm called minimax. After that comes Rock-Paper-Scissors, where a neat piece of modular arithmetic replaces a pile of if statements.

It uses ideas from Arrays, map, filter, reduce and forEach, Recursion, setTimeout and setInterval and Bubbling, Capturing and Delegation.

The pattern: rules, state, render

Keep three things apart:

Part What it is Example
Rules Pure functions that look at data and answer questions. No DOM. getWinner(board)
State The variables that describe the game right now. board, turn, scores
Render One function that reads the state and updates the page. render()

Event handlers do only one job: change the state, then call render(). Because the rules never touch the page, you can test them in the console before you've drawn a single square, which is exactly what you'll do first.

Step 1: The rules of Tic-Tac-Toe

The board is a flat array of nine cells, numbered 0 to 8 from the top-left, row by row. A cell holds "X", "O" or null:

TEXT
 0 | 1 | 2
---+---+---
 3 | 4 | 5
---+---+---
 6 | 7 | 8

A flat array is simpler than an array of rows: a click maps straight to an index, and the eight winning lines are just eight triples of indices. getWinner() checks each line: if all three cells hold the same non-empty value, that player has won, and the function also returns the line so the interface can highlight it.

JS Step 1: Rules and win detection

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

No output.

Two small helpers deserve a second look. board.flatMap((cell, i) => cell === null ? [i] : []) returns the indices of the empty cells in one pass: returning [i] keeps the index and returning [] drops it. And getWinner() returns null for "no winner", which is falsy, so if (winner) reads naturally.

Step 2: A two-player game

Now the state and the page. The state is a small object:

  • board: the nine cells;
  • turn: whose move it is;
  • result: null while playing, otherwise { player, line } for a win or { draw: true };
  • scores: wins for X and O and the number of draws;
  • starter: who goes first, which alternates each game so nobody has the permanent advantage.

The nine squares are real <button> elements, so they work with the keyboard, and each carries an aria-label such as "Row 2, column 3, X" so screen readers can follow the game. A single click listener on the board uses the button's data-index. play(index) ignores clicks on filled squares and after the game ends, which is where most Tic-Tac-Toe bugs live.

Step 2: Two-player Tic-Tac-Toe

Play a few rounds. Notice that the first game starts with X, the second with O, and so on, and that the board locks as soon as someone wins.

render() redraws everything from state each time, even if only one cell changed. For nine squares that costs nothing, and it removes a whole class of bugs where part of the screen shows stale data. Only worry about updating less when profiling tells you to.

Step 3: A computer opponent

A computer player is just a function: chooseMove(board, aiPlayer, level) takes the board and returns the index of a cell. You'll write three levels.

Easy picks a random empty cell.

Medium follows two simple rules, in order: if I can win this move, do it; if the opponent could win next move, block it; otherwise take the center, then a random cell. It plays a decent game but can be tricked.

Hard uses minimax. The idea: to choose a move, imagine every possible continuation of the game. Score a finished game +10 if the computer wins, -10 if it loses and 0 for a draw. The computer assumes that it will pick the move with the highest score on its turn and that the opponent will pick the lowest on theirs. By working backwards from the end of the game, every position gets a score, and the best first move is the one with the best score.

flowchart TD
  A["Computer to move"] -->|"picks the max"| B["Move 1: score 0"]
  A --> C["Move 2: score +10"]
  A --> D["Move 3: score -10"]
  C --> E["Opponent to move: picks the min"]
  E --> F["...and so on until the board is full or won"]

Minimax alternates between maximizing the computer's score and minimizing the opponent's, recursing until the game ends.

The recursion is minimax(board, turn, depth). A small trick: the score is 10 - depth for a win and depth - 10 for a loss, so the computer prefers winning sooner and losing later. Without it, it might choose a slow win over an immediate one. Tic-Tac-Toe is tiny (fewer than 550,000 positions from an empty board), so this runs instantly. To keep the game varied, the first move is a random corner or the center, and ties between equally good moves are broken at random.

The setTimeout of 450 ms before the computer moves isn't needed technically, but a move that appears instantly feels abrupt. While the computer "thinks", busy is true and clicks are ignored, so you can't move for it.

Step 3: Tic-Tac-Toe with a computer opponent

Try the "unbeatable" level. You'll never win; the best you can do is draw. Then switch to "easy" to see the difference. When you play as X and the computer is O, the computer starts every other game, which is the only time the first-move advantage is its own.

Look at the pattern inside findWinningMove(): it tries a move, checks the result and undoes it. minimax() does the same on a bigger scale. That's called backtracking, and it's why chooseMove() hands the AI a copy of the board. If the AI changed the real board during its search, the game would show moves nobody made.

Step 4: The rules of Rock-Paper-Scissors

Rock-Paper-Scissors has three choices and nine possible pairings. You could write nine if cases, but there's a pattern: each choice beats the one before it in a circle.

Number the choices 0 rock, 1 paper, 2 scissors. Paper (1) beats rock (0), scissors (2) beats paper (1), and rock (0) beats scissors (2), which wraps around the end of the list. Subtract and use the remainder to wrap:

JavaScript
(player - computer + 3) % 3
// 0 -> draw, 1 -> player wins, 2 -> computer wins

Adding 3 first keeps the number positive, because JavaScript's % can return negative values for negative inputs. The table below is generated from that one expression, not typed in.

JS Step 4: The rules as one expression

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

No output.

Step 5: The Rock-Paper-Scissors game

For the game itself, you'll play a best-of-five match: the first to three round wins takes the match. The state is tiny: the two scores, the last round and a matchOver flag. A history list shows each round so the player can see the computer isn't cheating.

A few details:

  • The computer's pick is chosen with Math.random(). Since the choices are equally likely and independent of yours, no strategy beats it in the long run.
  • The three buttons are real buttons with emoji and text labels, so they work for keyboard and screen-reader users. The keys R, P and S do the same as clicking.
  • After the match ends the choice buttons are disabled, and Play again starts a new match.
Step 5: Rock-Paper-Scissors match

Where to go from here

  • Bigger board. Make Tic-Tac-Toe 4 by 4 or 5 by 5 with "four in a row". Generate WIN_LINES with loops instead of typing them out. Plain minimax becomes too slow, so look up alpha-beta pruning and a depth limit.
  • Connect Four. The same pattern with gravity: a move is a column, and the piece falls to the lowest empty row.
  • Rock-Paper-Scissors-Lizard-Spock. Five choices: (player - computer + 5) % 5 is 1 or 2 when the player wins. Check that the idea still works.
  • A smarter RPS opponent. Keep the player's history and counter their most frequent choice. Players are not random!
  • Remember scores. Save scores with localStorage in a real page.
  • Test the rules. getWinner(), judge() and minimax() are pure functions, so they are perfect to cover with tests.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is the Tic-Tac-Toe board stored as a flat array of nine cells and not as three arrays of three?

    With a flat array, data-index from the clicked button is the cell number, and the eight winning lines are just eight lists of three indices.
  2. 2. In the games, what should an event handler do?

    Handlers update the state, and render() redraws the page from it. That keeps the rules, state and screen in sync.
  3. 3. What does minimax assume about the two players?

    Minimax maximizes the computer's score on its own turn and assumes the opponent plays their best move, which minimizes it.
  4. 4. Why does the minimax score use 10 - depth for a win?

    A win found at a smaller depth scores higher, so the computer takes an immediate win over a slower one (and delays a loss as long as possible).
  5. 5. What does (player - computer + 3) % 3 return when the player's choice is index 1 (paper) and the computer's is 0 (rock)?

    (1 - 0 + 3) % 3 = 1, which the game treats as a player win. Adding 3 keeps the value non-negative before the remainder wraps it.

Summary

  • Keep rules (pure functions), state (plain data) and render (one function) separate. Handlers change state and call render().
  • A flat array with WIN_LINES makes win detection a short loop, and ignoring illegal moves is part of the rules.
  • Alternate who starts, lock the board while the computer "thinks", and cancel pending timers when a new game begins.
  • Minimax searches every continuation, maximizing the computer's score and minimizing the opponent's. Try a move, recurse, then undo it.
  • Rock-Paper-Scissors needs no lookup table: (a - b + 3) % 3 gives draw, win or lose.
  • Real buttons, aria-labels and keyboard shortcuts make a game playable for everyone.

Next: Project: Currency, Unit and Grade Converters.