import objectdraw.*; import java.util.Random; import java.awt.Color; // a ball in a game of pong public class PongBall extends ActiveObject { // size of the ball private static final int BALL_SIZE = 30; // pause time in between movements private static final int PAUSE_TIME = 10; private double xspeed; private double yspeed; private FilledOval ball; private DrawingCanvas canvas; private FramedRect court; private FilledRect paddle; public PongBall(Location point, FramedRect court, FilledRect paddle, DrawingCanvas canvas) { ball = new FilledOval(point, BALL_SIZE, BALL_SIZE, canvas); this.canvas = canvas; this.court = court; this.paddle = paddle; Random rand = new Random(); yspeed = rand.nextDouble() + 1; if (rand.nextBoolean()) { yspeed = -yspeed; } xspeed = rand.nextDouble() + 1; if (rand.nextBoolean()) { xspeed = -xspeed; } start(); } public void run() { // move the ball repeatedly until it falls off screen while (ball.getY() < canvas.getHeight()) { ball.move(xspeed, yspeed); if (ball.overlaps(paddle) || ball.getY() < court.getY()){ yspeed = -yspeed; } if (ball.getX() < court.getX() || ball.getX() > court.getX() + court.getWidth() - ball.getWidth()) { xspeed = -xspeed; } pause(PAUSE_TIME); } ball.removeFromCanvas(); } }