Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 56 ยท Projects

Project: Tic-Tac-Toe

Build tic-tac-toe with jQuery: draw the board, alternate players, reject invalid moves, detect wins and draws with a lookup table, and reset the game.

Tic-tac-toe is the smallest game that still has every ingredient of a real one: a board, turns, rules that reject bad input, a way to win and a way to start over. It is a good exercise in separating game state (an array of nine cells) from what is drawn (a grid of buttons). You will write the rules once, and jQuery will only report the state on the screen.

Prerequisites

You should know delegated events, toggling classes and reading data attributes.

Plan the game

Nine cells, numbered 0 to 8 from the top left:

0 1 2
3 4 5
6 7 8

The whole game is described by three variables: board (an array of nine values, each "", "X" or "O"), turn (whose go it is) and over (true after a win or draw). Each cell on screen is a <button data-cell="N">, which gives keyboard and screen-reader support without extra work.

The rules are small enough to list:

  1. Players take turns, X first.
  2. Clicking a taken cell does nothing except show a short message (an invalid move).
  3. After every move, check for a win: three equal marks in one of eight lines (three rows, three columns, two diagonals).
  4. If no line is complete and the board is full, it is a draw.
  5. A New game button clears everything.

Detecting a win with a lookup table

Beginners often write long if chains for the eight lines. A table of the lines is shorter and cannot hide a typo among the conditions:

JavaScript
var LINES = [
  [0, 1, 2], [3, 4, 5], [6, 7, 8],   // rows
  [0, 3, 6], [1, 4, 7], [2, 5, 8],   // columns
  [0, 4, 8], [2, 4, 6]               // diagonals
];

function winningLine(board) {
  for (var i = 0; i < LINES.length; i++) {
    var a = LINES[i][0], b = LINES[i][1], c = LINES[i][2];
    if (board[a] && board[a] === board[b] && board[a] === board[c]) {
      return LINES[i];
    }
  }
  return null;
}

Returning the line itself (not just true) lets the page highlight the three winning cells.

Two-player tic-tac-toe

Notice how little the click handler does. It passes the cell number to play(), which owns every rule. That is the same separation you used in the to-do list: the handler translates the event, and one function changes the state and updates the page.

Disabling cells and the invalid-move message

Two layers protect against bad moves. The disabled property on a taken button stops mouse and keyboard activation in the browser. The board[i] !== "" check inside play() protects the game rules even if something else calls the function (a test, a keyboard shortcut, a future computer player). Never rely only on the interface to enforce rules.

The message goes into an element with role="alert", so screen readers announce it, and it is cleared on the next valid move so it does not linger.

Adding a computer opponent

Because the rules live in play() and winningLine(), adding a computer player is a small step. A simple version picks a winning move if it has one, then blocks the opponent, then takes the centre, then any free cell:

JavaScript
function computerMove() {
  var free = [];
  for (var i = 0; i < 9; i++) { if (board[i] === "") { free.push(i); } }

  function findLineFor(mark) {
    for (var k = 0; k < free.length; k++) {
      var test = board.slice();
      test[free[k]] = mark;
      if (winningLine(test)) { return free[k]; }
    }
    return null;
  }

  var move = findLineFor("O");             // win if possible
  if (move === null) { move = findLineFor("X"); }   // otherwise block
  if (move === null && board[4] === "") { move = 4; }
  if (move === null) { move = free[Math.floor(Math.random() * free.length)]; }
  return move;
}

// after a human move that did not end the game:
setTimeout(function () { play(computerMove()); }, 400);

The short delay makes the reply feel like a turn rather than an instant answer. Disable the board during the delay so the player cannot click twice. This heuristic never loses a game it could win or block, but it is not perfect; a full solution uses the minimax algorithm, which tries every continuation.

When you test game logic, call play() directly in a script, as the lesson example does, instead of clicking by hand. It is faster, repeatable, and it proves the rules work without the interface.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the game keep a board array instead of reading the marks from the buttons?

    State in a variable can be tested, copied and checked without touching the DOM. The page only displays it.
  2. 2. How many lines must be checked for a winner on a 3x3 board?

    Three rows, three columns and two diagonals make eight lines.
  3. 3. Why does play() check board[i] even though taken buttons are disabled?

    The interface is a convenience, not security. Game rules belong in the function that changes the state.
  4. 4. What is the benefit of winningLine() returning the line instead of true?

    Returning the three indexes tells the interface exactly which cells to highlight, while null still means no win.

Summary

  • Keep the game in a few variables (board, turn, over) and let one play() function enforce every rule.
  • A table of the eight winning lines is shorter and safer than a chain of if statements; return the line to highlight it.
  • Reject invalid moves in the game logic, and disable taken buttons as a convenience.
  • Delegated clicks on the board plus data-cell attributes keep the event code to a few lines.
  • With the rules in functions, adding a computer player or tests is easy.

Next: Project: Image Slider, Magnifier and Spotlight.