DEV Community

Arhan Khan
Arhan Khan

Posted on

Build a Connect Four Game with JavaScript

Connect Four is the perfect first board game to build in JavaScript. The rules are simple, the board is just a grid, and the win check — four in a row — teaches you the most useful pattern in game programming: scanning a grid in four directions.

What you are building

A 7-column, 6-row board where two players take turns dropping discs, and the game announces the winner as soon as someone gets four in a row.

The JavaScript: the board is an array

const ROWS = 6, COLS = 7;
let board = Array.from({ length: ROWS }, () => Array(COLS).fill(null));
let currentPlayer = 'red';

function dropDisc(col) {
  for (let row = ROWS - 1; row >= 0; row--) {
    if (!board[row][col]) {
      board[row][col] = currentPlayer;
      return row;
    }
  }
  return -1; // Column is full
}
Enter fullscreen mode Exit fullscreen mode

Starting from the bottom row and going up is how gravity works in this game. The first empty cell you find is where the disc lands.

The JavaScript: checking for a win

function checkWin(row, col) {
  const directions = [[0, 1], [1, 0], [1, 1], [1, -1]]; // right, down, diagonal x2
  for (const [dr, dc] of directions) {
    let count = 1;
    count += countDirection(row, col, dr, dc);
    count += countDirection(row, col, -dr, -dc);
    if (count >= 4) return true;
  }
  return false;
}

function countDirection(row, col, dr, dc) {
  let count = 0;
  let r = row + dr, c = col + dc;
  while (r >= 0 && r < ROWS && c >= 0 && c < COLS && board[r][c] === currentPlayer) {
    count++;
    r += dr;
    c += dc;
  }
  return count;
}
Enter fullscreen mode Exit fullscreen mode

Four directions, counted both ways from the last move. You only need to check around the disc that was just placed — the rest of the board cannot have changed.

Rendering the board

Render the array as a grid of divs, and re-render after every move. Keep the board array as the single source of truth, exactly like the reading list and Kanban apps: change the data, then redraw the screen from it.

The one thing to remember

Check for a win before switching players. If you switch first, the win check runs against the wrong colour, and the game announces the loser as the winner — a bug that looks correct in testing until the very first game ends.

Top comments (0)