Pacman: how do the eyes find their way back to the monster hole? [closed]
Asked Answered
T

23

322

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?

Tenebrific answered 30/6, 2010 at 10:43 Comment(7)
Are you sure hardcoding on the corner is good enough? This doesn't guarantee the best route. Imagine the ghost is facing a long narrow passage. By your algorithm he would have to go down that entire passage, reach a corner, and then take the fastest route. If you hard-coded on every square which direction to go, he might know to just turn around first.Judicious
@Mark, depends on your definition on a corner. If it is a T connection even if you just go straight in the top line, it is fine.Agronomy
@Thorbjørn: I'm not even talking about intersections. Take a look at this board: en.wikipedia.org/wiki/File:Pac-man.png. If the ghost was moving right and positioned at the second dot from the bottom-left, it wouldn't meet any intersection for a while. That will cause it to travel 10 squares further than if it had turned backwards (left) and taken the shortest path.Judicious
your solution makes use of waypoints (or bread crumbs), and I think that's a common used technique to speed up path finding algorithms.Spermary
thanks for all the answers! I just sticked to my previous solution and hardcoded the directions at every corner. To do it generic, it is required that the leveldesigner/a level file also defines this information in the level definition.Tenebrific
I amended my answer to add more detail from the original game; hopefully someone might find that useful or at least interesting.Hearken
@Mark: I think he meant every intersection, not every corner (if he did only the corners, because of the layout of the level they'd never make it back to the hole!)Heatstroke
H
153

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.
Hearken answered 30/6, 2010 at 10:50 Comment(13)
Yep, really effective, but rather hard to maintain if the map grows up.Laryngo
I think he means you could compute it at runtime (when the level is loaded but before you start playing it) but just once. That's not hard to maintain.Judicious
Yeah, or if there's a tool for creating the maps, as part of that.Hearken
There is nothing wrong with precomputing the return paths. You're trading storage (paths) for runtime performance.Unmoving
Thanks. I think Ill stick with this solution. Anybody knows how it was done in the original Pacman?Tenebrific
I bet it used the same algorithm the ghosts use to find you. (Because the code is already there!) Just a guess though.Fatuitous
you mean "monster hole", not "monster house"Millda
No, I don't. The original question used that term but it's not exactly legally binding.Hearken
In my experience, you also need a random part in the decision model that allows the ghost to pick the "wrong" choice at least every tenth time or so; otherwise, it will quickly get caught in sections of the labyrinth where the exits are on the "wrong" side.Translator
@ammoQ: That's still insufficient to yield results for arbitrary maze in reasonable time. Imagine a dead-end branch consisting of three tiny loops in a row, with the "true" exit at the end opposite of the monster hole. At each of the three crossings the eyes will gravitate towards the wrong path at 90% probability. That means 1 in 1000 tries will get the eyes through all 3 "trap" crossings. A much simpler solution is to "cheat" and just teleport the eyes to the destination after, say, 10s of futile search.Totipalmate
@SF: You are right, in some situations the 10% "error" rate doesn't quite cut it; increasing it to say 30% lets the eyes wander all through the lab without hitting the hole for a long time. That's why I came up with the flood-fill-solution that completely avoids this problem.Translator
@ammoQ: And now rewrite it for ZX81, with 4KB of RAM, leaving enough for the game! :-] Floodfill tends to be memory-hungry. Not a problem nowadays, but we need to think in terms of the original!Totipalmate
@SF: Haha, doing that on a ZX81 would be quite a challenge! Anyway, I remember that I had a nice Pac Man Clone on mine, though I had the 16KB memory extension.Translator
T
86

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.

Translator answered 30/6, 2010 at 13:10 Comment(5)
Yes. Floodfill is very good for pathfinding in any situation where the world isn't too big to make it viable. I would think it could be used even in large worlds by imposing a coarser grid whose connectivity was precalculated. It would make things go slightly out of the way but that would be better than the traffic jams I've seen in such games.Photic
To save space (for larger worlds, or constrained systems), you could save the direction to travel at every intersection, rather than saving a value for every tile. This is essentially what OP was suggesting.Heatstroke
BlueRaja: Sure, but it's more complex to do that and the result is not as optimal - the ghost gets eaten between two intersections, so he might run into the wrong direction for some time. My solution worked well on a en.wikipedia.org/wiki/HP_200LX so how much more constrained could it get?Translator
(I am late...) Yes flood-fill is good, however you do not actually need a full number, just a direction (two bits) in each square to point to the next square to use.Disaster
Matthieu: Yeah, that would be a possible optimization.Translator
Q
43

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...

