COS 126

Bouncing Ball
Programming Assignment 9 (warmup)

Due: before precept Monday (do not submit)

Write a Java applet that simulates a bouncing ball within a window.

This program will not be graded, and you need to add only a few lines of code to the software that we provide. Do this before precept. Program 9 itself will be a similar, but more complex simulation. If you have not done this warmup, you will find it difficult to complete Program 9 on time.

Part 0. Your starting point is the code MovingBall.java,   Ball.java, and MovingBall.html in the directory /u/cs126/files/bounce. Copy these files, along with the image file sun.gif and the sound file splat.au, into an otherwise empty directory. Then, type the command javac MovingBall.java. This creates MovingBall.class, which is referenced as an applet in MovingBall.html. Interpreting this via

    appletviewer MovingBall.html
displays a window and shows the track of a ball moving from the center out at an arbitrary angle. A ball is described by its position and velocity for the x and y coordinates, which are represented as double precision numbers. Java also supports multimedia data types including images and sound. A .gif file of the sun is used to display the ball.

The animation is achieved by implementing a standard graphics technique known as double buffering: first, draw the ball to an offscreen page, and then copy the page to the screen all at once. Now, draw the ball at its new position to the offscreen page, and then copy to the screen. Using the second page makes the animation smoother and reduces flicker.

Part 1. Your first task is to fix the code so that the ball doesn't leave the window. The ``true coordinates'' of the ball are intended to fall in the in interval [-.5, .5]. These are converted to ``screen coordinates'' in the method show(). Your task is to make them stay in that range, by maintaining the illusion that the ball bounces off the side of the window. This change involves only a few lines of code.

Part 2. Add a sound effect when the ball collides with the side of the window. Using Java's built-in multimedia capabilities, this will be easy. In addition to a position and velocity, each ball also has a sound of type AudioClip associated with it. The initial ball uses the file splat.au as its sound. To play a sound associated with an AudioClip, simply use the play method: to play the sound clip stored in variable sound, use "sound.play();".

Part 3. Add a second ball, with different initial position and velocity. You may use the image earth.gif and the sound file gong.au or find your own on the web. You should find this to be very easy to do in this object-oriented program.

You can check java.sun.com and other websites, and try all manner of things to jazz up this program. You may wish to try some of these methods and/or change the .html file to gain some appreciation for what is involved. If you do make such changes, stand back!


Copyright © 2000 Robert Sedgewick