OK... Java games 101.
You need to animate BOTH of your characters, in the run() method of a thread. Don't update anything in your paint() method, just paint. Don't update your character position in the keyPressed() method.
Here's some sample code... this isn't complete!! It is for example only, to see how a typical Java game is structured.
PHP Code:
public class MyGame extends Canvas implements Runnable {
private static final int MILLIS_PER_FRAME = 100; // 10 frames per second
private static final int MINIMUM_SLEEP = 10; // always sleep() for at least this
private static final int LEFT_KEY = -3; // this is right for Nokias, different on others
private boolean exitGame;
private boolean leftKeyPressed;
private boolean leftKeyReleased;
private int playerX;
public MyGame() {
exitGame = false;
(new Thread(this)).start();
}
public void run() {
// set exitGame to true to exit the game-thread
while (!exitGame) {
long startTime = System.currentTimeMillis();
// update the game state
// first, process input
if (leftKeyPressed) {
playerX--;
if (leftKeyReleased) {
leftKeyPressed = false;
leftKeyReleased = false;
}
}
// and other updates for the player, like:
// playerAnimationFrame++;
// next, update the "computer" character
updateComputerCharacter();
// paint the screen
repaint();
serviceRepaints();
// this keeps the frame rate regular
int timeTaken = (int)(System.currentTimeMillis() - startTime);
int sleepTime = MILLIS_PER_FRAME - timeTaken;
if (sleepTime < MINIMUM_SLEEP) {
// if the game doesn't sleep on every frame, it is possible that
// no time will be given to the event thread, and keyPressed() events
// won't be delivered promptly
sleepTime = MINIMUM_SLEEP;
}
if (sleepTime > 0) {
try {
Thread.sleep(sleepTime);
} catch (Exception e) {
// ignore
}
}
}
}
public void paint(Graphics g) {
// don't do anything here, except paint
drawBackground(g);
drawPlayer(g);
drawEnemy(g);
}
public void keyPressed(int key) {
// do nothing here, except record the event
switch (key) {
case LEFT_KEY:
leftKeyPressed = true;
break;
}
}
public void keyReleased(int key) {
// do nothing here, except record the event
switch (key) {
case LEFT_KEY:
leftKeyReleased = true;
break;
}
}
}
Why are there two booleans for one key? Why not?
Code:
// don't do this!!
boolean leftKeyPressed;
public void keyPressed(int key) {
if (key == LEFT_KEY) {
leftKeyPressed = true;
}
}
public void keyReleased(int key) {
if (key == LEFT_KEY) {
leftKeyPressed = false;
}
}
Don't do this, because it is possible to receive a pressed and released event during the same frame. With this code, the update code will never see that key pressed, because data will be lost.
Setting MINIMUM_SLEEP to zero will make the game faster. But on some devices, it will make it less responsive to user input. Slowing the game down like this actually makes it feel faster.
Hope this helps.
Cheers,
Graham.