PacMan and His Many Friends (Ghosts)

Well, my friend and I are working very diligently on a Pacman game and had it working perfectly... with just PacMan. We have never really explored or used threads, and have only used buffering sporadically.
So we decided to use Threads on this project of ours, since we wanted the Ghosts each to move at their own speed, and PacMan at his own, of course. So we wrote up our Ghost class... which reads something like this:
import java.lang.Thread;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import javax.swing.JApplet;
import java.awt.Image;
public class Ghost extends Thread{
     //Data Fields
     private Graphics g,G;
     private Image Buffer;
     private JApplet app;
     private int gX,gY,gridSize,speed;
     private char direction;
     private Point destination,homePoint;
     private int state;
     private String strat;
     private Color color;
     private boolean staticRoute,running;
     private Sleeper s;
     Ghost(){}
     Ghost(JApplet app,Graphics G,int x,int y,String s, Color c, int gridSize, int speed){
          this.app=app;
          Buffer = app.createImage(app.getWidth(),app.getHeight());
          Graphics g=Buffer.getGraphics();
          this.G=G;
          gX=x;
          gY=y;
          homePoint = new Point(x,y);
          strat=s;
          color=c;
          this.gridSize=gridSize;
          this.speed=speed;
          this.s = new Sleeper();
          this.g=g;
          running=true;
          calcDestination();
     public int getX(){ return gX; }
     public int getY(){ return gY; }
     public String getStrat(){ return strat; }
     public int getState(){ return state; }
     public Color getColor(){ return color; }
     public void run(){
          while(running){
               if(destination.equals(new Point(gX,gY)))
                    staticRoute=false;
               calcDestination();
               if(direction=='R')
                    PacMan.drawLevel(g,gX-1,gY);
               else if(direction=='L')
                    PacMan.drawLevel(g,gX+1,gY);
               draw();
               s.sleep(speed);
               G.drawImage(Buffer,0,0,app);
     public void stopRun(){
          running=false;
     public void die(){
          destination = new Point((int)homePoint.getX(),(int)homePoint.getY());
          staticRoute=true;
     public void draw(){
          g.setColor(color);
          g.fillOval(((gX+1)*gridSize-(gridSize*2))+2,((gY+1)*gridSize-(gridSize*2))+2,(gridSize*3)-4,(gridSize*3)-4);
     public void calcDestination(){ //Doesn't work as it will in final version, just makes it go back and forth along the bottom or top... trying to get two ghosts going at once
          if(!staticRoute){
               if(strat.equals("Test")){
                    if(gX==2 && gY==42){
                         destination = new Point(30,42);
                         direction='R';
                    else{
                         destination = new Point(2,42);
                         direction='L';
                    staticRoute=true;
               if(strat.equals("Test2")){
                    if(gX==2 && gY==2){
                         destination = new Point(30,2);
                         direction='R';
                    else{
                         destination = new Point(2,2);
                         direction='L';
                    staticRoute=true;
          calcPoint();
     public void calcPoint(){  //Excuse the utter stupidity of this method.  It is merely for testing and will be better implemented later.
          if(gY==(int)destination.getY() && (int)destination.getX()>gX)
               gX++;
          else
               gX--;
}Let me explain part of the development behind this...
First off we started with just PacMan.java. I wrote it pretty much on my own and made it so it would read a series of numbers from a textfile to generate a level. It also contained the speed and how much pelets were worth, but that's not relevant. It worked fine, all of it.
Then the next step was having a yellow 'circle' move around in that field in the way we wanted it to. That also worked.
The third step was implementing the warps, which could be represented and generated from the text field itself. This worked and was implemented quite well. However, we did not use Threads up until now.
The fourth and current step was the Ghost implementation. This isn't going as planned. We use two Graphics objects in our PacMan class (which extends JApplet) and simply drew everything in one step to the 'invisible' one, then at the end of the paint method, draw it all over to the 'visible' graphics object. That worked fine in the previous steps, as mentioned above. However, we ran into a problem with the different speeds of the Ghosts. We passed in the 'invisible' Graphics object and had the Ghosts draw themselves to that via the run method. That worked fine if the speed was the same, but when it was different it created problems. Another problem was that since we passed in the SAME Graphics object, if one of the two Ghost instances changed the color, then it could affect the color of what was being drawn in the main PacMan class. (Usually during the inital display of the level. We'd have red-colored dots.)
I know this all sounds very... overwhelming.. and trust me, it is for us too. I'm just not sure how to go about solving this problem. If you look at the code closely, I have two Graphics objects for each Ghost. One is the main one from the app, and the other is the one it draws itself to so it prevents Color conflicts. Then at the end of the 'run' method we try drawing the individual Ghost Graphics object to the bigger one... and it all just jumbles up.
I guess to cut to the chase, what I'm asking for is advice on how to have multiple Ghost Threads running and drawing constantly without conflicts with color or too much lag. (I noticed when we set all the speeds to the same thing then it worked, but it was very choppy) One guess of mine would be to put PacMan on his own Thread, but my brain is so fried I'm not quite sure where to begin. Any guidance/references would be appriciated.

Personally I think you've got the wrong approach.
Instead of creating a Thread for every ghost, you should keep yourself to the one you've got in the PackMan class.
Tough what you need to do is make the whole game frames based.
You've got a speed variable that you should use to add/increase the X/Y location each frame, something like:
Ghost[X].newTick();Where newTick() should be something like:
public void newTick(); {
     x += speed;
     y += speed;
}and instead of drawing inside the Ghost class you should draw in the PackMan class, no collision with double usage of the Graphics objects.
Well, I hope you've got the general idea, post a message if you would like a practical example.
GL HF

Similar Messages

  • Making a Maze For Pacman (and his monsters)

    Hi. Im new to making games. Ive so far gone through a space Invaders tutorial and done an asteroids clone. I now want to improve my knowledge further so am thinking about doing a Pacman game.
    However, I currently dont know how to go about making the maze, (which of course, restricts both the player and the monsters from crossing over the walls of this maze.)
    Thanks in advance to any one who helps.
    Andy

    Hi
    Ive created a game using tiles. However, My pacman currently doen't always stop properly at the walls. There seems to be two main problems.
    a)Each tile is 16 pixels wide. Pacman moves 4 pixels each time. This means that
    three quarters of the time, he's not properly in line with the corridor. However,
    I think my program only checks whether the pixel at the top left of pacman is in
    a tile that is not a wall. This means that pacman often can move half through a wall.
    b) Using System.out.println, Ive noticed that when a button is held down (such as the left arrow key), System.out.println is activated once, then there is about half a seconds pause, and only then does System.out.println begin to constantly activate. It seems that during that half second break, the system isn't going through the bit of code that checks whether the tile is a wall or not (meaning he'll walk straight through the tile)
    Here is some of my code...
       //When one of the arrow keys is pressed, a boolean is activated
       // and update speed is called
       public void keyPressed(KeyEvent e) {
            switch (e.getKeyCode()) {
              case KeyEvent.VK_UP : up = true; break;
              case KeyEvent.VK_LEFT : left = true; break;
              case KeyEvent.VK_RIGHT : right = true; break;
              case KeyEvent.VK_DOWN : down = true;break;
            updateSpeed();
    //Work out the x and y speeds (vx and vy)
    //This is done by checking if the tile is a wall.
    //The player speed is only maintained if it is not.
    private void updateSpeed() {
            vx=0;vy=0;
            if (down){
                 if (!Tiles.tileGrid[(y/tileSize)+1][x/tileSize])
                      vy = PLAYER_SPEED;
            if (up){
                 if (!Tiles.tileGrid[(y/tileSize)-1][x/tileSize])
                         vy = -PLAYER_SPEED;
            if (left){
                  if (!Tiles.tileGrid[y/tileSize][(x/tileSize)-1]){
                       vx = -PLAYER_SPEED;
                       System.out.println("yx" + y + " " +x);
             System.out.println("Grid" + (y/tileSize) + " " + (x/tileSize));}
            if (right){
                 if (!Tiles.tileGrid[y/tileSize][(x/tileSize)+1])
                      vx = PLAYER_SPEED;
             System.out.println("yx" + y + " " +x);
             System.out.println("Grid" + (y/tileSize) + " " + (x/tileSize));
          }

  • How do I stop unwanted and too many friend request...

    I started receiving way too many contact requests from unknown men, usually all military, Which I have been consistently blocking, but I want to know if my account has been jacked or what is going on and how to stop this, please. Anyone???

    just some clarifications changing your privacy settings will only prevent unwanted calls and/or IMs from people who are not in your contact list.  It will not prevent other users, both legitimate and potential scammers/spammers, from sending your contact requests.
    IF YOU FOUND OUR POST USEFUL THEN PLEASE GIVE "KUDOS". IF IT HELPED TO FIX YOUR ISSUE PLEASE MARK IT AS A "SOLUTION" TO HELP OTHERS. THANKS!
    ALTERNATIVE SKYPE DOWNLOAD LINKS | HOW TO RECORD SKYPE VIDEO CALLS | HOW TO HANDLE SUSPICIOS CALLS AND MESSAGES
    SEE MORE TIPS, TRICKS, TUTORIALS AND UPDATES in
    | skypefordummies.blogspot.com | 

  • My friend gave me his iphone 4s and the phone is asking me to activate it under my friends apple id and password. my friend and i were wondering what would happen when we activate the iphone 4s? we don't know if its just going to unlock it or somethinels

    my friend gave me his iphone 4s and the phone is asking me to activate it under my friends apple id and password. my friend and i were wondering what would happen when we activate the iphone 4s? we don't know if it ist going to unlock it so we can use it or if it is going to activate his phone again into the iphone 4s

    No it's not stealing. They have an allowance that you can share with so many computers/devices. You'll have to authorize her computer to play/use anything bought on your acct. You can do this under the Store menu at top when iTunes is open on her computer.
    As far as getting it all on her computer....I think but I am not sure (because I don't use the feature) but I think if you turn on Home Sharing in iTunes it may copy the music to her computer. I don't know maybe it just streams it. If nothing else you can sign into your acct on her computer and download it all to her computer from the cloud. Not sure exactly how to go about that, I haven't had to do that yet. I wonder if once you authorize her computer and then set it up for automatic downloads (under Edit>Preferences>Store) if everything would download. Sorry I'm not much help on that.

  • TS3988 I got my iPad from my friend and he done a full restore before I got it, but know that I have put my iCloud account on here I have contacts and his too. How can I fix this problem? !!!!!

    I got my iPad from my friend and he done a full restore before I got it, but know that I have put my iCloud account on here I have contacts and his too. How can I fix this problem? !!!!!

    As I said in the other thread that you posted in the other forum, your friend clearly has not restored the iPad correctly. I suggest that you undertake another restore and start again.

  • I got my iPad from my friend and he done a full restore before I got it, but know that I have put my iCloud account on here I have contacts and his too. How can I fix this problem? !!!!!

    I got my iPad from my friend and he done a full restore before I got it, but know that I have put my iCloud account on here I have contacts and his too. How can I fix this problem? !!!!!

    Welcome to the Apple community.
    Given what you've have described, your friend cannot have restored the iPad correctly. You need to decide whether you are willing to delete his contacts manually, or carry out another restore. Personally I think I would go for the restore.

  • I want to play guitar with a friend through my iphone and his ipad.

    I want to play guitar with a friend through my iphone4 and his ipad.  Is this possible???  I hooked my Iphone4 to a FM transmitter so I could hear my friend through my stereo.  However, whenever I played, his feed cut out.  Is there a way to play music in real time using these devices? 
    Thanks...
    Jeffrey Olson

    Delete unwanted message on iPhone and backup again. Do the same with iPad.

  • My iphone 4s siri is not working, it just worked for a while and stopped. I've checked the data plan and it is intact, i even switched my sim to a friends phone and his siri worked but mine refused even with a wireless network. pls help.

    My iphone 4s siri is not working, it just worked for a while and stopped. I've checked the data plan and it is intact, i even switched my sim to a friends phone and his siri worked but mine refused even with a wireless network. pls help.

    Troubleshooting Siri
    http://support.apple.com/kb/TS4079

  • Pacman and pacman -Syu

    I was 100% sure I already posted this message but it is not here, I think I have done something terribly wrong with the submit button.  :oops:
    As everybody (should) know in case you do a pacman -Syu and a newer version of pacman is out, you should stop it, then upgrade only pacman and after do again pacman -Syu.
    Could it be possible to have pacman that checks  if there is a newer version available and in that case do only pacman upgrade?
    This should save (especially newcomers) many problem.
    I know that newcomers start to take advantage from a such feature only from 0.6 but somewere we have to start.
    I think pacman is this case can have two operating mode:
    1) pacman -Syu
    2) pacman see a newer pacman version
    3) pacman warn the user  to do a pacman -S pacman  before the pacman -Syu and stop. Eventually with the option to force the -Syu anyway. If somebody wants to mess up his/her system they should be free to do it 
    Another way can be
    1) pacman -Syu
    2) pacman see a newer pacman version
    3) pacman automatically update itself and after stop  warning the user that pacman has been update and now he/she need to start pacman -Syu again

    I think this is a good idea. You should submit a feature request to the bugtracker.
    Bobonov wrote:
    I think pacman is this case can have two operating mode:
    1) pacman -Syu
    2) pacman see a newer pacman version
    3) pacman warn the user  to do a pacman -S pacman  before the pacman -Syu and stop. Eventually with the option to force the -Syu anyway. If somebody wants to mess up his/her system they should be free to do it 
    Another way can be
    1) pacman -Syu
    2) pacman see a newer pacman version
    3) pacman automatically update itself and after stop  warning the user that pacman has been update and now he/she need to start pacman -Syu again
    A third way would be:
    1) pacman -Syu
    2) See never pacman version
    3) "Do you want to update pacman y/n"
    4) If yes upgrade pacman
    5) Continue with normal update.

