import java.applet.*;
import java.awt.*;

public class Bounce2 extends Applet implements Runnable {

  Thread animation;

  Graphics offscreen;
  Image image;

  static final int NUM_SPRITES = 6;
  static final int REFRESH_RATE = 80;  // in ms

  Sprite sprites[];		// sprite array
  int width, height;		// applet dimensions

  public void init() {
    System.out.println(">> INIT <<");
    setBackground(Color.black);
    width = bounds().width;
    height = bounds().height;
    initSprites();
    image = createImage(width,height);
    offscreen = image.getGraphics();
  }

  public void initSprites() {

    sprites = new Sprite[NUM_SPRITES];

    // define sprite for border
    sprites[0] = new BouncingBitmap(37,37,getImage(getCodeBase(),"alien.gif"),this,width-1,height-1);
    sprites[1] = new BouncingRect(0,0,30,30,Color.yellow,width-1,height-1);
    sprites[2] = new BouncingRect(17,17,13,13,Color.red,width-1,height-1);

    // border of the smaller box
    sprites[3] = new RectSprite(0,0,114,114,Color.green);

    // this rect bounces in a smaller box!
    sprites[4] = new BouncingRect(13,13,17,17,Color.green,114,114);

    // define sprite for border
    sprites[5] = new RectSprite(0,0,width-1,height-1,Color.green);

    ((Moveable)sprites[1]).setVelocity(4,3);
    ((Moveable)sprites[2]).setVelocity(1,2);
    ((Moveable)sprites[4]).setVelocity(3,1);
    ((Sprite2D)sprites[4]).setFill(true);
    ((Moveable)sprites[0]).setVelocity(1,3);
    ((BitmapSprite)sprites[0]).setSize(32,24);
  }

  public void start() {
    System.out.println(">> START <<");
    animation = new Thread(this);
    if (animation != null) {
      animation.start();
    }
  }

  public void updateSprites() {
    for (int i=0; i<sprites.length; i++) {
      sprites[i].update();
    }
  }

  public void update(Graphics g) {
    paint(g);
  }

  public void paint(Graphics g) {

    offscreen.setColor(Color.black);
    offscreen.fillRect(0,0,width,height);

    for (int i=0; i<sprites.length; i++) {
      sprites[i].paint(offscreen);
    }
    g.drawImage(image,0,0,this);
  }

  public void run() {
    while (true) {
      repaint();
      updateSprites();
      try {
        Thread.sleep(REFRESH_RATE);
      } catch (Exception exc) { };
    }
  }

  public void stop() {
    System.out.println(">> STOP <<");
    if (animation != null) {
      animation.stop();
      animation = null;
    }
  }
}
    
