Skip to main content
๐ŸŽฎ Game Logic

What you're building

The entire 2048 game reduces to one operation: sliding a row left. Get that right and you can apply it four ways (left, right, up, down) to drive the full board.

You will implement:

  • slideLeft(row) โ€” takes a 4-element array of numbers (zeros = empty), returns the merged row slid left.
  • applyMove(board, direction) โ€” takes a 4ร—4 board (array of 4 rows) and a direction ("left", "right", "up", "down"), returns the new board after one move.

Requirements

slideLeft rules (canonical 2048 behaviour):

  1. Compact all non-zero tiles to the left, leaving zeros on the right.
  2. Merge adjacent equal tiles (left-to-right, first match wins); merged tile doubles.
  3. A tile produced by merging cannot merge again in the same move.
  4. Fill remaining spots with zeros so the row stays 4 elements long.

applyMove:

  • "left": slideLeft each row.
  • "right": reverse, slideLeft, reverse each row.
  • "up": transpose, apply left, transpose back.
  • "down": transpose, apply right, transpose back.

Stretch goals

  • Add a score accumulator that sums merged tile values.
  • Detect a "game over" state (no valid moves remain).

What this proves

Row/column transformations, immutable data manipulation, and translating a visual game mechanic into clean logic โ€” all classic array-manipulation interview fodder.

โšก 40 XP
solution.jsRuns in your browser
Loading editorโ€ฆ
Tests4 to pass
slideLeft compacts and merges
slideLeft does not double-merge
applyMove left slides all rows
applyMove right slides all rows

Run your code to check these.