/* *****************************************************************************
 *  Description: Creates a bouncing ball animation.
 *
 *  Note: This version differs from the one in Booksite 1.5 in the initial
 *  position of the ball, and random factors for the velocity and radius.
 **************************************************************************** */

public class BouncingBall { 
    
    // everything is in main() as this is not an object-oriented program
    public static void main(String[] args) {

        // initialize standard drawing
        StdDraw.setXscale(-1.0, 1.0);
        StdDraw.setYscale(-1.0, 1.0);
        StdDraw.enableDoubleBuffering();

        // initial values, random velocity and size
        double rx = 0.0, ry = 0.0;                    // position
        double vx = 0.015 - Math.random() * 0.03;     // x velocity
        double vy = 0.015 - Math.random() * 0.03;     // y velocity
        double radius = 0.025 + Math.random() * 0.05; // size

        // main animation loop
        while (true)  { 
            // bounce off wall according to law of elastic collision
            if (Math.abs(rx + vx) > 1.0 - radius)
                vx = -vx;
            if (Math.abs(ry + vy) > 1.0 - radius)
                vy = -vy;

            // update position
            rx = rx + vx; 
            ry = ry + vy; 

            // clear the background
            StdDraw.clear(StdDraw.GRAY);

            // draw ball on the screen
            StdDraw.setPenColor(StdDraw.BLACK); 
            StdDraw.filledCircle(rx, ry, radius); 

            // display and pause for 20 ms
            StdDraw.show();
            StdDraw.pause(20);
        } 
    } 
} 
