import java.applet.*;
import java.awt.*;
import Raster;
import Sprite;

public class Project1 extends Applet {
    Playfield course;
    Sprite ball;
    Animated fan;
    int count = 0;
    int g_nX, g_nY, g_nGotBall = 0, g_nCurrX, g_nCurrY;

	//  Output images
	Image iCourse, iBall, iFan;

	/**
	 *  Intialize the sprites, and tell to render
	 */
    public void init()
    {
	  String filename = "ball.jpg";
	  showStatus("Using " + filename);
	  ball = new Sprite(getImage(getDocumentBase(), filename));
	  ball.SetBackgroundTransparency();
	  ball.x = 120;
	  ball.y = 364;
	  ball.sWidth = 13;
	  ball.sHeight = 13;
	  count = 0;

	  filename = "fantotal.jpg";
	  showStatus("Using " + filename);
	  fan = new Animated(getImage(getDocumentBase(), filename), 7);
	  fan.SetBackgroundTransparency();
	  fan.x = 16;
	  fan.y = -19;
	  fan.sWidth = 194;
	  fan.sHeight = 97;
	  
        filename = "course.jpg";
        showStatus("Using " + filename);
        course = new Playfield(getImage(getDocumentBase(), filename));

	Render();
    }

	/**
	 *  This function was originally implemented to reduce flickering,
	 *	but when implemented with threads ends up skipping frames
	 *    and actually looking much worse.  I returned to the simple
	 *	update method.
	 */
    public void Render()
    {
        iCourse = course.toImage(this);

	  ball.Move();

	  fan.nextState();

	  //  Check if made it into hole going slow enough
	  if((ball.PixelInside(113, 89) == 1) && (ball.m_fVel < 3.0f))
	  {
		showStatus("Made it!  Final score: " + count);
	  }
	  else
	  {	
		showStatus("Strokes: " + count);
		iBall = ball.Render(this);
	  }

	  iFan = fan.Render(this);
    }
	 
	/**
	 * 	This function does the actual painting
	 */ 
    public void paint(Graphics g)
    {	
 	  Render();

        g.drawImage(iCourse, 0, 0, this);

	  ball.Move();

	  fan.nextState();

        ball.Draw(g, iBall, this);

	  fan.Draw(g, iFan, this);

	  if(g_nGotBall == 1)
        {
		g.drawLine(g_nX, g_nY, g_nCurrX, g_nCurrY);
	  }
    }

    public void update(Graphics g)
    {
        paint(g);
    }

	/**  
       *  This function has to detect if we clicked on the ball or not.
       */
    public boolean mouseDown(Event e, int x, int y)
    {	
	  g_nX = g_nCurrX = x;
	  g_nY = g_nCurrY = y;
	  if((g_nGotBall = ball.PixelInside(x, y)) == 1)
		count++;
        return true;
    }

	/**
	 *  Mouseup applies a velocity to the ball if we had it
	 */
    public boolean mouseUp(Event e, int x, int y)
    {
	if(g_nGotBall == 1)
	{
		ball.ApplyVelocity(x-g_nX, y-g_nY);
	}
        g_nGotBall = 0;
        return true;
    }

	/**
	 *  If we clicked on the ball and are draggin now, draw the vector line
     	 */
    public boolean mouseDrag(Event e, int x, int y)
    {
	 if(g_nGotBall == 1)
	{
		g_nCurrX = x;
		g_nCurrY = y;
	}
	repaint();
        return true;
    }
}
