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

public class Run extends Applet implements Runnable {
  Playfield playfield;
  Image backImage, output;
  AnimatedSprite sprite0, sprite1;
  Thread animate;
  long time;
  private static final String backImageName = "6_837logo.gif";
  private static final String sprite0Name = "Hello.gif";
  private static final String sprite1Name = "WorldAni.gif";

  public void init() {
    time=0;
    backImage = getImage(getCodeBase(),backImageName);
    sprite0 = new AnimatedSprite( getImage(getCodeBase(),sprite0Name), 1 );
    sprite1 = new AnimatedSprite( getImage(getCodeBase(),sprite1Name), 12);
    playfield = new Playfield(backImage,2);
    playfield.addSprite(0, sprite0);
    playfield.addSprite(1, sprite1);

    renderPlayfield( );
      getAppletContext().showStatus("Image  actual sprite location.");
  }
  
  public void start() {
    animate = new Thread(this);
    animate.start();
  }

  public void stop() {
    animate = null;
  }
                  
  public void run() {
    while (true) {
      try {
	animate.sleep(100);
      } catch (InterruptedException e) {
      }
      renderPlayfield( );
    }
  }

  public void renderPlayfield( ) {
    long nowTime = System.currentTimeMillis();
    if ((nowTime - time) > 10000)
      {
	System.gc();
	time = System.currentTimeMillis();
      }
    sprite0.nextState(3,3);      // ideally these should be variables!!!
    sprite1.nextState(-3,-3);    // These low (dx,dy) makes the sprites
    playfield.Draw();            // move very slowly, but when they move faster
    output = playfield.toImage();   // the image that you click on is outdated.
    repaint();
  }
                  
  public void paint(Graphics g) {
    g.drawImage(output, 0, 0, this);
  }

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

  public boolean mouseDown(Event e, int x, int y) 
  {
    if (playfield.IsSpriteHit(x,y))
      getAppletContext().showStatus(
"X: "+ x +", Y:"+ y + " Hit a non-transparent sprite pixel.");
    else
      getAppletContext().showStatus(
"X: "+ x +", Y: "+ y + " Didn't hit a non-transparent sprite pixel.");
    return true;
  }

} // end Run applet