  • I have iphone 4 and his on/off Button is brocken what can I do?

    I have iphone 4 and his on/off Button is brocken what can I do?

    This seems to be a network issue and is common globally.  Apple seems to need particularly good networks to operate consistently.
    I have friends and family with iPhones.  Here are a few experiences:
    I know that my friend is on holiday a couple of hours north of where I live.  I cant call her.  I call her partner who has a Nokia.  Same network same place, actually sitting beside each other on the beach.  The Nokia works fine, the iPhone, inoperative and no signal.
    My Brother has an iPhone 4.  We are meant to be in a convoy heading north.  I am talking to him on the phone and he agrees to pick up our dad.  he is on the motorway in the city.  He is not in the country in some poor coverage area.  I try and ring him straight back and it goes to answer service.  I try again.  I ring his wife, who is sitting right next to him in the car.  She has a Nokia - no problems.  His iPhone simply lost signal.  He was not talking on it.   His iPhone drops calls or is unable to make calls at all sorts of random places.  The worse the coverage, i.e. rural in the country the less service he has. 
    My Brother goes to China on business.  He is roaming.  His iPhone never lost signal and never dropped a call.
    Our conclusion.  An iPhone staying connected to a network is a delicate thing if you do not have a powerful network with good coverage, particularly 3G coverage if you have a 3G phone.  Your solution is to probably change networks and get one that has better coverage.  Your other solution might be to get  Nokia so that you can actually call people and use your iPhone for all of the cool email, games, iTunes and other functions it has.  Afterall that is what is was designed for - the phone thing seems to be an optional extra. 

