/*
Travell Perkins
6.837 Project 1
*/
import java.awt.*;
import java.util.Vector;
import java.awt.image.*;
import java.util.Random;


public class Playfield extends  Raster {

    //The thread that runs to continue the animation of this applet.
  public Raster raster = null;
  public Vector sprites = new Vector(3);
  public Playfield(Image img, Raster raster) {
    super(img);
    this.raster = raster;
  }

  //Add a sprite to this playfield.
  public void addSprite(Sprite s) {
      sprites.addElement(s);
  }
  public void Clear(){
    Color c = new Color(255,255,255);
    int white = c.getRGB();    
    for (int i=0; i < this.size(); i++){
      this.pixel[i] = white;
    }
  }
   
  public void Update(){
    Sprite sprite;
    for (int s=0; s <sprites.size(); s++) {
      //Get a sprite.
      sprite = (Sprite)(sprites.elementAt(s));
      sprite.flip(400,400);
      sprite.updatePosition();
    }
  }
  public void Draw(){    
    Sprite sprite;
    Random rand = new Random();
    int pix,r,g,b;
    int x1,y1,x2,y2;
    Color c;
    //this.Clear();
    //this was soom test code that did not alleviate the overall problem
    /* for (int i=0;i < 400;i++){
      for(int j=0;j <400;j++){
	r = Math.abs(rand.nextInt()) % 256;
	g = Math.abs(rand.nextInt()) % 256;
	b = Math.abs(rand.nextInt()) % 256;
	c = new Color(r,g,b);
	raster.setPixel(c.getRGB(),i,j);
      }}*/
    for (int s=0; s <sprites.size(); s++) {
      sprite = (Sprite)(sprites.elementAt(s));  

      x1 = 0;
      y1 = 0;
      x2 = sprite.width-1;
      y2 = sprite.height-1;
      if (sprite.location.x < 0) {
	x1 = -sprite.location.x;
      }
      if (sprite.location.y < 0) {
	y1 = -sprite.location.y;
      }
      if (sprite.location.x + sprite.width > raster.width) {
	x2 = raster.width - sprite.location.x;
      }
      if (sprite.location.y+sprite.height > raster.height) {
	y2 = raster.height - sprite.location.y;
      }
     
      
      for (int i=x1; i<x2; i++) {
	for (int j=y1; j<y2; j++) {
	  pix = sprite.getPixel(i,j);
	  if (pix <  8388607) 
	  raster.setPixel(pix,
			  i+sprite.location.x,
			  j+sprite.location.y);
	  
	}
      } 
    }
  }
    
}


  




	
  




