# Moving a ball with keys

## Recommended Posts

DeskGlue    114
Hi i'm sorta new to java programming and need help on a project that will hopefully help me create games. This program im trying to make is supposed to have a ball in an applet, and use keys to move it up down left and right. When it hits the end of the applet it stops. Here is the code.

import java.applet.*;
import java.awt.*;

public class Move extends Applet implements Runnable, KeyListener
{
private Image dbImage;
private Graphics dbg;
private int x_pos = 10;
private int y_pos = 100;
private int x_speed = 0;
private int y_speed = 0;
private int appletsize_x = 700;
private int appletsize_y = 400;
private KeyEvent e;

public void init()

{

}

public void start()

{

th.start();

}

public void stop(){
th.Stop();
th = null;
}

public void keyPressed(KeyEvent e)
{
if (e.getKeyChar() == w) {
x_speed = 0;
y_speed = -1;
}
else if(e.getKeyChar() == a) {
x_speed = -1;
y_speed = 0;
}
else if(e.getKeyChar() == s) {
x_speed = 0;
y_speed = 1;
}
else if(e.getKeyChar() == d) {
x_speed = 1;
y_speed = 0;
}
}

public void keyReleased(KeyEvent e)
{
if (e.getKeyChar() == w) {
x_speed = 0;
y_speed = 0;
}
else if(e.getKeyChar() == a) {
x_speed = 0;
y_speed = 0;
}
else if(e.getKeyChar() == s) {
x_speed = 0;
y_speed = 0;
}
else if(e.getKeyChar() == d) {
x_speed = 0;
y_speed = 0;
}
else{

}
}

public void keyTyped(KeyEvent e)
{

}

public void run()

{

// run a long while (true) this means in our case "always"
while (true)
{

x_pos+=x_speed;
y_pos+=y_speed;

// repaint the applet
repaint();

try
{
// Stop thread for 20 milliseconds
}
catch (InterruptedException ex)
{
// do nothing
}

// set ThreadPriority to maximum value

// Ball is bounced if its x - position reaches the right border of the applet
if (x_pos > appletsize_x - radius)
{

// Change direction of ball movement
x_speed = 0;

}
// Ball is bounced if its x - position reaches the left border of the applet
{

// Change direction of ball movement
x_speed = 0;

}

if (y_pos > appletsize_y - radius)
{
y_speed = 0;
}
{
y_speed = 0;
}

}

}

public void paint(Graphics g)

{

g.setColor  (Color.red);

}

public void update (Graphics g)
{

// initialize buffer
if (dbImage == null)
{
dbImage = createImage (this.getSize().width, this.getSize().height);
dbg = dbImage.getGraphics ();
}

// clear screen in background
dbg.setColor (getBackground ());
dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);

// draw elements in background
dbg.setColor (getForeground());
paint (dbg);

// draw image on the screen
g.drawImage (dbImage, 0, 0, this);

}

}


This doesnt work apparently for some reason that i cannot figure out. PLease help me with this its getting frustrating. It would also be nice to know how to assign the keys to up, down ,left and right arrow keys, instead of w a s d, and if i am doing anything else wrong, unorthodox, or something that i could have/ should have done in an easier way. [Edited by - DeskGlue on March 12, 2006 7:42:55 PM]

##### Share on other sites
dave    2187
1) Is this homework/coursework?
2) How is it not working, what is it doing?

Dave

##### Share on other sites
DeskGlue    114
its not homework or anything, its just something im trying to figure out because i want to program a game in the future.

And the problem is, it wont compile, and says that loads of variables and objects or something weren't initialized, but they were, i do hope i used that terminology correctly, initialized means to declare the variable right?

##### Share on other sites
Sabonis    169
No, initialized is much different than declared.
Three definitions you should know:

Declaration:
int x;

initialization:
int x =5;

assignment:
x = 5;

You should also know that declared variables initially contain garbage values because it is freshly allocated memory in the activation record. If you want to know more please read about activation records and stack management. If you do assembler this becomes a lot clearer but for now just make sure you know the differences in the definitions above :)

##### Share on other sites
Ezbez    1164
1. use [ source ] and [ /source ] tags around your code, please. Makes it more readable.

2. Elaborating on what the above poster said, if you do not initialize the variables (or assign them a value before using them), and you attempt to 'use' them, the program would(in all likelihood) crash or not work properly. At least it would in C/C++, but Java instead catches it and won't even let you compile.

By 'using' I mean something other than assigning a value to, initializing, or declaring it. For example, multiplying another variable by it and then assigning that to a third variable, would crash if you hadn't already assigned it a value.

##### Share on other sites
DeskGlue    114
thanks for the tip about the source tags, i didnt know there were any.

