//画布:
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
public class ExampleGameSprite extends GameCanvas implements Runnable
{
private boolean isPlay; //isPlay标志们决定游戏线程是否运行
private int Width,Height; //屏幕的宽度和高度
private final static int STEP=3; //人物移动的幅度
private Sprite hero=null; //游戏精灵
private int frameWidth,frameHeight; //精灵的帧宽度和高度
private int lastState=-1; //游戏动作的前一状态,用来设置当前帧
public ExampleGameSprite()
{
super(true); //抑制游戏键盘
Width=getWidth(); //获取屏幕宽度
Height=getHeight();
try
{
Image img=Image.createImage( "/Males_B51.png "); //加载图片资源
hero=new Sprite(img,32,48); //创建精灵
frameWidth=32; //帧宽度为32像素
frameHeight=48;
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void start()
{
isPlay=true;
Thread t=new Thread(this); //创建游戏线程
t.start(); //启动游戏线程
}
public void stop()
{
isPlay=false; //停止游戏循环
}
public void run()
{
Graphics g=getGraphics();
int timeStep=100;
while(isPlay)
{
long start=System.currentTimeMillis(); //获取线程的起始时间
input(); //获取用户输入
draw(g); //绘制屏幕
long end=System.currentTimeMillis(); //获取执行完毕的事件
int duration=(int)(end-start);
if(duration <timeStep) //如果执行时间小于循环预定时间,则等待到循环时间
{
try
{
Thread.sleep(timeStep-duration);
}
catch(InterruptedException ie)
{
}
}
}
}
private void input()
{
int keyStates=getKeyStates(); //获取键盘状态
if((keyStates&LEFT_PRESSED)!=0) //如果用户按下游戏左键
{
if(lastState!=LEFT_PRESSED) //如果前一状态不是向左
{
lastState=LEFT_PRESSED;
hero.setFrameSequence(new int[]{3,4,5}); //设置精灵向左的帧序列
//hero.setFrameSequence(new int[]{4,5,6});
}
else
{
hero.nextFrame(); //精灵自动跳转下一帧
}
if(hero.getX()-STEP> =0)
hero.move(-STEP,0); //精灵向左移动
else
hero.setPosition(0,hero.getY()); //如果精灵到达左边界,则保持不动
}
if((keyStates&RIGHT_PRESSED)!=0) //按下向右键
{
if(lastState!=RIGHT_PRESSED)
{
lastState=RIGHT_PRESSED;
hero.setFrameSequence(new int[]{9,10,11});
//hero.setFrameSequence(new int[]{10,11,12});
}
else
{
hero.nextFrame();
}
if(hero.getX()+frameWidth <Width)
hero.move(STEP,0);
else
hero.setPosition(Width-frameWidth,hero.getY());
}
if((keyStates&UP_PRESSED)!=0) //按下向上键
{
if(lastState!=UP_PRESSED)
{
lastState=UP_PRESSED;
hero.setFrameSequence(new int[]{6,7,8});
//hero.setFrameSequence(new int[]{7,8,9});
}
else
{
hero.nextFrame();
}
if(hero.getY()-STEP> =0)
hero.move(0,-STEP);
else
hero.setPosition(hero.getX(),0);
}
if((keyStates&DOWN_PRESSED)!=0) //按下向下键
{
if((lastState!=DOWN_PRESSED))
{
lastState=DOWN_PRESSED;
hero.setFrameSequence(new int[]{0,1,2});
//hero.setFrameSequence(new int[]{1,2,3});
}
else
{
hero.nextFrame();
}
if(hero.getY()+frameHeight <Height)
hero.move(0,STEP);
else
hero.setPosition(hero.getX(),Height-frameHeight);