I am working on developing JavaME games and am using an LG500G and Motorola EM326g as testing devices. At this very early stage, things are going wrong. I have a while(!stop){} game loop, and at a certain point a method will set stop to true, which will enter a block of code after the while loop, a sort of end-game condition. This always works fine in the emulator, in the various ways I have expressed it. However, I have never been able to get it to work on either of the phones. Instead, the game freezes and no further activity happens. The baffling thing is that when I compile code from other games I have studied which use the same looping mechanism, those games run as expected! What could I be doing wrong? Is there a way I could rephrase the code to get it to work? I am currently looking at a "game state manager" as a possible solution...but something as simple as this should just work!(by the way, I tried a simple while(!stop){} loop, but had to try an if(!stop){}else{} block within the while(true) loop. It did not work on the phones either:
import java.io.IOException;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.*;
public class GardenGameCanvas extends GameCanvas implements Runnable{
private Image tomato;
private Sprite tomatoSprite;
private boolean stop;
private int tomX;
private int tomY;
private LayerManager manager;
public GardenGameCanvas(){
super(false);
}
public void start() {
try{
tomato = Image.createImage("/tomato.png");
tomatoSprite = new Sprite(tomato, 16, 16);
tomX= 0;
tomY = getHeight()/2;
manager = new LayerManager();
manager.append(tomatoSprite);
stop = false;
}catch(IOException ioex){System.err.println(ioex);}
Thread runner = new Thread(this);
runner.start();
}
public void run() {
while(true){
if(!stop){
verifyGame();
checkInput();
update(getGraphics());
try {
Thread.currentThread().sleep(30);
} catch(Exception e) {}
}else{
endGame(getGraphics());
}
}
}
private void update (Graphics g){
g.setColor(0xFFFFFF); //white
g.fillRect(0, 0, getWidth(), getHeight());
buildGame(g);
tomatoSprite.setPosition(tomX, tomY);
manager.paint(g, 0, 0);
flushGraphics();
}
private void buildGame(Graphics g){
g.setColor(0x000000);
g.drawLine(0, getHeight()/2, getWidth(), getHeight()/2);
}
private void checkInput(){
int keyStates = getKeyStates();
if((keyStates & LEFT_PRESSED) != 0) {
tomX -= 1;
}
else if((keyStates & RIGHT_PRESSED) != 0) {
tomX += 1;
}
}
private void endGame(Graphics g){
g.setColor(0xFFFFFF);
g.fillRect(0,0,getWidth(), getHeight());
g.setColor(0x000000);
g.drawString("Game Over", getWidth()/2, getHeight()/2, Graphics.HCENTER);
flushGraphics();
}
private void verifyGame(){
if(tomX==getWidth()){
stop = true;
return;
}
}
}