Workshop › Wolfenstein-style 3D Maze › Step 15 of 18

Escape!

What we are doing

The exit E is a green wall. Walking up to it wins: everything stops and the time is shown. Space plays again.

```js
let state // 'playing' or 'won'

  state = 'playing'

// The player escapes by walking up to the exit.
function nearExit() {
  const row = MAP.findIndex((line) => line.includes('E'))
  const col = MAP[row].indexOf('E')
  return Math.hypot(player.x - (col + 0.5), player.y - (row + 0.5)) < 0.8
}

  if (event.key === ' ' && state === 'won') reset()

  if (state !== 'playing') return

  if (nearExit()) {
    state = 'won'
  }

  if (state === 'won') {
    ctx.fillStyle = 'rgba(15, 23, 42, 0.75)'
    ctx.fillRect(0, 0, canvas.width, H)
    ctx.fillStyle = '#22c55e'
    ctx.textAlign = 'center'
    ctx.font = 'bold 28px sans-serif'
    ctx.fillText('Escaped in ' + seconds(frames) + ' s', canvas.width / 2, H / 2)
    ctx.fillStyle = 'white'
    ctx.font = '16px sans-serif'
    ctx.fillText('Press Space to play again', canvas.width / 2, H / 2 + 30)
  }
```

What it means

Your turn

  1. Under player, write state; in reset, set it to 'playing'.
  2. Above the key listeners, write nearExit; in keydown, play again on Space.
  3. At the top of update, stop when not playing; at the end, win near the exit.
  4. At the end of draw, draw the winning screen.

Skills: Game states

All steps

  1. The map
  2. The player
  3. Ceiling, floor and a loop
  4. Turn around
  5. Walk
  6. Is it a wall?
  7. Stop at walls, slide along them
  8. A ray: where it starts
  9. A ray: the grid lines
  10. A ray: walk to the wall
  11. The 3D view
  12. No fish-eye
  13. Light and shade
  14. A timer
  15. Escape!
  16. Best time
  17. Touch controls
  18. Build it yourself: run