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

/********************************************************
 * Playfield class contains the sprites on the playfield
 * and controls their movements
 * It is also used to create the image for the applet
 *********************************************************/
class Playfield extends Raster {
  Raster background;          // background image
  AnimatedSprite sprite[];    // list of sprites on this playfield
  int lastSpriteHit;	      // index of last sprite to be hit

  // creates array of sprites
  public Playfield(Image bgnd, int numSprites) {
    super(bgnd);
    background = new Raster (bgnd);
    sprite = new AnimatedSprite[numSprites];
    lastSpriteHit = -1;       // no sprite has been hit yet
  }

  // adds a sprite to the playfield
  public void addSprite(int i, AnimatedSprite s) {
    sprite[i] = s;
  }

  // moves the last sprite that was hit
  public void moveRelSprite (int shiftx, int shifty) {
    sprite[lastSpriteHit].moveRel(shiftx, shifty);
  }

  // determines whether the mouse pointer is over a sprite
  public boolean hitSprite(int mousex, int mousey) {
    for (int cursprite = sprite.length - 1; cursprite >= 0; cursprite--) {
      // if sprite is hit...
      if (sprite[cursprite].isOverSprite(mousex, mousey)) {
	lastSpriteHit = cursprite;
	System.out.println ("hit: " + lastSpriteHit);
	return true;
      }
    }
    return false;
  }

  // continue ticking
  public void updateTick() {
    for (int cursprite = 0; cursprite < sprite.length; cursprite++) {
      // update sprites' state
      sprite[cursprite].tick();
    }
  }

  public void Draw() {
    int cursprite;

    // reset the background
    for (int s = 0; s < background.size(); s++)
      pixel[s] = background.pixel[s];
    // draw all sprites on the background
    for (cursprite = 0; cursprite < sprite.length; cursprite++) {
      // update sprite to be on background
      sprite[cursprite].Draw(this);
    }
  }

  // move sprites to top left corner
  public void resetSpritePositions() {
    for (int cursprite = 0; cursprite < sprite.length; cursprite++) {
      sprite[cursprite].moveRel(0-sprite[cursprite].x, 0-sprite[cursprite].y);
      sprite[cursprite].Draw(this);
    }
  }

  // change the track of a specified animated sprite
  public void changeTrack (int cursprite, int track) {
    sprite[cursprite].setTrack(track);
  }
}
  

