Talking to ActiveObjects |
We looked at a version of the basketball program in which the ball bounces to see how the main (extension of WindowController) class could interact with an active object. In Frogger, the vechicles and frog will also interact.
The ActiveObject has a method stopDribbling which simply sets the variable moving equal to false which in turn quickly causes the loops to terminate.
NOTE: We have labelled the declaration of "moving" to be "volatile" because 2 different threads acess it. Because of the compexities of computer memory and various optimizations performed by the compiler, current values of variables may not be held in memory. That is fine if there is only one thread accessing the variable, as it can keep track, but it fails miserably if there is more than one thread because they don't know about each other.
THE BOOK DOES NOT TALK ABOUT THIS!! This used to not show up in practice, but with multicore computers, it is much more important. Whenever you have two threads accessing (or updating) the same variable, you must declare it to be volatile.
One interesting thing that becomes obvious in the while loops of the bouncing ball run method is a feature of many loops -- they tend to be preceded by one or more statements that "initialize" the variables that are changed within the loop. That is, we have described the general structure of most loops as:
while ( some condition ) { do something depending on some variables change the variables used }
a more complete template would be:
set initial values of variables used in loop. while ( some condition ) { do something depending on some variables change the variables used }
Note: While it is beyond the scope of our discussion here, those who care can look at the example and discover how to use sounds in your programs. The sounds should be stored in ".au" files (this implies a standard audio format). They should be placed in the "classes" subdirectory of your JBuilder project.
Inside any class that manipulates a sound, you will need to
include java.applet.AudioClip;
In your WindowController (usually in the begin method), you can access a sound file by saying
getAudioClip("nameoffile.au")
this will return an object of class AudioClip which you should assign to an appropriate variable.
Once you have assigned a name to your AudioClip, invoking the play method on the AudioClip will play the sound. For example, in the loop above we say:
bounce.play();
Talking to ActiveObjects |