Workshop › Space Invaders-style › Step 15 of 21

Game over

What we are doing

The game ends when the last life is lost, or when an invader reaches the ship's height. Then everything stops and a dark band says GAME OVER.

```js
let state = 'playing' // 'playing' or 'over'

  if (lives <= 0) endGame()
}

function endGame() {
  state = 'over'
}

  if (state !== 'playing') return

  if (state !== 'playing') return

  if (alive().some((invader) => invader.y + invader.h >= SHIP_Y)) endGame()

  if (state === 'over') {
    ctx.fillStyle = 'rgba(0, 0, 0, 0.7)'
    ctx.fillRect(0, 200, canvas.width, 120)
    ctx.fillStyle = 'white'
    ctx.textAlign = 'center'
    ctx.font = 'bold 32px monospace'
    ctx.fillText('GAME OVER', canvas.width / 2, 250)
  }
```

What it means

Your turn

  1. Under lives, write state; in loseLife, end the game on the last life, and write endGame below it.
  2. At the top of update, and under the ship check, write the stop line.
  3. At the end of update, end the game when an invader lands.
  4. At the end of draw, draw the GAME OVER band.

Skills: 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