Vous êtes sur la page 1sur 77

Programming

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

Peeking into Computer Science | Alice Lab Manual


Control of flow ........................................................................................................................................ 51
Events ...................................................................................................................................................... 51
Event handing methods .......................................................................................................................... 51
Example 1: Ice Skater .......................................................................................................................... 51
Example 2: Mummy Catches Pharaoh ................................................................................................ 57
Other types of events ............................................................................................................................. 60
Lab 6: Object Oriented Programming ......................................................................................................... 62
Classes ..................................................................................................................................................... 62
Objects .................................................................................................................................................... 63
Methods .................................................................................................................................................. 63

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

Peeking into Computer Science | Alice Lab Manual

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”.

Peeking into Computer Science | Alice Lab Manual


3. Go through the tutorial instructions.

Lab 1: Introduction
5
The Alice Interface

5
1
2

3 4

1. The world window: shows the world being built.


2. The object tree: contains a list of objects in the world.

Peeking into Computer Science | Alice Lab Manual


3. The details area: provides further information on the world or the currently selected object.
4. The (method) editor area: allows you to make objects perform actions.
5. The events area: allows you to tell Alice when to make objects do certain things.

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.

The details area has three tabs:

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.

Peeking into Computer Science | Alice Lab Manual

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.

Peeking into Computer Science | Alice Lab Manual


To do this, we need to drag the isShowing property to the end of the instruction list and select false
from the menu.

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.

Peeking into Computer Science | Alice Lab Manual

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

Peeking into Computer Science | Alice Lab Manual


the scenes when a function is used as a method parameter:

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.

Peeking into Computer Science | Alice Lab Manual

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.

Peeking into Computer Science | Alice Lab Manual

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.

Peeking into Computer Science | Alice Lab Manual


Exercise 2
1. Open the file lab1.a2w.
2. Press the “Play” button to see what the world does.
3. Modify the 2nd instruction so that the shark rolls right by 2 revolutions.
4. Modify the 3rd instruction so that the shark says “I am hungry”.
5. Modify the 4th instruction so that the shark moves forward by its distance to the blueminnow3’s
tail minus 0.5
6. Using functions, modify the 1st instruction so that the bigfish moves forward by its distance in
front of the shark’s jaw.
7. Using properties, make the blueminnow turn black then disappear at the end of the instruction
list.
8. Using methods, make the bigfish think “I should get out of here”, after the blueminnow
disappears.

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.

Peeking into Computer Science | Alice Lab Manual

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.

Peeking into Computer Science | Alice Lab Manual

Lab 2: Sequential & Parallel Execution


15
Start

Cat turns towards


the rabbit

Rabbit turns
towards the cat

Rabbit says “Nice


day, isn’t it?”

Alice turns towards


them

Alice says “Hello


there”

Cat turns towards


Alice

Rabbit turns
towards Alice

Alice walks to the


cat and rabbit

Peeking into Computer Science | Alice Lab Manual


Alice says “I’m
Alice”

Stop

Lab 2: Sequential & Parallel Execution


16
As you can see from the flowchart, each of these instructions needs to be done in order, i.e. one
instruction is completed, before the following one begins. We can tell Alice to do these instructions in
order by using the do in order control statement.

To do this, drag the Do in order statement to the editor area.

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.

Lab 2: Sequential & Parallel Execution


17
Exercise 1
Using the flowchart above, fill the rest of the instructions in the Do in order block. This should not take
more than 5 minutes.

Peeking into Computer Science | Alice Lab Manual


Do together
There are many cases when instructions need to be done together, rather than one after the other. For
instance, instead of the cat turning to face the rabbit then the rabbit turning to face the cat, it would be
more meaningful if they both turn to each other at the same time.

Let us modify the previous flowchart to reflect changes made to actions that must be done together.

Lab 2: Sequential & Parallel Execution


18
Start

Cat turns towards Rabbit turns


the rabbit towards the cat

