/**
 *  The BouncingBalls class shows an example of how to create multiple turtles
 *  and have them run simultaneously.
 *
 */

import java.awt.*;
import javax.swing.*;
import java.util.*;
import com.otherwise.jurtle.*;

public class BouncingBalls extends Turtle
{

    private static int DELAY = 1;
    private static int SPEED = 5;
    private static int BALL_RADIUS = 5;
    private static Random rnd = new Random( System.currentTimeMillis() );


    /**
     *  Turtle constructor.
     */
    public BouncingBalls()
    {
        setHeading( rnd.nextInt( 360 ) );
        setPenColor( new Color( rnd.nextInt( 255 ),
                                rnd.nextInt( 255 ),
                                rnd.nextInt( 255 ) ) );
        setPenWidth( 1 );
    }


    /**
     *  Override the paintTurtle method to draw a ball rather than the 
     *  standard turtle triangle.
     */
    public void paintTurtle( Graphics g )
    {
        Point pt = getPosition();
        g.setColor( getPenColor() );
        g.fillOval( pt.x - BALL_RADIUS, pt.y - BALL_RADIUS,
                    2 * BALL_RADIUS, 2 * BALL_RADIUS );
    }

    /**
     * Entry point to the Turtle's code.  
     */
    public void runTurtle()
    {
        setAutoUpdate( false );
        //penUp();  // Comment this in to get balls without the lines
        Dimension size = getDisplaySize();
        Rectangle bounds = new Rectangle( 0, 0, size.width, size.height );
        int count = SPEED + 1;
        while ( true )
        {
            forward( 1 );
            double heading = getHeading();
            Point pt = getPosition();
            if ( !bounds.contains( pt ) )
            {
                if ( pt.x < 0 || pt.x > size.width )
                    setHeading( 360 - heading );
                else if ( pt.y < 0 || pt.y > size.height )
                    setHeading( 180 - heading );
            }
            if ( count++ > SPEED )
            {
                updateDisplay();
                pause( DELAY );
                count = 0;
            }
        }

    }


    /**
     *  Implement our own main() method so we can instantiate multiple BouncingBalls 
     *  turtles and start them.
     */
    public static void main( String[] args )
    {
        for ( int i = 0; i < 10; i++ )
            ( new BouncingBalls() ).start();
    }

}
