站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2ME 专题J2ME 2D小游戏入门之旅(二)完善周边工具类

J2ME 2D小游戏入门之旅(二)完善周边工具类

摘要: J2ME 2D小游戏入门之旅(二)完善周边工具类

二、完善周边工具类(图象、GameObject、Font)

虽然我们有了midp2.0的支持,但是有时还是需要一些辅助工具,方便我们使用。这怕是在进行真正的游戏设计之前最有趣的了。

1,首先是一个ImageTools工具类,提供一个方法帮助调用Image
public class ImageTools {
protected ImageTools() {
}

public static Image getImage(String str){
Image img=null;
try {
img = Image.createImage(str);
}
catch (Exception ex) {
System.out.println(ex);
}
finally{
return img;
}
}
}

2.GameObject,提供一个通用的游戏对象。

有了Sprite类,为什么还要GameObject呢?其实我们一般是将Sprite,看作成一个高级的Image,往往一个Sprite要被多个游戏对象调用,GameObject其实就是Sprite的状态类。GameObject提供简单的生命周期概念,动画更新速度;

public class GameObject {

public Sprite sprite;//内置的Sprite
public boolean alive;//存活标记
private int lifecount=0;//生命周期计数器
public int lifetime=0;//生命周期,以桢为单位
public int speed=0;//动画桢更新速度,(0至无穷,0代表每一桢跟新一个画面)
private int animcount=0;// /动画桢更新计数器

public GameObject(Image img,int width,int height){
sprite=new Sprite(img,width,height);
reset();
}

public void move(int dx,int dy){//相对移动
sprite.move(dx,dy);
}

public void moveto(int x,int y){//绝对移动
sprite.setPosition(x,y);
}

public void update(){//更新状态,动画桢更新,生命周期更新

if(!alive)
return;
if(++animcount>speed){
animcount=0;
sprite.nextFrame();
if(lifetime!=0 && ++lifecount>lifetime)
alive=false;
}
}

public void paint(Graphics g){//Paint

if(!alive)
return;
sprite.paint(g);
}

public void reset(){//复位
alive=true;
lifecount=0;
animcount=0;
sprite.setFrame(0);
}
}

3.封装字体类,你需要漂亮的字体吗?

我们经常需要用图片来输出文字,一个方便的字体类是必须的。我们希望仅仅提供一个图片,一个图片所描述的字符的数组,来初始化一个字体类。字体类提供一个类似Textout的方法,方便得在一个位置输出信息。先封装一个简单的版本,只支持英文和数字,并且输出不能自动换行。可能你有一个简单的思路,就是简单的保存字符数组,当打印的时候遍历数组,来查找每个字符在sprite的frameseq中的index,但当我们打印一个字符串的时候就会发现,太多的遍历操作耽误了宝贵时间,这里我们使用一个小技巧用容量换取速度,我们知道Character. hashCode()可以返回字符的ascii编码,常用字符将返回1-127;利用这一点,我们开辟一个128的数组charhash,将输入的字符c所在图片index存入charhash[c. hashCode()]中。以后也用这种映射方法来读取字符。charhash的元素初值为-1,以后只要数值大于0就是有效值。

public class Font {

Sprite sprite; //Sprite
int width,height; //每个char的尺寸
int[] charhash; //储存1-127个常见字符在sprite的frameseq中的位置
Graphics g;

public Font(Graphics g,Image img, int width, int height, char[] chars) {

this.g=g;
sprite=new Sprite(img,width,height);
this.width=width;
this.height=height;
charhash=new int[128];
for (int i = 0; i < charhash.length; i++) {
charhash[i]=-1;//没有代表此字符的图片
}
Character c;
for (int i = 0; i < chars.length; i++) {
c=new Character(chars[i]);
charhash[c.hashCode()]=i;
}
}

public void drawChar(char ch, int x, int y){
Character c=new Character(ch);
int hashcode=c.hashCode();
sprite.setPosition(x,y);
if(hashcode>=0){
sprite.setFrame(charhash[hashcode]);
sprite.paint(g);
}
}

public void drawString(String str, int x, int y){
int length=str.length();
for (int i = 0; i < length; i++) {
drawChar(str.charAt(i),x+width*i,y);
}
}
}

这样只要有一个实例font,就可以调用font.drawString(“hello”,0,0);

在0,0位置输出漂亮的图片字符串。怎么样还挺好使的吧:)



↑返回目录
前一篇: J2ME 2D小游戏入门之旅(三) 控制飞机的移动
后一篇: J2ME Read Cookies