  • TS2755 I turned off MMS today and suddenly all my text messages dissapeared from SMS 'inbox'. switched the iphone 4s on and off many times, nothing. If I search for an old text message by text I can see it, but it's not in the box of SMS

    I turned off MMS today and suddenly all my text messages dissapeared from SMS 'inbox'. switched the iphone 4s on and off many times, nothing. If I search for an old text message by text I can see it, but it's not in the box of SMS

    show this link to your friend http://support.apple.com/kb/ts5185

  • How can I add Yahoo msngr and MSN Msngr friends to iChat AV 3?

    Hi guys,
    I need to add yahoo and msn msnger friends to iChat AV v3.1.5.
    Can someone guide me or give directions how to do that?
    Anyone please,
    Many thanks,
    Zia

    Most of the JABBER Server (clients), have more IM client compatibility. Meaning,
    the way it was explained (that link), so just like you add a msn adress you can also add a Yahoo nickn.
    Youd should search for a Jabber server that handle a yahoo protocol connection too. If so, you can add yahoo too..
    anything else or help just add me on iChat.
    Sun1stDream.
    Carlos

  • Pacman and xorg

    Hi
    1 - pacman is working as I managed to install midnight commander with pacman -sy mc
    2 - pacman -S xorg does not work. Neither does pacman -Sy. The system reports that xorg is not in the sync db
    I have seen in response to pacman -sy that core, community and extra repository listings are downloaded - and that the system does become updated (including pacman herself).
    Ok wise people - what do I try next?
    Best Wishes;
    john./
    newbie to Arch, used debian for 5 years plus now..
    Last edited by jpa_cds (2007-12-19 18:09:02)

