int i = 0;
int k = 0;
try
{
for (i = 0; i < TYPE_NUM; i++)
{
for (k = 0; k < FRAME_NUM; k++)
{
fishImage[i][k] = Image.createImage("/fish" + i + k
+ ".png");
}
}
} catch (java.io.IOException e)
{
fishImage[i][k] = null;
}
// This MIDlet implicitly assumes that all the Images
// are the same width and height.
fishWidth = fishImage[0][0].getWidth();
fishHeight = fishImage[0][0].getHeight();
}
为了让鱼儿或者水草具有更好的随机性,代码是通过如下的算法来控制他们的方向的,下面以方向x为例说明
// mostly continue as we are, but sometimes randomly change
if ((ticksSinceLastChangeX > 20) && (rand(20) == 0))
{
vx = rand(2) * 2 - 1; // -1 or 1
ticksSinceLastChangeX = 0;
}
// if moving would take us off the left or right of the water,
// reverse
if (((vx < 0) && (x + vx < 0))
|| ((vx > 0) && (x + fishWidth + vx > FishTankCanvas.waterWidth)))
{
vx = -vx;
ticksSinceLastChangeX = 0;
}
当鱼接触到水的边缘的时候,它的速度方向会改变。在此前的代码是为了增加他的随机性。Fish的重新绘制也比较简单,这里用到了Nokia UI中的水平翻转的扩展功能
public void draw(Graphics g)
{
DirectGraphics dg = DirectUtils.getDirectGraphics(g);
Image img = fishImage[type][frame];
if (img != null)
{
if (vx < 0)
{
dg.drawImage(img, x, y, (Graphics.LEFT | Graphics.TOP),
DirectGraphics.FLIP_HORIZONTAL);
} else
{
dg.drawImage(img, x, y, (Graphics.LEFT | Graphics.TOP), 0);
}
}
frame = (frame + rand(2)) % FRAME_NUM;
}
我们可以看到每次绘画结束后都会把frame的编号随机设置一下,这样可以得到鱼儿本身运动的效果。
MIDlet的代码比较简单,直接给出
package example.fishtank;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class FishTankMIDlet extends MIDlet
{
private final FishTankCanvas canvas;