import java.awt.*;
import java.awt.image.*;

class AnimatedSprite extends Sprite 
{
    int frames;         // frames in animation
    int width;
    int height;
    int current_frame;
    Raster[] order; //holds the order in which the frames
                 //should be played
    int x; //holds upper left
    int y; //coord of current frame
    int[] orderdx;
    int[] orderdy;
    
    public AnimatedSprite(Image first,int frames,Color transparent)
    {
        super(first, transparent);
        this.frames = frames;
        current_frame = 0;
        order = new Raster[frames];
        orderdx = new int[frames];
        orderdy = new int[frames];
        order[0] = new Raster(first);
        width = order[0].getWidth();
        height = order[0].getHeight();
        x=150;
        y=0;
    }
    
    public void addState(int index,Image image, int dx, int dy)
    {
        order[index] = new Raster(image);
        orderdx[index] = dx;
        orderdy[index] = dy;
    }
    
    public void nextState()
    {
        x+=orderdx[current_frame];
        y+=orderdy[current_frame];
        if (current_frame<frames-1)
        {
            current_frame++;
        }
        else
        {current_frame=0;}
    }
    
    public void Draw(Raster bgnd)              // draws sprite on a Raster
    {
        //initialization values assume no clipping
        int startx=0;//horiz offset in case clipped at left
        int starty=0;//vert offset in case clipped at top
        
        int tempw=width;//stores new height and width if sprite
        int temph=height;//is clipped
                        
                        
        //check if its clipped horizontally
        if ((x+width)>bgnd.getWidth()) //then clipped on right side
        {
            tempw = bgnd.getWidth()-x;
            startx = 0;
        }
        if (x<0) //then clipped on left side
        {
            tempw = width+x;
            startx = -x;
        }
        //check if its clipped vertically
        if (y<0) //then clipped at the top
        {
            temph = height+y;
            starty = -y;
        }
        if ((height+y)>bgnd.getHeight())//then clipped at bottom
        {
            temph = bgnd.getHeight()-y;
            starty = 0;
        }
        
        //draw the appropriate portion of the sprite in the right
        //place on the background
        for (int i=0;i<tempw;i++)
        {
            for (int j=0;j<temph;j++)
            {
                if (!(order[current_frame].getColor(i+startx,j+starty)).equals(transparent))
                {
                    bgnd.setPixel(order[current_frame].getPixel(i+startx,j+starty),startx+x+i,starty+y+j);
                }
            }
        }
    }
    
}