二、完善周边工具类(图象、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位置输出漂亮的图片字符串。怎么样还挺好使的吧:)
