package com.xushouwei.cn;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class SimpleGameDemo extends MIDlet implements CommandListener{
private Command exitCommand;
private SimpleGameCanvas sg;
public SimpleGameDemo()
{
exitCommand=new Command("Exit",Command.EXIT,1);
sg=new SimpleGameCanvas();
sg.addCommand(exitCommand);
sg.setCommandListener(this);
Display.getDisplay(this).setCurrent(sg);
}
public void commandAction(Command c, Displayable d) {
// TODO Auto-generated method stub
if(c==exitCommand)
{
try {
destroyApp(false);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
notifyDestroyed();
}
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
}
class SimpleGameCanvas extends GameCanvas implements Runnable
{
//private static boolean suppressKeyEvents;
private boolean mTrucking;
private long mFrameDelay;
private int mX,mY;
private int mState;
public SimpleGameCanvas() {
super(true);
// TODO Auto-generated constructor stub
mX=getWidth()/2;
mY=getHeight()/2;
mState=0;
mFrameDelay=20;
start();
}
public void start()
{
mTrucking=true;
Thread t=new Thread(this);
t.start();
}
public void stop()
{
mTrucking=false;
}
public void run() {
// TODO Auto-generated method stub
Graphics g=getGraphics();
while(mTrucking==true)
{
tick();
input();
render(g);
try {
Thread.sleep(mFrameDelay);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
public void tick()
{
mState=(mState+1)%20;
}
public void input()
{
int keyStates=getKeyStates();
if((keyStates&LEFT_PRESSED)!=0)
{
mX=Math.max(0, mX-1);
}
if((keyStates&RIGHT_PRESSED)!=0)
{
mX=Math.min(getWidth(), mX+1);
}
if((keyStates&UP_PRESSED)!=0)
{
mY=Math.max(0, mY-1);
}
if((keyStates&DOWN_PRESSED)!=0)
{
mY=Math.min(getHeight(), mY+1);
}
}
public void render(Graphics g)
{
g.setColor(0xffffff);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(0x0000ff);
g.drawLine(mX, mY, mX-10+mState, mY-10);
g.drawLine(mX, mY, mX+10, mY-10+mState);
g.drawLine(mX, mY, mX+10-mState, mY+10);
g.drawLine(mX, mY, mX-10, mY+10-mState);
flushGraphics();
}
}