import java.awt.*;
import java.awt.image.*;

class Sprite extends Raster
{
	int x=0, y=0;           // current position of sprite on playfield
	boolean active = false; // set to true when the sprite was selected
							// if set to true, sprite will move to next mouse click
           
    public Sprite(Image img)     // initialize sprite with an image
    {
    	try {
            PixelGrabber grabber = new PixelGrabber(img, 0, 0, -1, -1, true);
            if (grabber.grabPixels()) {
                width = grabber.getWidth();
                height = grabber.getHeight();
                pixels = (int []) grabber.getPixels();
            }   
        } catch (InterruptedException e) {}
    }
    
   public boolean overlaps(int playfieldX, int playfieldY)
   //This procedure tests if a given playfield coord overlaps a non-transparent
   //pixel of the sprite at its current position  -- as required
   {
   //translate playfield's coord into sprite's
   	int xcoord = playfieldX-x;
   	int ycoord = playfieldY-y;
   	//check whether whithin sprite's bounds
   	if ((xcoord>=0) && (xcoord < width) && (ycoord>=0)&&(ycoord<height))
   	{
   		int alpha = (getPixel(xcoord, ycoord)) >> 24;
   		boolean transparent = ((alpha&0xFF) == 0) ? false : true;
   		return transparent;
   	}
   	else
   		return false;  //not in bounds ==> doesn't overlap
   }
   
    public void Draw(Raster img)       // draw a sprite on a Raster
    {
    	for (int i=0;i<pixels.length; i++)
    	{
     		int alpha = pixels[i]>>24;
     		boolean transparent = ((alpha&0xFF) == 0) ? true : false;
     		// assume (x,y) represent the top left corner of the sprite image	
     		if (!transparent)
     		{   //assume width != 0, i.e. images present
     			int xcoord = x+(i%width);
     			int ycoord = y+(i/width);
     			if ((xcoord < img.getWidth())&&(xcoord >=0) &&
     				(ycoord < img.getHeight())&& (ycoord >=0))  //clipping
	 	    		img.setPixel(pixels[i], xcoord, ycoord);
     		}   				
    	}
   }
      
   public void setActive()
   {
   		active = true;
   }
   
   public void setInactive()
   {
   		active = false;
   }
}