Quathlamba answered 30/6, 2010 at 11:17 Comment(3)
this was going to be my answer. It's the same as ammoQ's essentially, but I always remember about the pacman smell :)Revolver
Looks like the wikipedia article is dead/deleted. Top google result is this thread, but I think this comes close.Kendre
I got confused for a second but then instantly understood what is meant by "scent". It's such a great way to describe these scalar field things!Aylward
L
19

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.

Laryngo answered 30/6, 2010 at 10:47 Comment(0)
S
18

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.

EDIT

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 ... )

Sequel answered 30/6, 2010 at 10:48 Comment(4)
Yes it is working. However I would like to write good code and not only code. And additionally I added the last sentence in my question, so if possible the algorithm should be not only for one maze but for several.Tenebrific
mazes can also be generated (I have an algorithm that generates nice-looking pacman mazes), so a bit of automation is the way to goTranslator
"...or users can design them." In which case, you DO have a bazillion mazes.Millymilman
@Millymilman - I am aware of that. However, there is a distinction between the two cases. If it is the OP creating a bazzilion mazes, then it is an inconvenience to have to create the routing by hand. If it is end user ... it means that the OP has to write documentation, do endless troubleshooting of end users' mazes, field endless complaints about how unfriendly it is, etcetera. In other words the reasons for implementing automatic route generation are different.Sequel
C
13

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.

Cavalryman answered 5/7, 2010 at 3:28 Comment(2)
I really like this approach and I'll also try this oneTenebrific
This isn't correct; if they all followed this algorithm they would end up chasing him single file. The behavior of each ghost is different; you can find more info on the Wikipedia article.Joey
O
5

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.

Outsoar answered 1/7, 2010 at 4:38 Comment(2)
yes i have the logic to chase pacman already implemented, but im also not happy with it ;)Tenebrific
In my experience (I love writing pacman versions just for fun), doing that can lead to eyes getting stuck outside the hole for a long time. That's because the chasing algorithm generally goes along the lines of "if pacman is in the north, go north" but the maze could contain "traps" where the the eyes would have to go south first. Since pacman moves, the ghost will escape sooner or later, but the hole is a fixed target. (Note: I'm talking about generated mazes)Translator
N
3

It's a pathfinding problem. For a popular algorithm, see http://wiki.gamedev.net/index.php/A*.

Neural answered 30/6, 2010 at 10:47 Comment(0)
T
3

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.

Thessalonians answered 16/7, 2010 at 23:34 Comment(1)
I was going to suggest this. An outward flood-fill starting at the 'monster-hole'. I think your answer would benefit from a picture.Hereof
T
3

This was the best source that I could find on how it actually worked.

http://gameai.com/wiki/index.php?title=Pac-Man#Respawn 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.

Trilateration answered 11/1, 2012 at 19:7 Comment(0)
K
2

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 =)

Kapp answered 30/6, 2010 at 12:57 Comment(3)
To add even more realism, allow the ghosts themselves to be able to move through walls :DFatuitous
Those are ghost's opaque walls, but the second order ghosts, (ghost of a ghost) are more transparent. (you could find many user manuals with bugs transformed in features)Duotone
+1 for "second order ghosts" -- oh yes, the derivative of a ghost must surely transcend mere first order objects like walls... :)Realize
J
2

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
   next
 next

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.

