import java.awt.*;
import java.awt.image.*;

/*
 
	This class implements an animated sprite.  It is somewhat of a pain
in an Object-Oriented sense, because there is a good amount of code duplication
in the Draw() function.  Possibly, a drawline() function in the Sprite class
would allow some cleanup, but would incur a bit of overhead, due to the
function call.

*/

public class AnimatedSprite extends Sprite
{
	int framecount;
	int currentframe;
	int framesize;
	boolean switcher;
	
	public AnimatedSprite ( Image image, int xpos, int ypos, int frames )
	{
		super(image,xpos,ypos);
		framecount = frames;
		currentframe = 0;
		framesize = width/framecount;
		switcher = false;
	}

/* 
	The switcher variable is somewhat a toy to allow the user to switch
the direction of animation.  There probably should be a function to set up an
animation order of events and have the code cycle through, but the whole thing
is a real kludge anyway.

*/	
	public void nextFrame()
	{
		if (switcher)
		{
			if(++currentframe >= framecount)
			currentframe = 0;
		}
		else
		{
			if(--currentframe <= 0)
			currentframe = framecount-1;
		}	
	}
	
	void action()
	{
		switcher = !switcher;
	}
	
	public void nextFrame(int frameno)
	{
		currentframe = frameno;
	}
	
	public boolean query(int xpos, int ypos)
	{
			if (x <= xpos)
			if (y <= ypos)
				if (y+height >= ypos)
					if (x+framesize >= xpos)
					{
						int soffset = (ypos - y)*width + framecount*framesize + xpos - x;
						if (ColorModel.getRGBdefault().getAlpha(pixel[soffset]) > 0)
						{
							return true;			
						}
					}
			return false;
    }

/*
	This is a little different from the Sprite Draw() function, mainly 
because it has to adjust for the frame number.  Other than that, the Sprite
was pure boilerplate.

*/
	public void Draw(Raster bgnd)
	{
		int xpos = x, ypos = y;
		int destx, desty;
		int maxx, maxy;
		desty = ypos;
		destx = xpos;

		int homex = framesize*currentframe;
		int rastpixel[] = bgnd.getPixels();
		
		if (xpos > bgnd.width || ypos > bgnd.getHeight()) return;
		maxx = framesize+destx > bgnd.getWidth() ? bgnd.getWidth()-destx : framesize;
		maxy = height+desty > bgnd.getHeight() ? bgnd.getHeight()-desty : height;
		for ( ypos = 0; ypos < maxy; ++ypos)
		{
			ColorModel color = ColorModel.getRGBdefault();
			int soffset = ypos * width;
			int doffset = desty * bgnd.getWidth();
			destx = x;
			++desty;
			for ( xpos = homex ; xpos < homex+maxx ; ++xpos, ++destx)
			{
				if (doffset + destx > bgnd.size())
				{
				return;
				}
				if (color.getAlpha(pixel[soffset+xpos]) == 255)
				{
					rastpixel[doffset + destx] =  pixel[soffset+xpos];
				}
			}
		}
	}
}
