// Annamaria Cherubin: last edited on 9-28-1998
// 6.837 - Project #1
// SpriteApplet.java

package proj1;
import java.applet.*;
import java.awt.*;
import java.lang.*;

public class SpriteApplet extends Applet implements Runnable {
  Playfield playfield;
  AnimatedSprite sprite1, sprite2;
  Image backgroundImage, sprite1Image, sprite2Image;
  Image output;
  Thread animate;

  boolean debug = true;

  public void init() {
    if (debug) System.out.println("Starting init.");
    
    backgroundImage = getImage(getDocumentBase(), getParameter("background"));
    sprite1Image = getImage(getDocumentBase(), getParameter("ant"));
    sprite1 = new AnimatedSprite(sprite1Image, 5);
    int[] series = {0, 1, 2, 1, 0, 3, 4, 3};
    sprite1.addTrack(8, series);
    sprite1.addState(0, 0, 1, -20, 10);

    sprite2Image = getImage(getDocumentBase(), getParameter("wrld"));
    sprite2 = new AnimatedSprite(sprite2Image, 12);
    int[] series = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
    sprite1.addTrack(12, series);
    sprite1.addState(0, 0, 1, 10, 10);

    playfield = new Playfield(backgroundImage, 1);
    playfield.addSprite(0, sprite1);
    playfield.addSprite(1, sprite2);
    renderPlayfield( );
  } // end init
  
  public void start() {
    animate = new Thread(this);
    animate.start();
  } // end start
  
  public void stop() {
    animate = null;
  } // end stop
  
  public void run() {
    while (true) {
      try {
	animate.sleep(100);
      } catch (InterruptedException e) {
      }
      renderPlayfield( );
    }
  } // end run
                  
  public void renderPlayfield() {
    playfield.Draw();
    output = playfield.toImage();

    sprite1.nextState();
    //    sprite2.nextState();

    if (debug) System.out.println("Calling repaint.");
    repaint();
  } // end renderPlayfield
                  
  public void paint(Graphics g) {
    g.drawImage(output, 0, 0, this);
  } // end paint
  
  public void update(Graphics g) {
    paint(g);
  } // end update
  
  
  public boolean mouseDown(Event e, int x, int y) {
    sprite1.x = x;
    sprite1.y = y;
    sprite1.curTrack = 0;
    sprite1.frame = 0;
    
    sprite2.x = x;
    sprite2.y =y ;
    sprite2.curTrack = 0;
    sprite2.frame = 0;
    
    renderPlayfield( );
    return true;
  } // end mouseDown

} // end class SpriteApplet
