Workshop › Pac-Man-style Maze Chase › Step 13 of 42

Turn back at once

What we are doing

Turning into a side corridor waits for the next tile center, but turning back should not: when a ghost appears ahead you must flee now. The trick: 3 frames into a step from tile 9 to 8 is the same place as 5 frames into a step from tile 8 back to 9. So move to the tile you were heading to, flip dir, and set progress = frames - progress.

```js
const reverse = (dir) => [-dir[0], -dir[1]]

// Turning around in the middle of a tile: step into the next tile and walk back the rest of the way.
function turnAround(e) {
  if (e.progress === 0 || same(e.dir, STOP)) {
    e.dir = reverse(e.dir)
    return
  }
  e.col = wrap(e.col + e.dir[0])
  e.row += e.dir[1]
  e.dir = reverse(e.dir)
  e.progress = e.frames - e.progress
}

function steer(dir) {
  player.want = dir
  if (same(dir, reverse(player.dir)) && !same(dir, STOP)) turnAround(player)
}
```

What it means

Your turn

  1. Under same, write reverse.
  2. Above steer, write the comment and turnAround.
  3. In steer, under player.want = dir, write the new line.

Skills: Keyboard and mouse input

All steps

  1. The maze as text
  2. The game loop
  3. Draw the walls
  4. A set of pellets
  5. Draw the pellets
  6. The player
  7. Where can you walk?
  8. What a mover remembers
  9. One frame of movement
  10. Move every frame
  11. Turns you can press early
  12. Glide between tiles
  13. Turn back at once
  14. Swipes on a phone
  15. Eat the pellets
  16. Show the score
  17. Clear the maze
  18. A red ghost
  19. A ghost never turns back
  20. The ghost walks
  21. The ghost hunts you
  22. Four ghosts in the house
  23. One by one out of the house
  24. Scatter or chase?
  25. Every ghost to its corner
  26. Pink cuts you off
  27. Orange is shy
  28. Cyan works with red
  29. Wait for the first key
  30. Tell the player to start
  31. Three lives
  32. Caught!
  33. Game over
  34. Play again
  35. Frighten the ghosts
  36. Power pellets work
  37. Scared ghosts wander slowly
  38. Eat a scared ghost
  39. Blue, then flashing
  40. Harder levels
  41. A best score that lasts
  42. Build it yourself: the slow tunnel