Workshop › Space Invaders-style › Step 12 of 21

They shoot back

What we are doing

Now the invaders drop bombs. On some march steps (35% of them) a random column fires. Only the lowest invader in that column may fire, so a bomb never passes through its friends.

```js
let bombs = []

// Only the lowest invader in a column can fire, so bombs never pass through other invaders.
function dropBomb() {
  const living = alive()
  const shooter = living[Math.floor(Math.random() * living.length)]
  const lowest = living.filter((invader) => invader.x === shooter.x).reduce((a, b) => (b.y > a.y ? b : a))
  bombs.push({ x: lowest.x + INVADER_W / 2 - 2, y: lowest.y + INVADER_H, w: 4, h: 10 })
}

    if (Math.random() < 0.35) dropBomb()

  ctx.fillStyle = '#fb923c'
  for (const bomb of bombs) ctx.fillRect(bomb.x, bomb.y, bomb.w, bomb.h)
```

What it means

Your turn

  1. Above dir, write let bombs = [].
  2. Under march, write dropBomb; after march() in update, maybe drop a bomb.
  3. In draw, draw the bombs right under the bullets.

Skills: Arrays and objects, Game states

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