import java.awt.*; import java.util.*; /** * A small ball object that wanders randomly around a bounded area. * * CSE143 lecture demo Au01, Sp03, Sp04 * * @author Hal Perkins * @version 10/18/01, 4/16/03, 4/12/04, 1/21/05 */ public class Ball implements SimThing { // instance variables private int x, y; // current coordinates of this Ball private int dx, dy; // current motion direction in x and y // (sign gives direction, magnitude // gives speed) private Color color; // color of this ball private int diameter; // size of this ball private int maxx, maxy; // max x and y coordiantes /** * Construct a new Ball with the given coordinates, initial direction, and model. * @param x initial x coordinate of center of the ball * @param y initial y coordinate of center of the ball * @param dx initial change in x value on each simulation cycle * @param dy initial change in y value on each simulation cycle * @param c color of the ball * @param diameter diameter of the ball * @param model the model that this Ball is a part of */ public Ball(int x, int y, int dx, int dy, Color c, int diameter, SimModel model) { this.x = x; this.y = y; this.dx = dx; this.dy = dy; this.color = c; this.diameter = diameter; this.maxx = model.getWidth(); this.maxy = model.getHeight(); } /** * Return the current horizontal location of the center of this Ball * @return the current x coordinate of the ball */ public int getX() { return x; } /** * Return the current vertical location of the center of this Ball * @return the current y coordinate of the ball */ public int getY() { return y; } /** * Perform an appropriate action on each cycle of the simulation, * in this case advancing by dx,dy and reversing either direction * if we hit an edge of the simulation. */ public void action() { x = x + dx; if (x < diameter/2 || x > maxx - diameter/2) { dx = -dx; } y = y + dy; if (y < diameter/2 || y > maxy - diameter/2) { dy = -dy; } } /** * Draw a graphical representation of this ball at the given coordinates. * @param g Graphics context where the drawing should occur * @param h Horizontal screen coordinate where the center of this SimThing should appear * @param v Vertical screen coordinate where the center of this SimThing should appear */ public void render(Graphics g, int h, int v) { g.setColor(color); g.fillOval(h-diameter/2, v-diameter/2, diameter, diameter); } }