Judicious answered 30/6, 2010 at 13:59 Comment(0)
J
2

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

  1. Determine the eyes location relative position to the gate. i.e. Is it left above? Right below?
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. I've never seen a dead end in Pacman this code will not account for dead ends.
  7. 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()
   y
   origX = x
    while(eyesNotInPen())
       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)
                 move(origX)
                 x = getRelativeOppositeLatitudinalCoordofGate()
        else if (move(x) == false) {
            move(y)
    endWhile
Jemena answered 1/7, 2010 at 4:32 Comment(0)
H
2

I would propose that the ghost stores the path he has taken from the hole to the Pacman. So as soon as the ghost dies, he can follow this stored path in the reverse direction.

Hesper answered 19/8, 2010 at 12:1 Comment(2)
that path is most probably is going to be too longPapism
Whenever you revisit a node you could eliminate a loop from the history. That would make it quite a bit more direct. Might be more interesting than always following the same direct path, but fairly often it will include some rather silly almost loops (e.g. 3 sides of a square).Hereof
W
2

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.

Wareing answered 2/9, 2010 at 6:8 Comment(0)
D
2

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.

Derril answered 11/1, 2012 at 22:17 Comment(0)
P
1

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.

Panama answered 30/6, 2010 at 13:8 Comment(0)
P
1

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.

Pastry answered 30/6, 2010 at 13:12 Comment(0)
A
1
  1. Before the game begins save the nodes (intersections) in the map
  2. When the monster dies take the point (coordinates) and find the nearest node in your node list
  3. Calculate all the paths beginning from that node to the hole
  4. Take the shortest path by length
  5. Add the length of the space between the point and the nearest node
  6. Draw and move on the path

Enjoy!

Averyaveryl answered 11/4, 2012 at 10:42 Comment(0)
H
1

My approach is a little memory intensive (from the perspective of Pacman era), but you only need to compute once and it works for any level design (including jumps).

Label Nodes Once

When you first load a level, label all the monster lair nodes 0 (representing the distance from the lair). Proceed outward labelling connected nodes 1, nodes connected to them 2, and so on, until all nodes are labelled. (note: this even works if the lair has multiple entrances)

I'm assuming you already have objects representing each node and connections to their neighbours. Pseudo code might look something like this:

public void fillMap(List<Node> nodes) { // call passing lairNodes
    int i = 0;

    while(nodes.count > 0) {
        // Label with distance from lair
        nodes.labelAll(i++);

        // Find connected unlabelled nodes
        nodes = nodes
            .flatMap(n -> n.neighbours)
            .filter(!n.isDistanceAssigned());
    }
}

Flood-fill out from lair

Eyes Move to Neighbour with Lowest Distance Label

Once all the nodes are labelled, routing the eyes is trivial... just pick the neighbouring node with the lowest distance label (note: if multiple nodes have equal distance, it doesn't matter which is picked). Pseudo code:

public Node moveEyes(final Node current) {
    return current.neighbours.min((n1, n2) -> n1.distance - n2.distance);
}

Fully Labelled Example

Complete map

Hereof answered 11/8, 2017 at 16:15 Comment(0)
T
0

For my PacMan game I made a somewhat "shortest multiple path home" algorithm which works for what ever labyrinth I provide it with (within my set of rules). It also works across them tunnels.

When the level is loaded, all the path home data in every crossroad is empty (default) and once the ghosts start to explore the labyrinth, them crossroad path home information keeps getting updated every time they run into a "new" crossroad or from a different path stumble again upon their known crossroad.

Tang answered 15/3, 2015 at 12:50 Comment(0)
V
0

According to a lot of what I've read, including the Pac-Man dossier, it would appear the ghosts target the grid directly above the ghost house "door" and use the normal movement restrictions that they normally use for normal movement.

Valentinvalentina answered 28/1 at 2:22 Comment(0)
C
-2

The original pac-man didn't use path-finding or fancy AI. It just made gamers believe there is more depth to it than it actually was, but in fact it was random. As stated in Artificial Intelligence for Games/Ian Millington, John Funge.

Not sure if it's true or not, but it makes a lot of sense to me. Honestly, I don't see these behaviors that people are talking about. Red/Blinky for ex is not following the player at all times, as they say. Nobody seems to be consistently following the player, on purpose. The chance that they will follow you looks random to me. And it's just very tempting to see behavior in randomness, especially when the chances of getting chased are very high, with 4 enemies and very limited turning options, in a small space. At least in its initial implementation, the game was extremely simple. Check out the book, it's in one of the first chapters.

Cindiecindra answered 12/3, 2015 at 20:3 Comment(1)
yes, it did use some AI. And yes Blinky follows pacman when he's in chase mode (switches to it from time to time), so it's A.I. all rightCobaltous

© 2022 - 2024 — McMap. All rights reserved.