/* * File: MyBouncingBall.java * ------------------------- * This program animates a bouncing ball */ import acm.graphics.*; import acm.program.*; public class MyBouncingBall extends GraphicsProgram { public void run() { /* center of the ball */ int ballX = getWidth() / 2; int ballY = getHeight() / 2; /* draw a ball at the center */ GOval ball = new GOval(ballX - BALL_RADIUS, ballY - BALL_RADIUS, 2*BALL_RADIUS, 2*BALL_RADIUS); ball.setFilled(true); add(ball); /* initial velocity */ int dx = 1; int dy = 1; /* animation */ for (int i = 0; i < N_STEPS; i++) { if ((ballX + dx < BALL_RADIUS) || (ballX + dx > getWidth() - BALL_RADIUS)) /* ball has hit the left or right wall */ dx = -dx; if ((ballY + dy < BALL_RADIUS) || (ballY + dy > getHeight() - BALL_RADIUS)) /* ball has hit the top or bottom wall */ dy = -dy; ball.move(dx, dy); /* update ball center position */ ballX += dx; ballY += dy; pause(PAUSE_TIME); } /* for i */ } /* private constants */ private static final int BALL_RADIUS = 20; private static final int N_STEPS = 2000; private static final int PAUSE_TIME = 20; }