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

当前页面: 开发资料首页J2ME 专题TilePuzzle剖析(1)

TilePuzzle剖析(1)

摘要: TilePuzzle剖析(1)
TilePuzzle剖析(1)

作者:


在wtk的安装目录中有许多附带的源代码,可以作为我们学习的范例。所以这就是我们这篇文章的写作初衷。

1、MIDlet文件分析

类名和文件名相同的TilePuzzle.java文件。他继承自MIDlet类,也就是应用程序的框架类。
其中代码比较简单。前三行为包和库。
在类中显示定义了一个Board类的实例b,他就是在后面会看到的Canvas类的子类,用来显示图像。其中类构造函数中的b = new Board(this);就是在构建一个Board类的实例并为他分配内存空间。而在startApp方法中,Display.getDisplay(this).setCurrent(b);就是将b作为当前屏幕。这样我们就可以将精力集中在Board类中,来专注游戏的开发了。

/*
* @(#)TilePuzzle.java 1.3 04/01/27
*
* Copyright (c) 2000-2004 Sun Microsystems, Inc. All rights reserved.
* PROPRIETARY/CONFIDENTIAL
* Use is subject to license terms
*/


package example.tilepuzzle;

import javax.microedition.midlet.MIDlet;
import javax.microedition.lcdui.Display;

public class TilePuzzle extends MIDlet {

Board b;

public TilePuzzle() {
b = new Board(this);
}

public void startApp() {
Display.getDisplay(this).setCurrent(b);
}

public void pauseApp() { }

public void destroyApp(boolean unc) { }

}




2、Piece类分析

我们来看看Board.java吧。其中就是Piece类。
该类用来描述一个方格的相关属性:
String label; //标签
boolean inv;
int serial; // serial number for ordering
int ix, iy; // initial location in grid coordinates初始化在表格中的位置,表示该方格应该在的正确位置
int x, y; // current location in grid coordinates在表格中的当前位置
//在构造函数中初始化变量
Piece(String str, int ser, int nx, int ny, boolean v) {
label = str;
serial = ser;
x = ix = nx;
y = iy = ny;
inv = v;
}

然后是该类的成员函数的定义:
void setLocation(int nx, int ny) {//设定在表格中的当前位置
x = nx;
y = ny;
}

boolean isHome() {//判断是否已经移动到正确的位置
//当前位置和最初设定的位置相同,表示已经移动到正确的位置了

return (x == ix) && (y == iy);
}

void goHome() {//放回到正确的位置上
setGrid(this, ix, iy);
}

// assumes background is white假设背景是白色的
void paint(Graphics g) {//绘图
int px = x * cellw;//当前水平位置*方格的宽度得到他在屏幕上的像素点水平位置
int py = y * cellh;//当前纵向位置*方格的高度得到他在屏幕上的像素点纵向位置

if (label != null) {//只要标签不为空
if (inv) { //如果inv为真
//绘制黑边框,白底,黑字
// black outlined, white square with black writing
g.setColor(0);
g.setFont(font);
g.drawRect(px, py, cellw-2, cellh-2);
g.drawString(label,
px+cellxoff, py+cellyoff,
Graphics.TOP|Graphics.LEFT);
} else {//如果inv为假
//绘制黑底,白字

// black square with white writing
g.setColor(0);
g.fillRect(px, py, cellw-1, cellh-1);
g.setColor(0xFFFFFF);
g.setFont(font);
g.drawString(label,
px+cellxoff, py+cellyoff,
Graphics.TOP|Graphics.LEFT);
}
}
}
}
其中我们可以看到该类还是用了一些定义在Board.java文件中的Board类中的全局变量:
// grid width and height, in cells表格的宽高
int gridw;
int gridh;

// cell geometry in pixels单元的相应属性,宽高和纵横偏移
int cellw;
int cellh;
int cellyoff;
int cellxoff;
这样我们就在一个piece类中包含了一个单元方格的所有信息,位置、宽高、颜色、标签等




↑返回目录
前一篇: MIDP1.0中处理键盘输入
后一篇: J2ME的现状与发展(转贴)