Rabbit says “Nice


day, isn’t it?”

Alice turns towards


them

Alice says “Hello


there”

Cat turns towards Rabbit turns


Alice towards Alice

Alice walks to the Alice says “I’m


cat and rabbit Alice”

Stop

Peeking into Computer Science | Alice Lab Manual


Now the story makes more sense. Let us program the changes into our scene. To add a do together
control statement, drag it inside the do in order block as shown below.

Lab 2: Sequential & Parallel Execution


19
The first two instructions we want done together are the cat turning to the rabbit and vice versa. Drag
them both from the do in order block into the do together block.

Peeking into Computer Science | Alice Lab Manual

Lab 2: Sequential & Parallel Execution


20
Press play to see the difference.

Exercise 2

Peeking into Computer Science | Alice Lab Manual


Complete the flowchart shown above by adding two more do together blocks to the scene.

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.

Lab 2: Sequential & Parallel Execution


21
Start

Cat turns towards Rabbit turns


the rabbit towards the cat

Rabbit says “Nice


day, isn’t it?”

Alice turns towards


them

Alice says “Hello


there”

Cat turns towards Rabbit turns


Alice towards Alice

Alice moves right


foot forward

Alice moves left


foot forward
Alice says “I’m

Peeking into Computer Science | Alice Lab Manual


Alice”
Alice moves right
foot forward

Alice moves left


foot forward

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:

Lab 2: Sequential & Parallel Execution


22
Peeking into Computer Science | Alice Lab Manual
Now, add the do in order block into the last do together block in the scene.

Lab 2: Sequential & Parallel Execution


23
Peeking into Computer Science | Alice Lab Manual
Exercise 3
Complete the scene using the flowchart above.

Your program should now look like this:

Lab 2: Sequential & Parallel Execution


24
Peeking into Computer Science | Alice Lab Manual
You may have noticed that this instruction set causes Alice’s legs to move on their own, without the rest
of the body!! That is true. This is a mistake or a bug in our code.

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.

Lab 2: Sequential & Parallel Execution


25
Lab 3: Branching & Looping

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.

This exercise should take about 10 minutes.

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

Peeking into Computer Science | Alice Lab Manual


Husky?

Hare says “I am at Hare says “I am


your left” not at your left”

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.

Let us implement this in Alice. Open the file lab3If1.a2w.

Lab 3: Branching & Looping


26
The first thing we need to do is to drag the if/else structure into the method editor.

Notice that Alice gives you a choice for the initial condition between true and false. Select true.

Peeking into Computer Science | Alice Lab Manual


Now we need to change the condition to the one we used in our flowchart. To find out whether the hare
is to the left of the husky, we can use the hare object’s built-in functions.

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.

Lab 3: Branching & Looping


27
Exercise 2
Complete the above program so that it performs the instructions in the flowchart. In the world window,
move the husky or hare around (using your mouse) and run the program to test your code.

Peeking into Computer Science | Alice Lab Manual


Relational Operators
In the previous example, a built-in function was used to check a condition in our world. However, it is
difficult to provide built-in functions for everything that we may need in our code. Therefore, we can use
relational operators to write our own conditions. A relational operator is one which asks a question
about the relationship between two entities. The result of a relational operation is a Boolean value. Here
is the list of relational operators:

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?

Lab 3: Branching & Looping


28
Let us try to apply relational operators in our current world. Delete the previous if/else construct, so that
the method editor is empty.

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.

Drag a new if/else construct into the method editor window.

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.

Peeking into Computer Science | Alice Lab Manual

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.

Lab 3: Branching & Looping


29
Exercise 3
Complete the above code. Replace the 1st 2 in the relational operation with the height of the hare then
fill in the if and else blocks.

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.

Peeking into Computer Science | Alice Lab Manual

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.

Lab 3: Branching & Looping


30
Select world in the object tree and navigate to the world object functions. Drag the function random
number on top of the resize amount.

