In Pacman do the ghosts choose paths independently for finding pacman? - pacman

So I have been playing a lot of pacman on my cell lately and am wondering how do the ghosts seem to work independent of each other. I was thinking about how it would have been programmed.
One option that I thought of was threads. All 4 ghosts are running in their own threads and somehow find pacman's position. But it seems a bit to much to have four threads working and syncing would be hard. Also, google wrote pacman in Javascript which doesn't support threads, so it can be done without threads and there has to be an easier way.
My second thought was event handlers. I just wire the 'directionChanged' event that pacman will fire to 4 event handlers, one for each ghost. Each ghost then decides what path to take to get to pacman. This I think is more likely what is happening. But it can get slow if the event handlers are synchronously executed, because paths will have to be calculated sequentially and the 4th ghost will take time to change direction and this might create a visible lag (probably). Also, the ghosts would fire an event themselves when they hit a wall and their event handlers would change the ghosts direction. But given the frequency with which pacman changes directions and the four ghosts respond, event handlers also seem a bit too much.
I am saying the above ideas would be a bit too much because remember the game was written 30 years ago when cpu time and memory were scarce, so I think there has to be a much easier way.
Also, it seems that the ghosts are following different paths even when pacman is still. Do all the ghosts use completely different or differently optimized path finding algorithms?
I am more interested in finding out how all the ghosts seem to work for themselves simultaneously than the path finding algorithms they use. Thoughts?

There's a lot of great information about how pacman works here including some detailed write ups about the ghosts behavior.
**Note I found this information from Pathfinding Algorithm For Pacman a while ago.
EDIT:
This blog post has even more information about the ghosts.

You're drastically over-thinking this.
Threads and event-handlers are terribly slow by video game standards. Multi-threaded game engines are a relatively new invention, literally decades after Pacman was released. Pacman's meager logic will occur inside a single fairly tight loop, something like this very simplified pseudocode:
while (!pacman_dead) {
foreach ghost {
if (ghost has hit a wall) {
if (pacman to left) turn left
if (pacman to right) turn right
} else {
go straight
if (ghost touched pacman) {
pacman_dead = true
}
}
}
handle_input();
move_pacman();
draw_screen();
}
This is a fairly common pattern in gaming, and it gives the appearance of concurrence. Typically a game will run in a single loop, which advances the game state by some tiny increment in the space between screen redraws. This is why performance is still very important in game development: Your game must iterate over every in-game object which needs to do something or make some decision (AI-controlled opponents, moving platforms, simple animations, etc) and update their state at least 30 times per second.

Before rendering each frame, I would loop over the ghosts. No events, threads, or async issues that way. Each ghost probably has a very crude heuristic for scoring its moves and making up its mind (turning left or right, no action, whatev).
Here's an implementation you could check out. :)

Related

Can I run a DLL in a separate thread?

I have a program I'm writing in vb.net that has ballooned into the most complicated thing I've ever written. Because of some complex math and image rendering that's happening constantly I've been delving into multithreading for the first time to improve overall performance. Things have honestly been running really smoothly, but we've just added more functionality that's causing me some trouble.
The new functionality comes from a pair of DLLs that are each processing a video stream from a USB camera and looking for moving objects. When I start my program I initiate the DLLs and they start viewing the cameras and processing the videos. I then periodically ping them to see if they have detected anything. This is how I start and stop them:
Declare Function StartLeftCameraDetection Lib "DetectorLibLeft.dll" Alias "StartCameraDetection" () As Integer
Declare Function StopLeftCameraDetection Lib "DetectorLibLeft.dll" Alias "StopCameraDetection" () As Integer
When I need to check if they've found any objects I use several functions like this:
Declare Function LeftDetectedObjectLeft Lib "DetectorLibLeft.dll" Alias "DetectedObjectLeft" () As Integer
All of that works really well. The problem is, I've started to notice some significant lag in my UI and I'm thinking it may be coming from the DLLs. Forgive my ignorance on this, but as I said I'm new to using multiple threads (and incorporating DLLs too if I'm honest). It seems to me that when I start a DLL it running it's background tasks on my main thread and just waiting for me to ping it for information. Is that the case? If so, is it possible to have the DLL running on a sperate thread so it doesn't affect my UI?
I've tried a few different things but I can't seem to address the lag. I moved the code that pings the DLL and processes whatever information it gets into a sperate thread, but that hasn't made any difference. I also tried calling StartLeftCameraDetection from a separate thread but that didn't seem to help either. Again, I'm guessing that's because the real culprit is the DLL itself running these constant background tasks on my main thread no what thread I actually call it's functions from.
Thanks in advance for any help you might be able to offer!
There's a lot to grok when it comes to threading, but I'll try to write a concise summary that hits the high points with enough details to cover what you need to know.
Multi-threaded synchronization is hard, so you should try to avoid it as much as possible. That doesn't mean avoiding multi-threading at all, it just means avoiding doing much more than sending a self-contained task off to a thread to run to completion and getting the results back when it's done.
Recognizing that multi-threaded synchronization is hard, it's even worse when it involves UI elements. So in .NET, the design is that any access to UI elements will only occur through one thread, typically referred to as the UI thread. If you are not explicitly writing multi-threaded code, then all of your code runs on the UI thread. And, while your code is running, the UI is blocked.
This also extends to external routines that you run through Declare Function. It's not really accurate to say that they are doing anything with "background tasks on the main thread", if they are doing anything with "background tasks" they are almost certainly implementing their own threading. More likely, they aren't doing any task breakdown at all, and all of their work is being done on whichever thread you use to call them---the UI thread if you're not doing anything else.
If the work being done in these routines is CPU-bound, then it would definitely make sense to push it off onto a worker thread. Based on your comments on what you already tried:
I moved the code that pings the DLL and processes whatever information it gets into a sperate thread, but that hasn't made any difference. I also tried calling StartLeftCameraDetection from a separate thread but that didn't seem to help either.
I think the most likely problem is that you're blocking in the UI thread waiting for a result from the background thread.
The best way to avoid this depends on exactly what the routines are doing and how they produce results. If they do some sort of extended process and return everything in function results, then I would suggest that using Await would work well. This will basically return control to the UI until the operation finishes, then resume whatever the rest of the calling routine was going to do.
Note that if you do this, the user will have full interaction with the UI, and you should react accordingly. You might need to disable some (or all) operations until it's done.
There are a lot of resources on Async and Await. I'd particularly recommend reading Stephen Cleary's blog articles to get a better understanding of how they work and potential pitfalls that you might encounter.

