package examples.moveongrid;

import java.awt.Color;
import java.awt.Point;
import java.awt.geom.*;

import fang.GameLoop;
import fang.Sprite;

/**This example shows how to move
 * a circle smoothly on a 5 x 5 grid.
 * @author Jam Jenkins
 */
public class MoveOnGrid
			extends GameLoop
{
	/**this is the circle which moves
	 * around with the mouse*/
	private Sprite piece;

	private GridTracker gridTracker;

	/**adds the grid to the background
	 * and the circle in front*/
	public void startGame()
	{
		Grid grid=new Grid(5, 5, 0.1);
		grid.setScale(1);
		grid.setLocation(0.5, 0.5);
		canvas.addSprite(grid);

		Ellipse2D.Double circle=new Ellipse2D.Double(0, 0, 1, 1);
		piece=new Sprite(circle);
		piece.setScale(0.1);
		piece.setLocation(0.1, 0.1);
		piece.setColor(Color.YELLOW);
		canvas.addSprite(piece);

		gridTracker=new GridTracker(5, 5);
		gridTracker.setMoveTime(1);
		piece.setTracker(gridTracker);

		setHelp("resources/MoveOnGridHelp.txt");
	}

	/**gets the snapped to grid location
	 * @param point the horizontal and vertical
	 * screen location
	 * @return the snapped to grid column
	 * and row.  These are numbered 0...4.
	 */
	public Point getCell(Point2D.Double point)
	{
		int x=(int)Math.min(4, point.x*5);
		int y=(int)Math.min(4, point.y*5);
		return new Point(x, y);
	}

	/**moves the circle with the mouse.  When
	 * the user clicks, a circle is deposited
	 * in the nearest cell.
	 * @param timePassed not used
	 */
	public void advanceFrame(double timePassed)
	{
		//gets the position of a click
		Point2D.Double click=getPlayer().getMouse().getClickLocation();

		//a null click position means the
		//user did not click
		if(click!=null)
		{
			Point target=getCell(click);
			Point source=getCell(piece.getLocation());

			gridTracker.move(target.y-source.y,
			                 target.x-source.x);
		}
	}

	/**runs SnapToGrid as an application
	 * @param args not used
	 */
	public static void main(String[] args)
	{
		new MoveOnGrid().runAsApplication();
	}

}