Now we need to set restrictions so that the hare is not resized to a very large or very small value. This is

Peeking into Computer Science | Alice Lab Manual


why we need to set the minimum and maximum values for the random number to be generated.

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.

Lab 3: Branching & Looping


31
What the above code means is that the hare can be resized to a random number between 0.1*its
original size and 1.5*its original size. When the integerOnly parameter is set to false, it means that the
random number generated can contain decimals.

Run the movie a few times, and notice how the outcome has become unpredictable.

Peeking into Computer Science | Alice Lab Manual


Exercise 4
Open the file lab3Rep.a2w.

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:

Lab 3: Branching & Looping


32
We shall now use a new control statement called a loop. Drag it to your editor’s area.

Peeking into Computer Science | Alice Lab Manual

Lab 3: Branching & Looping


33
A menu shows up asking how many times you would like the loop to run. We need it to repeat 3 times.
Select other and type 3 using the keypad.

Peeking into Computer Science | Alice Lab Manual

Lab 3: Branching & Looping


34
Now drag the code you want repeated into the loop block.

Peeking into Computer Science | Alice Lab Manual

Lab 3: Branching & Looping


35
Exercise 5
Change the loop so that it repeats forever (infinity). Place an if/else block inside the loop so that the
movement and resizing only happens when the robot’s height is greater than 1.

Peeking into Computer Science | Alice Lab Manual


While loops
Notice now that the robot stops moving and shrinking once the height is 1 or less. The problem with this
program is that while the robot stops shrinking at the required size, the program remains stuck in the
loop indefinitely. We need our program to break the loop once the loop condition becomes false.

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.

Lab 3: Branching & Looping


36
Is condition
satisfied?

True

Do certain actions
False

Let us modify our previous example, so that it uses a while loop instead of loops and if constructs.

Drag the while control statement to the editor’s area.

Peeking into Computer Science | Alice Lab Manual

Lab 3: Branching & Looping


37
Similar to if/else statements, Alice provides you with a menu showing the Boolean values true and false.
This is because both while and if/else statements use conditions which must evaluate to a Boolean
value. Select true from the menu, then drag the part of the code you want to be repeated into the while
block.

Peeking into Computer Science | Alice Lab Manual

Lab 3: Branching & Looping


38
Now we just need to change the condition in the while statement. You can simply drag the conditional
operation we created previously for the if construct on to the condition title of the while block. Now
delete the parts of the code you don’t need any more.

Peeking into Computer Science | Alice Lab Manual

Lab 3: Branching & Looping


39
Exercise 6
Add a fighter object to your world. The fighter should be hovering on top of the robot as shown in the

Peeking into Computer Science | Alice Lab Manual


screenshot below.

Lab 3: Branching & Looping


40
While the robot is changing size and moving, the fighter should move downwards by half its distance
above the robot. This should only be done once and only if the fighter is larger than the robot.
Otherwise, the fighter should resize so that it is 1.5 times larger.

Peeking into Computer Science | Alice Lab Manual


Use a loop to repeat the if/else block twice.

Now try replacing the loop and the if/else statement with a while statement.

Lab 3: Branching & Looping


41
Lab 4: Lists

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.

Peeking into Computer Science | Alice Lab Manual

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.

Peeking into Computer Science | Alice Lab Manual


Your method should now look like this:

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.

Peeking into Computer Science | Alice Lab Manual

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.

Peeking into Computer Science | Alice Lab Manual

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.

Peeking into Computer Science | Alice Lab Manual

Lab 4: Lists
46
Now drag the method “lookToRight” into the “For all together” block.

Peeking into Computer Science | Alice Lab Manual

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.

Peeking into Computer Science | Alice Lab Manual

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.

Peeking into Computer Science | Alice Lab Manual

Now try running the scene.

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.

Peeking into Computer Science | Alice Lab Manual

Lab 4: Lists
50
Lab 5: Event Handling

