Академический Документы
Профессиональный Документы
Культура Документы
Lab Manual
1
Peeking into Computer Science | Alice Lab Manual
Lab 1: Introduction
Alice
2
Peeking into Computer Science | Alice Lab Manual
Table of Contents
Lab 1: Introduction........................................................................................................................................ 5
The Alice Interface .................................................................................................................................... 6
Objects ...................................................................................................................................................... 6
Lab 2: Sequential & Parallel Execution ....................................................................................................... 15
Do in order .............................................................................................................................................. 15
Do together ............................................................................................................................................. 18
Further nesting........................................................................................................................................ 21
Lab 3: Branching & Looping ........................................................................................................................ 26
Conditional execution ............................................................................................................................. 26
Relational Operators ............................................................................................................................... 28
Randomness ............................................................................................................................................ 30
Repetition................................................................................................................................................ 32
While loops ............................................................................................................................................. 36
Lab 4: Lists ................................................................................................................................................... 42
Lists ......................................................................................................................................................... 42
Sound (optional) ..................................................................................................................................... 48
Lab 5: Event Handling ................................................................................................................................. 51
Interactive programming & event handling ........................................................................................... 51
3
World-level methods .............................................................................................................................. 64
Class-level methods ................................................................................................................................ 67
Dummy objects (optional) ...................................................................................................................... 72
Method Parameters ................................................................................................................................ 74
Note:
All of the material in this lab manual is inspired by: Wanda Dann, Stephen Cooper, and Randy
Pausch, Learning to Program with Alice, Pearson – Prentice Hall, 2009.
The material in this manual is developed using Alice 2.2. We recommend that you download and
use this version from: http://www.alice.org/index.php?page=downloads/download_alice2.2
Lab 1: Introduction
4
Lab 1: Introduction
Alice is a programming language which allows programmers to easily create 3D animations and games.
Programs in Alice are created by dragging objects around the screen. The scene can then be played so
that the objects on the screen act out the script written for them.
Exercise 1
1. Open Alice on your computer.
2. When it loads, click “Start the Tutorial”.
Lab 1: Introduction
5
The Alice Interface
5
1
2
3 4
Objects
Each entity seen in the world window is an object. In this example, both the lake and the ice skater are
objects. Let us examine the details of the iceSkater object more closely.
Methods: As you probably understood from the previous exercise, methods are actions that an object
can do. As seen below, an iceSkater can be asked to skate, spin and do many more actions using
methods.
Lab 1: Introduction
6
Some methods, such as skate and move, require arguments (or parameters). Arguments are items of
information that must be supplied for an action to be performed. For instance, when asking the
iceSkater to skate, Alice needs to know how many steps it needs to skate.
Properties: characteristics of an object, such as its color and texture, are known as the object’s
properties.
Lab 1: Introduction
7
Try changing the color of the iceSkater to blue. By doing this, the color property of the iceSkater is
changed before the program runs. Change the color back to “no color”.
If we want to change a property while an animation is running, we have to add this change to the
instruction list. Assume we would like to change the iceSkater’s isShowing property from true to false
(making the iceSkater invisible), after the skater is done with her routine.
Lab 1: Introduction
8
Try playing the scene to see the difference.
Functions: While some object properties can be obtained directly through an object’s properties list,
others need to be obtained by using functions to ask questions about the object.
Lab 1: Introduction
9
In other words, functions are used to obtain information about an object, not to change the property of
an object. When Alice is asked a question about an object using a function, it returns a value as an
answer. This value may be a number, an object, or Boolean (true/false). This is what happens behind
Lab 1: Introduction
10
Function
calculates
IceSkater.skate
distance to tree.
howManySteps =
Distance is 5.
iceSkater’s
distance to
tree
IceSkater.skate
howManySteps = The calculated result is returned to where the function was called
The IceSkater
skates 5 steps
Functions can be used as arguments for methods. For instance, let us try to move the iceSkater forward
by the value of the height of the iceSkater. Drag the iceSkater move method from the method tab and
drop it as the last instruction in the method editor.
Lab 1: Introduction
11
Right now, the iceSkater is asked to move forward by 0.5 meters. To change this so that the forward
movement is equivalent to the iceSkater’s height, go to the functions tab, and drag the iceSkater’s
height function on top of the 0.5 meters argument.
Lab 1: Introduction
12
This instruction can now be read as: Move the iceSkater forward, by the number of meters that is
equivalent to the iceSkater’s height. The height function returns the value of the iceSkater’s height, and
passes it as an argument to the move function.
Lab 1: Introduction
13
Exercise 3
1. Create a new world using the green grass template.
2. Change the color of the grass to blue, so that it now looks like an ocean.
3. Add an island object (from Environments) and a goldfish (from Ocean). Make sure they are both
visible.
4. Get the fish to roll left by 2 revolutions.
5. Resize the island by a scale of 1.5.
6. Using methods, let the fish say “Yikes!”
7. Make the fish move forward by its distance in front of the island * 1.5.
8. Change the color of the grass to dark gray.
Exercise 4
Create a world using the snow template. Add two snowwomen and one snowman to the scene. A
snowman is trying to meet a snowwoman who is talking to another snowwoman. He turns to face the
snowwoman and says “Hello”. She turns to look at him then looks back at her friend, and continues the
conversation. The snowman’s face turns red, and he hangs his head down.
Lab 1: Introduction
14
Lab 2: Sequential & Parallel Execution
Do in order
Open the file lab2.a2w. There are three characters in the scene: Alice, the rabbit, and the cat. We would
like to get the cat to turn towards the rabbit and the rabbit to turn towards the cat. The rabbit then says
“Nice day isn’t it?”
Alice then turns towards them and says “Hello there”. The cat and the rabbit turn to her. She then walks
towards them and says “I’m Alice”.
The above example seems like a fairly simple one to implement. Before we do that, let us draw up a
flowchart of our scene.
Rabbit turns
towards the cat
Rabbit turns
towards Alice
Stop
To place instructions in the Do in order block, simply drag the instructions into the block as shown Peeking into Computer Science | Alice Lab Manual
below.
Let us modify the previous flowchart to reflect changes made to actions that must be done together.
Stop
Exercise 2
Further nesting
We can have as many levels of do together and do in order blocks nested in each other as we need. Let
us make Alice’s walking more realistic. Instead of her whole body moving at once, we can program it so
that her right leg moves first, then her left leg, and so on. Let us modify the flowchart accordingly.
Stop
To achieve this, we need to do the movements sequentially, but at the same time execute Alice’s talk
method. This can be done by adding a do in order block inside the do together block.
First, delete the existing Alice move method. Your instructions list should look like this:
Exercise 4
Modify the flowchart and the program so that Alice’s legs do not walk on their own! Hint 1: Use
methods to move all of Alice along with her legs. Hint 2: Use the turn method for the legs instead of the
move method. Hint 3: Use the duration parameter in the methods you call to time the actions together.
Remember that the default time for each action is 1 second.
Exercise 5
Create a new world using the grass template. Add a hawk to the scene. Add instructions to the scene so
that the hawk flaps its wings twice while flying forward, and then does a complete rotation in the sky.
Exercise 1: Review
Open the file lab3.a2w. The scene contains two ice skaters and a bunny.
The scene starts with iceSkater turning towards iceSkater2. IceSkater2 then turns towards iceSkater.
Then, iceSkater2 and iceSkater both move to pose2. At the same time, the bunny moves up by 0.5
meters. Make the bunny hopping more realistically by turning the bunny’s legs.
IceSkater and iceSkater2 then move to pose3, while the bunny moves downwards. Similarly, adjust the
bunny’s legs so that they are back at their original position.
Conditional execution
Sometimes, you may want an instruction to be executed only if a condition is true. For instance, a
pedestrian will cross the road only if the pedestrian light says WALK. Otherwise, the pedestrian waits.
This conditional execution can be performed by the if/else control structure. This structure checks a
specified condition, and makes a decision about whether or not a section of the code will be run.
Let us take a specific example: A hare and a husky stand next to each other. If the hare is to the left of
the husky, the hare says “I am at your left”. Otherwise, it says “I am not at your left”. This is what the
flowchart may look like:
Is the Hare to
True the left of the False
Notice that the answer to the condition must be either true or false. frue and false are known as
Boolean values (after the great mathematician George Boole). All conditions in the if/else structure must
evaluate to a Boolean value.
Notice that Alice gives you a choice for the initial condition between true and false. Select true.
Click the hare in the object tree window or in the world window. From the functions tab in the details
window, drag the Hare’s function “is to the left of” into if condition, replacing true.
A==B Is A equal to B?
A!=B Is A not equal to B?
A>B Is A greater than B?
A>=B Is A greater than or equal to B?
A<B Is A less than B?
A<=B Is A less than or equal to B?
We now want the husky to scratch its ears for 2 seconds and wag its tail with turn scale 1 and duration
scale 2 (in parallel) if the height of the hare is less than or equal to 2. Otherwise, the husky needs to walk
a number of cycles equal to the hare’s height.
To use relational operators, click object world in the object tree. Go to the functions of the world object.
Underneath the heading math, you will notice the relational operators shown earlier.
Drag the operator we need on top of the true tile next to the if/else statement. Select any numbers you
like for a and b. For this example, we selected 2 and 2 respectively.
If we keep the code as it is above, the if block will always be the one that is executed. This is because
2<=2 will always evaluate to true.
Randomness
The problem with the above code is obvious: What is the point of using conditional statements if the
values we are comparing are fixed?
This is where we can introduce randomness into our programs. We can set the size of the hare to a
random size at the beginning of the program using the world function random.
Start by dragging the hare method resize before the if/else block. Select 2 (or any other number) as the
resizing factor.
Now we need to set the resize factor to a random number. Keep in mind that while the hare’s height
and size are directly proportional, they are not the same thing.
Now we need to set restrictions so that the hare is not resized to a very large or very small value. This is
Select the more menu next to the random number function and set the minimum to 0.1 and the
maximum to 1.5. Also make sure the intergerOnly parameter is set to false.
Run the movie a few times, and notice how the outcome has become unpredictable.
Get the robot to kick its left leg and at the same time point its cannon forward. The robot must return to
its initial position each time. The robot needs to repeat this three times. The robot must also get smaller
by 0.9 at every repetition.
Repetition
After the previous example, you are probably thinking that there has to be an easier way to repeat
instructions without copying the same instructions over and over again. Well there is!
Remove the redundant instructions so that your code looks like this:
This can be done by using a while control statement, instead of using loops and if/else statements like
we did above.
A While statement keeps repeating the code inside its block until the while condition becomes false.
When the condition is false, the program continues to execute the code that comes after the while
block. The following is a flowchart of how while statements work.
True
Do certain actions
False
Let us modify our previous example, so that it uses a while loop instead of loops and if constructs.
Now try replacing the loop and the if/else statement with a while statement.
Lists
Open the file lab4lists.a2w.
The world consists of three different cows – making up a cow dance group. A world-level method called
lookToRight has been created. This method takes an object parameter named aCow. The world also
starts off playing a sound clip for the cows to dance to.
Let us fill in the method lookToRight. The first thing we need to do is turn the cow’s head 0.2 revolution
to the right. This is not as straightforward as it may seem.
First, drag the cow.head’s turn method into the lookToRight method space. Set the method to turn right
by 0.2 revolutions.
The above code turns the head of the 1st cow only, not the head of the parameter aCow. We can change
that using a function called “part named”.
Take a look at the cow functions (not cow.neck.head). At the very bottom you will see the “part named”
function. Drag that over cow.neck.head in the turn method.
Lab 4: Lists
42
Now we need to enter the specific name of the cow part we want to turn. Looking at the object tree, we
know that the part is neck.head. Note that Alice is case sensitive, so be sure to spell the names correctly.
Lab 4: Lists
43
The final step would be to use the aCow parameter rather than the cow object. Drag the aCow
parameter from next to the method name to replace cow in the turn method call.
Lab 4: Lists
44
Exercise 4
Complete the world.lookToRight method so that the cow’s head is back to its original position. (Hint:
right-click the turn method and select “make a copy”. You can then make the required changes.)
Exercise 5
Get the cows to all turn their heads together at the beginning of the song.
Since all the objects we are moving are of the same type and use the same methods and body parts, we
can simply add them all to a list.
To do this, click on “world” in the object tree, then select “create new variable” in the world’s
properties.
Name the variable “listOfCows”. Choose the type to be Object, select the “make a List” checkbox, and
then add the three cows as items in the list.
Lab 4: Lists
45
We now created a variable, containing all three cows. Let us see how we can use this structure. Delete
the code you added previously which called the lookToRight method.
The two main statements we shall use with lists are named “For all in order” and “For all together”. The
1st statement performs operations on lists sequentially, i.e. one list item at a time. The 2nd statement
performs operations on all list items simultaneously.
Drag the “For all together” statement underneath the “play sound” method call. When prompted, select
the listOfCows list that was just created.
Lab 4: Lists
46
Now drag the method “lookToRight” into the “For all together” block.
Select “item_from_listOfCows” as the method parameter. Try running your program now.
Lab 4: Lists
47
Exercise 6
Modify your program so that the cow’s turn their heads one at a time rather than all together.
Exercise 7
Complete the dance! Start off with the head turn followed by a synchronized kick (all together). At the
end of it, each cow should moo individually.
Sound (optional)
Nobody debates that, with very few exceptions, the use of sound is necessary in any good animation,
video, or game.
Open the file lab4.a2w. The world contains three animals, and the first method calls a class-level
method: horse.neigh.
Playing the animation and viewing the code for the horse.neigh method will show you that all it does is
turn the mouth of the horse downwards then upwards.
What is lacking here is the actual sound of the horse neighing. To add a sound file to the horse, go to the
horse’s properties, and expand the sound section as shown below.
We now have two options: we can either import a sound file, or record one ourselves. Click on “import
sound”.
Lab 4: Lists
48
Make sure you have downloaded the file horse-neigh1.wav. Import that file into the world.
To play the sound file, go to the horse methods and drag the method “play sound” to horse.neigh. Select
the sound file we just imported from the list of sounds shown.
Lab 4: Lists
49
Exercise 8
Create a class-level method for the cow class called mooing. In this method, the cow should turn its
lower mouth in the same way the horse does. Notice that the cow class already has a built-in “moo”
sound file so there is no need to import one. Call this method from the world.my first method.
Exercise 9
Create a similar class-level method called cluckCluck for the chicken class. Notice that a chicken sound is
available, but it does not belong to the chicken class. It belongs to the world object. Fix the durations so
that the chicken sound does not go on after the chicken’s mouth movement is complete. Call this
method from the world.my first method.
Exercise 10
Doesn’t it seem a little redundant to do the same thing for all three classes? Create a new world-level
method named introduction. This method takes as parameters the animal part that needs to be turned
(mouth/lower mouth) and the sound the animal needs to make. Call this method three times, so that
the horse, cow and chicken all get the chance to introduce themselves in their own languages.
Lab 4: Lists
50
Lab 5: Event Handling
Control of flow
Control of flow refers to the control on the order of actions in a program. Noninteractive programs are
computer-centric, where the order of actions is predetermined by the programmer. On the other hand,
interactive programs are user-centric, where the order of actions is determined at runtime based on
user interactions such as mouse clicks and key presses on the keyboard.
Events
Every time the user provides some sort of input, through a mouse click or key press for instance, we say
an event is generated.
In this example and the following two exercises (Exercises 1–2), we want to make the IceSkater respond
to a number of key presses on the keyboard. Note that the Events editor in Figure 1 is empty. The Events
editor is where the event handling methods are linked to the events. When an event is generated, it
triggers the linked event handling method as a response.
To create an event in Alice, you first have to press the create new event button close to the top-left
corner of the Event editor, which then shows a list containing the types of events you can create (see
Figure 2).
When the world starts, we want the IceSkater to prepare for skating, which can be achieved by the user-
defined method prepare to skate. Therefore, here the “start of the world” is generating an event, which
After pressing the create new event button, choose When the world starts from the list. This will
introduce a When the world starts tile in the Events editor. Next, as shown in Figure 3, drag the
IceSkater’s prepare to skate method onto Nothing in this tile. Now the start of the world event is linked
to the event handling method prepare to skate. Press the Play button to see what the IceSkater does.
Next, we want the IceSkater to skate one step forward when the Up arrow key is pressed on the
keyboard. After pressing the create new event button, choose When a key is typed from the list. This
will introduce a When a key is typed tile at the end of the instruction list in the Events editor. Choose Up
in place of any key in this tile as shown in Figure 4. Then drag the IceSkater’s skate method onto Nothing
in this tile and choose 1 for value of the argument howManySteps.
Now, the instructions in your Events editor should look as shown in Figure 5.
Press the Play button and then the Up arrow key on the keyboard a few times to see what the IceSkater
does. Observe that nothing happens while the Up arrow key is in a pressed state. The IceSkater skates
for 1 step when the Up arrow key is released after being pressed.
Now, we want the IceSkater to keep on skating forward while the Up arrow key is in a pressed state and
stop skating when the Up arrow key is released after being pressed. To achieve this, delete the last tile
we created in the Events editor and reintroduce a When a key is typed tile. Then right-click on this tile,
go to change to, and choose to click on While a key is pressed. This will change the When a key is typed
tile to a While a key is pressed tile.
Once again, press the Play button and then the Up arrow key to see what the IceSkater does.
Exercise 1
Extend the world from Example 1 to handle the following events:
(i) While the Down arrow key is pressed, make the IceStaker skate backwards. Use the IceSkater’s
stake backwards method as the event handling method.
(ii) While the Left and Right arrow keys are pressed, make the IceSkater turn left and right,
respectively. Use the IceSkater’s built-in turn method as the event handling method.
(iii) When the Space bar is pressed, make the IceSkater jump. Use the IceSkater’s jump method as the
event handling method.
Hints: Make use of either Let the mouse move the camera or Let the mouse orient the camera event.
These events have built-in event handlers; i.e. you will not need to write an event handling method or
use any built-in method to carry out the responses for these events.
Next, as shown in Figure 10(b), the mummy has the following two user-defined methods:
(i) takeSteps, which acts in the same way as ourOwnPharaoh’s takeSteps method, but this method is
defined for the mummy object;
(ii) resetPose, which sets the mummy to its initial pose.
Finally, as shown in Figure 10(c), the 3D Text has its text property set to “Mummy got the pharaoh!”,
font property set to Agency FB Bold, isShowing property set to false, and a particular color is chosen for
the text.
In this example and the following four exercises (Exercises 3–6), we want the mummy to catch
ourOwnPharaoh. The user will be able to control mummy’s movement using the keyboard and
ourOwnPharaoh will wander around randomly as if he is scared and trying avoid being caught by the
mummy. If the mummy catches ourOwnPharaoh, ourOwnPharaoh will scream and get unconscious.
Exercise 3
Extend the world from Example 2 to handle the following events:
(i) While the Up arrow key is pressed, make the mummy walk forward. Anytime the Up arrow key is
pressed, the mummy should start walking from its initial pose and anytime the Up arrow key is
released after being pressed, the mummy should return to its initial pose. Use mummy’s takeSteps
and resetPose methods as event handling methods.
(ii) While the Left and Right arrow keys are pressed, make the mummy turn left and right, respectively.
Use the mummy’s built-in turn method as the event handling method.
(iii) Let the mouse move the camera.
Exercise 5
Create and define a world-level method named didMummyCatchPharaoh that will check if the mummy
could catch ourOwnPharaph and carry out an appropriate sequence of actions, if true. In the
didMummyCatchPharaoh method, check if ourOwnPharaoh is within less than 1 meter of any of
mummy’s forearms. If yes, then execute the following instructions:
(i) ourOwnPharaoh should get scared. Make use of ourOwnPharaoh’s user-defined method getScared.
(ii) The following actions should take place simultaneously: the 3D Text should turn to face the camera
and show up; the mummy should raise both of its hands out of joy.
(iii) Set the world-level Boolean variable isPharaohFree to false.
Exercise 6
Create two world-level variables named turnDirection and turnRevolutions, both of type Number. Now,
define the previously created world-level play method, which will contain the main body of the
program. The play method should:
(i) assign two randomly generated values to the variables, turnDirection and turnRevolutions;
Exercise 8
Extend the world resulting from Exercise 7 so that if the user clicks one of the cows, the cow that has
been clicked should swish its tail. Make use of the tailSwish method that accepts two parameters, times
and speed, both of type Number. The times parameter represents the number of times the cow should
swish its tail and the speed parameter represents the speed at which it should swish its tail.
Exercise 9
Modify and extend the world resulting from Exercise 8 as follows:
(i) Add a strawBale object from the Farm gallery. Resize (not during runtime) the added strawBale
object to be twice as big compared to its original size.
(ii) Allow the user to move each cow as well as the strawBale individually using the mouse.
(iii) Create and define a world-level method named walkTowardsBale such that each of the three cows
walks towards the strawBale if it is more than one meter away from it, for a random number of
steps, at a random speed, at the same time. Make use of the walkTowards method.
(iv) Create a world-level variable named distance of type Number and initialize it to 0.
(v) Delete all the existing instructions from world.my first method and redefine it to contain an infinite
While loop, within which it assigns the distance between the strawBale and the camera to the
Now, press the Play button and move the strawBale around using the mouse to see what the cows do.
During the last series of Alice labs, you probably noticed that the programs can easily become long and
complicated – even if they only implement a few seconds of animation!
The longer a program becomes, the more difficult it becomes to debug and modify, not to mention
understanding it. This is why a paradigm known as object-oriented programming (OOP) is commonly
used. OOP allows large programs to be broken down into smaller, more manageable pieces. The main
components of OOP are classes, objects and methods.
Classes
In Alice, all of the types of models that can be added into a world are known as classes, such as the class
BeachChair below
The screenshot above shows two instances (objects) of the Camel class. However, each Camel object has
a different name, size and color.
Methods
A method is a sequence of instructions that can be called when needed. In previous tutorials, we used
many of the methods that were built into Alice objects, such as moving, turning, and making a skater
skate. These built-in methods can be grouped into our own methods, making programs easier to read
and debug, and pieces of code easier to reuse and modify.
Class-level methods only give instructions to a single object. For instance, we may write a skate method
for the iceskater and a hop method for the bunny.
The next exercise will explain how to create world-level methods in Alice.
Exercise 2
Click on File->New World. In the tutorial tab, select tutorial 2 and follow its steps.
World-level methods
Open file lab6egypt.a2w.
The program is broken down into two world-level methods. First, the mummy and the pharaoh are
oblivious to one another. They then notice each other, and the pharaoh runs away!
noticeEachOther
Program
runAway
Start by clicking the world object in the object tree. Then in the method list, select create new method.
First, let us add the getScared method to the main program. Go to the “my first method” editor and
drag the getScared method between noticeEachOther and runAway.
After the camera is set to show the pharaoh more closely, we can now show how scared the pharaoh is.
Exercise 3
Let’s show how scared the pharaoh is! Get the pharaoh’s beard and nose to grow by 1.2, and at the
Class-level methods
It would be much neater if all of the code we just added for the pharaoh was in its own method. Since
these instructions are specific to the pharaoh, we can create a class-level method.
Click pharaoh from the object tree, and then select “create new method” from the methods list.
Exercise 4
In the world.getScared method, append instructions to set the camera point of view to the pharaoh’s
head. After that, implement and call a getScared method for the mummy where his/her head grows by a
factor of 1.2 then shrinks by a factor of 0.83 (1/1.2). At the same time, the mummy yells “Oooooh!”
Now we need to shift the camera’s perspective back to the original view. Since there are no objects
where the camera originally was, we cannot move the camera back to that perspective. For this reason,
Alice allows you to place dummy objects where we want to move the camera to.
You will now notice a new folder in the object tree named “Dummy Objects”. Expanding “Dummy
Objects” shows “dummy”, the dummy object we just created.
We can also add parameters to the methods we create. Let us take a look at the world.runAway
method.
Exercise 5
Move the large do together loop (using the clipboard) into a new class-level method for the pharaoh.
Name the method takeSteps. Call takeSteps from inside the loop in the world.runAway method.
As you can see from the dialog box, parameters can have numerous types. Obviously, the type we need
is Number. Set the name of the parameter as numberOfSteps.
Now we want to repeat the code in the method a numberOfSteps times. Create a loop structure, and
drag the large do together block into it.