import java.awt.*;
import java.util.*;
public class BouncingBallFixed {
   public static int BALL_RADIUS = 6;
	public static int WINDOW_SIZE = 300;
	/**
	 * draw the ball on the screen
	 */
	public static void drawBall(Graphics g, Point ballLocation) {
	   g.setColor(Color.YELLOW);
	   g.fillOval(ballLocation.x-BALL_RADIUS/2,
		           ballLocation.y-BALL_RADIUS/2,
					  BALL_RADIUS*2,
					  BALL_RADIUS*2);
	}
	/**
	 * move the ball and bounce at the edge of the screen
	 * @param ballLocation location of ball
	 * @param dx speed in x direction
	 * @param dy speed in y direction
	 */
	public static void moveBall(Point ballLocation, Point speed) {
		ballLocation.x += speed.x;
		ballLocation.y += speed.y;
		if (ballLocation.x > WINDOW_SIZE-BALL_RADIUS || 
		    ballLocation.x < BALL_RADIUS) {
		   speed.x = -speed.x;
		}
		if (ballLocation.y > WINDOW_SIZE-BALL_RADIUS || 
		    ballLocation.y < BALL_RADIUS) {
		   speed.y = -speed.y;
		}
	}
   public static void main(String[] args) {
	   Point location = new Point();
		Point speed = new Point();
		Random randomizer = new Random();
	   DrawingPanel panel = new DrawingPanel(WINDOW_SIZE,WINDOW_SIZE);
		// set a random location
		location.setLocation(
		   randomizer.nextInt(WINDOW_SIZE-BALL_RADIUS)+BALL_RADIUS,
		   randomizer.nextInt(WINDOW_SIZE-BALL_RADIUS)+BALL_RADIUS);
		// set a random speed
		speed.x = randomizer.nextInt(BALL_RADIUS)+1;
		speed.y = randomizer.nextInt(BALL_RADIUS)+1;	
		// keep going until there is a click
		while (!panel.mouseClickHasOccurred(DrawingPanel.LEFT_BUTTON)) {
		   Graphics g = panel.getGraphics();
			// clear, draw, then copy to screen
			// double buffering reduces flicker
			g.clearRect(0,0,WINDOW_SIZE,WINDOW_SIZE);
		   BouncingBallFixed.drawBall(g,location);
			panel.copyGraphicsToScreen();
			// update location and delay
			BouncingBallFixed.moveBall(location,speed);
			panel.sleep(100);
		}
		panel.closeWindow();
	}
}