Interactive programming & event handling


So far, we have focused on developing movie-style animations in Alice. These programs are not
interactive. In this lab, you will learn how to write interactive programs in Alice, where the users can
interact with the objects in an Alice world using mouse and keyboard.

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.

Event handing methods


An event may trigger a response or move objects in the scene to positions that lead to some condition
(such as a collision) that triggers a response. A response to an event can be an action or a sequence of
actions that needs to be carried out. Responding methods are written to perform the intended
responses, and the events are linked to the indented responding methods. Such responding methods

Peeking into Computer Science | Alice Lab Manual


are known as event handling methods.

Example 1: Ice Skater


Open the file Lab5-Example1.a2w. The World contained in this file is adapted from the solution of
Exercise 1 from Lab 1, which can be found on page 4 of this lab manual. As shown in the Figure 1 below,
the World consists of a lake and an IceSkater object. The IceSkater has the following four user-defined
methods:
(i) prepare to skate, which sets the IceSkater to an initial pose;
(ii) skate, which accepts the number of steps the IceSkater has to skate through an argument variable
(parameter) named howManySteps and makes the IceSkater skate for howManySteps steps;
(iii) skate backwards, which accepts the number of steps the IceSkater should skate backwards through
an argument variable named howManySteps and makes the IceSkate skate backwards for
howManySteps steps; and

Lab 5: Event Handling


51
(iv) jump, which makes the IceSkater jump.

Figure 1. Objects, methods, and Events editor

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.

Peeking into Computer Science | Alice Lab Manual

Lab 5: Event Handling


52
Figure 2. Types of events

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

Peeking into Computer Science | Alice Lab Manual


should trigger a response carried out by the event handling method prepare to skate.

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.

Lab 5: Event Handling


53
Figure 3. Linking an event handling method to an event

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.

Peeking into Computer Science | Alice Lab Manual

Figure 4. Choosing the Up arrow key

Now, the instructions in your Events editor should look as shown in Figure 5.

Lab 5: Event Handling


54
Figure 5. After linking the event handling method skate with the Up arrow key press event

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.

Figure 6. Introducing a While a key is pressed tile

Peeking into Computer Science | Alice Lab Manual


Next, choose Up in place of any key in the newly introduced While a key is pressed tile. As shown in
Figure 7, this tile allows you to mention what action should take place at the start of a key press (in the
Begin part), while the key is in a pressed state (in the During part), and when the key is released (in the
End part).

Figure 7. After introducing the While a key is pressed tile

Lab 5: Event Handling


55
Now, drag the IceSkater’s skate method onto <None> in the During part of this tile and choose 1 for
value of the argument howManySteps. Also, drag the IceSkater’s prepare to skate method onto <None>
in the Begin part and onto <None> in the End part of this tile. This allows the IceSkater to start skating
from her initial pose when the Up arrow key is pressed and she should again return to her initial pose
when the Up arrow key is released. At this point, the instructions in your Events editor should look as
shown in Figure 8.

Figure 8. After introducing the 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.

Peeking into Computer Science | Alice Lab Manual


Exercise 2
Note that in the worlds resulting from Example 1 and Exercise 1, the IceSkater can go off the screen
while skating. Can you think of a way to fix this problem? There are two easy solutions – one is to move
the camera and the other is to change camera orientation such that the IceSkater is visible.

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.

Lab 5: Event Handling


56
Example 2: Mummy Catches Pharaoh
Open the file Lab5-Example2.a2w. As shown in the Figure 9 below, the world consists of a pyramid, a
sphinx, an ourOwnPharaoh, a mummy, and a 3D Text object.

Figure 9. Added objects

ourOwnPharaoh has the following two user-defined methods (Figure 10(a)):


(i) takeSteps, which accepts the number of steps ourOwnPharaoh has to take and the duration of each
step in argument variables named numberOfSteps and timePerStep, respectively, and the method

Peeking into Computer Science | Alice Lab Manual


