public class Enemy extends com.jpemartin.jtb.VisibleObject {
(...)
protected static final int _speed = 2;
public Enemy(HasSize world, int x0, int y0) throws Exception {
init(world,x0,y0);
}
/** all one-time initialization, called by the ctor. **/
protected void init(HasSize world, int x0, int y0) throws Exception {
_alive=true;
// get enemy to initial state
x = x0;
y = y0;
_move = new MoveLeftRight(world.getWidth(),_speed);
_draw = new DrawAnim("gamedata/gpatrol_b32.png");
}
(...) // move and draw are the same as Ship's
}
We also modify the main loop to create the Enemy object and call its move and draw method for every frame. Here is a screenshot of the resulting game.
public class MyGame extends BaseApp {
Collection<Enemy> _enemies;
(...)
/** main game loop **/
public void run() {
try {
_ship = new Ship(this);
_enemies = new ArrayList<Enemy>();
for (int i=0; i<5; i++) {
_enemies.add( new Enemy(this, 10+i*20, 20+40*i));
}
createImageAndGraphics();
while (_gameRunning) {
for (Enemy e : _enemies) {
e.move(this);
}
_ship.move(this);
drawWorld();
showAndWait();
}
} catch (Exception x) {
x.printStackTrace();
throw new RuntimeException("Sorry, there's some sort of bug",x);
}
}
/** draw what the player sees **/
public void drawWorld() {
if (null==_dbImage) return;
synchronized(_dbImage) {
_dbg.setColor(Color.BLACK);
_dbg.fillRect(0, 0, getWidth(), getHeight());
for (Enemy e : _enemies) {
e.draw(_dbg);
}
_ship.draw(_dbg);
}
}
(...)
}
public class Enemy extends com.jpemartin.jtb.VisibleObject {
protected static Drawable _draw;
(...)
/** all one-time initialization, called by the ctor. **/
protected void init(HasSize world, int x0, int y0) throws Exception {
(...)
if (null==_draw) {
_draw = new DrawAnim("gamedata/gpatrol_b32.png");
}
}
(...)
}
Next: 6