Workshop › Sokoban › Step 8 of 29

Center the level

What we are doing

The level sits in the top-left corner. We measure it (rows and the longest row), and shift everything by ox and oy so it is centered, leaving room at the top and bottom for text.

```js
const TOP = 48 // room for the level number and the move counter
const BOTTOM = 40 // room for the hint line

  // Center the level on the canvas.
  const rows = LEVELS[level].length
  const cols = Math.max(...LEVELS[level].map((line) => line.length))
  const ox = (canvas.width - cols * TILE) / 2
  const oy = TOP + (canvas.height - TOP - BOTTOM - rows * TILE) / 2
  const tile = (x, y, color, inset = 0) => {
    ctx.fillStyle = color
    ctx.fillRect(ox + x * TILE + inset, oy + y * TILE + inset, TILE - inset * 2, TILE - inset * 2)
  }
```

What it means

Your turn

  1. Under const TILE = 48 write the TOP and BOTTOM lines.
  2. In draw, above const tile, write the comment and the four lines.
  3. In tile, add ox + and oy + at the start of the first two numbers. Press Run.

Skills: Drawing on a canvas

All steps

  1. A level written as text
  2. The canvas and the pen
  3. The warehouse floor
  4. A function that draws
  5. A name for every tile
  6. Read the walls
  7. Draw the walls
  8. Center the level
  9. The goals
  10. The boxes
  11. The player
  12. Two more levels
  13. One step
  14. Walk with the arrows
  15. Boxes are in the way
  16. Push a box
  17. A box on a goal turns green
  18. Solved!
  19. On to the next level
  20. Which level?
  21. A line at the bottom
  22. Count the moves
  23. A photo of the game
  24. A photo before every move
  25. Undo
  26. Restart
  27. A record for every level
  28. Show the record
  29. Build it yourself: count the pushes