COS 126

Bouncing Ball
Programming Assignment 8 (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 8 itself will be a similar, but more complex simulation. If you have not done this warmup, you will find it difficult to complete Program 8 on time.

Your starting point is the code and MovingBall.html in the directory /u/cs126/code. Copy these files into an otherwise empty directory, then type the command javac 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.

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.

Second, add code to remove the tracking ``feature'' and just show the ball as it moves along. This involves implementing a standard idiom in graphics: to give the appearance of motion, ``erase'' the image of the ball at the old position before drawing it at the new position. The tricky part is to make sure that it stays displayed long enough for you to see it before you erase it! If you like, arrange to have the background in a light (or gray) color, the paths in white, and the ball in a dark (or black) color.

Third, add a second ball, with different initial position and velocity. You should find this to be very easy to do in this object-oriented program.

You can check, for example,
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!

Programming Assignment 8 involves having the balls move in more complicated paths than straight lines.

Copyright © 1998 Robert Sedgewick