/**
 * A game of Pick up the Peanuts.  Pick up the Peanuts has a player
 * and an elephant who race to pick up peanuts.
 *
 * @author Jim Glenn
 * @version 2K9 translated to Java
 * @version 1.0 1982 or so in Atari BASIC
 */

public class PeanutsModel extends GameModel
{
    /**
     * The objects in this game.  Distinguished objects (OK, all of them)
     * are kept separately from the list for easy access.
     */

    private Player player;
    private Elephant elephant;
    private Peanut peanut;

    /**
     * Creates a new Pick up the Peanut game with player and elephant
     * at their starting positions (left and right respectively)
     * and a randomly placed peanut.
     */

    public PeanutsModel()
    {
	// create player near middle of left edge
	player = new Player(0.1, 0.5);
	addSprite(player);

	// create elephant near middle of right edge

	elephant = new Elephant(0.9, 0.5);
	addSprite(elephant);

	// throw a peanut at a random location

	makePeanut();
    }

    /**
     * Returns the current peanut in this game.
     *
     * @return the peanut
     */

    public Peanut getPeanut()
    {
	return peanut;
    }

    /**
     * Forwards move events to the player.  The direction is given
     * as an x- and a y-component.
     *
     * @param dx -1, 0, or 1
     * @param dy -1, 0, or 1
     */

    public void movePlayer(int dx, int dy)
    {
	player.move(dx, dy);
    }

    /**
     * Places a new peanut randomly in this game.
     */

    private void makePeanut()
    {
	if (peanut != null)
	    {
		removeSprite(peanut);
	    }

	peanut = new Peanut(Math.random(), Math.random());
	addSprite(peanut);
    }

    /**
     * Handles collisions between the given objects.
     *
     * @param s1 a sprite
     * @param s2 a sprite that has collided with s1
     */

    protected void handleCollision(Sprite s1, Sprite s2)
    {
	if (s1 instanceof Peanut || s2 instanceof Peanut)
	    {
		// swap to make s1 the one that ate the peanut

		if (s1 instanceof Peanut)
		    {
			Sprite temp = s1;
			s1 = s2;
			s2 = temp;
		    }

		if (s1 instanceof Player)
		    {
			// player ate the peanut
		    }
		else
		    {
			// elephant ate the peanut
		    }

		// make a new peanut

		makePeanut();
	    }
	else
	    {
		// must be player/elephant

		player.trample();
	    }
    }
}


