Example 1: The fish should swim back and forth This can only be achieved with a selection using if. In this example the method isNearBorder() checks if the fish is in a cell next to the grid's border. If this is the case, it swims back.
|
move() | This moves the actor to the next cell. When initializing an actor, its starting direction of 0° is set (east). The direction can be changed with the method setDirection() (absolute) or turn() (relativ) |
if (isNearBorder()) turn(180) |
Checks if nemo is in a border cell and turns it 180° |
With setHorzMirror(boolean b) a sprite of an actor can be mirrored. If b is true, the mirrored picture is shown. If b is false the mirrored picture is set back to its normal view.
|
![]() |
![]() |
// JGameEx2.java import ch.aplu.jgamegrid.*; import java.awt.Color; public class JGameEx2 extends GameGrid { public JGameEx2() { super(10, 10, 60, Color.red, "sprites/reef.gif"); Fish2 nemo = new Fish2(); addActor(nemo, new Location(2, 4)); show(); } public static void main(String[] args) { new JGameEx2(); } } // ------------- class Fish -------------------- class Fish2 extends Actor { public Fish2() { super("sprites/nemo.gif"); } public void act() { move(); if (isNearBorder()) { turn(180); setHorzMirror(!isHorzMirror()); } } } |
setHorzMirror(true) | Mirrors the sprite. By default setHorzMirror(b) is set to false |
isHorzMirror() | Returns true if the sprite is mirrored |
setHorzMirror(!isHorzMirror()) | If the sprite is not mirrored, mirror it and vice veras |
Example 3: Controlling actors movements with random numbers
The fish changes its direction randomly after each step by 5° or -5°.
|
// JGameEx3.java import ch.aplu.jgamegrid.*; import java.awt.Color; public class JGameEx3 extends GameGrid { public JGameEx3() { super(50, 50, 12, "sprites/reef.gif"); Fish nemo = new Fish(); addActor(nemo, new Location(10, 20)); show(); } public static void main(String[] args) { new JGameEx3(); } } // ------------- class Fish -------------------- class Fish extends Actor { public Fish() { super("sprites/nemo.gif"); } public void act() { if (Math.random() < 0.5 ) turn(5); else turn(-5); if (isNearBorder()) { turn(180); setHorzMirror(!isHorzMirror()); } move(); } } |
Math.random() | Returns a multi-digit random number between 0 and 1 |
if (Math.random() < 0.5) turn(5); else turn(-5); |
More or less 50% of the random numbers are smaller than 0.5. This turns the fish 5°. Otherwise it is turned -5° |