import objectdraw.*; import java.util.Random; // a ball in a game of pong public class PongBall extends ActiveObject { // size of the ball private static final int BALL_SIZE = 30; // speed of the ball private double yspeed = 0.1, xspeed = 0.1; // pause time in between movements private static final int PAUSE_TIME = 30; private FilledOval ball; private FramedRect court; private FilledRect paddle; private DrawingCanvas canvas; private Random rand = new Random(); public PongBall(Location point, FilledRect paddle, FramedRect court, DrawingCanvas aCanvas) { ball = new FilledOval(point, BALL_SIZE, BALL_SIZE, aCanvas); canvas = aCanvas; this.court = court; this.paddle = paddle; yspeed = (rand.nextDouble() - 0.5) / 2; xspeed = (rand.nextDouble() - 0.5) / 2; start(); } public void run() { double lastTime = System.currentTimeMillis(); // move the ball repeatedly until it falls off screen while (ball.getY() < canvas.getHeight()) { // determine how much time has passed double currentTime = System.currentTimeMillis(); double elapsedTime = currentTime - lastTime; // restart timing lastTime = currentTime; // move the ball the appropriate amount given the time passed ball.move(xspeed * elapsedTime, yspeed * elapsedTime); if (ball.getX() < court.getX() || ball.getX() > court.getX() + court.getWidth() - ball.getWidth()) { xspeed = -xspeed; } if (ball.overlaps(paddle) || ball.getY() < court.getY()){ yspeed = -yspeed; } // pass a bit more time pause(PAUSE_TIME); } ball.removeFromCanvas(); } }