Workshop › Zelda-style Dungeon › Step 8 of 22

The sword

What we are doing

Space (or a tap away from the pad) swings the sword for 12 frames. The sword is a box in front of the hero, in the direction it faces. While swinging the hero stands still, and holding Space does not swing again and again.

```js
let swing // frames left of the sword swing

  swing = 0

  if (DIRS[event.key] || event.key === ' ') event.preventDefault()
  if (event.key === ' ' && !event.repeat) {
    if (swing === 0) swing = 12
  }

  else if (swing === 0) swing = 12

// The sword: a box from the middle of the player out to 30 pixels in front, so it also hits an enemy right on top of you.
function swordBox() {
  const [dx, dy] = player.dir
  const cx = player.x + SIZE / 2 + dx * 15
  const cy = player.y + SIZE / 2 + dy * 15
  const w = dx ? 30 : 8
  const h = dy ? 30 : 8
  return { x: cx - w / 2, y: cy - h / 2, w, h }
}

  if (dir && swing === 0) {

  if (swing > 0) swing -= 1

  if (swing > 0) {
    const s = swordBox()
    ctx.fillStyle = '#e5e7eb'
    ctx.fillRect(s.x, s.y, s.w, s.h)
  }
```

What it means

Your turn

  1. Above held, write swing; at the top of reset, set it to 0.
  2. In keydown, keep Space from scrolling and swing on a real press; on a tap away from the pad, swing too.
  3. Above update, write swordBox; walk only when not swinging; count the swing down at the end of update.
  4. In draw, draw the sword before ctx.restore().

Skills: Keyboard and mouse input, Game states

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