Workshop › Space Invaders-style › Step 18 of 21

Play again

What we are doing

Now Space after GAME OVER starts a new game. newGame puts every starting value back — ship, wave, score, lives, reload, state — and spawns the first wave. The game itself starts by calling it too.

```js
let ship

let lastShot
let wave
let score
let lives
let state // 'playing' or 'over'

function newGame() {
  ship = { x: canvas.width / 2 - SHIP_W / 2, y: SHIP_Y, w: SHIP_W, h: SHIP_H }
  wave = 1
  score = 0
  lives = 3
  lastShot = -COOLDOWN
  state = 'playing'
  spawnWave()
}

  if (event.key === ' ') {
    if (state === 'over') newGame()
    else shoot()
  }

newGame()
```

What it means

Your turn

  1. Make ship, lastShot, score, lives, state plain declarations and add wave.
  2. Under spawnWave, write newGame.
  3. Make Space play again when the game is over.
  4. At the bottom, call newGame() instead of spawnWave().

Skills: Game states, 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