Methods of Lag Handling in iOS (SpriteKit)

Hey I've been working my way through making my first app, and I've hit the first problem that I don't even know how to begin fixing.
I am making a SpriteKit game, and as I've been coding, performance has been slowly dropping. Clearly I am not handling lag well at all. (~20-30 fps on device)
The thing is though, I'm not sure how to tackle this issue. I am going through and trying to loosen the load on each frame, but..
Are there any methods of lag handling that most people use?
I tried setting up a timer system, so that I know how much each segment of code takes to run, but the data wasn't too helpful.
It doesn't even look like a specific segment of code is taking that long at all.
This is kind of a broad question I guess, but how should you go about lag handling in SpriteKit?

How does CheatEngine's speed hack work?

Cheat Engine comes with a feature called speed hack which basically can slow down or increase speed of the game. Actually, not only games, if there is a software with clock ticking it can speed-en up that too. How does that work? I might imagine there is some internal clock on which these things run but not sure how these things happen on low level.
While this feature has worked on most of the games I tried, it has also failed on many, for eg, NFS Most wanted. Why? Is there any different mechanism on which these games run or it is just some anti-cheat?
Three years later, I think I know enough to answer my own question. :)
A computer program usually communicates with the kernel using predefined functions called system calls. Each OS has a different set of calls but often they do similar things like — allocating memory, reading and writing files, or handling processes. According to this page, there are around 480+ system calls in Windows NT kernel.
For any purpose that deals with the hardware, programs usually resort to system calls because that's what OS does best and one of these things happen to be knowing time. Computer games often need to render 60 frames / second and to make this happen they need to call the rendering function every 16.6ms. On Windows, "GetTickCount()" is usually used for this which returns number of milliseconds passed since the Windows has been up ("If no of milliseconds passed since the last tick count is more than 16ms, render a new frame else continue.").
SpeedHacking, in general, works by injecting code into the running process and hacking the timing functions to return sped-up / slowed-down "ticks" to modify the program's running speed.
Although, I can't be sure how exactly CE achieved this (the source code is pretty hard to understand) but another programmer pulled off a similar thing (video) on Linux. In the source code, you can see how the author modified a similar system call for Linux ("gettimeofday()") for this.
go gettimeofday_orig;
int val;
gettimeofday_orig=(go)dlsym(RTLD_NEXT,"gettimeofday");
if (!timezero)
{
timezero = new timeval;
val = gettimeofday_orig(timezero,tz);
(*tv) = (*timezero);
return val;
}
I am not sure how it's detected but I would be going with #Harold's idea that the game probably spots the DLL getting injected.
Cheat Engines Old Speedhack:
Runs the application in a very high priority thread
Uses timed sleeping to speed up the game
When a function is called, it will be given an emulated timer which is sped up
Cheat Engines New Speedhack:
When the Cheat Engine speed dll is injected into the program, it is modified to the speed you selected in the Cheat Engine panel
Sets a base reference of the current time
returned time = basetime+((currenttime-basetime)*speed
Detection:
Both Methods are easy to detect by sending a packet with the time every couple of seconds to be validated by a server
The game may be able to detect the dll being injected
Source:
http://wiki.cheatengine.org/index.php?title=Cheat_Engine:Internals#Speedhack
I think the reason why it does not work in some applications (mostly games) is that some games link the in-game clock to the frames per second. Therefore your game will slow down or crash if you try to speedhack it.
Source: http://hackerbot.net/tutorials/353-speed-up-hack-slow-down-cheat
Personally I have only encountered very few games that wouldnt react to the speedhack. Even if they are tied to the FPS, you can still speedhack it to some degree.

Rewriting a threaded Objective-C 'story engine' in CoffeeScript: How to script actions & conditions sequentially without a ton of callbacks?

I have been experimenting with porting the underlying 'story engine' of my Objective-C iPhone adventure Scarlett and the Spark of Life to HTML5 using CoffeeScript (and I am looking into IcedCoffeeScript).
The graphical part can just use DIVs on the DOM — the requirements there are fairly simple. The problematic part is the 'command and control' story-type commands. The ideal is to be able to express high-level story commands — including conditionals — and have them executed sequentially. So, for example, in faux-CoffeeScript:
scarlett.walkTo(200,300)
scarlett.turnTo(0)
story.wait(0.8)
if interesting
scarlett.think('Looks interesting.')
else
scarlett.think('Looks boring.')
In Objective-C (this was back when scripting languages like Lua were banned on the App Store), we achieved this by having two threads. The main thread ran cocos2d-phone which handled all the OpenGL calls, animation and other cocos niceties. The 'story' thread handled the command-and-control of the story, and if necessary the thread would sleep, awaiting an NSCondition before returning from a function and proceeding to the next call.
It sounds awkward, but it allowed us to express story commands and conditionals in a sequential, natural way, just using normal-looking code. Note that in the example above, the if check for the variable interesting would be evaluated right before Scarlett says something, not at the start of the function. Also, the walkTo(), turnTo(), wait() and think() calls will not return until their associated animation, delay or text box is finished back on the main thread.
What I'm struggling with is how to achieve this expressiveness using web technologies. As I see it, my options are:
Using a Web Worker as the story 'thread'. However, as far as I'm aware, workers can't sleep, and state isn't shared so they can't even perform a busy wait.
Using a callback chain, probably utilising IcedCoffeeScript's await and defer keywords to keep the code tidier. Even with those, though, that's a lot of extra line noise.
Somehow evaluate lines from the story script one-by-one as strings. I can't help feeling that it would be highly problematic.
(Similar in some ways to 3.) Write the story commands in a specially-designed interpreted language, where the program counter could be stopped and started as needed. It seems like this is unnecessarily re-inventing the wheel.
I can't help feeling like I'm overlooking some really obvious solution, though. Am I looking at this back-to-front, somehow? Is there an acknowledged pattern for scripting sequential actions and conditionals over time using actual code, without a mountain of callbacks?

What is the "Fountain Development Model"?

It is mentioned on the Systems Development Life Cycle page on Wikipedia:
To manage this, a number of system development life cycle (SDLC) models have been created: waterfall, fountain, spiral, build and fix, rapid prototyping, incremental, and synchronize and stabilize.
I found a few things on Google, but I felt that they were vague and they just didn't click for me. Perhaps an explanation from someone here might be more clear.
Fountain: Stand in a circle and throw some patterns and key words in the air to see where they land. Pick up only the ones that land inside the circle. Repeat until cancelled.
Waterfall: Wrangle everyone into a boat, then yell "Geronimo!" while going over Niagra Falls. Pick up the shattered pieces then rinse and repeat. Make sure it's well documented what part of the boat each individual should be sitting in, what they should be holding on to, how loud to yell, and exactly where they should land. See form 3684-B for additional instructions.
Spiral: Pick one team member and have everyone else spin them around in circles until dizy.
Build and Fix: Just throw it against the wall to see what sticks. If something falls off add some duct tape. Used gum may also work. Any part that won't stay stuck, just throw away.
Rapid Prototyping: Do exactly what the client asked for. Repeat until they figure out what they want.
Incremental: Only build the parts you want to, and only when you want to do it. An alternate version is to only build the parts they scream loudest for, and only when they are actually standing at your desk waiting for it.
Synchronize and Stabilize: Like Spiral except only one person at a time spins the unlucky team member. When their turn is over, stop the spinning for a moment.
Waterfall is a model that enforces control and avoids parallelism; every requirement for a task has to be fulfilled before starting the task. Fountain says that a new task can be started before all requirements are met, because not all requirements are necessary at the start of the task.
Think of this: Super Mario Game,
Waterfall: first, design everything, then get hardware done (Hardware Team), then create some test sprites, then code the engine, then create artwork, then music and finish.
Fountain: while the hardware team is doing its job, artwork starts conceptual work, and coding starts some prototyping on preexisting hw. When artists and hw finishes, coders integrate these onto their code and continue 'til finishing the game...
As I understand it, they essentially contain the same steps but a fountain approach is much more iterative, with less focus on initial design and more on analysis.
You basically bodge your way through things. See what needs to happen, and improve it. See what needs to happen. Improve it.
It's more agile but at the cost of project stability. Waterfall is a lot better for large projects.