makes ourOwnPharaoh take numberOfSteps steps consuming timePerStep seconds per step;
(ii) getScared, which makes ourOwnPharaoh scream and fall on the ground to show him getting
unconscious.

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.

Lab 5: Event Handling


57
(a) (b) (c)
Figure 10. User-defined methods and set properties

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.

Peeking into Computer Science | Alice Lab Manual


First, create a world-level method named play. Keep its body empty for now. We want this play method
to be the event handling method that should be called as long as ourOwnPharaoh does not get caught
by the mummy. To perform this, let us first create a world-level Boolean variable named isPharaohFree
and set its initial value to be true. This Boolean variable should be true as long as ourOwnPharaoh does
not get caught by the mummy. Now, introduce a While something is true tile in the Events editor from
the list you can access by pressing the create new event button. Drag the isPharaphFree Boolean
variable onto <None> of this While something is true tile as shown in Figure 11. Also, drag the play
method onto Nothing in the During part of this tile.

Lab 5: Event Handling


58
Figure 11. Using a While something is true event

Now, your Events editor should look as shown in Figure 12.

Peeking into Computer Science | Alice Lab Manual


Figure 12. The While something is true event

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.

Lab 5: Event Handling


59
Exercise 4
Create and define a method named randomMove for ourOwnPharaoh that will allow him to randomly
wander around. More specifically, define the method randomMove as follows:
(i) It should accept two arguments named directionToTurn and revolutionsToTurn, both of type
Number.
(ii) If the value of directionToTurn is less than 0.5, make ourOwnPharaoh turn left; otherwise turn right.
The turn should be for revolutionsToTurn revolutions.
(iii) Make ourOwnPharaoh walk forward using its takeSteps method.

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;

Peeking into Computer Science | Alice Lab Manual


(ii) make ourOwnPharaoh make a random walking movement (make use its randomMove method
using turnDirection and turnRevolutions as arguments); and
(iii) check if the mummy could catch ourOwnPharaoh (make use of the didMummyCatchPharaoh
method).

Other types of events


Other than what you have seen in the examples and exercises above, Alice 2.2 allows us to use four
other types of events, which are When the mouse is clicked on something, When a variable changes, Let
the mouse move <objects>, and Let the arrow keys move the <subject>. The last two of these four types
of events have built-in event handlers. The next three exercises (Exercises 7–9) will involve the use of
these types of events.

Lab 5: Event Handling


60
Exercise 7
Open Lab5-Exercise7.a2w. The world contained in this file is the solution to Exercise 7 from Lab 4, which
can be found on page 47 of this lab manual. Now, extend this world to carry out the following actions:
(i) Allow the user to move each cow individually using the mouse. Make use of the world-level list
variable listOfCows.
(ii) Allow the user to move the camera using the arrow keys on the keyboard.

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

Peeking into Computer Science | Alice Lab Manual


previously created world-level variable distance.
(vi) Create an event that triggers the walkTowardsBale method as a response to change in the world-
level variable distance.

Now, press the Play button and move the strawBale around using the mouse to see what the cows do.

Lab 5: Event Handling


61
Lab 6: Object Oriented Programming

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

Peeking into Computer Science | Alice Lab Manual

Lab 6: Object Oriented Programming


62
Objects
Once an instance of a class is added to the world, it is known as an object. Objects of the same class
share the same methods and properties. However, each object is unique. Objects of the same class have
different names and can have different values for their properties.

The screenshot above shows two instances (objects) of the Camel class. However, each Camel object has
a different name, size and color.

Peeking into Computer Science | Alice Lab Manual


Exercise 1
Recreate the world shown above. Notice that the camel names are camelo and camely and that camely
has red ears.

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.

There are two types of methods: world-level and class-level.

Lab 6: Object Oriented Programming


63
World-level methods are ones which give instructions to more than one object. For instance, a world
method called makeConversation, could ask the skater and snowman to discuss the weather among
themselves.

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!

