Wednesday 3 December 2008

Update(), Paint(), tick and the TickTimer Thread

The (Container) method update() may be called, and the default action includes background clearance. We override this to call just the DisplayManager.paint() function.

// Bridge.update() is called when repaint() has been suggested
public void update(Graphics g)
{
displaymanager.paint(g);
}

Another overridden Container method

// Bridge.paint() is called when a complete refresh is necessary
public void paint(Graphics g)
{
displaymanager.refresh(g);
}

This is the tick() function, the heartbeat of the applet. This is aimed to be called every nth of a second, and all the sprites and the cursor are dealt with.

I'm not sure about dodging out altogether if cursor is in WAIT state.

If the current scene is already inventory, we should ignore an inventory request.

The zone cursor selection should take place before the sprite cursor selection, surely.


public void tick()
{
int thisCursor;
// If the current cursor is "hourglass", do nothing
if (currCursor == Cursor.WAIT_CURSOR) return;
// Check for flags from Javascript
if (invFlag)
{
invFlag = false;
popscene = currscene;
currscene = changeScene("inventory");
thisscene = bridgedata.fetchCurrentScene();
}
if (saveFlag)
{
saveFlag = false;
saveString = saveGame();
}
if (restoreFlag)
{
restoreFlag = false;
restoreGame(restoreData);
}
thisCursor = Cursor.DEFAULT_CURSOR;
Vector slist = bridgedata.getCurrentSprites();
for (int ii=0; ii < slist.size(); ii++)
{
// get all the sprites
Sprite sprite = (Sprite)slist.elementAt(ii);
// tick them
sprite.tick(ticks, mousex, mousey);
// cursor them
if (sprite.cursoron)
{
Rectangle r = sprite.getExtent();
if (r.contains(mousex, mousey))
{
thisCursor = sprite.cursor;
}
}
}
int zc = thisscene.getZoneCursor(mousex, mousey);
if (zc != -1)
{
thisCursor = zc;
}
if ((thisCursor != currCursor) && (currCursor != Cursor.WAIT_CURSOR))
{
currCursor = thisCursor;
setCursor(Cursor.getPredefinedCursor(currCursor));
}
repaint();
}

Ticktimer runs as a separate thread, attempting to call tick() n times a second. It uses System time in milliseconds. If it misses any ticks, it figures out how many ticks it has missed and increments the variable ticks accordingly. Some activities, especially sprite movement, care that the ticks have jumped, others just ignore it.

class Ticktimer extends Thread
{
private long interval;
public void run()
{
while (true)
{
timenow = System.currentTimeMillis();
interval = timenow-timewas;
if (interval > FRACTION)
{
interval /= FRACTION;
ticks += interval;
timewas += (interval*FRACTION);
tick();
}
try
{
sleep(((FRACTION-1)>0)?(FRACTION-1):(1));
}
catch(InterruptedException e)
{
return;
}
}
}
}

No comments: