CPSC 124 (Winter 1998): Lab 3
Subroutines (Part 1)

THE THIRD LAB IN COMPUTER SCIENCE 124 deals with using subroutines that have been written for you and with writing the insides of subroutines whose basic format is already written for you. In the process, you will create an applet and learn something about how applets respond to event and how they can use multi-threading. You will also get more experience with using while statements and if statements. Next week, we'll move on to designing and writing complete programs that include subroutines that you write from scratch.

You'll need several project folders from the cpsc124 folder on the network. Copy the following folders into the java folder on your M drive: "Jumping Square Starter", "Mosaic Starter #1", and "Mosaic Starter #2". Each of these is the starting point for one of the exercises at the end of the lab.

Sample solutions for each of the exercises can be found on the following separate pages: Exercise 1. Exercise 2. Exercise 3.

The exercises at the end of the lab are due in class on the Monday following the lab.

Outline of the Lab:

About the MosaicFrame Class

A subroutine is a set of instructions for performing some task, chunked together into a "black box" and given a name. A programming language can have some built-in subroutines, like Math.random(), that are a part of the basic language and are always available. A programmer can also write new subroutines and then use them in the same way that built-in subroutines can be used. Of course, one programmer can also use subroutines written by another programmer. For example, you have already used subroutines defined in the Console class, which is not a standard part of Java but was provided to you to perform certain kinds of input/output tasks.

In the first two exercises of the lab, you will again be using subroutines that have already been written as methods in a class that is provided to you. The class is called MosaicFrame. An object in this class represents a window containing a grid of colored rectangles. Initially, all the rectangles are black, but methods are provided for setting the color of a given rectangle and for checking on the current color of a given rectangle.

You should open the folder "Mosaic Starter #1." (If you have not already copied it into the java folder of your M drive, do that now.) Execute the program. You'll see a small red rectangle that wanders around in a black window. (Actually, the "motion" is an illusion that is achieved by turning various little squares in the window from red to black and back again.) You will want to read the source file, MosaicApplication.java, since you will have to modify this file to do Exercise 1. You might also want to look at the comments in MosaicFrame.java, since that is the file that defines all the methods that have been provided for working with MosaicFrame windows. You'll only need a few of the methods, though, and those are mentioned below.

A MosaicFrame window can be created and opened with a statement such as:

MosaicFrame mosaic = new MosaicFrame(20,30);

The window created will have 20 rows and 30 columns of rectangle. Each rectangle will be 10 pixels by 10 pixels (so it is, in fact, a square). The name of the window is "mosaic", and this variable can be used to call methods for checking as setting colors. You can, of course, use a different name for the window, and you can use different numbers of rows and columns. It is also possible to specify the width and the height to be used for the rectangles. See the Java source code files for details.

If there are R rows in the window, then they are numbered from 0 to R-1. Similarly, if there are C columns, they are numbered from 0 to C-1. You can specify a particular rectangle by giving the number of the row that it is in and the number of the column that it is in. If you use row or column numbers outside the valid ranges, it won't crash the program. However, it's still an error and you might not get the effect that you want. I will be looking for this type of error when I grade your lab reports. You should try to avoid them by careful and thoughtful programming.

To use a MosaicFrame, you have to know a little about the way colors are specified on a computer. Any color that can be displayed on a computer is made up of some combination of the "primary colors," red, green, and blue. In MosaicFrame, the level of each primary color is given as an int number in the range 0 to 255. A color is specified by three numbers giving the levels of red, green, and blue in the color. Colors specified in this way are referred to as "RGB colors." A color with a red component equal to 0 contains no red at all; a color with a red component equal to 255 contains the maximum possible amount of red. Black is given by red, blue, and green components all equal to 0. White is given by all components equal to 255. (In MosaicFrame, if you try to use numbers outside the range 0 to 255 to specify a color, any number less than 0 will be treated the same as 0, and any number bigger than 255 will be treated the same as 255.)

Here are some methods that you can use with a variable, mosaic, of type MosaicFrame:

The following methods are used to find out the current levels of red, green, and blue in a given rectangle. The value returned by the routine would ordinarily be assigned to a variable of type int, as in: "b = mosaic.getBlue(r,c);"

Finally, here is a useful method that indicates whether or not the mosaic window has been closed by the user. The method returns a boolean value. In the sample program in "Mosaic Starter #1", this method is used in a while loop that continues as long as the window is open.

(Note, by the way, that the mosaic window is similar to the one that I describe in Section 3.6 of the text. However, in the text, color components are specified as real numbers between 0.0 and 1.0 instead of an integers between 0 and 255. I decided to switch to integers because integers are what are actually used in the computer to represent colors. Here is the source code for MosaicFrame and for another class, MosaicCanvas which it uses. You should not expect to understant the source code at this point in the course.)

A Better Random Walk

For your first exercise, you will modify the program in "Mosaic Starter #1" so that it does a more interesting kind of random walk. The effect that you will try to achieve is shown in a sample applet on a separate page. You should look at the example and read the comment on that page.

The changes that you have to make to MosaicApplication.java are actually fairly small, but you won't be able to do them easily unless you really understand how the original random walk program works. Read the source code, read the comments, and make sure you understand what is going on. (You can also read the source code here.)

You want to modify the program so that a "disturbance" wanders around the window. This is not much different from the wandering red square, except that the disturbance itself is invisible. Each time the disturbance visits a square, you want to read the level of green in that square, add 10 to that level (up to a limit of 255), and reset the color of the square.

You'll want to make the "delay" in the while loop pretty small to get a good effect. I use "mosaic.delay(5)" in my applet.

You might want to try this program using red, blue, or gray instead of green. (A gray color is one that has equal red, blue, and green components.)

Conversion Experience

For your second exercise, you should use the starter folder "Mosaic Starter #2." Copy it into the java folder on your M drive, if you have not already done so. Open the project in this folder, and execute the program. You get a window filled with randomly colored squares. This is produced by a single call to the method mosaic.fillRandomly(). (You can read the source code here.)

Your assignment is to add a while loop to the main() routine so that the program will behave like the sample solution to this exercise, which is shown as an applet on a separate page.

In your loop, you should first choose a random square by choosing a random row and a random column. Randomly select one of the four neighbors of that square, and convert the color of the selected square to the color of its selected neighbor.

(This program models, in a vague way, a population where people have a tendency to be like their neighbors or to join coalitions with their neighbors. Let's say each color represents a political party. Initially, everyone belongs to a different party. However, people look around at what their neighbors are thinking, and they have some tendency to be converted by their neighbor's opinion. What will happen in the long run? Remember that "extinction is forever." Once the last square of a give color is converted, that color is gone forever.)

The while loop you want to write has some similarities to the loop in "Mosaic Starter #1." In fact, you might want to copy-and-paste that loop into the program in "Mosaic Starter #2." However, the problem here is significantly different and you should not expect everything to carry over exactly. Think about what you want to do, and plan your while loop before you start working on it.

An Applet with Action

For the third exercise of the lab, you will be working on an applet. The starting point is the folder "Jumping Square Starter." Copy it to your M drive if you have not already done so. Open the project in the "Jumping Square Starter" folder and execute it. (You can also read the source code here.) The applet displays a red square in a random position. Each time the user clicks on the red square, it jumps to a new location. You'll also see that the number of seconds that have elapsed since the applet started is displayed in the upper left corner of the applet. (Note that the applet might flicker a bit when the time changes or when the square jumps. There is a way to fix this, but I am trying to keep things simple for now. We will return to this problem later in the course.)

Your assignment is to turn this modest little applet into a duplicate of the rather annoying applet that is shown on a separate page. The new version is a kind of game. The square jumps around randomly. The user tries to click on it. The applet keeps track of how may time the user hits the square and how many times the user misses. These numbers are displayed on the applet along with the elapsed time.

There are two different things going on in this applet: It responds to the event that occurs when the user clicks on the applet. And it has another process or thread that runs continuously, like a separate program. It is this thread that keeps track of the time. In the final version of the applet, the same thread also moves the square around even when the user doesn't click on it.

Here's how it works. First of all, the class MosaicApplet has a so-called "mouseDown" method, which takes the form:

         public boolean mouseDown(Event evt, int x, int y) {
               . // commands to be executed when user clicks in the applet
             return true;

This method is an event handler. It is a routine that is called by the system when the user clicks on the mouse. It is not ordinarily called from elsewhere in the program. Your job as a programmer is to write the inside of the mouseDown() routine to specify what should happen when the user clicks on the applet. The x and y parameters, which are provided by the system when the routine is called, tell you the horizontal and vertical coordinates of the point in the applet where the user clicked.

The other aspect of this applet is the separate thread that runs independently of user-generated events. The MosaicApplet class begins with the line

public class MosaicApplet extends Applet implements Runnable

To say that a class "implements Runnable" means, essential that it has a "public void run()" method that can be run as the program of an independent thread. In this example, the thread is created in the applet's start() method, which is called by the system when the applet starts to run. As soon as the thread starts, it begins to execute the run() method of the applet. The run() method is provided for the use of this thread, and it is not meant to be called directly. By filling in the run() method, you are in effect writing a program for the thread. Any class that contains a run() method can be used to create threads in the same way, and it is possible for a program to create many threads that are executed concurrently (in addition to the basic, original thread that I have been referring to as the "system.")

Your job is to make several modifications to the MosaicApplet class:

After your applet is created, you will want to publish it on the Web so that you can annoy your friends in California. To do this, you will have to use FTP to copy the files JumpingSquare.class and JumpingSquare.html to your account on hws3.hws.edu. If you don't remember how to do this, review Lab 1. You might want to edit JumpingSquare.html to add some text or make the page look a bit fancier. If you want some hints on maintaining your Web site, look back at Lab 2.

Exercises to Turn in

Exercise 1. Turn in a print out of the "random walk" program that you modified above. The work you did was all in the file MosaicApplication.java, and that is the only file you should turn in. Make sure that it follows good programming style. You will have to erase some of the comments that are there and replace them with your own.

Exercise 2. Turn in a print out of the MosaicApplication.java file for the "conversion" program that you wrote above. Again, make sure it follows proper style.

Exercise 3. For this exercise, turn in a copy of the JumpingSquare.java program that you modified above. For this one time, you don't have to worry about getting the comments right. I also want to check that you have successfully added the applet to your web site on hws3.hws.edu. Please give me the URL for your page.

Optional Extra-credit Exercise. If you like, you can get a few points of extra credit by making one of your "mosaic" programs from Exercise 1 or Exercise 2 into an applet and adding it to your Web site. Use the folder "Mosaic Applet Starter" as a starting point. Like the JumpingSquare applet, the MosaicApplet has a run() method. You should be able to copy your program (except for the line that creates the MosaicFrame) into the run method of the MosaicApplet. You might want to make up your own mosaic program. Be creative! You could even make the applet respond to mouse clicks by providing a "public void boolean mouseDown(Event evt, int x, int y)" method.

[ Lab Index | Online Notes ]