import java.awt.*;
import java.awt.image.*;
import java.applet.*;
import java.awt.event.*;
/* My applet works as follows:
   It has 2 animated sprites. When the user clicks on a sprite, it becomes 
   activated. (If a user clicks on a point where the two sprites overlap,
   both become activated).
   When the user clicks the second time, activated sprite(s) move
   in the direction of the second mouseclick.

   The original idea was to have the activated sprites stop right by the
   point of the second mouseclick, but I ran out of time :(
   Also, when the sprites do not move, they rotate in place. (Could have them
   staying motionless, but also ran out of time :( )

   In principle, if the applet is used with non-animated sprites, then 
   the upon the second mouseclick, the activated sprite(s) move to the point
   of the click.

   */
public class SpriteApplet extends Applet implements Runnable 
{
  Playfield playfield;
  Image output;
  //mouse listener that will capture mouse events
  MouseListen listener = new MouseListen(this);
    
  Thread animate;
    
  public void init() 
  {
    playfield = new Playfield(getImage(getDocumentBase(),
				       getParameter("image")), 0);
    // the applet can work with either the sprites or animated sprites
  // Sprite monkey = new Sprite(getImage(getDocumentBase(),
  //				getParameter("sprite1")));
  //	Sprite ant = new Sprite(getImage(getDocumentBase(),
  //			   	getParameter("sprite2")));

  	//	playfield.addSprite(monkey);
  	//	playfield.addSprite(ant);	
    AnimatedSprite monkey = new AnimatedSprite(getImage(getDocumentBase(),
					   getParameter("aniSprite1")), 7);
    AnimatedSprite ant = new AnimatedSprite(getImage(getDocumentBase(),
					  getParameter("aniSprite2")), 5);
	
    playfield.addSprite(monkey);
    playfield.addSprite(ant);
   
    renderPlayfield( );
    addMouseListener(listener);
  }
     
  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() 
     {
       
       playfield.Draw();
       output = playfield.toImage();
  
       for (int i=0; i<playfield.numOfSprites; i++)
	 // for animated sprites, call the nextState function
	 // that determines where to draw the sprite next
	 if (playfield.sprite[i] instanceof AnimatedSprite)     
	   ((AnimatedSprite)playfield.sprite[i]) .nextState();
         repaint();
     }
  
  public void paint(Graphics g) 
  {
    g.drawImage(output, 0, 0, this);
  }
  
  public void update(Graphics g) 
  {
    paint(g);
  }

 }

