// // general purpose reusable bouncing ball abstraction // Described in Chapter 4 of // Understanding Object-Oriented Programming with Java // by Timothy A Budd // Published by Addison-Wesley // // see ftp://ftp.cs.orst.edu/pub/budd/java/ReadMe.html // for further information // import java.awt.*; /** * general class for Balls * * @version 1.0 * @author Timothy Budd * */ public class Ball { /** surrounding rectangle for the Ball */ protected Rectangle location; /** the initial delta along the x axis */ protected double dx; /** the initial delta along the y axis */ protected double dy; /** the color of the ball */ protected Color color; /** * Constructor to init both position and size * *
color is hard-coded to Color.blue * * @param x the initial x coordinate of the center * @param y the initial y coordinate of the center * @param r the radius of the cannonball */ public Ball (int x, int y, int r) { location = new Rectangle(x-r, y-r, 2*r, 2*r); dx = 0; dy = 0; color = Color.blue; } // functions that set attributes public void setColor (Color newColor) { color = newColor; } public void setMotion (double ndx, double ndy) { dx = ndx; dy = ndy; } // functions that access attributes of ball /** * recompute the radius of the ball from the surrounding rectangle * * @return the radius */ public int radius () { return location.width / 2; } public int x () { return location.x + radius(); } public int y () { return location.y + radius(); } public double xMotion () { return dx; } public double yMotion () { return dy; } public Rectangle region () { return location; } // functions that change attributes of ball public void moveTo (int x, int y) { location.setLocation(x, y); } /** * move the ball by the current @see dx and @see dy values */ public void move () { location.translate ((int) dx, (int) dy); } public void paint (Graphics g) { g.setColor (color); g.fillOval (location.x, location.y, location.width, location.height); } }