BouncingBall.java


Below is the syntax highlighted version of BouncingBall.java.


/*************************************************************************
 *  Compilation:  javac BouncingBall.java
 *  Execution:    java BouncingBall
 *  Dependencies: StdDraw.java
 *  Implementation of a 2-d bouncing ball in the box from (-1, -1) to (1, 1).
 *
 *  This code is already complete. You will make an object-oriented version
 *  of it as described in the next file.
 *  
 *  The 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 { 
    public static void main(String[] args) {

        // set the scale of the coordinate system
        StdDraw.setXscale(-1.0, 1.0);
        StdDraw.setYscale(-1.0, 1.0);

        // 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.setPenColor(StdDraw.GRAY);
            StdDraw.filledSquare(0, 0, 1.0);

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

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