Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Sprite Movement when key is pressed
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
huskiesgoaler34




PostPosted: Thu Jun 02, 2011 12:40 pm   Post subject: Sprite Movement when key is pressed

Hey, I am trying to create a similar game to PacMan called PacMaze. I was able to put all the Sprites i want onto the screen but I am having trouble getting my sprite, the yellow PacMan to move. I put in code that I thought would move the sprite when each arrow key was pressed but it isn't working. However, there are no errors. The program works fine but the sprite doesn't move. (Note: I know that it flickers (I'll fix that later) and I don't want the ghosts to move yet, just the PacMan.) Can someone help me out. I inserted the if statements but the image isn't moving. Thanks in advance.

code:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.image.*;
import java.util.*;
import sun.audio.*;    //import the sun.audio package
import java.io.*;


public class PacMaze extends JApplet implements Runnable, KeyListener
{
  static Font gameFont = new Font("SanSerif", Font.BOLD, 72);
  int width;
  int height;
  ArrayList <Rectangle> walls;
  Image backgroundBuf;
  Image screenBuf;
  Image img;
  Image pinkGhost;
  Image blueGhost;
  JLabel player;
  int x = 0;
  int y = 0;
  int speed = 10;
  Graphics2D background;
  Thread thread;
 
  public static void Music (){
 
//  InputStream in = new FileInputStream("Opening_Sound.mp3");
//// Create an AudioStream object from the input stream.
//AudioStream as = new AudioStream(in);         
//// Use the static class member "player" from class AudioPlayer to play
//// clip.
//AudioPlayer.player.start(as);           
//// Similarly, to stop the audio.
//AudioPlayer.player.stop(as);

  }



 
  public void init ()
  {
    Music();
    img = getImage (getCodeBase(),"Animated_PacMan_Left.gif");
    pinkGhost = getImage (getCodeBase(),"Pink_Ghost.gif");
    blueGhost = getImage (getCodeBase(),"Blue_Ghost.gif");
    player = new JLabel (new ImageIcon (img));
    player.setSize (img.getWidth (this), img.getHeight (this));
    addKeyListener (this);
    setFocusable (true);
    width = this.getWidth();
    height = this.getHeight();
    walls = new ArrayList <Rectangle> ();
    buildWalls();
       
  }
  public void keyReleased (KeyEvent ke) {}   //have to be here (all 3 methods)
  public void keyTyped (KeyEvent ke) {}
  public void keyPressed (KeyEvent ke) {
    int code = ke.getKeyCode();
    if (code == KeyEvent.VK_UP)
      y-=speed;
    else if (code == KeyEvent.VK_DOWN)
      y+=speed;
    else if (code == KeyEvent.VK_LEFT)
      x-=speed;
    else if (code == KeyEvent.VK_RIGHT)
      x+=speed;
    player.setLocation (x,y);
   
   
  }
 
  public void start ()
  {
   
   
    if (thread == null )
      thread = new Thread (this);
    thread.start();
   
  }
 
  public void stop ()
  {
   if (thread != null )
    thread.interrupt();
   thread = null;
  }
 

 
 
public void buildWalls( )
 
{   // create Rectangle objects and store in ArrayList walls
 
  int wallThickness = 10;
     
  walls.add (new Rectangle (0,0, width, wallThickness));//top border
  walls.add (new Rectangle (0,0, wallThickness, height)); //left border     /BORDERS AROUND APPLET FRAME
  walls.add (new Rectangle (width-wallThickness,0, wallThickness,height));//right border
  walls.add (new Rectangle (0, height-wallThickness,width,wallThickness));//down border
 
  walls.add( new Rectangle( 50,height-wallThickness-240, wallThickness, 65 ) ); //top space divider on left side
  walls.add( new Rectangle( 50,height-wallThickness-120, wallThickness, 70 ) );  //bottom space divider on left side     
  walls.add( new Rectangle( 50,height-wallThickness-50, width-120, wallThickness ) ); //bottom horizontal piece
  walls.add( new Rectangle( 50,height-wallThickness-250, width-200, wallThickness ) ); //top horizontal piece (left)
  walls.add( new Rectangle( 50,height-wallThickness-250, width-220, wallThickness ) ); //top horizontal piece (right)
  walls.add( new Rectangle( 180,height-205, wallThickness, 100 ) );  //middle piece
 
  }

public void paintWalls ()
{
  backgroundBuf = createImage (width, height);
  background = (Graphics2D) backgroundBuf.getGraphics();
  background.setColor (Color.black);
  background.fillRect (0,0,width, height);
  background.setColor (Color.RED);
 
  for (int i=0; i<walls.size(); i++)
  {   
    Rectangle r = (Rectangle) walls.get (i);
 background.fillRect (r.x, r.y, r.width, r.height);
      }
}
public void paint (Graphics g)
{
 
  g.drawImage (screenBuf,0,0, this);
  g.drawImage (img,345,255,this);
 // g.drawImage (img,50,15,this);  MY TESTING PACMAN
  g.setColor (Color.BLUE);
  g.drawString("START" , 340, 250);
  g.setColor (Color.BLUE);
//  g.drawString("FINISH" , 0, 20);
 
/////////////////////////////////////////////CIRCLES FOR FOOD/////////////////////////////////////////////////////////
  g.setColor(Color.YELLOW);
  g.fillOval (300,265,10,10);
  g.fillOval (260,265,10,10);
  g.setColor(Color.GREEN);   //LOWER LEVEL
  g.fillOval (218,262,15,15);
  g.setColor(Color.YELLOW);
  g.fillOval (180,265,10,10);
  g.fillOval (140,265,10,10);
  g.fillOval (100,265,10,10);
  g.fillOval (60,265,10,10);
  g.fillOval (21,265,10,10);
  g.drawImage (pinkGhost,15,255,this);//pink ghost sprite
 
 
  g.fillOval (21,225,10,10);
  g.setColor(Color.GREEN);
  g.fillOval (19,180,15,15);
  g.setColor(Color.YELLOW);
  g.fillOval (21,140,10,10);
  g.fillOval (21,100,10,10);   //left moving upward
  g.fillOval (21,60,10,10);
  g.fillOval (21,21,10,10);
  g.drawImage (blueGhost,13,133,this);//blue ghost sprite
 
  g.fillOval (61,21,10,10);
  g.fillOval (101,21,10,10);
  g.fillOval (141,21,10,10);   //moving right at top
  g.fillOval (181,21,10,10);
  g.fillOval (221,21,10,10);
  g.fillOval (261,21,10,10);
 
  g.fillOval (261,61,10,10);
  g.fillOval (221,61,10,10);
  g.fillOval (181,61,10,10);
  g.fillOval (141,61,10,10);  //second line of food
  g.fillOval (101,61,10,10);
 
 
}
public void run ()
{
  paintWalls ();
  screenBuf = createImage (width, height);
  Graphics gapplet = (Graphics2D) screenBuf.getGraphics();
 
  while (true)
  {
    gapplet.drawImage (backgroundBuf, 0,0, this);
    repaint();
    try {
      Thread.sleep (10);
    } catch (Exception ex) { stop (); }
  }
   
}
}
Sponsor
Sponsor
Sponsor
sponsor
huskiesgoaler34




PostPosted: Thu Jun 02, 2011 5:27 pm   Post subject: Re: Sprite Movement when key is pressed

I tried searching the site as well as the internet and I really haven't been able to find an answer to my problems....
Zren




PostPosted: Thu Jun 02, 2011 7:07 pm   Post subject: RE:Sprite Movement when key is pressed

Pretty sure you forgot this line of some sort:
typingArea.addKeyListener(this);

http://download.oracle.com/javase/tutorial/uiswing/events/keylistener.html
Java:

public class KeyEventDemo ...  implements KeyListener ... {
    ...//where initialization occurs:
        typingArea = new JTextField(20);
        typingArea.addKeyListener(this);

        //Uncomment this if you wish to turn off focus
        //traversal.  The focus subsystem consumes
        //focus traversal keys, such as Tab and Shift Tab.
        //If you uncomment the following line of code, this
        //disables focus traversal and the Tab events
        //become available to the key event listener.
        //typingArea.setFocusTraversalKeysEnabled(false);
    ...


Since your object is both the target area and the listener, I'm guessing you'd do something like: this.addKeyListener(this);
huskiesgoaler34




PostPosted: Thu Jun 02, 2011 8:42 pm   Post subject: Re: Sprite Movement when key is pressed

Yeah, your right that I used the addKeyListener (this) statement. I added the section of code that you provided. It complied but it still didn't make my sprite move. I took a look at the link you gave me and by understanding, the typing.area commands, from my understanding, allow the result of whether or not a key was pressed to be displayed (in a text frame). I have already included code (if statements, variable declarations, etc.) but it doesn't move the sprite. I added the key listener, I have the Key Pressed, Released, etc. methods. What am I missing?
Zren




PostPosted: Thu Jun 02, 2011 8:46 pm   Post subject: RE:Sprite Movement when key is pressed

It looks like the coordinates that you're drawing the pacman image to screen is hardcoded... g.drawImage (img,345,255,this);
huskiesgoaler34




PostPosted: Thu Jun 02, 2011 8:49 pm   Post subject: Re: Sprite Movement when key is pressed

Does that mean i will have trouble getting the sprite to move? By the way, what does hard coded mean?
huskiesgoaler34




PostPosted: Thu Jun 02, 2011 8:56 pm   Post subject: Re: Sprite Movement when key is pressed

Hard coding (also, hard-coding or hardcoding) refers to the software development practice of embedding what may, perhaps only in retrospect, be regarded as input or configuration data directly into the source code of a program or other executable object, or fixed formatting of the data, instead of obtaining that data from external sources or generating data or formatting in the program itself with the given input.

Ok, now I now what hardcoding means but what is the problem when it comes to making the image move?
Zren




PostPosted: Thu Jun 02, 2011 9:35 pm   Post subject: RE:Sprite Movement when key is pressed

The numbers are constant. They don't change. They aren't variable. You have x and y variables but you aren't using them.

Actually you are, but you're using them for the location of a label. Which you never pack into anything. In other words, it's down on paper, but you never make it and put it on something.

http://download.oracle.com/javase/tutorial/uiswing/examples/components/LabelDemoProject/src/components/LabelDemo.java

Since you're drawing the image, and are locally storing the coordinates, why are you using a label instead of:

g.drawImage (img, x, y, this);
Sponsor
Sponsor
Sponsor
sponsor
huskiesgoaler34




PostPosted: Fri Jun 03, 2011 12:57 pm   Post subject: Re: Sprite Movement when key is pressed

Thanks Zren. I finally found my problem. I am finally able to make the PacMan move. Thanks again.
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 9 Posts ]
Jump to:   


Style:  
Search: