package ballworld; import cs101.lang.Animate; /** * The Bouncer class represents a Ball which maintains its own position * and velocity, and bounces off the walls of the world in which it resides. */ public class Bouncer implements Ball, Animate { private double x; // The current X-coordinate of this Ball private double y; // The current Y-coordinate of this Ball private double radius; // The current radius of this Ball private double xVel; // The current X-velocity of this Ball private double yVel; // The current Y-velocity of this Ball private World myWorld; // The world in which this Ball resides /** * Class constructor. * Initialize this instance of the Bouncer class. */ public Bouncer() { // Initialize the x and y velocities of this Bouncer object this.xVel = Math.random()-0.5; this.yVel = Math.random()-0.5; // Initialize the x and y position of this Bouncer object this.x = 0; this.y = 0; // Initialize the radius of this Bouncer object this.radius = 5; // Explicitly set myWorld to null this.myWorld = null; } /** * Returns current X-coordinate of this Ball. */ public double getX() { return this.x; } /** * Returns current Y-coordinate of this Ball. */ public double getY() { return this.y; } /** * Returns current radius of this Ball. */ public double getRadius() { return this.radius; } /** * Sets the world in which this ball resides to be "theWorld". */ public void setWorld(World theWorld) { this.myWorld = theWorld; } /** * Moves this Ball to the location at which the user clicked. */ public void userClicked(double atX, double atY) { this.x = atX; this.y = atY; } /** * If the user typed a 'd', removes this Ball from myWorld. Otherwise * ignores the keypress. */ public void userTyped(char key) { if (key == 'd') { this.myWorld.removeBall(this); } else { // Ignore keypress } } /** * This Ball's implementation of the Animate interface. Causes this Ball * to move in a direction until it hits the boundary of the world in which * it resides. When it hits a boundary, it "bounces" off of it * and begins to move in the opposite direction. */ public void act() { if (this.getX() + this.getRadius() >= this.world.getMaxX() || this.getX() - this.getRadius() <= this.world.getMinX()) { this.xVel *= -1; } if (this.getY() + this.getRadius() >= this.world.getMaxY() || this.getY() - this.getRadius() <= this.world.getMinY()) { this.yVel *= -1; } this.x += this.xVel; this.y += this.yVel; } }