Workshop › 2048 › Step 1 of 26

2048: The board

Slide numbered tiles and merge equal ones to reach 2048. A 2D grid, a pure slide-and-merge function reused in four directions, and swipe input.

What we are doing

2048 is played on a 4×4 board: slide the tiles, merge equal ones, reach 2048. First the measurements and an empty board: a cream page with a square, brown board under a strip for the score.

```js
const canvas = document.getElementById('game')
const ctx = canvas.getContext('2d')

const SIZE = 4
const GAP = 12
const CELL = (canvas.width - GAP * (SIZE + 1)) / SIZE // 85
const TOP = 60 // room for the score above the board

function draw() {
  ctx.fillStyle = '#faf8ef'
  ctx.fillRect(0, 0, canvas.width, canvas.height)
  ctx.fillStyle = '#bbada0'
  ctx.fillRect(0, TOP, canvas.width, canvas.width)
}

draw()
```

What it means

Your turn

Write the code under the three comment lines, then press Run.

Skills: Drawing on a canvas

All steps

  1. The board
  2. Sixteen cells
  3. A grid of numbers
  4. A color for every number
  5. Numbers on the tiles
  6. Big numbers, smaller text
  7. Find the empty cells
  8. A new tile
  9. Two tiles to start
  10. Slide a row
  11. Merge equal tiles
  12. Move left
  13. The arrow key
  14. Only real moves count
  15. Right is left, reversed
  16. Up and down are columns
  17. Score
  18. Is there a move left?
  19. Game over
  20. Making 2048
  21. Win and lose screens
  22. Space to go on
  23. Best score
  24. Swipes
  25. A tap is not a swipe
  26. Build it yourself: undo