import java.awt.*;
import java.awt.image.*;
import java.applet.*;
import java.awt.event.*;

public class SpriteApplet extends Applet implements Runnable 
{
	Playfield playfield;
	Image output;
	// a mouse listener to the applet
    MouseListen listener = new MouseListen(this);
    Thread animate;
    
    public void init() 
    {
    	playfield = new Playfield(getImage(getDocumentBase(),
   						          getParameter("image")));

	  	AnimatedSprite monkey = new AnimatedSprite(getImage(getDocumentBase(),
  								getParameter("aniSprite1")), 7);
		AnimatedSprite ant = new AnimatedSprite(getImage(getDocumentBase(),
  								getParameter("aniSprite2")), 5);
	
		playfield.addSprite(monkey);
		playfield.addSprite(ant);
		//Note that both animated and static sprites can be added
		//to the playfield; up to MAX_SPRITES.
	 
    	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();  // falls back to raster.toImage()
        
        for (int i=0; i < playfield.numOfSprites; i++)
	        if (playfield.sprite[i] instanceof AnimatedSprite)
	        //if animated sprite, tell it to recalculate its next state
    			((AnimatedSprite)playfield.sprite[i]).nextState();
        repaint();
     }
              
     public void paint(Graphics g) 
     {
     	g.drawImage(output, 0, 0, this);
     }

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

