Workshop › Space Invaders-style › Step 8 of 21

The invaders

What we are doing

Five rows of nine invaders, each row with its own color. Each invader remembers its row and whether it is still alive; only the living ones are drawn.

```js
const ROWS = 5
const COLS = 9
const INVADER_W = 28
const INVADER_H = 20
const SPACING_X = 44
const SPACING_Y = 36
const ROW_COLORS = ['#f472b6', '#a78bfa', '#a78bfa', '#34d399', '#34d399']

let 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 })
  }
}

function alive() {
  return invaders.filter((invader) => invader.alive)
}

  for (const invader of alive()) {
    ctx.fillStyle = ROW_COLORS[invader.row]
    ctx.fillRect(invader.x, invader.y, invader.w, invader.h)
  }
```

What it means

Your turn

  1. Under COOLDOWN, write the invader constants and ROW_COLORS.
  2. Under lastShot, build invaders.
  3. Above shoot, write alive; in draw, draw the living invaders after the background.

Skills: Arrays and objects, Loops

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