/** * Ball -- represents one ball in the Ball World application * @author Rhys Price Jones * @version 14xi08, revisited 23ii11 */ import java.awt.*; public class Ball implements CanBeTold { protected Canvas canvas; protected int xpos, ypos; protected int xvelocity,yvelocity; protected int diameter; protected Color color; // Construct a ball of diameter d at (x, y) moving at (xv, yv) on Canvas c public Ball(Canvas canvas, int x, int y, int xv, int yv, int d, Color c) { xpos = x; ypos = y; xvelocity = xv; yvelocity = yv; diameter = d; color = c; this.canvas = canvas; } // Two getters and two setters // in case we want to reuse this code (currently not used) public int getXVelocity(){ return xvelocity; } public int getYVelocity(){ return yvelocity; } public void setXVelocity(int xv){ xvelocity = xv; } public void setYVelocity(int yv){ yvelocity = yv; } // How the ball moves around the campus public void move(){ // by making width and height be recomputed at each // call to move() the application will immediately // respond to resizing by the user. int width = canvas.getWidth(); int height = canvas.getHeight(); xpos+=xvelocity; // advance in the horizontal direction, but... if(xpos+diameter > width){ // if you've gone over the right xpos = xpos - 2*(xpos+diameter-width); // bounce back xvelocity = -xvelocity; } if(xpos < 0){ // if you've gone over the left edge xpos = -xpos; // bounce back xvelocity = -xvelocity; } ypos+=yvelocity; if(ypos+diameter > height){ // if you've gone over the bottom ypos = ypos - 2*(ypos+diameter-height); // bounce yvelocity = -yvelocity; } if(ypos < 0){ // if you've gone over the top ypos = -ypos; // bounce yvelocity = -yvelocity; } } public void draw(){ // Would it be more efficient to set myGraphics as an instance // variable, just once in the constructor? // Or is it better to recompute it every time we draw the ball? // See comments in method move() above. // Is that point applicable here too? Graphics myGraphics = canvas.getGraphics(); myGraphics.setColor(color); myGraphics.fillOval(xpos,ypos,diameter,diameter); } public void respond(){ move(); draw(); } }