import java.awt.*;
import java.awt.image.*;

class CarSprite extends AnimatedSprite
{
	// Background raster
	MyRaster background;
	
	int nXStart, nYStart;
	int nXDest, nYDest;

	final static int nMax = 10;
	int nNum;
	boolean bMove;

	// direction the car is facing
	boolean bFacingRight;

	public CarSprite(Image image, Image imageflipped, MyRaster bgnd)		// initialize sprite with 2 images
	{
		super(image, 2);
		addSprite(1, new Sprite(imageflipped));

		background = bgnd;

		nXStart = nXDest = background.getWidth()/2;
		nYStart = nYDest = background.getHeight()/2;
		setCenterPosition(nXStart, nYStart);

		nNum = 0;
		bMove = false;

		bFacingRight = true;
	}

	public void setDestination(int x, int y)
	{
		// If the user clicked on the sprite of the car
		if ((x >= getXPosition()) && (x < getXPosition() + getWidth()) &&
			(y >= getYPosition()) && (y < getYPosition() + getHeight()))
		{
			// If the mouse click hit a non transparent area, then don't do anything
			if (getAlpha(x-getXPosition(),y-getYPosition())>0)
				return;
		}
		nXStart = getCenterXPosition();
		nYStart = getCenterYPosition();
		nXDest = x;
		nYDest = y;
		nNum = 0;
		bMove = true;

		setSpeed((int)((nXDest-nXStart)/nMax), (int)((nYDest-nYStart)/nMax));

		if (bFacingRight != (nXDest >= nXStart))
			nextFrame();

		bFacingRight = (nXDest >= nXStart);
	}

	public void nextState()
	{
		if (!bMove)
			return;

		if (nNum==nMax)
		{
			bMove = false;
		}
		else
		{
			super.nextState();
			nNum++;

			// If the next step is in the ocean then return
			if (background.getColor(getCenterXPosition()+getXSpeed(), getCenterYPosition()+getYSpeed()).getRed()==0)
			{
				bMove = false;
			}
		}
	}
}