Take a minute to look at the code before we continue.

The program is broken down as follows:

noticeEachOther

Program

runAway

Peeking into Computer Science | Alice Lab Manual


Let us add another world-level method called getScared, between noticeEachOther and runAway.

Start by clicking the world object in the object tree. Then in the method list, select create new method.

Lab 6: Object Oriented Programming


64
In the new method dialog box, type getScared. In this method, we want the camera to focus on the
mummy, then show him/her scared. The same should then happen to the pharaoh.

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.

Peeking into Computer Science | Alice Lab Manual

Lab 6: Object Oriented Programming


65
Now let’s go back to creating the getScared method. We can control where the camera is focused at
using the camera’s methods. Click the camera object, and then drag the method “set point of view to”
to the body of getscared method in the method editor area. The camera point of view should be set to
the mummy’s head.

Peeking into Computer Science | Alice Lab Manual

Lab 6: Object Oriented Programming


66
Run the program to see what effect this has.

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

Peeking into Computer Science | Alice Lab Manual


same time, get his hat to spin 1 full revolution. This should happen while the pharaoh yells “Aaaaah!”

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.

Lab 6: Object Oriented Programming


67
Peeking into Computer Science | Alice Lab Manual
Name the method getScared. To copy the code from the world.getScared method, drag the entire do
together block that we need into the clipboard on the top-right corner of the Alice interface.

Lab 6: Object Oriented Programming


68
Now, delete the do together block and replace it with a call to our new method, pharaoh.getScared.

Peeking into Computer Science | Alice Lab Manual

Lab 6: Object Oriented Programming


69
Go back to the pharaoh.getScared method and drag the contents of the clipboard into the editor’s area.

Peeking into Computer Science | Alice Lab Manual

Lab 6: Object Oriented Programming


70
Now our pharaoh.getScared method is complete!

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!”

Peeking into Computer Science | Alice Lab Manual

Lab 6: Object Oriented Programming


71
Dummy objects (optional)
The world.getScared method should now look like this:

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.

Peeking into Computer Science | Alice Lab Manual


To add a dummy object, click on the green ADD OBJECTS button.

Click on the “more controls” button.

Lab 6: Object Oriented Programming


72
Now click on the “drop dummy at camera” button. This places a dummy object at the camera’s original
position so that we can always go back to it.

Select the green DONE button.

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.

Peeking into Computer Science | Alice Lab Manual


Click on camera in the object tree, and set its point of view to dummy.

Lab 6: Object Oriented Programming


73
Method Parameters
Method parameters (also called arguments) allow you to send information to methods. Most of the
built-in methods you used so far required parameters. For instance, the turn method requires two
parameters: the direction and the amount of turning.

We can also add parameters to the methods we create. Let us take a look at the world.runAway
method.

Peeking into Computer Science | Alice Lab Manual

Lab 6: Object Oriented Programming


74
The code looks very complicated and long. One way we could restructure it is by creating a class-level
method for the pharaoh that instructs him to take one step forward.

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.

Peeking into Computer Science | Alice Lab Manual


Now doesn’t that look much better? Let us further improve the takeSteps method so that the number of
steps is a parameter. From the pharaoh.takeSteps method, select the “create new parameter” button.

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.

Lab 6: Object Oriented Programming


75
To repeat the loop numberOfSteps times, drag the parameter numberOfSteps to set the loop repetition
times.

Peeking into Computer Science | Alice Lab Manual

Lab 6: Object Oriented Programming


76
We can now remove the loop from the world.runAway method. Set the numberOfSteps to 2.

Peeking into Computer Science | Alice Lab Manual


Exercise 6
Add another parameter to the pharaoh.takeSteps method. Name the parameter timePerStep. The
amount of time each of the steps should take is timePerStep. Don’t forget to set the duration of the
individual limb movement using expressions and maths.

Lab 6: Object Oriented Programming


77