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

/**
 * This class implements a movable bitmapped object.
 */
public class Sprite extends Raster {
    protected int x, y;          // current position of sprite on playfield

    ////////////////////////// Constructors //////////////////////////

    /**
     * Initialize a sprite at the origin with an image i.
     */
    public Sprite(Image i) {
	super(i);

	x = 0; 
	y = 0;
    }

    /**
     * Initialize a sprite at point (x,y) with an image i.
     */
    public Sprite(Image i, int x, int y) {
	super(i);

	this.x = x;
	this.y = y;
    }

    ////////////////////////// Methods //////////////////////////

    /**
     * Draws the sprite on a Raster b.
     */
    public void draw (Raster b) {
	int xp, yp;     // xp and yp are the position of the current pixel in b
	int xmin, ymin; // xmin and ymin are the starting position in b 
	int fg, bg;     // fg and bg are the current fore/background pixels  

	// If position of sprite is off the left, start at left anyhow.
	if (x < 0)
	    xmin = 0;
	else
	    xmin = x;

	// If position of sprite is off the top, start at top anyhow.
	if (y < 0)
	    ymin = 0;
	else
	    ymin = y;

	// Go from xmin to end of sprite (x+width) or end of b (b.width).
	for (xp = xmin; xp < x+getWidth() && xp < b.getWidth(); xp++) {
	    for (yp = ymin; 
		 yp < y + getHeight() && yp < b.getHeight(); 
		 yp++) {
		
		fg = getPixel(xp-x,yp-y);
		bg = b.getPixel(xp,yp);
		b.setPixel(Pixel.over(fg,bg), xp, yp);

	    }
	}
    }

    /**
     * Undraws the sprite on a Raster b with the original background o.
     */
    public void undraw(Raster b, Raster o) {
	int xp, yp;     // xp and yp are the position of the current pixel in b
	int xmin, ymin; // xmin and ymin are the starting position in b 
	int fg, bg;     // fg and bg are the current fore/background pixels  

	// If position of sprite is off the left, start at left anyhow.
	if (x < 0)
	    xmin = 0;
	else
	    xmin = x;

	// If position of sprite is off the top, start at top anyhow.
	if (y < 0)
	    ymin = 0;
	else
	    ymin = y;

	// Go from xmin to end of sprite (x+width) or end of b (b.width).
	for (xp = xmin; xp < x+getWidth() && xp < b.getWidth(); xp++) {
	    for (yp = ymin; 
		 yp < y + getHeight() && yp < b.getHeight(); 
		 yp++) {
		b.setPixel(o.getPixel(xp,yp), xp, yp);
	    }
	}
	
    }

    /**
     * Returns true if point (i,j) is in a non-transparent part of the Sprite.
     */
    public boolean inside(int i, int j) {

	if ((i >= x) && (i < x + getWidth())
	    && (j >= y) && (j < y + getHeight())
	    && ! Pixel.isTransparent(getPixel(i-x, j-y))) {
	    return true;
	} else {
	    return false;
	}
    }

}
