Sunday, May 27, 2012

Pacman: how do the eyes find their way back to the monster hole?

I found a lot of references to the AI of the ghosts in Pacman, but none of them mentioned how the eyes find their way back to the central ghost hole after a ghost is eaten by Pacman.

In my implementation I implemented a simple but awful solution. I just hard coded on every corner which direction should be taken.

Are there any better/or the best solution? Maybe a generic one that works with different level designs?

Source: Tips4all


  1. Actually, I'd say your approach is a pretty awesome solution, with almost zero-run time cost compared to any sort of pathfinding.

    If you need it to generalise to arbitrary maps, you could use any pathfinding algorithm - breadth-first search is simple to implement, for example - and use that to calculate which directions to encode at each of the corners, before the game is run.

    EDIT (11th August 2010): I was just referred to a very detailed page on the Pacman system: The Pac-Man Dossier, and since I have the accepted answer here, I felt I should update it. The article doesn't seem to cover the act of returning to the monster house explicitly but it states that the direct pathfinding in Pac-Man is a case of the following:

    continue moving towards the next intersection (although this is essentially a special case of 'when given a choice, choose the direction that doesn't involve reversing your direction, as seen in the next step);
    at the intersection, look at the adjacent exit squares, except the one you just came from;
    picking one which is nearest the goal. If more than one is equally near the goal, pick the first valid direction in this order: up, left, down, right.

  2. I've solved this problem for generic levels that way: Before the level starts, I do some kind of "flood fill" from the monster hole; every tile of the maze that isn't a wall gets a number that says how far it is away from the hole. So when the eyes are on a tile with a distance of 68, they look which of the neighbouring tiles has a distance of 67; that's the way to go then.

  3. For an alternative to more traditional pathfinding algorithms, you could take a look at the (appropriately-named!) Pac-Man Scent Antiobject pattern.

    You could diffuse monster-hole-scent around the maze at startup and have the eyes follow it home.

    Once the smell is set up, runtime cost is very low.

    Edit: sadly the wikipedia article has been deleted, so WayBack Machine to the rescue...

  4. Any simple solution that works is maintainable, reliable and performs well enough is a good solution. It sounds to me like you have already found a good solution ...

    An path-finding solution is likely to be more complicated than your current solution, and hence more likely to require debugging. It will probably also be slower.

    IMO, if it ain't broken, don't fix it.


    IMO, if the maze is fixed then your current solution is good / elegant code. Don't make the mistake of equating "good" or "elegant" with "clever". Simple code can also be "good" and "elegant".

    If you have configurable maze levels, then maybe you should just do the pathfinding when you initially configure the mazes. Simplest would be to get the maze designer to do it by hand. I'd only bother automating this if you have a bazillion mazes ... or users can design them.

    (Aside: if the routes are configured by hand, the maze designer could make a level more interesting by using suboptimal routes ... )

  5. You should take a look a pathfindings algorithm, like Dijsktra's Algorithm or A* algorithm. This is what your problem is : a graph/path problem.

  6. In the original Pacman the Ghost found the yellow pill eater by his "smell" he would leave a trace on the map, the ghost would wander around randomly until they found the smell, then they would simply follow the smell path which lead them directly to the player. Each time Pacman moved, the "smell values" would get decreased by 1.

    Now, a simple way to reverse the whole process would be to have a "pyramid of ghost smell", which has its highest point at the center of the map, then the ghost just move in the direction of this smell.

  7. Assuming you already have the logic required for chasing pacman why not reuse that? Just change the target. Seems like it would be a lot less work than trying to create a whole new routine using the exact same logic.

  8. It's a pathfinding problem. For a popular algorithm, see*.

  9. I think your solution is right for the problem, simpler than that, is to make a new version more "realistic" where ghost eyes can go through walls =)

  10. Here's an analog and pseudocode to ammoQ's flood fill idea.

    queue q
    enqueue q, ghost_origin
    set visited

    while q has squares
    p <= dequeue q
    for each square s adjacent to p
    if ( s not in visited ) then
    add s to visited
    s.returndirection <= direction from s to p
    enqueue q, s
    end if

    The idea is that it's a breadth-first search, so each time you encounter a new adjacent square s, the best path is through p. It's O(N) I do believe.

  11. I don't know much on how you implemented your game but, you could do the following:

    Determine the eyes location relative position to the gate. i.e. Is it left above? Right below?
    Then move the eyes opposite one of the two directions (such as make it move left if it is right of the gate, and below the gate) and check if there are and walls preventing you from doing so.
    If there are walls preventing you from doing so then make it move opposite the other direction (for example, if the coordinates of the eyes relative to the pin is right north and it was currently moving left but there is a wall in the way make it move south.
    Remember to keep checking each time to move to keep checking where the eyes are in relative to the gate and check to see when there is no latitudinal coordinate. i.e. it is only above the gate.
    In the case it is only above the gate move down if there is a wall, move either left or right and keep doing this number 1 - 4 until the eyes are in the den.
    I've never seen a dead end in Pacman this code will not account for dead ends.
    Also, I have included a solution to when the eyes would "wobble" between a wall that spans across the origin in my pseudocode.

    Some pseudocode:

    x = getRelativeOppositeLatitudinalCoord()
    origX = x
    x = getRelativeOppositeLatitudinalCoordofGate()
    y = getRelativeOppositeLongitudinalCoordofGate()
    if (getRelativeOppositeLatitudinalCoordofGate() == 0 && move(y) == false/*assume zero is neither left or right of the the gate and false means wall is in the way */)
    while (move(y) == false)
    x = getRelativeOppositeLatitudinalCoordofGate()
    else if (move(x) == false) {

  12. How about each square having a value of distance to the center? This way for each given square you can get values of immediate neighbor squares in all possible directions. You pick the square with the lowest value and move to that square.

    Values would be pre-calculated using any available algorithm.

  13. dtb23's suggestion of just picking a random direction at each corner, and eventually you'll find the monster-hole sounds horribly ineficient.

    However you could make use of its inefficient return-to-home algorithm to make the game more fun by introducing more variation in the game difficulty. You'd do this by applying one of the above approaches such as your waypoints or the flood fill, but doing so non-deterministically. So at every corner, you could generate a random number to decide whether to take the optimal way, or a random direction.

    As the player progresses levels, you reduce the likelihood that a random direction is taken. This would add another lever on the overall difficulty level in addition to the level speed, ghost speed, pill-eating pause (etc). You've got more time to relax while the ghosts are just harmless eyes, but that time becomes shorter and shorter as you progress.

  14. Knowing that pacman paths are non-random (ie, each specific level 0-255, inky, blinky, pinky, and clyde will work the exact same path for that level).

    I would take this and then guess there are a few master paths that wraps around the entire
    maze as a "return path" that an eyeball object takes pending where it is when pac man ate the ghost.

  15. The ghosts in pacman follow more or less predictable patterns in terms of trying to match on X or Y first until the goal was met. I always assumed that this was exactly the same for eyes finding their way back.

  16. I would propose that the ghosts stores the path he has taken from the whole to the Pacman. So as soon as the ghosts dies, he can follow this stored path in the inversed direction.

  17. This was the best source that I could find on how it actually worked.
    When the ghosts are killed, their disembodied eyes return to their starting location. This is simply accomplished by setting the ghost's target tile to that location. The navigation uses the same rules.

    It actually makes sense. Maybe not the most efficient in the world but a pretty nice way to not have to worry about another state or anything along those lines you are just changing the target.

    Side note: I did not realize how awesome those pac-man programmers were they basically made an entire message system in a very small space with very limited memory ... that is amazing.

  18. Short answer, not very well. :) If you alter the Pac-man maze the eyes won't necessarily come back. Some of the hacks floating around have that problem. So it's dependent on having a cooperative maze.

  19. Before the game begins save the nodes (intersections) in the map
    When the monster dies take the point (coordinates) and find the
    nearest node in your node list
    Calculate all the paths beginning from that node to the hole
    Take the shortest path by length
    Add the length of the space between the point and the nearest node
    Draw and move on the path