Methods allow programs to add new procedural abstractions to the programming language. In this lab exercise, for example, you write a method to draw a composite stick figure.
Create a program that renders the (non-animated) stick figure shown to the right. There are a number of approaches to doing this; for the sake of this exercise, use the following algorithm, which includes a method that renders the stick figure:
This routine returns nothing (i.e., We suggest that you center the figure’s head at
coordinates ( Save this program for use in the next exercise. |
One nice feature of the code in the previous exercise is that it groups all the figure-drawing code in one appropriately named method. This improves the readability of the program and encourages reuse of that method.
Modify your previous program so that you can draw two stick figures in different locations (as shown on the right). You can do this as follows:
Save this program for use in the next exercise. |
Methods can also return values. This is useful when your program must compute a certain value frequently.
Modify your previous program so that it animates the two stick figures using Brownian motion (as shown on the right). You can do this as follows:
When you have this code working, let it run for a while. There
is a good chance that at least one of the figures will wander
“off” the output window. Fix this by constraining each of
your coordinate values to be on the visible output window (using
This method can receive either an x coordinate or a y
coordinate, and returns a new, legal value based on its arguments. For
example, if Save this program so that you can turn it in later. |
Methods are valuable for building useful procedural abstractions. We don't need to restrict ourselves to parameterizing just the x-y coordinates of the stick figure.
Modify your program to animate a growing (or shrinking) stick figure. The example on the right shows two stationary figures, each growing at different rates. Implement this as follows:
Save the final version of your program so that you can turn it in later. |
Modify your program so that the color of the stick figure is based on how far it is from the other figure. For example, the image to the right shows two animated stick figures that get redder the closer they get to the sun. To do this, you’ll need to use a distance method such as the one we developed in the lecture and the text. |
Submit all the code and supporting files for the exercises in this lab.