import java.awt.*;
import java.util.*;
public class BouncingBall {
   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, int dx, int dy) {
		ballLocation.x += dx;
		ballLocation.y += dy;
		if (ballLocation.x > WINDOW_SIZE-BALL_RADIUS || 
		    ballLocation.x < BALL_RADIUS) {
		   dx = -dx;
		}
		if (ballLocation.y > WINDOW_SIZE-BALL_RADIUS || 
		    ballLocation.y < BALL_RADIUS) {
		   dy = -dy;
		}
	}
   public static void main(String[] args) {
	   Point location = new Point();
		Random randomizer = new Random();
		int dx, dy;
		DrawingPanel panel = new DrawingPanel(WINDOW_SIZE,WINDOW_SIZE);
		location.setLocation(
		   randomizer.nextInt(WINDOW_SIZE-BALL_RADIUS)+BALL_RADIUS,
		   randomizer.nextInt(WINDOW_SIZE-BALL_RADIUS)+BALL_RADIUS);
		dx = randomizer.nextInt(BALL_RADIUS)+1;
		dy = 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);
		   BouncingBall.drawBall(g,location);
			panel.copyGraphicsToScreen();
			// update location and delay
			BouncingBall.moveBall(location,dx,dy);
			panel.sleep(100);
		}
		panel.closeWindow();
	}
}