Learn how to write program code to set the stage for your Alice animation programs. Also learn how to use concurrent programming to improve the appearance of your animations.
Last Updated: August 27, 2007
By Richard G. Baldwin
Alice Programming Notes # 125
Part of a series
This tutorial lesson is part of a series designed to teach you how to program using the Alice programming environment under the assumption that you have no prior programming knowledge or experience.
Have some fun
Because Alice is an interactive graphics 3D programming environment, it is not only useful for learning how to program, Alice makes learning to program fun. Therefore, you should be sure to explore the many possibilities for being creative provided by Alice while you are learning to program using these tutorials. And above all, have fun in the process of learning.
The main theme of the earlier lesson titled "Setting the Stage Manually, Part 2" (see Resources) was to teach you how to interactively call methods on objects, primarily to use that process as an alternative to moving and rotating objects with the mouse while setting the stage. I also explained how this capability can be used to test short animation sequences one step at a time before committing them to animation code.
Properties, methods, and functions
I taught you about the properties, methods, and functions that belong to each object. I explained how to distinguish between methods and functions. Following that, I concentrated primarily on calling methods interactively, but I also made some use of properties later.
Exposing the red, green, and blue axes
I explained the need, and showed you how to expose the red, green, and blue coordinate axes belonging to an object in order to be able to execute the proper amount of yaw, pitch, and roll on that object during the animation process.
Viewpoint
I explained the concept of viewpoint as used in the Alice programming environment.
Initial alignment of the world
I taught you how to "zero out" the world by causing the viewpoints of all of the objects in the world to be aligned with the viewpoint of the world. I recommended that you do this at the beginning of every program, whether you are setting the stage manually or are setting the stage in program code.
Setting display preferences
I taught you how to set your display preferences to cause certain text material to be displayed in Java style rather than Alice style. I recommended that you do this because it will better prepare you to move on to languages such as Java, C++, and C# later.
The potential for collisions
I taught you a little about collisions and explained that an animation program normally needs to know the viewpoints of all objects in order to properly deal with collisions.
Making interactive method calls
I taught you how to make interactive method calls to set the viewpoint for an object.
I provided a list of methods that may be useful for making interactive method calls.
A repeatable viewpoint for the camera
I explained the reasons why, and then taught you how to set a repeatable viewpoint for the camera. In so doing, I related the directions in the world to the points on a compass.
The right-hand rule and the airplane rule
I taught you about the right-hand rule and the airplane rule as two different aids for visualizing the effects of causing an object to undergo yaw, pitch, and roll.
Controlling the motion of body parts
I showed you how to interactively call methods to control the motion of the body parts of an actor, using the lower portion of the left leg and the left foot of an ice skater as an example. In the process, I showed you how to use properties to cause a body part to become invisible in order to expose the red, green, and blue axes belonging to the object.
A short preview of animation
In the way of a preview, I explained some of the things that you will encounter once you start incorporating method calls in executable animation code.
I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the figures and listings while you are reading about them.
Once you have mastered Alice, I recommend that you also study the other lessons in my extensive collection of online programming tutorials. You will find a consolidated index at www.DickBaldwin.com.
In the earlier lesson titled "Learn to Program using Alice, Setting the Stage Manually, Part 2" (see Resources), I taught you something about methods. I taught you how to interactively call various methods to manipulate the players in a world. I explained that the ability to interactively call methods provides at least the following two benefits:
I explained that future lessons would use program code to do most of the work required to set the stage. I also explained that program code would be used to write animation programs.
Your first introduction to Alice programming
In this lesson, I will present and explain six programs that use program code to replicate (and in some cases to improve upon) the things that you accomplished using interactive method calls in the earlier lesson.
The first four programs will emphasize setting the stage by executing program code. Each of these programs will accomplish essentially the same thing, but each program will illustrate better program design than the ones before it.
The last two programs will emphasize improvements in the animation process, culminating with the use of concurrent programming.
In this lesson, I will concentrate on the mechanics of writing simple Alice programs. In subsequent lessons, I will teach you the finer points of programming including such things as program design, program logic, etc.
Executable files are available
Executable files for the programs presented in this lesson are available for downloading in Alice a2w format (see Downloads). To view these programs in action, just download the zip file, extract the files into a folder of your choice, and open them one at a time in your Alice environment.
Program behavior
When writing the first four programs in this lesson, you will create a new world and populate it with a parking meter and an ice skater. Program execution will consist of the following actions in sequence:
The last two programs will emphasize improvements in step 4 in the above list of steps.
At any point during the writing of the program code, you can click the Play button to see what you have accomplished so far.
Setting the display style to Java Style in Color
For all of the programs in this and subsequent lessons, you should begin by using what you learned in an earlier lesson to make certain that your display preference is set to Java Style in Color. This will better prepare you for moving on to other languages such as C++, C#, and Java later.
The program named Alice0125a
A complete listing of this program is shown in Listing 11 near the end of this lesson.
All of the program listings in this lesson were created by pulling down the File menu in the Alice development environment and selecting the menu item titled Export Code For Printing. That causes the program to be written into an HTML file with a name of your choosing. You can open that file for viewing in any modern web browser. If you don't know what an HTML file is, don't worry about it. It isn't important insofar as learning to program in Alice is concerned.
Creating your new world
In previous lessons, you learned how to create a new world and how to populate that world with objects. Create your new world and populate it with a parking meter and an ice skater positioned approximately as shown in Figure 1.
Figure 1. New world populated with parking meter and skater.
Return to the Code Edit screen
Once you finish populating your new world, it would be a good idea to pull down the File menu and save your program in a directory of your choosing with a file name of Alice0125a. Then click the large Done button on the right side of the screen to return to the Code Edit screen. It will look something like Figure 2 except much larger.
Figure 2. Code Edit screen.
The Code Edit pane
You will use drag-and-drop operations to write your program code into the large edit pane in the bottom right portion of the screen. The edit pane is empty in Figure 2. After you have finished writing your program, the edit pane will look something like that shown in Figure 3, except that the screen shot in Figure 3 was reduced in size to make it fit into this narrow publication format.
Figure 3. Edit pane containing program code.
The drag-and-drop programming paradigm
To write programs in Alice, you drag tiles from other parts of the screen and drop them into the edit pane. Mainly, you drag tiles from the areas immediately to the left and immediately below the edit pane, but there may be occasions when you drag tiles from other locations as well.
The edit pane at startup
When you begin a new program, and before you drag any tiles into the edit pane, the words Do Nothing will appear in the edit pane. The first tile that you drop into the edit pane will replace those words with a line of program code.
|
Positioning your tile before you drop it
When you drag a tile to create a new line of code and hover at the edit screen, a green horizontal line will appear. You can move the line up and down the screen within the contents of the edit pane by dragging the tile up and down accordingly. Whenever the line is in the correct position, and the border on the tile that you are dragging is green, you can drop the tile. (Don't drop a tile when its border is red.) When you drop the tile, it will produce a line of program code at the position of the green line.
Filling in the blanks
Sometimes you need to drag a tile to replace something in an existing line of program code instead of creating a new line of program code. In that case, you will see a green box instead of a green line. When you drop the tile, that will cause code to appear in place of the green box.
Each tile has a handle
If you look carefully at the tiles in Figure 3, you will see that there is an area on the left end of each tile containing a large number of dots. This is a handle, which is meant to be the place that you grab a tile with the mouse in order to drag it. Sometimes you can drag a tile by grabbing it somewhere other than at the handle, but it is probably a good idea to use the handle.
Easier to do than to describe
This is actually easier to do than it is to describe. You should practice dragging and dropping tiles into the edit pane until you get the feel of it.
If you create a line of program code and decide later that you really don't need it, just drag it to the top of the screen and drop it into the trash can. You can also right-click on the handle and a popup menu will appear with a delete option. You can also use that option to get rid of lines of program code that you no longer need.
Disabling code
A common approach to debugging programs is to disable some of the code and allow the remaining code to execute in an attempt to isolate the code that is causing a problem. You can disable code one line at a time, or one block at a time by right-clicking the handle and then selecting disable in the popup menu that appears. To re-enable the code, just right-click the handle on the disabled code and select enable in the popup menu.
Rearranging lines of code
If you need to rearrange the order of lines of program code, you can simply drag the individual lines up and down the screen to rearrange them into a different order.
Some preliminary information
As I explained earlier, the entire program listing for your first program is shown in Listing 11 near the end of the lesson. For the time being, you can ignore everything in the listing down to the line that reads as follows:
public void my_first_method ( ) {
I will explain everything above that line in future lessons.
|
The beginning of my_first_method
The line of code shown above indicates the beginning of a method named my_first_method. About all you need to know about this method at this point is:
Let's be a little more specific
To be a little more specific, the syntax (format) for every method consists of a signature and a body.
The signature of this method is everything to the left of the "{" character in the line of text shown above.
The body consists of everything between that "{" character and a "}" character (at the end of the skeleton). The body of the skeleton is empty when you create a new world.
We will populate the body of the method with comments and program instructions to accomplish the goals of the program.
Will explain in fragments
Throughout this and subsequent lessons, I will explain the programs in fragments. The code fragment that you see in Listing 1 was copied from the complete program listing in Listing 11. (All of the program listings in this lesson were produced using the display format "Java Style in Color.")
Listing 1. Align objects to the world.
// Align objects to the world |
ground .setPointOfView( world ); |
parkingMeter .setPointOfView( world ); |
iceSkater .setPointOfView( world ); |
Align the objects with the world
In an earlier lesson, you learned how to select objects from the object tree and interactively call methods on those objects to cause the center point and the orientation (viewpoint) of all of the objects (including the ground, which looks like ice or snow in this program) to be aligned with the viewpoint of the world. The program code shown in Listing 1 will do that automatically, and you should recognize the syntax as being very similar to the syntax that you used to interactively call the same methods.
A slightly different format
Note that program code has a slightly different format when it appears on the edit screen than it does when it appears in an output program listing. Listing 1a shows a screen shot of the actual edit screen for the code fragment from the output code listing shown in Listing 1.
Listing 1a. The actual edit screen format for Listing 1.
Procedure for writing the code
To write this code, select the ground object in the object tree and select the methods tab in the details panel below the object tree. You should recognize the names of many of the methods in the details panel as being the same as the methods that you called interactively in the earlier lesson.
When you interactively called a method in the earlier lesson, you were usually required to work through a series of menus to specify the parameters that you wanted to pass to that method. The process is very similar when writing program code.
Your first line of program code
|
Write two more lines of code
Now replicate the bottom two lines of code in Listing 1a by first selecting parkingMeter and later selecting iceSkater in the object tree and dragging the setPointOfView method tile for each of those objects into the edit pane.
Write a comment
In Alice, C++, C#, and Java, comments begin with //. (C++, C#, and Java may also allow other formats for comments.) The purpose of comments is solely to provide information to humans. They have no effect on the program.
To replicate the comment in Listing 1a, drag the tile showing // from below the edit pane and drop it right above the first line of program code. It should appear there as a comment with the words No comment. Click on those words and replace them with the words Align objects to the world.
Congratulations, you can now play your world
You have now written your first set of sequential Alice program instructions. Click the Play button in the upper-left corner to "play your world".
As the program runs, you should see the ice skater and the parking meter move to the same spot on the ground. When the motion stops, the ground, the parking meter, and the ice skater will all have been aligned with the center point of the world. Your final screen should look something like Figure 4.
Figure 4. Objects aligned with the world.
|
Since we haven't established a fixed camera viewpoint yet, your picture may look different from mine. The important point is that the parking meter and the ice skater should be located at the same spot on the ground when the code that you created finishes executing.
Click the Stop button in the World Running window to get back to the Code Edit screen.
Set the camera to a known viewpoint
In the earlier lesson, you learned how to set the camera to a known viewpoint. The code in Listing 2 will accomplish the same thing that you accomplished manually in the earlier lesson.
Listing 2. Set the camera to a known viewpoint.
// Set the camera to a known viewpoint |
camera .setPointOfView( ground ); |
camera .turn( RIGHT , 135/360 revolutions ); |
camera .moveAwayFrom( target = parkingMeter , amount = 10 meters ); |
camera .move( UP , 1.5 meters ); |
This code will:
Procedure for writing the code in Listing 2
Begin by creating the comment shown in Listing 2 immediately below the code that you have already placed in the edit pane.
Select the camera in the object tree and then drag the method tiles identified in Listing 2 into the edit pane below the comment. For each case, select the method parameters shown in Listing 2.
Now play your world again
Play your world again. You should see a lot of ugly things happening as the camera moves around seeking its final viewpoint. (We will make those actions invisible later.) You should end up with an image very much like that shown in Figure 5. Once again, the skater and the parking meter are occupying the same spot on the ground and have the same orientation.
Figure 5. Objects aligned and camera set to known viewpoint.
Set skater to her starting viewpoint
At this point, all the objects have been aligned with the world and the camera has been set to a known viewpoint. The next step is to set the viewpoints that the objects are to occupy when the show begins.
We will leave the parking meter at its current viewpoint and adjust the viewpoint of the ice skater to that indicated in Listing 3.
Listing 3. Set skater to her starting viewpoint.
// Set skater to her starting viewpoint |
iceSkater .turn( RIGHT , 0.25 revolutions ); |
iceSkater .moveAwayFrom( target = parkingMeter , amount = 2 meters ); |
By now, you should know how to write the code to match the code in Listing 3 without help from me. Write the code and then play your program.
The stage is set
When this code finishes executing, the stage has been set and we are ready for the show to begin. The camera and all of the objects have a known viewpoint relative to the center point of the world. The image in your World Running window should look very much like Figure 6.
Figure 6. The stage is set.
Improvements to be implemented later
Later, you will learn how to:
Let the show begin
In an earlier lesson, we used interactive method calls, examination of the axes for the skater's lower leg and foot, consideration of yaw, pitch, and roll, and some other things as well, to determine how to cause the skater to bend her left leg at the knee and to point her toes out behind her. Once we figured out how to do everything correctly, the code turned out to be fairly simple. The program code that emulates our earlier interactive method calls is shown in Listing 4.
Animate the skater's leg and foot
Write the code shown in Listing 4 and add it to the code that is already in the edit window.
Listing 4. Animate the skater's leg and foot.
// Animate the skater's leg and foot |
iceSkater.leftLeg.lowerLeg .turn( FORWARD , 0.25 revolutions ); |
iceSkater.leftLeg.lowerLeg.foot .turn( FORWARD , 0.12 revolutions ); |
Now play your program.
|
After the code is executed to set the stage, the skater should bend her knee, and then bend her ankle to cause her toes to point away from her body, ending up in the position shown in Figure 7.
Figure 7. Skater position at the end of the show.
When we first start learning to program, it is tempting to write large programs as a very long sequence of programming instructions. However, that is not good programming style. Programs written in that style have a number of problems, not the least of which is simply the difficulty of scrolling up and down the screen to find what we need while we are editing and developing the program.
Need to separate the code into modules
It is better programming style to break a program up into a group of related modules. That is the purpose of methods and functions in Alice.
Re-usable code
One of the reasons for breaking code up into modules, (such as Alice primitive methods and functions), is to make them easily re-usable. For example, the world object has a function named Math.sqrt that can be called to compute and return the square root of a number. The members of the Alice team at Carnegie Mellon were good enough to write that code for us and to provide it in the form of a standard Alice function. As a result, whenever we need to compute the square root of a number, we don't need to "reinvent the wheel" and write that code ourselves. Rather, all we need to do is to re-use the code written by the Alice team by calling the function.
If we need to compute the square roots of ten different numbers at ten different times during the execution of the program, we can simply call the sqrt function ten times passing each different number as a parameter when we make the call. It isn't necessary to duplicate all of the code necessary to compute the square root of a number each time a square root value is needed.
Better program organization
Another reason for breaking a program up into modules is simply to provide better program organization. For example, the program that we discussed earlier in this lesson had two distinctly different sections of code:
Setting the stage
One section of code was used to set the stage. That section of code involved aligning all of the objects with the center point of the world, setting the viewpoint of the camera to a known viewpoint, and setting the viewpoint of the parking meter and the skater to their prescribed viewpoints for the beginning of the show.
It makes a lot of sense to break this code out into a separate module. In fact, it might make sense to break it out into three different modules, where each module accomplishes one of the actions listed above. However, in this program, I will combine all three of those actions into a single method (module) named setTheStage.
Presenting the play
The other distinctly different section of code in the program discussed above is the code that animates the skater's leg and foot. That is the only part of the action that is intended to be seen by the viewer. I will break that code out into a separate method (module) named playTheShow.
The main method
As I explained earlier, whenever you create a new world, an empty skeleton of a method named my_first_method is automatically created as a method belonging to the world. By default, each time you play your program, this method will be executed first. (This default behavior can be changed, but we won't get into that in this lesson.)
The Java, C#, C, and C++ programming languages all have a method or function that is executed first when a program written in one of those languages is executed. In those languages, that method or function is named either main or Main, depending on the language. To be consistent with those languages, beginning with the program in this section of this lesson and continuing into future lessons, I will rename the method named my_first_method to main.
Renaming the method
To rename the method, do the following:
The program named Alice0125b
The behavior of this program is the same as the behavior of the program named Alice0125a that I explained above. Only the program organization is different. Therefore, I will explain only those aspects of the program that are different.
A complete listing of the program is presented in Listing 12 near the end of the lesson, and an executable copy is available for downloading (see Downloads). As usual, I will explain the program in fragments.
The main method
The new version of the main method is shown in its entirety in Listing 5.
Listing 5. The main method for the program named Alice0125b.
|
If you compare the code in Listing 5 with the method named my_first_method in Listing 11, you will see that much more than simply the name has changed. Essentially the entire program was contained in the method named my_first_method in the previous program. The main method in this program simply calls two other methods named setTheStage and playTheShow to get the job done. These are the two new methods that I created for the reasons that I explained earlier.
The method named setTheStage
The method named setTheStage is shown in its entirety in Listing 6.
Listing 6. The method named setTheStage for the program named Alice0125b.
|
If you examine the code in the body of the method shown in Listing 6, you will see that with one exception, it is identical to the code in Listing 11 that was used to set the stage for the earlier program. Thus, when this method is called by the code in the main method, it will perform the following three actions:
The doInOrder construct (block)
By default, the programming statements in an Alice program will be executed in the order that they appear in the program. This is called sequential execution of code. (You will learn about selection logic and looping later.)
A doInOrder block is used to ensure that all of the programming statements (or code blocks) enclosed in its body (the code within its matching curly braces) are executed in sequential order. (In programming jargon, code within a matching pair of curly braces is referred to as a block of code.) If you include a doTogether block inside a doInOrder block, the statements or code blocks inside the doTogether block will be executed concurrently, but the entire block will be executed in sequential order relative to the surrounding statements or code blocks.
|
But, isn't that the default?
Yes, sequential execution is the default. The inclusion of the doInOrder block here is superfluous, and had nothing to do with the execution order for the code. Rather, the doInOrder block was included here to make it more convenient for me to copy the code from one place to another through the use of the Alice clipboard.
|
The Alice clipboard
You can use the standard Windows clipboard in typical ways for the cutting, copying, and pasting of text when writing an Alice program.
In addition, there is a picture of a clipboard in the upper-right corner of the Alice development environment. (You can add more clipboards if you need them using the Edit/Preferences/Seldom Used menus.) You can drag individual programming statements, or entire blocks of statements to the clipboard from one part of a program and then drag them from the clipboard to another part of the program as a means of copying programming statements from one part of a program to another part of the program.
Dragging entire blocks of code
To avoid having to drag each individual statement from the old version of the program to the new version, I elected to:
As you can see in Listing 6, this caused all of the code to be enclosed in the body of a doInOrder block in the new program. With a little effort, I could have dragged the statements out of that block and then deleted the empty block. However, since it wasn't doing any harm, I decided to leave it there just in case I want to copy that code into a method in another version of the program later. (As you work with Alice, you will learn a variety of tricks and techniques that can make your job easier.)
The method named playTheShow
The new method named playTheShow is shown in it entirety in Listing 6b.
Listing 6b. The method named playTheShow for the program named Alice0125b.
|
This method also contains a doInOrder block for the same reasons that I explained earlier. If you ignore the doInOrder block and compare the code in Listing 6b with the code in Listing 11, you will see that the code is the same as the code that was used in the earlier program to cause the skater to bend her knee and then bend her ankle.
|
This program has been modularized into an improved organization by separating the code required to set the stage from the code required to play the show. In subsequent versions of the program, I will modify the code in the method named setTheStage to cause it to be more appropriate, but I won't need to disturb the code in the method named playTheShow.
I will also create some versions of the program that incorporate my best version of the method named setTheStage and modify the method named playTheShow to provide improved animation of the skater.
The flow of control
When you click the Play button, the method named main is automatically executed.
The code in the main method calls the method named setTheStage, causing those actions necessary to set the stage to be executed. In programming jargon, we say that when one method calls another method, control passes from the calling method to the called method. In other words, in this case control over the program execution passes from the main method to the method named setTheStage.
As the code in the method named setTheStage calls other methods, such as the method named setPointOfView, control passes to those methods. As each of those methods completes its task, it returns control to the method named setTheStage.
Finally, when the method named setTheStage completes all of its tasks, it returns control to the method named main.
At that point, the main method calls the method named playTheShow, passing control to that method. When that method completes all of its tasks, it returns control to the main method, which has nothing more to do.
When the main method runs out of tasks, the program essentially becomes dormant waiting for you to click the Stop button at the top of the WorldRunning window shown in Figure 7.
Run the program
Go ahead and click the Play button and observe the running of this new version of your program. It should behave exactly as the previous program behaved, ending up with the skater in the position shown in Figure 7.
When you ran either of the previous two programs, you probably noticed that it took a while to set the stage. Your viewers probably don't want to watch the stage being set, so we need to do something about that. We will deal with that problem in two steps. In this program, we will greatly reduce the time that it takes to set the stage. In the next program, we will make all of the objects invisible during the short period that the stage is being set to eliminate any undesirable flashing on the screen.
More options
If you load either of the previous two programs and take a close look at the edit pane, you should see something similar to Figure 8.
Figure 8. Edit pane.
Notice that each of the program instructions in Figure 8 has the word more at the end followed by a small triangle pointing downward. If you click that triangle, a popup menu will appear that provides more options regarding the execution of that instruction.
For example, Figure 9 shows a partial screen shot resulting from clicking the triangle on the setPointOfView method and then selecting duration in the first popup menu that appeared. Selecting duration caused the second popup menu to appear. Selecting an amount of time from that menu specifies how long the program should take in executing the action specified by that program instruction. Note that there is a big dot beside of 1 second, which is the default value.
Figure 9. Setting the duration.
That is really slow for a computer
However, the computer doesn't need a full second to execute that instruction. One second is an eternity in computer execution terms.
In this program, you will instruct each of the statements in the setTheStage method to execute as quickly as possible by setting the duration value to 0 for each instruction in the method.
The program named Alice0125c
A complete listing for this program is presented in Listing 13 near the end of the lesson. The method named setTheStage is shown in its entirety in Listing 7.
Listing 7. The method named setTheStage for the program named Alice0125c.
|
An examination of Figure 7 will show that I set the duration value to 0 for every method call contained in the setTheStage method. This should cause the method to execute much more quickly.
Steps for creating the program
You can create this program very easily by saving the previous program under a new name and then editing the method named setTheStage to set the duration value for every method call in the setTheStage method to 0.
Play the world
Go ahead and do that and then play the program. Depending on the speed of your computer, your computer may complete the setTheStage method more quickly or less quickly than my computer. Regardless, the execution of the method named setTheStage should be much faster than before.
Undesirable flashing
However, on my computer, the situation is still far from ideal. Albeit very fast, there is some undesirable flashing on the screen while the stage is being set. You wouldn't want your viewers to have to contend with that, so we will need to make at least one more improvement to the method. In the next version of the program, we will cause the objects to be invisible while the stage is being set and make them fade into view at the end of the setTheStage method.
The program named Alice0125d
You can create this program by saving the previous program under a different file name and then edit the new version. A complete listing of the program is presented in Listing 14 near the end of the lesson.
|
We will make two changes to the new version. First, we will manually set the opacity property for the ground, parkingMeter, and iceSkater objects to 0% during the manual process of setting the stage. This will make them invisible when the program starts running, allowing only the blue sky to show during the process of setting the stage.
Fade in
Then we will add method calls to the setTheStage method to cause those three objects to become visible at the end of the setTheStage method. However, instead of making them all become visible instantly, we will cause the parking meter and the ice skater to fade into visibility. Then the setTheStage method will return control to the main method, which in turn will call the playTheShow method.
The method named setTheStage
A complete listing of the method named setTheStage is shown in Listing 8.
Listing 8. The method named setTheStage for the program named Alice0125d.
|
Except for adding some explanatory comments, the only changes to the method were the addition of the last three statements in Figure 8. After the skater has been moved to the viewpoint that she is to occupy at the start of the show, these three statements cause the ground, the parking meter, and the skater to become visible.
Two ways to control visibility
There are two different ways to control the visibility/invisibility of objects in Alice:
The isShowing property
Most, if not all objects have a property named isShowing, which has a boolean value that is either true or false. If true, the object is completely visible. If false, the object is completely invisible.
The opacity property
Most, if not all objects also have another property named opacity. (Opacity is the reverse of transparency.) This property can have any value ranging from 0 to 1. If the value is 0, the object is completely transparent which makes it invisible. If the value is 1, the object is 100% opaque (non transparent) making it completely visible. Values between 0 and 1 cause it to have some degree of opacity or transparency.
The initial opacity values
As I explained earlier, during the process of manually setting the stage, I set the opacity value for the ground, the parking meter, and the ice skater to 0, thereby causing these objects to be totally transparent when the program starts running. At the end of Listing 8, I used program code to change their opacity value to 1 causing them to become 100% opaque.
Setting a property value in program code
To add a statement to a program to set a property value, follow these steps:
The three new statements
The first of the three new statements in Listing 8 caused the ground to become opaque with a duration of 0 seconds. As a practical matter, this caused the ground to become instantly visible.
The second of the three new statements caused the parking meter to become opaque with a duration of one second. This caused the parking meter to fade in from being totally invisible to being totally visible over the span of one second.
Finally, the last of the three new statements caused the ice skater to fade in from being totally invisible to being totally visible over the span of two seconds.
Then the setTheStage method returned control to the main method.
Play the world
Create the new version of the program and play it and you will see the effect of these new features of the program.
Now that we have the setTheStage method in pretty good shape, let's do a little work on the animation by upgrading the method named playTheShow. What we want to do is to cause the skater to pause for one second after she points her toe and then reverse the process so that she ends up with both skates on the ice.
The program named Alice0125e
A complete listing of this program is presented in Listing 15 near the end of the lesson, and an executable version can be downloaded (see Downloads). All of the changes were made to the method named playTheShow, which is shown in its entirety in Listing 9.
Listing 9. The playTheShow method for the program named Alice0125e.
|
The wait statement
I added three statements to this method. The first statement that I added is the wait statement near the middle. There is a wait tile below the edit pane. I dragged it up and dropped it below the two statements that were previously there and set the duration to one second.
The other two new statements
Then I used the clipboard to copy the first two statements to the end of the method and adjusted their parameters to cause them to be mirror images, so to speak, of the first two statements. After raising her leg and pointing her toes, these three new statements cause the skater to pause for one second and then to lower her skate back to the ice.
The results
If you create and play this program, the skater should end up in the position shown in Figure 10 after first raising and then lowering her leg and foot.
Figure 10. End of the run for program named Alice0125e.
Watch that next step, it's a big one
This is a topic (concurrent programming) that is not typically
included in introductory programming courses because it describes a capability
that is relatively difficult to implement in programming environments other than
Alice.
You may have noticed that the skater first bends her knee and then bends her ankle so as to point her toes out behind her. It would look much more natural if she were to do both of those things at the same time (concurrently). I will teach you how to make that happen with this program.
The program named Alice0125f
One of the tiles that appears below the edit pane is labeled doTogether. If you drag that tile into your program, and then put two or more program instructions inside the matching pair of curly braces associated with that tile, all of the instructions within those curly braces will be executed concurrently.
Furthermore, they will all start executing at approximately the same time. (On a computer with a single processor, it is not generally possible for two or more methods to begin execution at exactly the same time.) However, depending on the value that you provide for the parameter named duration, some of the methods may finish executing before others.
A pair of doTogether constructs (blocks)
In this program, we will drag the doTogether tile into the method named playTheShow twice, creating two such blocks. One block will be above the wait statement, and the other block will be below the wait statement. Then we will drag the two statements that cause the skater to raise her leg and point her toes into the first doTogether block. We will drag the two statements that cause the skater to lower her leg and resume her normal foot position into the second doTogether block.
A complete listing of the program is shown in Listing 16 near the end of the lesson and a downloadable executable version is available in Downloads. A listing of the modified version of the playTheShow method is shown in Listing 10.
Listing 10. The playTheShow method for the program named Alice0125f.
|
The key to success
The key thing to note in Listing 10 is the pair of doTogether blocks that were created as described above.
Create and play the world
If you create and play this program, you will probably agree that having the skater bend her knee and her ankle concurrently looks more natural than having her perform those two actions in sequence. This simple example illustrates the importance of concurrent programming for animation. We will frequently use the doTogether block in future lessons.
I encourage you to use the code in Listing 11 through Listing 16 to write (or download) and play these six programs. Experiment with the programs, making changes and observing the results of your changes. Above all, have a little fun in the process.
In this lesson, I have presented and explained six programs that use program code to replicate (and in some cases to improve upon) the things that you accomplished using interactive method calls in an earlier lesson.
The first four programs emphasized setting the stage by executing program code. Each of these programs accomplished essentially the same thing, but each program illustrated better program design than the ones before it.
The last two programs emphasized improvements in the animation process, culminating with the use of concurrent programming.
In this lesson, I have concentrated on the mechanics of writing simple Alice programs. In subsequent lessons, I will teach you the finer points of programming including such things as program design, program logic, etc.
The primary topic for the next lesson will be program design based on what is commonly referred to as top-down design (also known as divide and conquer).
Create a new world using the Snow template. Place a parking meter and an ice skater in the world. Do not perform any manual operations to set the position or orientation of the ground, the parking meter, the ice skater, or the camera. However, you may perform manual operations to cause the objects in the world to be invisible at startup.
Rename the default method main.
Write the following two world-level methods, and cause these two methods to be called in sequence by the code in the main method:
Cause the ground, the skater, and the parking meter to be invisible when you click the Play button or the Restart button to play your world.
Assume that the blue axis belonging to the ground points due south.
In the method named setTheStage:
Cause the above actions to take place as quickly as possible while the objects are invisible. Then do the following in sequential order:
Then terminate the method named setTheStage.
Write the code in the method named playTheShow to cause the skater to transition from her original default standing position on the ice to the pose and viewpoint shown in Figure 11 over a period of one second. Note that the skater does not move horizontally in this method. Also she does not rotate around her green axis. In other words, she is 2 meters from the parking meter facing in the general direction of the parking meter in Figure 11.
Then terminate the method named playTheShow.
The final view of your world be must as shown in Figure 11 with the skater centered horizontally in the window. When you adjust the size of your World Running... window to match the size of Figure 11, the sizes of the parking meter and the skater must be as shown and the relationships among the skater, the parking meter, and the horizon must be as shown.
Save your world in a file named Alice125LabProjA.a2w and be prepared to deliver it to your instructor in whatever manner the instructor specifies.
Make certain that your preferences are set to Java Style in Color.
Select Export Code For Printing... on the File menu and save your source code in a file named Alice125LabProjA.html. Also be prepared to deliver this file to your instructor in whatever manner the instructor specifies.
Figure 11. Required final program output for lab project A.
View a movie of the lab project
You can download and play a small, low-quality movie of my version of the lab project as it being executed from the Resume button (see Downloads). This movie was designed to give you a rough idea of how your program should behave. The movie was purposely reduced in size and recorded in a low-quality format to reduce the file size and hence reduce the download time.
Because of the low quality of the movie, the execution of your program should provide much smoother animation, and should be less grainy than the movie. Also, because of the low quality of the movie, the timing in the movie doesn't necessarily match the duration times specified for the lab project.
I attempted to synchronize the beginning of the recording with the beginning of the program execution by starting, then quickly pausing, and then resuming the execution. If you watch closely, when the movie starts running, you will see the mouse pointer click the Resume button, and the movie will show one complete pass through the program.
You should view this movie in its original size. If you allow the media player to enlarge it, the quality will be poor.
Listing 11. Code for the program named Alice0125a.
Alice0125a's CodeCreated by: Dick BaldwinworldEvents
Methods
|
Listing 12. Code for the program named Alice0125b.
Alice0125b's CodeCreated by: Dick BaldwinworldEvents
Methods
|
Listing 13. Code for the program named Alice0125c.
Alice0125c's CodeCreated by: Dick BaldwinworldEvents
Methods
|
Listing 14. Code for the program named Alice0125d.
Alice0125d's CodeCreated by: Dick BaldwinworldEvents
Methods
|
Listing 15. Code for the program named Alice0125e.
Alice0125e's CodeCreated by: Dick BaldwinworldEvents
Methods
|
Listing 16. Code for the program named Alice0125f.
Alice0125f's CodeCreated by: Dick BaldwinworldEvents
Methods
|
Copyright 2007, Richard G. Baldwin. Faculty and staff of public and private non-profit educational institutions are granted a license to reproduce and to use this material for purposes consistent with the teaching process. This license does not extend to commercial ventures. Otherwise, reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.
Richard has participated in numerous consulting projects and he frequently provides onsite training at the high-tech companies located in and around Austin, Texas. He is the author of Baldwin's Programming Tutorials, which have gained a worldwide following among experienced and aspiring programmers. He has also published articles in JavaPro magazine.
In addition to his programming expertise, Richard has many years of practical experience in Digital Signal Processing (DSP). His first job after he earned his Bachelor's degree was doing DSP in the Seismic Research Department of Texas Instruments. (TI is still a world leader in DSP.) In the following years, he applied his programming and DSP expertise to other interesting areas including sonar and underwater acoustics.
Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.
-end-