long timeTaken = System.currentTimeMillis() - startTime;
if (timeTaken < MILLIS_PER_TICK)
{
synchronized (this)
{
wait(MILLIS_PER_TICK - timeTaken);
}
} else
{
currentThread.yield();
}
}
} catch (InterruptedException e)
{
}
}
由于在屏幕的下方有一部分是泥土,因此在这里调用了repaint(0,0,waterWidth,waterLength)。其实FishTankCanvas同时也是一个容器类,它是Fish和Weeds的容器。他去更新Fish和Weeds的状态然后调用各自的draw()方法来重新绘制。下面我们看看FishTankCanvas是如何绘制的
private synchronized void drawFishTank(Graphics g)
{
// Draw the water
g.setColor(0, 255, 255);
g.fillRect(0, 0, waterWidth, waterHeight);
// Draw the sand
g.setColor(255, 128, 64);
g.fillRect(0, waterHeight, waterWidth, getHeight());
// Draw the weeds and fishes
for (int plane = 0; plane < NUM_PLANES; plane++)
{
if (plane == WEEDS_PLANE)
{
weeds.draw(g);
}
for (int i = 0; i < fishes.size(); i++)
{
Fish fish = (Fish) (fishes.elementAt(i));
if (fish.getZ() == plane)
{
fish.draw(g);
}
}
}
}
接下来我们研究一下Fish和Weeds的代码,它们就是有很多图片构成的。实现的结果和MIDP2.0中的Sprite差不多。Fish和Weeds的图片都是有类型之分的,每个类型又有几个桢。这样才可以构造出不同的对象,并且相同的对象在不同的时刻也有不同的状态。
private static final int TYPE_NUM = 3;
private static final int FRAME_NUM = 2;
private static final Image[][] fishImage;
Fish和Weeds都是采用了静态初始化块的方式来初始化相应的二维数组。例如
static
{
fishImage = new Image[TYPE_NUM][FRAME_NUM];