import java.awt.Color;

/**
 * A human player in Pick up the Peanuts.
 *
 * @author Jim Glenn
 * @version 0.1 1/21/2009
 */

public class Player extends Sprite
{
    /**
     * The size of the human player.
     */

    public static final double DEFAULT_SIZE = 0.025;

    /**
     * The amount of time, in seconds, that this player takes to recover
     * from being trampled.
     */

    private static final double RECOVERY_TIME = 0.5;

    /**
     * Constants for state.
     */

    private static final int STATE_TRAMPLED = 1;

    /**
     * The direction this player will go when it recovers from being trampled.
     */

    private int recoverDx;
    private int recoverDy;

    /**
     * Creates a new human player at the given position.
     * The player will be red.
     *
     * @param initX an x-coordinate within the world this playwe will be in
     * @param initY a y-coordinate within the world this Player will be in
     */

    public Player(double initX, double initY)
    {
	super(initX, initY, DEFAULT_SIZE, Color.RED);
    }

    /**
     * Returns the maximum speed of this player.
     *
     * @return the speed
     */

    public double getMaximumSpeed()
    {
	return 0.2;
    }

    /**
     * Changes the velocity of this player so that it is moving in
     * the given direction.  Its speed will be set to the maximum.
     *
     * @param dx -1, 0, or 1
     * @param dy -1, 0, or 1
     */

    public void move(int dx, int dy)
    {
	if (getState() != STATE_TRAMPLED)
	    {
		setVelocity(getMaximumSpeed() * dx, getMaximumSpeed() * dy);
	    }
	else
	    {
		recoverDx = dx;
		recoverDy = dy;
	    }
    }

    /**
     * Tramples this player.  This player will not be able to move until
     * it recovers.
     */

    public void trample()
    {
	if (getState() != STATE_TRAMPLED)
	    {
		setState(STATE_TRAMPLED);
		recoverDx = 0;
		recoverDy = 0;
	    }
    }

    /**
     * Updates this player.
     *
     * @param t the time since the last update
     * @param m the model this player belongs to
     */

    public void update(double t, GameModel m)
    {
	if (getState() == STATE_TRAMPLED)
	    {
		if (getStateTime() > RECOVERY_TIME)
		    {
			setState(STATE_NORMAL);
			setVelocity(recoverDx, recoverDy);
		    }
		else
		    {
			setVelocity(0, 0);
		    }
	    }
	
	super.update(t, m);

	// do wraparound

	if (x < getBoundingRadius() / 2)
	    {
		x = m.getWidth() - getBoundingRadius() / 2;
	    }
	else if (x + getBoundingRadius() / 2 > m.getWidth())
	    {
		x = getBoundingRadius() / 2;
	    }

	if (y < getBoundingRadius() / 2)
	    {
		y = m.getHeight() - getBoundingRadius() / 2;
	    }
	else if (y + getBoundingRadius() / 2 > m.getHeight())
	    {
		y = getBoundingRadius() / 2;
	    }
    }
}