    Shining, Cerebral, thanks for your replies.
    pacman -Sg does indeed list all goups and xorg is missing. So I will switch mirror, run pacman -Sy and see!
    aaha! The GB repositry at manchester.sch..... perhaps is incomplete. I have commented that out, and am using repository in france. It looks as though it is going to work now.
    Just as a newbie point - I have not found a really useful guide to pacman anywhere  -  just many posts etc. The how-tos int he wiki seem to be fine if it all goes to plan, but did not provide the info you good fokk were able to give me.
    France is giving me some 'transient resolver failures' probably a router dropping packages somewhere.. OK maybe i need to run the select utility which packman has to find nearer repository.
    Thanks!

  • I have the iphone 3gs that my dad gave me. he passed away and his itunes account was cancelled. my phone somehow when i turned it on, disabled for 21 million minutes. i need to know if theres a way to unlock it without restoring.

    well, my dad gave me his iphone 3gs when he got a new iphone. he passed away and his itunes account was terminated and my iphone is disabled for 21 million and something minutes and i dont even know how it happened. my phone has been disabled for a really long time and i calculated the time span of how many minutes its locked and it would be locked for 41 years. THERE IS NO WAY IM WAITING THAT LONG!!!! i really need to know if theres a way to unlock my iphone 3gs without restoring it and an itunes account. help me please pleeeease PLEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEASE!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    To recover it at this point you need to restore it using the computer it was last backed up to. This will remove the passcode.

