Workshop › Zelda-style Dungeon › Step 5 of 22

Walls

What we are doing

Walls # and locked doors D stop bodies. blocked checks the four corners of a 22-pixel box. move tries across and down separately, so a body slides along a wall instead of sticking to it, and says whether it was stopped. Doors are drawn brown.

```js
const solidTile = (ch) => ch === '#' || ch === 'D'

// Does a box at (x, y) overlap a wall? Outside the room counts as open, so the player can walk out of a gap.
function blocked(x, y) {
  for (const [cx, cy] of [[x, y], [x + SIZE - 1, y], [x, y + SIZE - 1], [x + SIZE - 1, y + SIZE - 1]]) {
    const row = Math.floor(cy / T)
    const col = Math.floor(cx / T)
    if (row >= 0 && row < ROWS && col >= 0 && col < COLS && solidTile(tiles[row][col])) return true
  }
  return false
}

// Move a body, one axis at a time, stopping at walls. Returns true if it was stopped.
function move(body, dx, dy) {
  let stopped = false
  if (blocked(body.x + dx, body.y)) stopped = true
  else body.x += dx
  if (blocked(body.x, body.y + dy)) stopped = true
  else body.y += dy
  return stopped
}

      if (ch === 'D') {
        ctx.fillStyle = '#92400e'
        ctx.fillRect(x + 2, y + 2, T - 4, T - 4)
      }
```

What it means

Your turn

  1. Replace move with solidTile, blocked and the new move, with their comments.
  2. In the tile drawing, draw doors after the floor.

Skills: Collision detection

All steps

  1. A room
  2. The hero
  3. The game loop
  4. Walk
  5. Walls
  6. A touch pad
  7. Next room
  8. The sword
  9. Enemies
  10. Strike!
  11. They chase you
  12. They wander
  13. Ouch
  14. Blinking and hearts
  15. Keys and hearts
  16. A world that remembers
  17. The locked door
  18. A timer
  19. Game over
  20. The stairs out
  21. Best time
  22. Build it yourself: cleared rooms