DEV Community

Arhan Khan
Arhan Khan

Posted on

Build a Tic Tac Toe Game with JavaScript

Tic Tac Toe is the smallest real game you can build, and that is exactly why it is a great beginner project. Nine cells, two players, eight ways to win — and the code teaches you state, event handling, and win detection in under a hundred lines.

What you are building

A 3x3 grid. Two players take turns placing X and O. After every move the game checks for a win or a draw, shows whose turn it is, and offers a restart button.

The HTML and state

Keep the board in a simple array of 9 values. null means empty:

<div class="board" id="board"></div>
<p id="status">Player X's turn</p>
<button id="restart">Restart</button>
Enter fullscreen mode Exit fullscreen mode
let board = Array(9).fill(null);
let currentPlayer = "X";
let gameOver = false;

const winningLines = [
  [0, 1, 2], [3, 4, 5], [6, 7, 8],
  [0, 3, 6], [1, 4, 7], [2, 5, 8],
  [0, 4, 8], [2, 4, 6],
];
Enter fullscreen mode Exit fullscreen mode

Handling a move

Render the board from the array, and re-render after every move. One click handler covers the whole board:

function handleClick(index) {
  if (board[index] || gameOver) return;

  board[index] = currentPlayer;
  render();

  const winner = checkWinner();
  if (winner) {
    document.getElementById("status").textContent = "Player " + winner + " wins!";
    gameOver = true;
    return;
  }

  if (!board.includes(null)) {
    document.getElementById("status").textContent = "It is a draw!";
    gameOver = true;
    return;
  }

  currentPlayer = currentPlayer === "X" ? "O" : "X";
  document.getElementById("status").textContent = "Player " + currentPlayer + "'s turn";
}

function checkWinner() {
  for (const [a, b, c] of winningLines) {
    if (board[a] && board[a] === board[b] && board[a] === board[c]) {
      return board[a];
    }
  }
  return null;
}
Enter fullscreen mode Exit fullscreen mode

Why this project matters

The pattern here — state in an array, a render function, and a single source of truth — is the same pattern behind much bigger apps. React, Vue, and every other framework are built around this idea: change the data, re-render the view.

What to add next

Add a scoreboard that survives restarts, highlight the winning line in a different colour, or build a simple computer opponent that picks a random empty cell. A minimax AI is a fun stretch goal once the random opponent works.

Top comments (0)