  • HT4623 After update IOS7 my iPad mini getting slowly and all my friend online on Facebook cannot show?

    After update my iPad mini getting slowly and all my friend chat online never show on Facebook screen? How to fix all of this? All the video I have stop and play and getting long to play....please help me...before update IOS7 I have no problem at all...

    Try this  - Reset the iPad by holding down on the Sleep and Home buttons at the same time for about 10-15 seconds until the Apple Logo appears - ignore the red slider - let go of the buttons. (This is equivalent to rebooting your computer.) No data/files will be erased.
    How to Fix a Slow iPad
    http://ipad.about.com/od/iPad_Troubleshooting/ss/How-To-Fix-A-Slow-iPad.htm
    iPad running slow? How to speed up a slow iPad
    http://appletoolbox.com/2012/07/ipad-running-slow-how-to-speed-up-a-slow-ipad/
    You may have many apps open which can possibly cause the slowdown and possibly the loss of wifi. In iOS 4-6 double tap your Home button & at the bottom of the screen you will see the icons of all open apps. Close those you are not using by pressing on an icon until all icons wiggle - then tap the minus sign. For iOS 7 users, there’s an easy way to see which apps are open in order to close them. By double-tapping the home button on your iPhone or iPad, the new multitasking feature in iOS 7 shows full page previews of all your open apps. Simply scroll horizontally to see all your apps, and close the apps with a simple flick towards the top of the screen.
     Cheers, Tom

Maybe you are looking for

  • Printer CD will not install software and drivers

    Laptop: Acer Aspire 3690 series Model: BL50 OS: Windows Vista SP2 Home Basic (32 bit) Printer: HP Desktop F4100 series *To my knowledge both laptop and printer are old models, with the laptop being as old as 7 years. Short Story: After formatting my

  • SSL - Always Prompted with "Request Authentication"

    Hi, We have developed an Applet which works as an Download Manager and we had it signed as it needs to access the file system of the users. We have two deployment environments one over SSL (Entrust) and other Non-SSL. The signed applet works well ove

  • Iphone 5 not working in usb socket of 2011 nissan navara teckna

    My vehicle is 1 year old and worked very well with my iphone 4.  Since upgrading to an iphone 5 I cannot get the usb socket to accept it.  It does not recognise it, or indeed charge the phone. is it my phone or a problem with the vehicle not recognis

  • I think my motherboard might be done. :(

    Here's my post from another forum: I started having problems with my computer a few weeks ago, and they just kept getting worse and worse. Here are my specs: Intel Q6600 MSI P6N SLI Platinum 500W Ultra PSU (crappy, I know) I originally had 2x2GB Cors

  • I need more disk space how do I do this?

    need more disk space how do I do this?