Dev.to WebDev 🛠 Dev 👁 2 📖 2 min read

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

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
}

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;
}

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.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.