Workshop › Pac-Man-style Maze Chase › Step 21 of 42
The famous ghost brain is simple: of the allowed directions, take the one whose next tile is closest to a target, in a straight line. There is no path-finding: the ghost can take a wrong turn, and that is why you can outsmart it. For now the target is the player.
```js
function target(g) {
return player
}
const t = target(g)
const distance = (d) => (g.col + d[0] - t.col) ** 2 + (g.row + d[1] - t.row) ** 2
g.dir = options.reduce((bestDir, d) => (distance(d) < distance(bestDir) ? d : bestDir))
```distance(d) is the squared straight-line distance from the next tile in direction d to the target. Squares are
enough for comparing and avoid Math.sqrt. ** is "to the power of".reduce walks the list keeping one "best so far": each option replaces it only if it is strictly closer, so ties
go to the earlier one (up, left, down, right).chooseGhost, write target.chooseGhost, replace g.dir = options[0] with the three new lines.Skills: Game states, Arrays and objects
← The ghost walks Four ghosts in the house →