- Code: Select all
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
public class ALVGameCanvas
extends GameCanvas
implements Runnable
{
private boolean isPlay; // Game Loop runs when isPlay is true
private long delay; // To give thread consistency
private int currentX, currentY; // To hold current position of the 'X'
private int width; // To hold screen width
private int height; // To hold screen height
private boolean show;
private Image image;
public ALVGameCanvas()
{
super(true);
width = getWidth();
height = getHeight();
currentX = width / 2;
currentY = height / 2;
delay = 20;
}
// Automatically start thread for game loop
public void start() throws IOException {
isPlay = true;
Thread t = new Thread(this);
t.start();
image= Image.createImage("/Transparent.png");
}
public void stop() { isPlay = false; }
public void run() {
Graphics g = getGraphics();
flushGraphics();
while (isPlay == true) {
input();
drawScreen(g);
try { Thread.sleep(delay); }
catch (InterruptedException ie) {}
}
}
// Method to Handle User Inputs
private void input() {
int keyStates = getKeyStates();
// Left
if ((keyStates & LEFT_PRESSED) != 0)
currentX = Math.max(0, currentX - 1);
// Right
if ((keyStates & RIGHT_PRESSED) !=0 )
if ( currentX + 5 < width)
currentX = Math.min(width, currentX + 1);
// Up
if ((keyStates & UP_PRESSED) != 0)
currentY = Math.max(0, currentY - 1);
// Down
if ((keyStates & DOWN_PRESSED) !=0)
if ( currentY + 10 < height)
currentY = Math.min(height, currentY + 1);
}
// Method to Display Graphics
private void drawScreen(Graphics g) {
g.setColor(0xffffff);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(0x00ffff);
//g.drawImage(tempImage, 0, 0, 0);
g.drawString("X", currentX, currentY, 0);
if(currentY > (height /2)+3) show = true;
if(show)
g.drawImage(image, currentX, currentY, 0);
flushGraphics();
}
}
this code works and the image will show. this is not the original intention however. this is the original code for that drawScreen method
- Code: Select all
private void drawScreen(Graphics g) {
g.setColor(0xffffff);
g.fillRect(0, 0, getWidth(), getHeight());
g.drawImage(image, currentX, currentY, 0);
flushGraphics();
}
guess what! when I run the original on my NokiaN95 the application crashed stating an unhandled exception. I tried commenting out that g.drawImage() part, deploy again and it works!
F.Y.I. It's not an issue of if the image was loaded, exists in the jar etc. coz it was. As proof by the final code I made where I had to put that show boolean which i set to true after I activated a certain condition(which in my case is to move the currentY to be more than half the screen) and when it does the image now appears and moves along the cursor. never expected this from java. I guess microsoft does have reason to clone java. it seems to have a good idea on OOP but it's bugged gravely and I'm not even within half the lesson and the lesson already failed on me.
P.S. both code will work on the emulator. but not in the phone
