import java.lang.System;
import java.util.Vector;
import java.awt.Image;

class Playfield extends Raster {
  Raster background;          // background image
  Vector sprite;    // list of animated sprites on this playfield
  
  public static final int CONTINUE = 0;
  public static final int STOP = 1;
  public static final int BOUNCE = 2;
  public static final int DESTROY_SELF = 0;
  public static final int DESTROY_OBSTACLE = 0;
  

  public Playfield(Image bgnd) {
    super(bgnd);

    background = new Raster(bgnd);

    sprite = new Vector();
  }
  
  public void addSprite(int layer, AnimatedSprite s) {
    sprite.insertElementAt(s, layer);
  }

  public void Draw() {
    System.arraycopy(background.pixel, 0, this.pixel, 0, this.pixel.length);

    for (int i=0; i < sprite.size(); i++)
      ((AnimatedSprite)sprite.elementAt(i)).Draw(this);
  }

  public void collisionCheck(AnimatedSprite s) {
    AnimatedSprite target;
    int action, side;

    /* Leaving playfield */
    if (!s.getBounds().intersects(bounding_rect)) {
      if (s.leftPlayfield() == DESTROY_SELF)
	sprite.removeElement(s);
      return;
    }

    if (s.x < 0 || s.x+s.getWidth() > width)
      if (s.y < 0 && s.y < s.x || 
	  s.y+s.getHeight() > height && s.y+s.getHeight() > s.x+s.getWidth()) ;
      else {
	
	if (s.impactedPlayfieldBoundary(Sprite.HORIZONTAL) == DESTROY_SELF)
	  sprite.removeElement(s);
	return;
      }
    if (s.y < 0 || s.y+s.getHeight() > height) {
      if (s.impactedPlayfieldBoundary(Sprite.VERTICAL) == DESTROY_SELF)
	sprite.removeElement(s);
      return;
    }
      
    /* Collide with other sprites */
    for (int i=0; i < sprite.size(); i++) {
      target = (AnimatedSprite)sprite.elementAt(i);
      if (s != target && (side = s.intersects(target)) != Sprite.NONE) {
	target.impactedBy(s, action = s.impacted(target, side));
	if (action == DESTROY_SELF)
	  sprite.removeElement(s);
	else if (action == DESTROY_OBSTACLE)
	  sprite.removeElement(target);
      }
    }
  }

   public void clicked(int x, int y) {
     AnimatedSprite s;
     /* Who owns that point? */
     for (int i=0; i < sprite.size(); i++) {
       s = (AnimatedSprite)sprite.elementAt(i);
       if (s.getBounds().contains(x, y) && s.getPixel(x-s.x,y-s.y) >> 24 != 0)
	 s.clicked();
     }
   }
}
