Workshop › Zelda-style Dungeon › Step 15 of 22

Keys and hearts

What we are doing

Walking onto a key k picks it up; walking onto a heart h gives back a heart (up to 3). The tile becomes floor. Keys are yellow, hearts red, and the top strip counts your keys.

```js
let keysHeld

  keysHeld = 0

  // Things on the tile under the middle of the player.
  const col = Math.floor(cx / T)
  const row = Math.floor(cy / T)
  const here = tiles[row][col]
  if (here === 'k' || here === 'h') {
    if (here === 'k') keysHeld += 1
    else hearts = Math.min(3, hearts + 1)
    tiles[row][col] = '.'
  }

      if (ch === 'k') {
        ctx.fillStyle = '#eab308'
        ctx.fillRect(x + 10, y + 8, 12, 16)
      }
      if (ch === 'h') {
        ctx.fillStyle = '#e11d48'
        ctx.fillRect(x + 9, y + 9, 14, 14)
      }

  ctx.fillStyle = 'white'
  ctx.font = 'bold 16px sans-serif'
  ctx.textAlign = 'left'
  ctx.fillText('Keys ' + keysHeld, 100, 30)
```

What it means

Your turn

  1. Under hearts, write keysHeld; in reset, set it to 0.
  2. In update, before the swing countdown, pick up what is under the hero.
  3. In the tile drawing, draw keys and hearts; in the top strip, write the keys.

Skills: Game states, 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