Workshop › Space Invaders-style › Step 17 of 21

A wave in a function

What we are doing

When all invaders are gone, a new wave should come. So building the formation moves into a function, spawnWave, which also clears the bullets and bombs and starts the march fresh. The game calls it once at the start.

```js
let bullets
let invaders
let bombs
let dir // +1 marching right, -1 marching left
let lastStep
let lastShot = -COOLDOWN

function spawnWave() {
  invaders = []
  for (let row = 0; row < ROWS; row++) {
    for (let col = 0; col < COLS; col++) {
      invaders.push({ x: 40 + col * SPACING_X, y: 60 + row * SPACING_Y, w: INVADER_W, h: INVADER_H, row, alive: true })
    }
  }
  bullets = []
  bombs = []
  dir = 1
  lastStep = now
}

spawnWave()
```

What it means

Your turn

  1. Replace the variables from bullets to lastStep with the short list.
  2. Above overlaps, write spawnWave.
  3. At the bottom, call spawnWave() above requestAnimationFrame(loop).

Skills: Functions

All steps

  1. The ship
  2. The game loop
  3. Move the ship
  4. Stay on screen
  5. Fire
  6. Bullets fly
  7. A short reload
  8. The invaders
  9. The march
  10. Hit!
  11. Score
  12. They shoot back
  13. Bombs fall
  14. Lives
  15. Game over
  16. Best score
  17. A wave in a function
  18. Play again
  19. Waves
  20. Faster and faster
  21. Build it yourself: an extra life