ColoredBall.java


Below is the syntax highlighted version of ColoredBall.java from §3.2 Creating Data Types.


/*************************************************************************
 *  Compilation:  javac ColoredBall.java
 *  Execution:    java ColoredBall
 *  Dependencies: StdDraw.java
 *
 *  Implementation of a 2-d ball moving in the square with x and y
 *  coordinates between -1 and 1. Bounces off the walls upon collision.
 *  
 *
 *************************************************************************/
import java.awt.Color;

public class ColoredBall { 

    // instance variables
    private double rx, ry;   // position
    private double vx, vy;   // velocity
    private double radius;   // radius
    private Color  color;    // color

    // constructor
    public ColoredBall() {
        rx = 0.5;
        ry = 0.5;
        vx = 0.015 - Math.random() * 0.03; 
        vy = 0.015 - Math.random() * 0.03; 
        radius = 0.025 + Math.random() * 0.05;
        color = Color.getHSBColor((float) Math.random(), 1.0f, 1.0f);
    }
   
    // move the ball one step
    public void move() {
        if ((rx + vx < radius) || (rx + vx > 1 - radius)) vx = -vx;
        if ((ry + vy < radius) || (ry + vy > 1 - radius)) vy = -vy;
        rx = rx + vx;
        ry = ry + vy;
    }

    // draw the ball
    public void draw() { 
        StdDraw.setColor(color);
        StdDraw.go(rx, ry);
        StdDraw.spot(2*radius);
    }



    // test client
    public static void main(String[] args) {

        // create and initialize two balls
        ColoredBall b1 = new ColoredBall();
        ColoredBall b2 = new ColoredBall();
        System.out.println("Memory address of b1 = " + b1);
        System.out.println("Memory address of b2 = " + b2);
        
        // animate them
        StdDraw.create(500, 500);
        StdDraw.setScale(0, 0, 1, 1);
        while (true) {
            StdDraw.clear(Color.black);
            b1.move();
            b2.move();
            b1.draw();
            b2.draw();
            StdDraw.pause(50);
            StdDraw.show();
        }
    }
}


Last updated: Thu Oct 21 07:44:42 EDT 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.