Basically, im rtying to move a ball in 4 directions, and this is the code i tried to use to make that happen.

  public void keyPressed(KeyEvent e){if (e.getKeyChar() == w) {x_speed = 0;y_speed = -1;}else if(e.getKeyChar() == a) {x_speed = -1;y_speed = 0;}else if(e.getKeyChar() == s) {x_speed = 0;y_speed = 1;}else if(e.getKeyChar() == d) {x_speed = 1;y_speed = 0;}}public void keyReleased(KeyEvent e){if (e.getKeyChar() == w) {x_speed = 0;y_speed = 0;}else if(e.getKeyChar() == a) {x_speed = 0;y_speed = 0;}else if(e.getKeyChar() == s) {x_speed = 0;y_speed = 0;}else if(e.getKeyChar() == d) {x_speed = 0;y_speed = 0;}else{}}public void keyTyped(KeyEvent e){}

This way, apperently is not working, because it wont compile. And the old way is deprecated so it doesnt allow that.
i basically want to know how to use the 1.5 keylistener feature. I couldnt find a tutorial for key events in java 1.5.

Also, how could i set the keys instead of W A S and D to the arrow keys (non number pad). Thank you.

[Edited by - DeskGlue on March 12, 2006 7:59:14 PM]

##### Share on other sites
dAmAtA_cHiP    194
i know next to nothing about java so im only going by my c++ knowledge here, but in java do you not need the ' ' around characters to specify that they are actually characters?

e.g e.getKeyChar() == 'd'

if thats not compiling, its the only thing i can think of. also, if its not compiling, posting the errors you get should make it easier for others to help you

good luck :)

##### Share on other sites
DeskGlue    114
Oh, i am so stupid. You are right i think, but it still doesn't compile after i did that.

i think it has to do with the way im using the KeyEvent class, and/or the KeyListener class.

a lot of errors say that it cant find the symbol KeyListener, and other things, but i am doing this according to a tutorial, so i dont think it could be wrong, except for the KeyEvent because the tutorial has the deprecated way shown.

Here is the tutorial.

http://www.javacooperation.gmxhome.de/TutorialStartEng.html

##### Share on other sites
DeskGlue    114
please someone help, i even looked in the API but I couldnt find any other way to use this right.

i edited it again, and the problem was that, i had not imported java.awt.event but i had java.awt. and also there was a problem with initializing the variable so i declared it then set it to a value, but now it says i am using or overriding deprecated java API.

[source="java"]import java.applet.*;import java.awt.*;import java.awt.event.*;public class Move extends Applet implements Runnable, KeyListener{	private Image dbImage;	private Graphics dbg;	private int x_pos = 10;	private int y_pos = 100;	private int radius = 20;	private int x_speed = 0;	private int y_speed = 0;	private int appletsize_x = 700;	private int appletsize_y = 400;	private Thread th;		public void init()		{		addKeyListener(this);	}		public void start()		{			th = new Thread(this);		th.start();			}		public void stop(){		th.stop();		th = null;	}		public void keyPressed(KeyEvent e)	{		if (e.getKeyChar() == 'w') {			x_speed = 0;			y_speed = -1;		}		else if(e.getKeyChar() == 'a') {			x_speed = -1;			y_speed = 0;		}		else if(e.getKeyChar() == 's') {			x_speed = 0;			y_speed = 1;		}		else if(e.getKeyChar() == 'd') {			x_speed = 1;			y_speed = 0;		}	}		public void keyReleased(KeyEvent e)	{		if (e.getKeyChar() == 'w') {			x_speed = 0;			y_speed = 0;		}		else if(e.getKeyChar() == 'a') {			x_speed = 0;			y_speed = 0;		}		else if(e.getKeyChar() == 's') {			x_speed = 0;			y_speed = 0;		}		else if(e.getKeyChar() == 'd') {			x_speed = 0;			y_speed = 0;		}		else{					}	}		public void keyTyped(KeyEvent e)	{			}						public void run()		{				 // lower ThreadPriority	Thread.currentThread().setPriority(Thread.MIN_PRIORITY);	// run a long while (true) this means in our case "always"	while (true)	{				x_pos+=x_speed;		y_pos+=y_speed;		      // repaint the applet      repaint();      try      {            // Stop thread for 20 milliseconds            Thread.sleep (20);      }      catch (InterruptedException ex)      {            // do nothing      }      // set ThreadPriority to maximum value      Thread.currentThread().setPriority(Thread.MAX_PRIORITY);            // Ball is bounced if its x - position reaches the right border of the appletif (x_pos > appletsize_x - radius){      // Change direction of ball movement      x_speed = 0; }// Ball is bounced if its x - position reaches the left border of the appletelse if (x_pos < radius){      // Change direction of ball movement      x_speed = 0; }if (y_pos > appletsize_y - radius){	y_speed = 0;}else if (y_pos < radius){	y_speed = 0;}	}			}		public void paint(Graphics g)		{				g.setColor  (Color.red);		g.fillOval (x_pos - radius, y_pos - radius, 2 * radius, 2 * radius);			}		public void update (Graphics g)	{      // initialize buffer      if (dbImage == null)      {            dbImage = createImage (this.getSize().width, this.getSize().height);            dbg = dbImage.getGraphics ();      }      // clear screen in background      dbg.setColor (getBackground ());      dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);      // draw elements in background      dbg.setColor (getForeground());      paint (dbg);      // draw image on the screen      g.drawImage (dbImage, 0, 0, this);	}				}

[Edited by - DeskGlue on March 13, 2006 2:03:25 PM]