DEV Community

Arhan Khan
Arhan Khan

Posted on

Build a 2048 Game with JavaScript

2048 is the sliding-tile puzzle where you merge matching numbers to reach 2048. It looks simple, but it teaches the most valuable game skill there is: writing one pure function that handles a move in any direction, then reusing it four times.

The board is a 4x4 grid of numbers, stored as a 2D array. A move in any direction is really the same operation — slide the tiles together and merge equal neighbours — applied to rows for left/right and columns for up/down. So you write one slide function for a single row, and reuse it:

let board = Array.from({ length: 4 }, () => Array(4).fill(0));
let score = 0;

function slideRow(row) {
  const tiles = row.filter((n) => n !== 0);
  for (let i = 0; i < tiles.length - 1; i++) {
    if (tiles[i] === tiles[i + 1]) {
      tiles[i] *= 2;
      score += tiles[i];
      tiles.splice(i + 1, 1);
    }
  }
  while (tiles.length < 4) tiles.push(0);
  return tiles;
}
Enter fullscreen mode Exit fullscreen mode

Moving left applies slideRow to every row. Moving right reverses each row, slides, and reverses back. Up and down do the same thing on columns by transposing the board first — one helper turns columns into rows:

function transpose(grid) {
  return grid[0].map((_, i) => grid.map((row) => row[i]));
}

function move(direction) {
  let next = board.map((row) => [...row]);
  if (direction === "left") next = next.map(slideRow);
  if (direction === "right") {
    next = next.map((row) => slideRow(row.reverse()).reverse());
  }
  if (direction === "up") next = transpose(transpose(next).map(slideRow));
  if (direction === "down") {
    next = transpose(transpose(next).map((row) => slideRow(row.reverse()).reverse()));
  }
  if (JSON.stringify(next) !== JSON.stringify(board)) {
    board = next;
    spawnTile();
    render();
  }
}
Enter fullscreen mode Exit fullscreen mode

The JSON comparison is the key detail: if the board did not change, the move was invalid and no new tile should spawn. After every valid move, a new tile (a 2, or a 4 with 10% probability) appears in a random empty cell:

function spawnTile() {
  const empty = [];
  board.forEach((row, r) =>
    row.forEach((cell, c) => {
      if (cell === 0) empty.push([r, c]);
    })
  );
  if (!empty.length) return;
  const [r, c] = empty[Math.floor(Math.random() * empty.length)];
  board[r][c] = Math.random() < 0.9 ? 2 : 4;
}
Enter fullscreen mode Exit fullscreen mode

Keyboard controls are a single keydown listener, and the game is over when the board is full and no move changes anything — check that by testing all four directions against a copy of the board. Touch support is a bonus: record the touchstart position, compare it with touchend, and call move with the swipe direction.

Ways to extend it: colour tiles by value with a scale that goes up to 2048, animate the slide with CSS transitions, add an undo button that stores the previous board, or store the best score in localStorage. The slide-and-merge function is a clean example of writing logic once and reusing it — the habit that keeps game code small.

Top comments (0)