The source code of all examples is included in the JGameGrid distribution.
Ex03: A Less Object-Oriented Program Design
If you are not so much OOP-minded and prefer a more procedural approach, you can avoid the declaration of your own Actor class. This is possible because GameGrid also implements an empty act() method that is called once in every simulation cycle (after all Actor's act()). We override this method and put all animation code here. Because we need access to the actor in the overridden act(), nemo must be declared as instance variable and all methods must be prefixed with the variable name.
import ch.aplu.jgamegrid.*;
import java.awt.Color;
public class Ex03 extends GameGrid
{
private Actor nemo = new Actor("sprites/nemo.gif");
public Ex03()
{
super(10, 10, 60, Color.red, "sprites/reef.gif");
addActor(nemo, new Location(2, 4));
show();
}
public void act()
{
nemo.move();
if (!nemo.isMoveValid())
{
nemo.turn(180);
nemo.setHorzMirror(!nemo.isHorzMirror());
}
}
public static void main(String[] args)
{
new Ex03();
}
}
|
Execute the program locally using WebStart.
The runtime behavior is the same as Ex01. Which code do you prefer?
Ex03a: Introducing Events: the GGActListener
It is possible to implement the same functionalities without extending the application class. This may be necessary if the application class is derived from another class as it is normally the case in a GUI based program where the application class is derived from JFrame. Now we have the problem that we cannot override GameGrid.act() in the application class. How can we execute the animation code in every simulation cycle?
The JGameGrid package includes a certain number of event listeners that may be registered to get callback invocations of user defined methods whenever an event occurs. The implementation follows closely the Java Event Model using Listener interfaces. The GGActListener interface declares (but does not implement) a single method void act(). A class that implements this interface may be registered through the addActListener() method. Now its act() method is called as event callback in every simulation cycle. Here is the solution for our problem:
import ch.aplu.jgamegrid.*;
import java.awt.Color;
public class Ex03a implements GGActListener
{
private Actor nemo = new Actor("sprites/nemo.gif");
public Ex03a()
{
GameGrid gg =
new GameGrid(10, 10, 60, Color.red, "sprites/reef.gif");
gg.addActor(nemo, new Location(2, 4));
gg.addActListener(this);
gg.show();
}
public void act()
{
nemo.move();
if (!nemo.isMoveValid())
{
nemo.turn(180);
nemo.setHorzMirror(!nemo.isHorzMirror());
}
}
public static void main(String[] args)
{
new Ex03a();
}
} |
Execute the program locally using WebStart.
Again the runtime behavior is the same as Ex01.
|