Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Trouble with Java Keyboard EventDispatcher

Posted on 2014-01-06
4
Medium Priority
?
361 Views
Last Modified: 2014-01-10
I'm hoping someone can help me.  I am new to Java and have this project for school where we are building a "Pacman" game using Karel Robot.  I almost have everything working but I am getting funny results with my keyboard handler which allows the user to change the direction of  the Pacman.  The game is setup so Pacman will continually move in the direction he is facing until it comes to a wall or until the user presses the UP, DOWN, LEFT or RIGHT keys.  The problem I think I am having is that when a key is pressed, depending on which direction Pacman is facing, I may need to execute multiple "turns".  Karel only has a turnLeft method so the turnRight method consists of 3 turn lefts while the turnAround method consists of 2 turnLefts.

I'm not sure what is happening.  For example, the Pacman starts out moving "West" and comes to a wall.  I hit the UP arrow key to go North and the Pacman actually turns South, East and then North.  The problem is it doesn't always happen this way.

Here is the code that I am using.  Can someone please help or give me suggestions for finding and fixing the problem.  It is already 1:00 am and the project is due at 8:00 am.

import kareltherobot.*;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.awt.KeyEventDispatcher;
import javax.swing.KeyStroke;
import java.awt.Color;

public class Pacman extends Superbot
{
   public static int currentpacmanAve;
   public static int currentpacmanSt;
   public static Directions.Direction currentpacmanDirection;
   public static boolean pacmanDied=false;
   public static boolean superpacman=false;
   public static int superpacmanCounter=0;
   private int tempA;
   private int tempS;
   private Directions.Direction tempD;

   
   public Pacman(int s, int a,Direction direction,int b)
   {
      super( s, a, direction, b);
      currentpacmanAve = a;
      currentpacmanSt = s;
      currentpacmanDirection = direction;
      World.setupThread(this);
   }
   
   public void startPacman()
   {       
      // Setup Keyboard Focus Manager
      KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
      focusManager.addKeyEventDispatcher(
            new KeyEventDispatcher() {
               @Override
                  public boolean dispatchKeyEvent(KeyEvent e) {
                  String key = KeyStroke.getKeyStrokeForEvent(e).toString();
                  if (key.equals("pressed C")) //changes world color 
                  {
                     PacmanWorld.changeLayoutColor();
                  }
                  if(key.equals("pressed A")||key.equals("pressed LEFT")) //moves pacman west 
                  {
                     if(!facingWest())
                     {
                        if(facingEast())
                        {
                           turnAround();
                              
                        }
                        else
                        {
                           if(facingSouth())
                           {
                              turnRight();
                           }
                           else
                           {
                              turnLeft();
                           }
                        }
                     }
                  }
                  if(key.equals("pressed W")||key.equals("pressed UP")) //moves pacman north
                  {
                     if(!facingNorth())
                     {
                        if(facingSouth())
                        {
                           turnAround();
                        }
                        else
                        {
                           if(facingWest())
                           {
                              turnRight();
                           }
                           else
                           {
                              turnLeft();
                           }
                        }
                     }
                  }
                  if(key.equals("pressed S")||key.equals("pressed DOWN")) //moves pacman south
                  {
                     if(!facingSouth())
                     {
                        if(facingNorth())
                        {
                           turnAround();
                        }
                        else
                        {
                           if(facingWest())
                           {
                              turnLeft();
                           }
                           else
                           {
                              turnRight();
                           }
                        }
                     }
                  }
                  if(key.equals("pressed D")||key.equals("pressed RIGHT")) //moves pacman east
                  {
                     if(!facingEast())
                     {
                        if(facingWest())
                        {
                           turnAround();
                        }
                        else
                        {
                           if(facingNorth())
                           {
                              turnRight();
                           }
                           else
                           {
                              turnLeft();
                           }
                        }
                     }
                  }
                  if(key.equals("pressed K")) //pacman dies(test only)
                  {
                     Pacman.pacmanDied=true;
                  }
                  
                  return false;
               }
            });

      int superpacmanCounter=0; 
      int beeperCounter=0;
      pacmanDied = false;
      while(!pacmanDied)
      {
         if(nextToABeeper())
         {
            pickBeeper();
            beeperCounter++;
            PacmanWorld.score+=10;
         }
         if(nextToABeeper())
         {
            pickBeeper();
            superpacman=true;
            beeperCounter++;
            PacmanWorld.score-=10;
         }
         if(beeperCounter==PacmanWorld.totalBeepers)
         {
            PacmanWorld.worldbuilder();
         }
         if(frontIsClear())
         {
            move();
            TrackPacmanPosition();
            CheckIfInWarp();
            if(superpacman==true)
            {
               superpacmanCounter++;
               if(superpacmanCounter > 20)
               {
                  superpacman=false;
                  superpacmanCounter=0;
               }
            }
            System.out.printf("score=%d\n", PacmanWorld.score);
         }
      }
      setVisible(false);
      System.out.println("Pacman Died");
   }
   
   private void TrackPacmanPosition()
   {
               if(facingWest())
            {
               currentpacmanAve--;
            }
            if(facingEast())
            {
               currentpacmanAve++;
            }
            if(facingNorth())
            {
               currentpacmanSt++;
            }
            if(facingSouth())
            {
               currentpacmanSt--;
            }
      System.out.printf("Pacman current position: Street=%d  Avenue=%d\n", currentpacmanSt, currentpacmanAve);
   }
   
   private void CheckIfInWarp()
   {
      if ((currentpacmanAve == PacmanWorld.warp1Avenue && currentpacmanSt == PacmanWorld.warp1Street) ||
          (currentpacmanAve == PacmanWorld.warp2Avenue && currentpacmanSt == PacmanWorld.warp2Street) )
      {
         //setVisible(false);
         tempA = currentpacmanAve;
         tempS = currentpacmanSt;
         tempD = currentpacmanDirection;
         // Find boundary to go to opposite side of maze
         MoveToBoundary();
         MoveToBoundary();
         MoveToBoundary();
         if (tempD == Directions.East || tempD == Directions.West)
         {
            // Move to Street where warp begins
            while (tempS < currentpacmanSt)
            {
               move();
               tempS++;            
            }
            // Turn back into warp to return to maze
            if (tempD == Directions.West)
            {
               turnLeft();
               currentpacmanAve = PacmanWorld.maxAvenues;
            }
            else
            {
               turnRight();
               currentpacmanAve = 1;
            }
         }
         else
         {
             // Move to Avenue where warp begins
            while (tempA < currentpacmanAve)
            {
               move();
               tempA++;            
            }
            // Turn back into warp to return to maze
            if (tempD == Directions.North)
            {
               turnLeft();
               currentpacmanSt = 1;
            }
            else
            {
               turnRight();
               currentpacmanSt = PacmanWorld.maxStreets;
            }
         }
         setVisible(true);
      }
   }  
   
   private void MoveToBoundary()
   {
      while (frontIsClear())
      {
         move();
      }
      if (tempD == Directions.West || tempD == Directions.North)
         turnLeft();
      else if (tempD == Directions.East || tempD == Directions.South)
         turnRight();
   }
   
   private boolean NoWallsAroundPacman()
   {
      if (!frontIsClear())
         return false;
      turnLeft();
      if (!frontIsClear())
      {
         turnRight();
         return false;
      }
      turnLeft();
      if (!frontIsClear())
      {
         turnAround();
         return false;
      }
      turnLeft();
      if (!frontIsClear())
      {
         turnLeft();
         return false;
      }
      return true;
   }
}

Open in new window


I appreciate any help I can get!
0
Comment
Question by:dyarosh
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 35

Expert Comment

by:girionis
ID: 39764604
Where is the turnRight() method?
0
 

Author Comment

by:dyarosh
ID: 39764770
turnRight is in the Superbot class and consists of  3 turnLeft statements
0
 
LVL 35

Accepted Solution

by:
girionis earned 1500 total points
ID: 39764924
Then the only thing I can think of is that you probably keep the up key pressed more than once so it turns several times.  What happens if you put a system.out statement with a test message? Do you see it more than once?
0
 

Author Closing Comment

by:dyarosh
ID: 39770733
It looks like the problem is in the Karel Robot class.  I did as you suggested and the only keystrokes were the ones I pressed.  However when tracing the Robot's movements, it looked like Karel turned the Robot and moved down an avenue when it should not have.
0

Featured Post

The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses

715 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question