/* demo of BitmapLoops and user interaction */ import java.applet.*; import java.awt.*; public class GameManager extends Applet implements Runnable { Thread animation; Graphics offscreen; Image image; static final int REFRESH_RATE = 80; // in ms Image ufoImages[] = new Image[6]; // 6 ufo Images Image gunImage; // gun image GunManager gm; UFOManager um; int width, height; // applet dimensions public void init() { showStatus("Loading Images -- WAIT!"); setBackground(Color.black); // applet background width = bounds().width; // set applet dimensions height = bounds().height; loadImages(); um = new UFOManager(width, height, ufoImages, this); gm = new GunManager(width, height, gunImage, um.getUFO(), this); um.initialize(gm); // initialize gun parameters image = createImage(width,height); // make offscreen buffer offscreen = image.getGraphics(); } public void loadImages() { MediaTracker t = new MediaTracker(this); gunImage = getImage(getCodeBase(),"image/gun.gif"); t.addImage(gunImage,0); for (int i=0; i < 6; i++) { ufoImages[i] = getImage(getCodeBase(), "image/ufo" + i + ".gif"); t.addImage(ufoImages[i],0); } try { // wait for all images to finish loading t.waitForAll(); } catch (InterruptedException e) { } if (t.isErrorAny()) { // check for errors showStatus("Error Loading Images"); } else if (t.checkAll()) { showStatus("Images successfully loaded"); } // initialize the BitmapLoop } public boolean mouseMove(Event e,int x,int y) { gm.moveGun(x); return true; } public boolean mouseDrag(Event e,int x,int y) { gm.moveGun(x); return true; } public boolean mouseDown(Event e,int x,int y) { gm.fireMissile(x); return true; } public void start() { showStatus("Starting Game!"); animation = new Thread(this); if (animation != null) animation.start(); } public void updateManagers() { gm.update(); um.update(); } // override update so it doesn't erase screen public void update(Graphics g) { paint(g); } public void paint(Graphics g) { offscreen.setColor(Color.black); offscreen.fillRect(0,0,width,height); // clear buffer gm.paint(offscreen); um.paint(offscreen); g.drawImage(image,0,0,this); } public void run() { /* this is the video game loop: while playing game { 1. paint objects 2. update objects 2.1 make sure you don't hog the processor 3. pause for an interval of time } */ while (true) { repaint(); updateManagers(); Thread.currentThread().yield(); try { Thread.sleep (REFRESH_RATE); } catch (Exception exc) { }; } } public void stop() { showStatus("Game Stopped"); if (animation != null) { animation.stop(); animation = null; } } }