Workshop › Scorched Earth-style Artillery › Step 17 of 23

Win or lose

What we are doing

When a shot leaves a tank at 0 health the game is over: you win if it's the computer's tank, you lose if it's yours. A box says so, and Space starts a new game with new hills.

```js
function endTurn() {
  if (tanks[1].hp === 0) state = 'won'
  else if (tanks[0].hp === 0) state = 'lost'
  else {
    turn = 1 - turn
    state = 'aiming'
    if (turn === 1) thinking = 60
  }
}

    if (state === 'won' || state === 'lost') reset()
    else if (turn === 0) fire()

  if (state === 'won' || state === 'lost') {
    ctx.fillStyle = 'rgba(15, 23, 42, 0.8)'
    ctx.fillRect(140, 110, 280, 80)
    ctx.fillStyle = 'white'
    ctx.textAlign = 'center'
    ctx.font = 'bold 22px sans-serif'
    ctx.fillText(state === 'won' ? 'You win!' : 'You lose', W / 2, 145)
    ctx.font = '15px sans-serif'
    ctx.fillText('Space or tap to play again', W / 2, 172)
  }
```

What it means

Your turn

  1. Rewrite endTurn with the win and lose checks first.
  2. On Space, start again when the game is over.
  3. At the end of draw, draw the game-over box.

Skills: Game states

All steps

  1. The ground
  2. Hills
  3. Two tanks
  4. The barrel
  5. The game loop
  6. Aim
  7. Angle and power
  8. Fire!
  9. Flight
  10. Boom
  11. Craters
  12. Falling tanks
  13. Damage
  14. Taking turns
  15. The computer's shot
  16. Hitting a tank
  17. Win or lose
  18. Wind
  19. The computer aims
  20. Aim with the mouse
  21. Drag and let go
  22. The atan2 trap
  23. Build it yourself: a trail