AliceEBook PDF
AliceEBook PDF
Wanda P. Dann
Carnegie Mellon University
Stephen Cooper
Saint Joseph’s University
Randy Pausch
Carnegie Mellon University
Prentice Hall
Boston Columbus Indianapolis New York San Francisco Upper Saddle River
Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto
Delhi Mexico City Sao Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo
Vice President/Editorial Director: Marcia Horton Cover Image: Image of computer
Editor-in-Chief: Michael Hirsch ©Alexander Kalina/Shutterstock. Alice
Executive Editor: Tracy Dunkelberger characters courtesy of the Alice Team at
Editorial Assistant: Stephanie Sellinger Carnegie Mellon University.
Vice President of Marketing: Patrice Jones Media Editor: Dan Sandin/Wanda Rockwell
Marketing Manager: Yezan Alayan Project Management: Rose Kernan, Nesbitt
Marketing Coordinator: Kathryn Ferranti Graphics, Inc.
Vice President, Production: Vince O’Brien Composition and Illustration: Nesbitt
Managing Editor: Jeff Holcomb Graphics, Inc.
Production Project Manager: Kayla Printer/Binder: Von Hoffman/R.R. Donnelly
Smith-Tarbox Jefferson City
Manufacturing Buyer: Lisa McDowell Cover Printer: LeHigh-Phoenix
Art Director: Jayne Conte Color/Hagerstown
Cover Designer: Marta Samsel, Black Horse
Design
Credits and acknowledgments borrowed from other sources and reproduced, with permission, appear
on the Credits page in the endmatter of this textbook.
For images on pages 24–25: © Viacom International Inc. All Rights Reserved. Nickelodeon,
SpongeBob SquarePants and all related titles, logos and characters are trademarks of Viacom
Inernational Inc.
Copyright © 2012, 2009, 2006 Pearson Education, Inc., publishing as Prentice Hall. All rights
reserved. Manufactured in the United States of America. This publication is protected by Copyright,
and permission should be obtained from the publisher prior to any prohibited reproduction, storage in a
retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying,
recording, or likewise. To obtain permission(s) to use material from this work, please submit a written
request to Pearson Education, Inc., Permissions Department, 501 Boylston Street, Suite 900, Boston,
Massachusetts 02116.
Many of the designations by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and the publisher was aware of a trademark
claim, the designations have been printed in initial caps or all caps and appear on the Trademark
Information page in the endmatter of this textbook.
Dann, Wanda.
Learning to program with Alice / Wanda P. Dann, Stephen Cooper, Randy Pausch.—3rd ed.
p. cm.
Includes bibliographical references and index.
ISBN 0-13-212247-2
1. Object-oriented programming (Computer science)—Computer-assisted instruction—
Computer programs. 2. Alice (Computer program language) 3. Object-oriented
programming (Computer science)—Study and teaching (Middle school)—Computer
programs. 4. Computer animation—Computer programs. 5. Three-dimensional display
systems—Computer programs. I. Cooper, Stephen (Stephen Charles) II. Pausch, Randy.
III. Title.
QA76.64.D36 2012
005.1'17—dc22
10 9 8 7 6 5 4 3 2 1—RRD—14 13 12 11 10
Foreword xi
Preface xiii
Acknowledgments xxi
About the Authors xxiii
vii
viii Contents
Appendix
Appendix A Using Alice 331
Part 1: Running Virtual Worlds in Alice 331
Part 2: Using Popup Menus to Create an Initial Scene 345
Introductory programming has always been a frustrating course for many students, and recent
attempts to include object-oriented programming in the first semester have only compounded
an already difficult learning experience. This is especially worrisome when recent surveys
show a 23 percent decline in the number of CS majors. We simply can’t afford to discourage
students by needlessly frustrating them in their first exposure to computing.
The Alice system represents a breakthrough in teaching object-oriented computing: in
Alice, objects are easily visible, because they are reified as three-dimensional humans, animals,
furniture, etc. The state of Alice objects is changed via method calls such as “move forward one
meter” or “turn left a quarter turn”—these messages are easily and intuitively understood by
students. Computation is displayed via animations of these state changes: one can hardly
imagine a more visceral way to express the notion of embodying state in an object and using
computation to change that state. One of Alice’s real strengths is that it has been able to make
abstract concepts concrete in the eyes of first-time programmers.
Any good teacher knows that if a student is not motivated to learn, all the pedagogy and
technique in the world won’t help: students learn best when they are internally motivated.
While we can create that motivation via rewards and punishments (i.e., “grades”), the Alice
system uses a purer form of motivation: it bases programming in the activity of storytelling,
which is universally compelling: as we say in Los Angeles, “everybody wants to direct.”
By using 3D graphics as the authoring medium, the Alice system speaks directly to a
generation raised on video games and Pixar’s films; the authors leverage that by using
“storyboarding” as a metaphor for computer program design—storyboarding being one of the
few “design activities” that can be immediately understood by a college freshman.
Coupled with the high-level concepts such as reifying objects, the Alice system provides
a well-engineered drag-and-drop user interface, inspired by the Squeak system’s editor, that
allows students to drag program components around the screen and guarantees that the student
cannot make a syntax error.
One could make the argument that Alice is one of the most novel systems to hit
introductory computing in the last twenty years—and it’s arriving just in time!
ALAN KAY
xi
This page intentionally left blank
Preface
This book and the associated Alice system take an innovative approach to introductory
programming. There have been relatively few innovations in the teaching of programming in
the last 30 years, even though such courses are often extremely frustrating to students. The
goal of our innovative approach is to allow traditional programming concepts to be more easily
taught and more readily understood. The Alice system is free and is available at www.alice.org.
Instructional materials
An errata list, lecture notes, links to other instructional materials, and examples of course
schedules can be found at www.aliceprogramming.net. Contact your local Pearson sales rep-
resentative to get access to the instructor resources.
Figure P-1-1. Programs in Alice (top) can optionally be displayed with a Java-like syntax (bottom)
3 4
5 6, 7, 8,
10 9
11
ercises were provided to allow the instructor to choose exercises most appropriate for their
students. Examples of larger, more free-form “projects” are provided at the end of later
chapters. (A “project” is a more advanced exercise that takes more time.)
Projects are meant to turn on the creative spirit, not weigh the student down. Where
feasible, we recommend “open-ended” projects. An open-ended project is one which asks
students to design their own animation beginning with their own storyline and using objects of
their choosing. We do require that a project meet certain requirements—for example, “an
interactive world, containing two or more interactions with the mouse, at least three methods,
using a decision statement, and having objects from two classes you have created by writing
class-level methods and saving out the new classes.” Alice lends itself particularly well to
student demonstrations of their worlds to the rest of the class on the project due date.
Each chapter has a “Tips & Techniques” section. Collectively, these sections and
Appendices A and B comprise a mini User’s Guide to Alice. The Tips & Techniques cover
animation in Alice rather than traditional fundamental concepts of programming presented in
the major chapter material. The techniques explained in these sections are strategically placed
throughout the text, laying the groundwork for using these techniques in programming examples
that follow. Tips & Techniques provide a guide for those who want to learn more about
animation with Alice. Appendix A is a “getting started” tutorial. Appendix B describes how to
manage the interface. Use of the interface is also integrated with text examples for programming
concepts, where needed. The Tips & Techniques sections enrich the flavor of the book with
selected “how-to” topics.
later as part of coverage of topics in Chapters 6 and 7. Another flexible sequencing option is
to reverse Chapters 7 and 8 to allow coverage of recursion before Loop and While control
structures.
In working with instructors in various high school, college and university settings, we found
that topic selection and sequences are often based on time constraints for a particular course
structure, pedagogy, and philosophy of teaching. If you are limited to three or four weeks as part
of a larger course, you may wish to assign exercises throughout with only one project at the end.
Also, you can use Tips & Techniques sections as reading assignments, not requiring classroom
presentation time. The following Sequence Chart illustrates some examples of sequences.
Alice
The latest version of the Alice software and online galleries of 3D models can be downloaded
from www.alice.org. A DVD is supplied with this book. The DVD contains two versions of
Alice 2.2, one for PC and one for Mac. If you are using a PC with Linux, check the Web site
www.alice.org for a version compatible with your system. The Alice Web site also provides
instructions for installation, Frequently Asked Questions, and links for receiving bug reports.
We maintain active debugging and support for Alice 2.2. Check www.alice.org for the latest
releases.
The software included on the DVD is meant for individual use and is not adjusted for use
in a networked lab environment. Visit www.alice.org download page for Alice 2.2, where you
will find the latest instructions on how to install Alice 2.2 in a networked lab environment.
The Alice system is 3D graphics and memory intensive. The Alice development team has
a set of minimum and recommended requirements for running Alice. Please note that many older
laptops do not meet these requirements. It is extremely important to try Alice on the specific
machines you will be using, just to be sure.
Operating system requirements:
PC
Windows®7, Windows XP or Vista
Mac®
at least OS® X 10.4
Minimum hardware requirements:
A processor running at 500 MHz or better
VGA graphics card capable of high (16 bit) color
256 MB of RAM
Video resolution of 1024 * 768
A sound card
Recommended hardware requirements:
A processor running at 1.0 GHz or better
16 MB 3D video card (see www.alice.org for more details)
500 MB of RAM
Alice works well with digital projection systems for classroom demonstrations. Projectors
limited to 800 * 600 video resolution will work, although 1024 * 768 is best.
WANDA DANN
STEPHEN COOPER
RANDY PAUSCH
This page intentionally left blank
Acknowledgments
Seymour Papert’s Logo and Rich Pattis’s Karel the Robot were great inspirations in using a
visible micro world. Alan Kay and the Squeak team inspired us to create the mouse-based
program editor, and we were also inspired by the syntax-directed editor work done by Tim
Teitelbaum. We are indebted to George Polya, Mike Clancy, and Doug Cooper for our
problem-solving approach.
Our deep gratitude goes to early testers and users of our text and instructional materials
for their helpful comments and suggestions: Susan Rodger (Duke University), Rick Zaccone
(Bucknell University), Bill Taffe (Plymouth State), Angela Shifflet (Wofford College), and
William Taylor (Camden County College). In addition, we are thankful for the assistance of our
students: Toby Dragon (Ithaca College), Kevin Dietzler (Saint Joseph’s University), Patricia
Hasson (Saint Joseph’s University), and Kathleen Ryan (Saint Joseph’s University). Our sincere
thanks to Sue Mitchell, Calhoun Community College, who provided examples and consultation
on the addition of flowcharts and implementation strategy diagrams for the second edition.
For the third edition, our thanks to Leslie Spivey (Edison Community College) who provided
a thorough list of typos and image errors for correction. Also for the third edition, our thanks to
Dean Johnson (Fort Atkinson High School, WI) for his generous contributions of ideas, worlds,
and write-ups for new exercises and projects. Many of the ideas were inspired by the work of his
students, including Justin Scroggins, Scott Rupprecht, Tommy Johnson, Ramsey Statz and
Mercedes Bernard. These contributions add strength and vitality to the third edition.
The life and breath of the Alice software is dependent on a group of creative, energetic,
and dedicated graduate students, undergraduate students, and staff members at Carnegie Mellon
University. Without these people, Alice does not live and we could not have written this textbook.
The primary authors of Alice 2 include Ben Buchwald, Dennis Cosgrove, Dave Culyba, Cliff
Forlines, Jason Pratt, and Caitlin Kelleher; a more complete list is available at www.alice.org.
Many artists at Carnegie Mellon have graciously placed their work into the gallery for the
benefit of others. We list Sarah Hatton, Mo Mahler, Shawn Lawson, and Tiffany Pomarico
here, but the contributors run into the hundreds. Tommy Burnette, Kevin Christiansen, Rob
Deline, Matt Conway, and Rich Gossweiller all made seminal contributions to earlier versions
of Alice at the University of Virginia. We also thank the University for its support and
encouragement of earlier versions of Alice.
We are most grateful to Madeleine Pitsch, Carnegie Mellon University, who implemented
updates for Alice, version 2.2. We owe many thanks to Dennis Cosgrove who provided guidance
and assistance to us, as well to Barbara Ericson, Georgia Institute of Technology, who generously
contributed some of the code and provided consultation for the export video implementation.
And sincere thanks to Jennifer Mung’Au for implementing a walk method for most of the
person models in the amended People gallery. Special thanks are due to Pamela Lawhead and
Aik Min Choong, University of Mississippi, who provided bug fixes and support for Alice 2.2.
This material is based upon work partially supported by the National Science Foundation
under Grant Numbers 0302542, 0339734, 0126833, 0624528, 0623808, 0624479, 0624642, and
0624654. Any opinions, findings, and conclusions or recommendations expressed in this
material are those of the author(s) and do not necessarily reflect the views of the National
Science Foundation.
We gratefully acknowledge the reviewers of the first edition: Mary Ann Amy-Pumphrey,
De Anza College; Leland Beck, San Diego State University; Elizabeth Boese, Colorado State
University; Deb Deppeler, University of Wisconsin; Kendra Dinerstein, Utah State University;
John Dougherty, Haverford College; Odis Hayden Griffin, Jr., Virginia Tech; Mark Guzdial,
xxi
xxii Acknowledgments
Georgia Institute of Technology; Richard Pattis, Carnegie Mellon University; Sally Peterson,
University of Wisconsin; Susan Rodger, Duke University; William Taylor, Camden County
College; Suzanne Westbrook, University of Arizona; Rick Zaccone, Bucknell University.
We also thank the reviewers of the second edition, who provided valuable comments and
suggestions: Gilbert Armour, Virginia Western Community College; Marni Ferner, University
of North Carolina Wilmington; Michelle Folsom, Pacific Lutheran University; Stephen J.
Hartley, Rowan University; Christopher Haynes, Indiana University; Barbara Holt, Northern
Virginia Community College; Kelly Schultz, Kalamazoo College; Roxanne H. Stalvey, College
of Charleston; Katherine St. John, Lehman College.
We thank Tracy Dunkelberger of Pearson and Alan Apt for supporting this effort. Over
the last ten years Electronic Arts, Sun Microsystems Foundation, Oracle, Hyperion, Google,
DARPA, NASA, Apple, Ford, Intel, Microsoft Research, and SAIC have contributed support
for the development of the Alice system, for which we are most grateful.
About the Authors
Wanda P. Dann is Senior Systems Scientist and Director of the Alice Project at Carnegie
Mellon University. Her research interests include visualization in programs and programming
languages and innovative approaches to introductory programming.
Randy Pausch was Professor of Computer Science, Human-Computer Interaction, and Design,
Carnegie Mellon University, and founding Co-Director of CMU’s Entertainment Technology
Center. He consulted with Google, Walt Disney Imagineering, and Xerox PARC. Randy passed
away July, 2008, after a valiant fight with pancreatic cancer.
xxiii
This page intentionally left blank
Learning to Program with Alice
This page intentionally left blank
Part I
Introduction
to Alice
1
This page intentionally left blank
Chapter 1
Getting Started
with Alice
3
4 Chapter 1 Getting Started with Alice
in our cars, and computer modeling that allows us to design new drugs to fight diseases like
AIDS. Computer programmers help to make all of these technological advances possible.
Computers, and the software that computer programmers write for them, have revolu-
tionized the entertainment industry. Computer gaming is becoming increasingly popular. The
Pew Internet and American Life Project reported (in 2003) that about 70 percent of college
students play online computer games at least once a week. Movies in the Star Wars series, and
the special effects in them, are only possible because of computers. By the way, one of the
undergraduate authors of the Alice system graduated and went to work at ILM (Industrial
Light and Magic), who do the special effects for Star Wars films. So the next time you watch
The Phantom Menace, look for Tommy Burnette in the credits!
Computers help us communicate with each other by maintaining complex cellular tele-
phone networks, they aid marine research by tracking animal migratory patterns, and they
allow us to explore space. None of these things would be possible without computers.
Of course, many of the people who write the software for these projects are professionals
who have spent years studying programming. But even people who are not planning to be
professionals can benefit greatly from even a single course in programming. Modern applica-
tions, like spreadsheets and word processors, give end users the opportunity to save time and
effort by using “macros” or other programming-like features that tell the computer to do
something long and tedious, instead of having the user do it. Also, if you have even a little
experience with programming, you’re much more likely to become the “go to” person in an
office where computers are used, which can help you get ahead in your career.
Most importantly, even one course in computer programming can be useful as a way of
learning a new way to think, much as taking a drawing course is a way to learn how to look
at the world differently. Learning to think in new ways is always extremely valuable. Many
of us talk about how we’d like to improve our general problem-solving skills. “Problem solv-
ing” is really just finding an answer to a question or figuring out how to perform a task.
Computer programming is a pure, distilled form of problem solving. So, learning to program
a computer will truly help you learn a new way to think—enabling you to find answers to
questions and figure out how to make things work.
How you will learn to program with this book and Alice
This book and the associated Alice system will teach you to program a computer, but in a
fundamentally different and more enjoyable way than ever before. In terms of tone, we have
worked very hard to make learning to program as painless as humanly possible. Most
programming, especially in introductory computing courses, has the feeling of mundane
calculation: add up a bunch of numbers, and print out their sum and average. Often, students
find these courses frustrating because of all the obscure technical details they must get right
before anything will work at all. Students often talk about singing songs in ritual attempts to
appease the computer gods. We felt there had to be a better way.
This book uses a completely different approach that is only recently possible due to the
increased power of desktop computers and the development of novel software that uses that
power, especially for 3D graphics. The Alice system, which is provided freely as a public
service by Carnegie Mellon University,1 provides a completely new approach to learning to
program. Originally developed as part of a research project in Virtual Reality,2 Alice lets you
be the director of a movie, or the creator of a video game, where 3D objects in an on-screen
virtual world move around according to the directions you give them. Rather than using
obscure computer terms, you use natural English language words, like “move forward” or
1
We also gratefully thank the University of Virginia, where an earlier version of Alice was developed.
2
We gratefully acknowledge the support of the National Science Foundation, DARPA, Intel, and a number
of other sponsors who have supported the Alice project: a complete list is available at www.alice.org.
1-1 Introduction to Alice 5
“turn right.” Best of all, you can’t make mistakes! Well, of course you can always make some
mistakes, such as telling one of your objects to move forward when you meant to move it
backward. You can’t, however, make the kind of “computer mistake” that most students get
frustrated by—where you type something wrong and you can’t figure out why the program
won’t run at all.
If the term “computer programmer” makes you think of some poor drudge hunched
over a computer keyboard in a darkened room—don’t worry! You’ll almost never even touch
the keyboard when using the Alice system. You will create programs by dragging words and
objects around on the screen using the mouse. Then, when you press the “Play” button (cir-
cled in Figure 1-1-1), the objects in the 3D world on your screen will come to life and act out
the script you have written for them! So, in a sense, being a “computer programmer” using
Alice is really like being a movie director, a puppeteer, or a choreographer—anyone who
gives people instructions about what to do in a precise but limited vocabulary.
After you’ve learned how to use Alice, you’ll understand all the fundamental ideas
involved in programming. Then, you will be in great shape to use one of the “real world”
languages where you have to type with the keyboard and get all the commas and semicolons
in the right place. You will know how to program, and all you’ll have to learn are the particu-
lar grammar “rules” (sometimes called the “syntax”3 ) of languages like Java, C+ +, C #, or
whatever.
3
Not to be confused with sin tax, a tax on things like cigarettes or alcohol.
6 Chapter 1 Getting Started with Alice
to describe well-written programs. We recommend that you think of a computer program not
only as a way to tell the computer what to do, but also as a way to tell another human being
what you want the computer to do.
A computer program is not only “a way to tell the computer what to do.”
A computer program is a way to tell another human being what you want the
computer to do.
That makes it a lot easier to talk about whether something is “elegant.” A program is
elegant if other human beings can easily understand and appreciate the intentions of the orig-
inal programmer. For this reason, one basic part of writing a computer program is to include
documentation (comments in the program, a Web page for reference, or an accompanying
written document) that helps another human being understand what you were trying to do.
The key to computer programming is to get a handle on the fundamental ideas. At its
heart, programming is really very simple. All computer programs are made from very simple
ideas:
A list of instructions: For example, “Beat eggs; mix in flour, sugar, and shortening;
pour into baking pan; then bake at 375 degrees for 45 minutes.” Computer scientists call
this sequential processing.
Ifs: For example, “IF it is raining, take an umbrella.” Computer scientists call this
conditional execution.
Repeating behavior: For example, “Stomp your foot five times” or “WHILE there are
cookies on the plate, keep eating cookies.” (That last part actually sounded kind of fun!)
Computer scientists call this looping, or iteration.
Breaking things up into smaller pieces: For example, “The way we’re going to clean
the house is to first clean the kitchen, then clean the bathroom, then clean each of the
three bedrooms one at a time.” Okay, so that doesn’t sound like as much fun as eating
the cookies, but it’s still a pretty easy concept. Computer scientists call this problem
decomposition, or stepwise refinement, or top-down design, but it’s really an ancient
philosophical approach called reductionism. Regardless of what you call it, it means
that to do a complicated task, break it down into a list of simpler tasks. The result of
accomplishing all the simpler tasks is that the complicated task is accomplished.
Compute a result: Here we perform a sequence of steps to obtain a result that is an
answer to a question. For example, “Look in the phone book and find the number for
Rebecca Smith,” or “Put this baby on a scale and tell me how many pounds she weighs.”
Actually, each of these actions embodies a question: “What is Rebecca’s phone
number?” or “How much does the baby weigh?” A question is known as a function in
computer programming. Asking a question so as to compute a result (find an answer) is
known as calling a function.
Computer programming is really just using these ideas in various combinations. What can
make things hard is complexity. The truth is that most computers “understand” only about 100
different instructions. The millions of programs that run on computers use these same 100
instructions in different orders and combinations. So where is the complexity? Think about it
like this: In a chess game, there are only six kinds of chess pieces, and each piece moves in a
simple pattern. Chess is a complicated game because of all the possible combinations of moves.
To put this another way, writing a computer program is like putting on a stage play with
200 actors, 500 costumes, and 5 live camels that appear in Act II, Scene IV. Things can get
complicated just because that’s a lot to keep track of! This book will teach you some tricks for
managing complexity and for planning out how to write programs before you actually try to
make them work. In fact, learning how to think about arranging a sequence of instructions
to carry out a task (how to design a program) is probably the most valuable part of
learning to program.
1-1 Introduction to Alice 7
call decision
In a flowchart, a word or phrase is written inside each symbol, to give some detail about the
represented action.
• A terminal symbol represents the beginning or ending of a complete program or a log-
ical piece of a larger program. The words often seen within a terminal symbol include:
“start,” “begin,” “end,” “stop,” and “return.”
• The input/output symbol represents an action where the user of the program is being
asked for information (input) or when the program is displaying a result (output).
The words often seen in this symbol include: “read Á ”, “print Á ”, and “write.”
• The processing symbol is used to illustrate any mathematical operation (addition, subtrac-
tion, multiplication, and division), or the execution of a built-in instruction or statement.
• In a program that has been broken down into several pieces, one piece of the program
may call on another piece to perform a task. A call symbol represents the action of one
piece of a program calling another piece of the program.
• The decision symbol represents an action where a decision is to be made. The outcome
of a decision will be a Boolean value, which is either true or false. The words within a
decision symbol express the condition (or test) that is being evaluated.
The symbols in flowcharts are connected by flow lines (arrows) and other connectors, such as
a circle (where multiple arrows may converge) and a pentagon (to indicate the flowchart con-
tinues on another sheet of paper). Connectors are illustrated in Figure 1-1-3.
The circle is an on-page connector. (If the page is too short, an on-page connector is used to
begin the rest of the flowchart on the same page, but in a different location.) The home plate
is an off-page connector. When there is no more room on the page to continue, the off-page
connector is used to begin a second (third, fourth, etc.) page, as needed. An example of a tra-
ditional flowchart is shown in Figure 1-1-4. This is a simple design that uses flow lines but
does not need other connectors. To follow the logic of the flowchart design, start at the top and
read downward (top to bottom).
start
read a
value
display the
value
entered and
X
stop
and the interface to help you get started. This section works hand-in-hand with the Getting
Started exercises in Appendix A. We suggest that you read this section and work through the
Getting Started exercises while sitting at a computer where you can try things out as you read.
Figure 1-2-2. 3D world with the tortoise and hare, front and back view
An Alice virtual world begins with a template for an initial scene. The templates are
shown in the opening window when Alice is started. The templates can be seen in Figure 1-2-3,
where we have selected an initial scene composed of a blue sky and a grassy-green ground
surface.
To make it easy to create a new world and populate it with all kinds of objects, the Alice
developers have provided a huge number of 3D models. In a way, a 3D model is like a blue-
print used to design a house. The blueprint provides a model of what the house will look like,
the location and size of each room in the house, and some instructions for the housing con-
tractor to follow in actually building the house. Likewise, an Alice 3D model tells Alice how
to create a new object in the scene. The 3D model provides instructions on how to draw the
object, what color it should be, what parts it should have, its size (height, width, and depth),
and many other details.
The installation of Alice on your computer includes a Local gallery that contains a selec-
tion of 3D models. Additional models can be found in the Web gallery (http://www.alice.org)
and on the DVD provided with this book. Easy access to the 3D models in a gallery collection is
provided by the scene editor, shown in Figure 1-2-4. If you have the DVD in your DVD ROM
when you start Alice, a DVD gallery folder will also appear in the folder. Examples and exer-
cises in this book use models from both the Local and the Web galleries. If you want to use a 3D
model that does not appear in the Local gallery, you can find it on the DVD or the Web gallery.
Alice is not a 3D graphics drawing program. This is why generous galleries of 3D mod-
els are provided. It is not possible, though, to think of everything someone may want for a vir-
tual world. To help you build people objects of your own, custom builder tools (hebuilder and
shebuilder) are available in the People folder of the Local gallery. Details on using these tools
are provided in Chapter 5 Tips & Techniques.
Figure 1-2-4. Scene editor with Local and Web Gallery folders
It is important to notice, for example, that directions are left and right with respect to the
astronaut object, not the camera’s point of view. An object’s orientation is the direction and
angle at which an object is facing forward. When you mouse-click an object in an Alice
world, a yellow bounding box is displayed, as seen in Figure 1-2-6. The bounding box high-
lights the selected object.
12 Chapter 1 Getting Started with Alice
Not all objects have their center located at their center of mass. Those that generally sit
or stand on the ground or a table have their center located at the bottom of their bounding box.
For people objects, the center point is between their feet, as shown in Figure 1-2-8. This is
because a person’s feet are on the ground and the distance of the person above the ground is
zero (0) meters.
Other kinds of objects that do not have a center at the center of mass are those that are
“held” when used, such as a baseball bat. The center point of a baseball bat is where it would be
held, as illustrated in Figure 1-2-9. The center is on the handle so that when you rotate it, it will
“swing” about that point.
Concept: Distance
One object’s distance to another is measured from its center. For example, the bird’s distance
downward to the ground in Figure 1-2-10 is measured from the bird’s center.
1-2 Alice concepts 13
Figure 1-2-10. Distance downward to the ground is measured from the center
Concept: Position
The center of an object is the point used as its “position” in a world. Alice automatically puts
the center of the ground at the center of the world. In Figure 1-2-11, a set of coordinate axes
is positioned at the center of the ground. In the properties list for the ground (located in the
Figure 1-2-11. The center of the ground is located at the center of the world
14 Chapter 1 Getting Started with Alice
details panel at the lower left of Figure 1-2-11), you can see that the center of the ground is
located at (0, 0, and 0).
Like the ground, any object in the world is located relative to the center of the world.
The bird in Figure 1-2-12 is located at position ( -3.41, 1.59, 6.15). That is, the center of the
bird is 3.41 meters left, 1.59 meters above, and 6.15 meters forward of the center of the
world.
Figure 1-2-12. The bird’s position relative to the center of the world
Concept: Animation
In Alice, you will build virtual worlds and create animations by moving the objects in a world
in the same way that objects are moved in a flight simulator or a video game. You will use
many of the same techniques to give the illusion of motion as are used by animators to create
animated cartoons for film studios such as Disney® and Pixar®. Animation is a fantasy of
vision, an illusion. To generate this illusion, the filmmaker and artist collaborate to create a
sequence of artwork frames (drawings or images) where each has a slightly different view of
a scene. The scene is drawn with objects, and then redrawn with the objects positioned in a
slightly different place. The scene is drawn again and the objects moved just a bit more, over
and over and over! Figure 1-2-13 illustrates a sequence of frames in Alice.
1-2 Alice concepts 15
3D text
To add a 3D text object to a world, click on the Create 3D Text thumbnail in the Local Gallery,
as seen in Figure T-1-1.
16 Chapter 1 Getting Started with Alice
A text dialog box pops up for entering text, as in Figure T-1-2. The dialog box allows
font, bold, and italic selections, and a text box where words can be typed.
When the Okay button is clicked, Alice adds a text object to the world and an entry for
the object in the Object tree. The name of the object is automatically “3D Text”, as seen in
Figure T-1-3.
Figure T-1-3. The text object is added to the scene and object tree
1-2 Alice concepts 17
The text object can be positioned using mouse controls in the same way as any other
object. To modify the text in the object string, click on the text in the properties list of the
details panel. Then, enter a new string of text in the popup dialog box, illustrated in
Figure T-1-4.
Note that modifying the string in the text object does not modify the name of the object.
The name is still as it was when the text object was originally created, as seen in Figure T-1-5.
Alice will add the flat image to the world. The billboard in Figure T-1-7 illustrates one of
the uses of billboards—providing information to the user about how to play a game or simu-
lation. In this example, a billboard provides instructions for how to use the keyboard to con-
trol the motion of an object. (Keyboard control examples are used in Chapter 5.)
Summary
At the end of each chapter, we present a summary and a list of important concepts. The pur-
pose of a summary is to pull together the information and ideas presented in the chapter into
a meaningful whole. The purpose of a list of important concepts is to provide a quick review
and study guide.
In this chapter, a computer program was presented as a sequence of instructions that tell
the computer what to do. Importantly, a computer program is also a way to tell another human
being what you want the computer to do. Learning to think about arranging a sequence of
instructions to carry out a task (how to design a program) is probably the most important part
of learning to program.
Alice is a 3D animation software tool that can be used to learn how to design and write
computer programs. Alice allows you to quickly create cartoon-like animations of objects in
a 3D virtual world. The objects are three dimensional, having width, height, and depth. Each
object has an orientation that provides a sense of direction. That is, an object “knows” which
way is up, down, left, right, forward, and backward relative to itself.
Programming Terms
class flowchart
computer program object
design
Animation Terms
3d model animation
three dimensional orientation
virtual world
Questions
(In addition to Chapter 1, these questions assume you have completed the tutorial in
Appendix A.)
1. The tutorial in Appendix A illustrates two different kinds of animations: movies and
interactive. What is the difference between the two?
2. List three ways in which a class (3D model) is similar to a blueprint for a house.
3. What are the six directions an Alice object can move?
4. Is the center of an Alice object always located at its center of mass? Justify your answer.
5. What does it mean to say that an object is egocentric, in terms of motion?
6. Use a diagram to illustrate the distance between two Alice objects. Describe the dis-
tance in a sentence.
7. An Alice billboard is considered 2D rather than 3D. Why?
8. Look up the term “programming language” in a dictionary or on the web. What is the
definition and does Alice meet this definition of a programming language?
9. Sketch and label the symbols used in creating a flowchart.
Exercises
The exercises below are to verify that you have learned and are comfortable using the Alice
software. The goal in each exercise is to create an initial scene for a world. Alice will period-
ically prompt you to save your world. (Instructions on how to save a world are provided in the
Getting Started exercises in Appendix A.) A name for your world is suggested by the name of
the exercise. For example, the world in Exercise 1 could be named Island.a2w.
The objects in each world are created from the 3D models in the Alice gallery. Most
models are located in the Local Gallery included in the Alice installation. If the model is
not in the Local gallery, look for the model in the DVD gallery or the online Web gallery
(www.alice.org).
1. Island
Create an island scene. Start by choosing a water world template. Add an island
object (from the Environments gallery folder). Use the scene editor to position the
island a bit to the right of the center of the scene. Now, add a fish (from the Ocean
gallery) to the scene. You may find that the fish is invisible because it is located
behind the island or is not properly positioned. Use the scene editor and its quad view
to arrange the fish so it looks like it is swimming in the water to the left of the island.
Use the camera controls to zoom out so the island and the fish are both in the cam-
era’s view.
20 Chapter 1 Getting Started with Alice
2. Winter
Add two snowmen (People gallery folder) to a snowy scene. Use a snow template initial
world. Then, create a snowman stack by using the scene editor’s quad view to position
one snowman on top of the other (vertically), as shown below.
3. Snowpeople Pile
Build a “wall” of four snowpeople by tipping them over on their sides and piling them
on top of one another. (Use methods, mouse controls, and quad view.) Four snowpeople
(alternating between snowman and snowwoman) might be used to produce a wall that
looks like this:
4. Tea Party
As a tribute to Lewis Carroll, create a Tea Party for Alice Liddell and the white rabbit.
In addition to AliceLiddell (People) and the whiteRabbit (Animals), the party should
include a table (Dining Table in Furniture folder on DVD or Web gallery) and three
chairs (Furniture), a teapot, a toaster, and a plate (Kitchen). Use method instructions,
the mouse, and quad view to properly position objects like the teapot or toaster on the
table. The picture below is provided as an example. Use your imagination to make a
better scene, if you wish.
Exercises 21
Right-click on each soldier and use methods (from the popup menu) to rotate the arms
of the soldiers to salute each other. Or, use the mouse controls in the scene editor to
rotate the arms into position. (Use the “affect subparts” checkbox to allow the mouse to
rotate their arms.) Raise the left arm of each soldier (at about a 45-degree angle with the
horizontal plane). The result should be a scene where all four soldiers are saluting. This
is not an animation—all you are trying to do is set up the scene.
Hint: If you check the “affect subparts” checkbox to allow the mouse to rotate subparts of
an object, remember to uncheck the box before using the mouse for some other purpose!
6. Mysterious Underwater World
Create a mysterious underwater world. Use the sand template. Change the World Prop-
erties so that the atmosphereColor is blue, the ambientColor is black, the ambientLight-
Brightness is 0.1, and the fogDensity is 0.03. Add at least four of the following objects:
seaweed (Ocean), FireCoral (Ocean), Mt. Fuji (Japan), island2 (Environments), Sail-
boat (Vehicles), BigBoat (Vehicles), Boeing707 (Vehicles). Be creative by adding
objects that would make the world mysterious.
Chapter 2
Program Design
and Implementation
While the programs presented in the first few chapters of this text are reasonably clear-cut, we
think it is advisable to start building good designs early on. Then, when programs begin to get
more complicated, the time invested in learning how to design good program solutions will
pay great dividends.
Scenario example
Let’s consider an example scenario: After traveling through space, a robot-manned craft has
just made a breathless landing on the surface of a moon. The robot has already climbed out of
the lunar Lander and has set up a camera so earthbound scientists at the NASA center in Hous-
ton can view this historic event. Through the camera (the scene in our world), we can see the
robot, the lunar Lander and some nearby rock formations. Suddenly an alien peeks out from
behind a rock and looks at the robot. The robot is surprised and rotates its head all the way
around. The robot walks over to take a closer look and the alien hides behind the rocks. Finally,
the robot looks at the camera, signals danger, and says “Houston, we have a problem!”
From this scenario, we have answers to questions:
• What story is to be told? This scenario tells a humorous story about a robot’s first
encounter with an alien on a distant moon.
• What objects are to be used? The objects are the robot, a lunar Lander, and an alien. The
background scenery should depict a moon surface in a space world.
• What actions are to take place? The actions include the alien peeking out from behind a
rock, the robot turning its head around and moving toward the alien, the alien hiding
behind the rocks, and the robot sending a message back to earth.
Design
A storyboard is the design approach we will use to create a solution to a problem or plan a
list of actions to perform a task, as specified in the scenario. At Pixar, Disney, and other major
animation studios, animators break down a long scenario into sequences of many short sce-
narios. For each scenario, a storyboard is created to depict the sequence of scenes. The story-
board may consist of dozens of scene sketches, drawn by animation artists or generated by
computer animation specialists using computer software. Figure 2-1-1 illustrates storyboard
sketches from SpongeBob SquarePants, Episode 106, by Nickelodeon™.
The storyboard approach to design that breaks a problem or task down into smaller sub-
problems or tasks is not unique to computer programmers and animators. Playwrights, for
24 Chapter 2 Program Design and Implementation
example, break their plays down into individual acts and the acts into individual scenes. Engi-
neers break down complicated systems (e.g., jet airplanes and claw hammers) or devices
(e.g., microcircuits) into component parts to make the problem more manageable.
Visual storyboards
A visual storyboard breaks down a scenario into a sequence of major scenes with transitions
between scenes. Each sketch is a representation or a snapshot of a scene (state) in the anima-
2-1 Scenarios and storyboards 25
tion. Each snapshot is associated with objects in certain positions, colors, sizes, and poses.
When one or more transitions (changes) occur in the animation, the transition leads to the next
scene (state).
The snapshots are numbered in sequence and labeled with necessary information. For
short animations, the breakdown might be presented on one large sheet of paper. For more
complex designs, a separate sheet of drawing paper might used for each scene, allowing the
animation artist to easily rearrange or discard scenes without starting over.
26 Chapter 2 Program Design and Implementation
Scene Number:
(sketch)
Description
Sound:
Text:
sent the surface of the moon. Using simple figures, hand-sketched storyboards are quick
and easy to create.
For illustrations in this book, we use Alice’s scene editor to add objects to a world and
then patiently arrange the objects in various poses. As each successive scene is created, a
screen capture is made and copied to a document. Figure 2-1-4 illustrates screen captures in a
storyboard for the beginning of the robot’s first encounter animation. (We used the spiderRo-
bot and the alienOnWheels from the SciFi folder in the gallery.) Naturally, screen captures for
a storyboard are fancier than hand-drawn sketches, but they take longer to put together.
Textual storyboards
While professional animation artists use visual storyboards as part of their project develop-
ment process, not everyone has the patience to make dozens of sketches. A textual storyboard
is a good alternative. It looks something like a “to-do list” and allows us to prepare a planned
28 Chapter 2 Program Design and Implementation
structure for writing program code. To take advantage of the strengths of each, both visual and
textual storyboards are used throughout this book.
The lines of text in a textual storyboard provide an ordered list of actions. The lines are
written in an outline format and indentation makes the storyboard easy to read. Notice that
two lines are in italics. These lines organize the actions—some actions are to be done in
order (one at a time), others are to be done together (at the same time). The first four actions
are performed in order (the alien moves up, alien says “Slithy toves?”, robot’s head turns
around, robot turns to look at the alien). The next action, where the robot moves toward the
alien to take a closer look, is actually a composite of actions performed simultaneously (the
robot moves forward at the same time as the robot’s legs simulate a walking action).
In computing terminology, a textual storyboard is called an algorithm—a list of actions
to perform a task or solve a problem. The actions in a textual storyboard are very close to (but
not quite) actual program code and so they are often known as pseudocode.
What is a program?
As you know, a program is a list of instructions (actions) to accomplish a task. You can think
of an Alice program as being somewhat like a script for a theatrical play. A theatrical script
tells a story by describing the actions to be taken and the words to be delivered by actors on
stage. In a similar manner, an Alice program prescribes the actions to be taken and the sound
and text to be used by objects in a virtual world.
Actually, this storyboard is incomplete because (in the interests of space) we did not fin-
ish the story. The scenario described a sequence of actions: (1) the alienOnWheels moves up
from behind the rocks, (2) the alienOnWheels says “Slithy toves?”, (3) the spiderRobot’s
head turns around, (4) the spiderRobot turns to look at the alienOnWheels, (5) the spiderRo-
bot moves toward the alienOnWheels to get a closer look, (6) the alienOnWheels hides
behind a rock, (7) the spiderRobot looks at the camera, and (8) the spiderRobot says “Hous-
ton, we have a problem!” Let’s complete the textual storyboard by adding the remaining
actions, as shown next.
Up to now, we have illustrated the use of visual and textual storyboards to design (plan)
a program to create the animation. You may recall that flowcharting is a more traditional
design tool. Although storyboards are fun to use, flowcharts are also quite useful in creating a
design for an animation program. Figure 2-2-3 is a flowchart that expresses a design for the
First Encounter example.
Compare the textual storyboard to the flowchart. At the beginning of the textual story-
board is the statement “Do the following steps in order.” This means that the actions in the
program will be performed in sequence, one after the other, as the program runs. A flowchart
design assumes sequential order, following the flow lines of the visual diagram. In this flow-
chart, the actions are performed by the robot and alien from “start” to “stop” (top to bottom of
the diagram). The actions performed by the robot and alien are all built-in methods, provided
by the Alice software for each object added to a world.
About midway down the textual storyboard, another statement says, “Do together.” The
actions indented within the Do together will be carried out simultaneously. The robot moving
forward and the robot’s legs walking are to be performed at the same time, so as to simulate a
robot walk. Since these two actions are to be done together, a single processing symbol is
used for both actions and the word “and” is used to indicate that these two actions are
performed at the same time.
32 Chapter 2 Program Design and Implementation
start
alien moves up
alien says
“Slithy
toves?”
robot moves
toward the alien
and at the same
time, robot legs
walk
robot says
“Houston,
we have a
problem”
stop
In our example, we want to translate the storyboard to program code. We begin with
the first step, making the alienOnWheels peek up from behind the rocks. One of the alienOn-
Wheels’ methods is move—we can use this method to make the alienOnWheels move
upward. The next step is to have the alienOnWheels say, “Slithy toves?” The alienOnWheels
has a say method that can be used for this purpose. In a similar manner, each action in the
storyboard will be translated to instructions, using the built-in methods of the objects in the
world.
Do in order
To tell Alice to do instructions in sequential order, a Do in order block is dragged into the
editor, as shown in Figure 2-2-5.
The first four instructions can now be placed within the Do in order block. First, the
alienOnWheels is selected in the Object tree. Then, the alienOnWheels’s move method tile is
34 Chapter 2 Program Design and Implementation
selected and dragged into the Do in order, as shown in Figure 2-2-6. The move method
requires arguments—which direction and how far (amount) the alienOnWheels should
move. (An argument is an item of information that must be supplied so Alice can execute the
action.) In this example, the alienOnWheels is hidden behind the rocks and we want the
alienOnWheels to move upward so the direction is up. The rocks are not very tall, so we will
try a distance of 1 meter. (If this distance is not enough or is too much, we can adjust it later.)
The method name and its arguments are the components of an instruction.
The second instruction is to have the alienOnWheels say, “Slithy toves?” Select
alienOnWheels in the Object tree and drag in the say method tile. Select other as the argu-
ment, as shown in Figure 2-2-8. A popup dialog box provides a text area where you can enter
the words you want to appear. Type “Slithy toves?” without the quotes, as illustrated in
Figure 2-2-9 and then click OK.
The first two instructions are shown in Figure 2-2-10. When this program is run (it is
perfectly fine to try out the effect of just one or two Alice instructions by clicking on the Play
button), the alienOnWheels will move up from behind the rocks and then say, “Slithy toves?”
For the third instruction, the spiderRobot’s head is to turn around a full revolution (to
express surprise). How can we turn the spiderRobot’s head? Clicking the + next to spiderRo-
bot in the Object tree causes its subparts to be displayed. Click on the + next to spiderRobot’s
neck in the Object tree. Then clicking on the spiderRobot’s head in the Object tree allows
access to instructions for moving its head. Drag the turn method tile into the editor and select
left as the direction and 1 revolution as the amount of turn, as shown in Figure 2-2-11.
36 Chapter 2 Program Design and Implementation
In the fourth instruction, the spiderRobot will turn to face the alienOnWheels. The third
instruction (above) rotated the spiderRobot’s head. In this instruction, we want the entire spi-
derRobot to turn to face the spiderRobot turn to face method tile is dragged into the editor and
alienOnWheels is selected as the target argument, as illustrated in Figure 2-2-12.
The program code with the first four instructions completed is shown in Figure 2-2-13.
Do together
The next step in the storyboard requires two things to occur at once: the spiderRobot moving
forward at the same time as its legs move up and down. A Do together tile is dragged into the
Do in order, as shown in Figure 2-2-14. Notice the horizontal (green in the editor) line in
Figure 2-2-14. A green line indicates where the Do together instruction will be dropped.
The result of this modification, illustrated in Figure 2-2-15, is that the Do together
block is nested within the Do in order block. Nesting means that one program statement is
written inside another. Note that nesting the Do together inside the Do in order just happens
to be the best way to animate this example. A Do together does not have to be inside a Do in
order. These two coding blocks can work together or can work separately in many different
combinations.
Now, methods can be dragged into the Do together block to simultaneously have the
spiderRobot move forward and walk. The move forward instruction is easy. Just add a spider-
Robot move instruction with forward as the direction and 1 meter as the distance, as illus-
trated in Figure 2-2-16.
The spiderRobot has several legs. To simplify our program, we will animate the walk-
ing action of just two legs (backLeft and frontRight). The spiderRobot does not have a method
named “walk.” We have to write our own instructions to make the robot’s legs move in a walk-
ing action. Looking at the object tree for the robot’s subparts, you can see that each leg is seg-
mented. A leg “walks” by turning a segment of the leg. The motion simulates a turn at the
joint where the segments are connected (similar to bending your knee).
To visualize the actions needed to make the legs work, study the flowchart-like diagram
in Figure 2-2-17. The diagram breaks down the walking action into simple steps, where par-
allel process symbols represent actions that are carried out at the same time. That is, the robot
moves forward at the same time as the backLeftLegUpperJoint and the frontRightLegUpper-
Joint turn. In this diagram, the joint turn actions of each leg are enclosed in a blue dotted-line
box to indicate that (although these actions are in parallel) each consists of a sequence (Do in
order). That is, the leg turns are each a Do in order, nested within the Do together.
Converting the design into program code is now much easier than trying to write the
program by trial and error. Let’s begin by creating an instruction to turn the backLeftLegUp-
perJoint. First select the backLeftLegUpperJoint subpart of the backLeftLegBase subpart of
the spiderRobot in the Object tree and then drag the turn method tile into the Do together
block, as shown in Figure 2-2-18.
Note that popup menus allow you to select arguments for the direction and the amount
of turn. Select forward as the direction and other as the amount. When other is selected as the
amount, a number pad (looks like a calculator) pops up on the screen. We chose 0.1 revolu-
tions, clicking the buttons on the number pad to make our selection. How did we know to use
0.1 revolutions as the amount? Well, we didn’t. We just tried several different amounts until
we finally found one that worked to give the best bending motion for the leg joint. This is an
example of a trial-and-error strategy. While we always recommend good planning strate-
gies, sometimes trial and error is useful.
Naturally, when a leg joint is turned in one direction it must turn back again (to maintain
balance). The two turn instructions for the backLeft leg are shown in Figure 2-2-19.
Using the same technique, instructions are created to turn the frontRight leg. The
completed walking instructions are shown in Figure 2-2-20.
Bugs
You will recall that the four steps in creating an animation program are: read, design,
implement, and test. Now that several lines of code have been written (implemented), it is a
good idea to test whether what you have written thus far works the way you thought it would.
You do not have to wait until the entire program is completed. To test the instructions written
thus far, the Play button is clicked. The alienOnWheels pops up from behind the rocks and
then says “Slithy toves?” The spiderRobot’s head turns around and then the spiderRobot turns
to face the alienOnWheels. So far so good, but when the spiderRobot moves forward, the legs
do not walk. That is, the leg joints do not appear to turn at all!
The reason the leg joints do not turn is that the program has a bug. (Errors in computer
programs are generally referred to as bugs. When we remove bugs from a program, we debug
the program.) The problem is, in the code shown above, the leg-joint-turn instructions are
written inside a Do together. Of course, if the joints both forward and backward at the same
time, they effectively cancel each other and the spiderRobot’s legs do not walk at all! To fix
this problem, it is necessary to place the backLeft leg-joint-turn instructions within a Do in
order block and also the frontRight leg-joint-turn instructions within a Do in order block, as
illustrated in Figure 2-2-21.
Now the spiderRobot’s backLeft and frontRight legs walk! There is one other useful
observation to make. Animation instructions, by default, require one second to run. Normally,
within a Do together block, each of the instructions should take the same amount of time. Since
it takes one second for the spiderRobot to move forward 1 meter, the walking action of each leg
2-2 A first program 41
should also take one second. However, there are two steps in bending the leg joint (forward and
then backward). Each step in bending the leg joint should require one-half second. To change
the duration, click on more Á (at the far right of the instruction where the duration is to be
changed), select the duration menu item, and select 0.5 seconds, as shown in Figure 2-2-22.
Using a property
We still need to complete the final four actions described in the storyboard (alienOnWheels
moves down, the spiderRobot turns to face the camera, spiderRobot’s head turns red, and spi-
derRobot says “Houston, we have a problem!”). You have already used a move, turn to face,
and say instruction—so these will be easy to create. The only new instruction is the one that
requires the spiderRobot’s head to turn red (a danger signal). To make this happen, we use the
color property of the spiderRobot’s head. To view the list of properties of the spiderRobot’s
head, select the spiderRobot’s head in the Object tree and select the properties tab in the
details area (lower left of the Alice window), as shown in Figure 2-2-23.
What we want to do is change the color of the spiderRobot’s head after it turns to face
the camera. Of course, the properties can be changed when the initial world is created. But,
we want to change the color property while the animation is running. (The technical term for
“while the animation is running” is “at runtime.”) An instruction must be created to set the
color. Figure 2-2-24 demonstrates dragging in the color property tile to create a set instruc-
tion. The color tile in the properties list for the spiderRobot’s head is dragged into the Do in
order block. Then, the color red is selected from the popup menu of available colors.
42 Chapter 2 Program Design and Implementation
The final code for the entire animation is listed in Figure 2-2-25.
Figure 2-2-25. The program code for the entire First Encounter animation
Comments
Now that we have written our first program, it is time to look at a useful component in
programs—comments. Comments are NOT instructions that cause some action to take place.
This means that Alice can ignore comments when running a program. However, comments
are considered good programming “style” and are extremely useful for humans who are read-
ing a program. Comments help the human reader understand what a program does. This is
particularly helpful when someone else wants to read your program code to see what you
wrote and how you wrote it.
Comments in Alice are created by dragging the green // tile into a program and then
writing a description of what a sequence of code is intended to do. Figure 2-2-26 illustrates
2-2 A first program 43
World.my first method with a comment added. Where it is not obvious, a comment should be
included at the beginning of a method to explain what the method does. This kind of comment
is like writing a topic sentence in a paragraph—it summarizes what is going on.
Also, small sections of several lines of code that collectively perform some action can
be documented using a comment. An additional comment has been added in Figure 2-2-27.
This comment explains that this small section of the code is to have the spiderRobot move for-
ward as its legs walk.
Figure T-2-1. Using a bounding box to view the center of a whole object
The direction an object moves is egocentric. That is, the direction an object moves is relative
to its own orientation. To illustrate, an example world is shown in Figure T-2-3 where a
chicken is facing a monkey. A tree is positioned in the background as a point of reference.
The instruction in world.my first method tells the monkey to move left 2 meters.
Figure T-2-3. Initial world scene and move instruction in world.my first method
Figure T-2-4 illustrates the scene after the world runs and the monkey has moved left 2
meters. Compare this ”after scene” to the ”before scene” in Figure T-2-4, above. As you look
at the ”after scene”, it may appear to you that the monkey has moved to the right. Indeed, rel-
ative to the chicken, the monkey has moved to the right. The important thing to notice is that
the monkey moves relative to its own sense of what is ”left” and what is ”right”. Likewise,
any object moves relative to its own sense of orientation.
46 Chapter 2 Program Design and Implementation
Figure T-2-4. Final world scene, after the monkey moves to its left
turn
• left
• right
• forward
• backward
A turn left or right is a motion similar to turning a door on its hinges. A turn forward or
backward is a motion similar to lifting or closing a hinged lid, as on a jewelry box or a picnic
basket.
An object can roll in only two directions (up, down, forward, and backward are not
included).
roll
• left
• right
A roll left or right is a motion similar to a clockwise or counter-clockwise twist of a door
knob.
As with the move method, the motion for turn and roll are egocentric and are relative to
the orientation of the object. In addition, turn and roll are also relative to the center of the
object or its subpart’s connection to the rest of the body.
2-2 A first program 47
If the whole object is rotating, the rotational motion occurs around the center of the
whole object. For example, the instructions shown below make the monkey move up 2 meters
and then turn forward 1 full revolution.
The images in Figure T-2-5 show the sequence of a turn forward motion, a somersault
in mid-air. The screen shots were taken as the turn forward instruction was executing. As the
monkey turns, the axes object turns with it and illustrates that the orientation of the monkey is
consistent with the motion of the monkey. Because the center of the monkey object is between
its feet, the rotation pivot point is also between the monkey’s feet.
Likewise, a roll rotation for the whole monkey occurs around the center, at the mon-
key’s feet. The following code moves the monkey up 1 meter and rolls the monkey right one
complete revolution.
The images in Figure T-2-6 show the sequence of a roll right motion, a sideways cart-
wheel. The screen shots were taken as the roll right instruction was executed. Once again, the
rotation pivot point is at the monkey’s feet.
If a subpart of an object is rotated (rather than a whole object), the rotational motion
occurs around the center of the subpart. The center of the subpart is generally where subpart
is connected to the rest of the object, that is at the joint. Think about a joint connection in
terms of your own body. For example, your upper arm is connected to the rest of your body
48 Chapter 2 Program Design and Implementation
by a skeletal joint at the shoulder. When your upper arm rotates, it does so by rotating at the
joint. For this reason, a joint connection may be thought of as a pivot point.
For Alice objects, the location of a joint connection for a subpart can be found by
selecting the subpart in the object tree and viewing the intersection of the axes in the bound-
ing box that encloses the subpart. In Figure T-2-7, the monkey’s left arm subpart has been
selected in the object tree and the axes intersect at the shoulder, the pivot point for rotating
the monkey’s left arm.
Figure T-2-7. Using a bounding box to view the pivot point for rotating a subpart
To better illustrate the orientation of the left arm subpart, we have embedded an axes
object at the pivot point, as shown in Figure T-2-8.
In this example, the following code rotates the monkey’s left arm 0.5 revolution (one-half turn
around) at the pivot point where the arm is connected to the rest of the monkey’s body.
The images in Figure T-2-9 show the sequence of motion. The screen captures were
made as the turn forward instruction was executed. The rotation’s pivot point is at the mon-
key’s shoulder. The forward motion of the arm is relative to the orientation of the arm where
it is connected to the rest of the monkey’s body.
Figure T-2-9. A turn rotation for the monkey’s left arm subpart
We recommend that you start Alice, add several objects to the world, and play around
with move, turn, and roll. There are hundreds of different models and the design of the inter-
nal skeletal structure of the body is not necessarily the same from one 3D model to the next.
It is important to observe how the subparts are connected and what the orientation is at the
joint connection, as the skeletal structure has a very real effect on how rotational motion is
carried out when the program runs.
One last word of advice regarding move, turn, and roll: A sequence of several motions,
one after another, has a cumulative effect and can leave an object and its subparts in a twisted
position. You may need to “unwind” some of the motion to return to the object to a more
appropriate position.
The code we wrote to make the monkey and ball move forward together is shown in
Figure T-2-11.
Imagine our surprise when the ball moved in one direction and the monkey moved in a
different direction, ending up well away from the ball, suspended in midair. Why did this hap-
pen? Well, the ball is an example of an object for which we can’t tell (just by looking at it)
which direction is forward and which direction is backward. Evidently, in positioning the ball
and the monkey in the scene, we positioned the ball so its forward direction was not the same
as the forward direction for the monkey, as illustrated in Figure T-2-12. So, when the ball and
the monkey each move forward, they move in different directions.
Figure T-2-12. The monkey and toyball move forward in different directions
The way to solve this problem is to synchronize the orientation of the two objects. In
this example, we will use a toyball.orient to(monkey) instruction, as shown in Figure T-2-13.
The result is shown in Figure T-2-14. Now, the toy ball has the same orientation (the
same sense of direction) as the monkey. This means that the two objects will move in the same
direction when a move forward instruction is given to each.
The orient to instruction may seem a bit weird, but it simply tells Alice that the first
object should take on the same sense of direction as the second object. So, if we orient two
objects to have the same orientation, then the two objects are synchronized—they have the
same sense of up, down, left, right, forward, and backward.
2-2 A first program 51
Figure T-2-14. Now the monkey and the toyball have the same orientation
To synchronize the movement of the chicken and the horse, you can make the horse be
a vehicle for the chicken. To create this special effect, select chicken in the object tree and
then select the properties tab (under the object tree at the lower left of the window). Then click
on the white tile to the right of the word vehicle. A list of possible vehicles is shown in a
popup menu, from which horse can be selected, as illustrated in Figure T-2-16. Now, when the
horse moves, the chicken will move with it.
When more … is clicked, a popup menu allows you to select from a list of three
arguments—duration, style, and asSeenBy—as shown in Figure T-2-18.
The duration argument tells Alice an amount of time (in seconds) for animating the
movement. (Alice assumes that the amount of time for a movement is 1 second.) A zero (0)
duration is an instantaneous movement. Negative values are not used. In the First Encounter
example in this chapter, a duration argument was used to shorten the amount of time for turn-
ing the robot’s leg joints to simulate walking.
The style argument specifies the way in which one movement instruction blends into the
next. The options are gently (begin and end gently), abruptly (begin and end abruptly), begin
gently (and end abruptly), and end gently (and begin abruptly). To get the right degree of
“smoothness” for a movement, it is often worthwhile to experiment with style.
As described in Chapter 1, each object in Alice has its own sense of direction (orienta-
tion). But, you can use the asSeenBy argument to tell Alice to use an orientation of one object
to guide the movement of another object. This is best explained by using an example. Suppose
we have a helicopter (Vehicles in DVD or Web gallery) on a pilot training mission, as shown
in Figure T-2-19.
The code in Figure T-2-20 is intended to roll the helicopter left and then move it
upward.
54 Chapter 2 Program Design and Implementation
Running the animation, we see that the result is not what we had in mind. When the hel-
icopter moves upward, it does so from its own sense of direction, as in Figure T-2-21.
What we had wanted, however, was an upward movement with respect to the ground.
To correct this problem, we clicked on more and then selected asSeenBy ground, as in
Figure T-2-22.
The resulting code, shown in Figure T-2-23, gives the desired movement.
The point at method may be used to aim the boat at the lighthouse location. Then,
movement instructions may be used to move the boat toward the island and the lighthouse, as
in Figure T-2-25.
While this instruction does turn the lifeboat toward the lighthouse, it also has the effect
of tipping the boat so it seems to be sinking on one end, as seen in Figure T-2-26.
The point at instruction aligns the center of the lifeboat with the center of the lighthouse,
which is higher in elevation than the boat, as shown in Figure T-2-27. As a result, the boat tips.
You may, or may not, want the boat to tip. To provide some control of the point at
instruction, additional arguments are available in the more … popup menu, as seen in Figure
T-2-28. Selecting true for the onlyAffectYaw argument allows an object to point at another
object without tipping (pitching). Yaw is technical term meaning a left–right turning motion,
and pitch is a tipping, rocking-chair kind of motion. (When onlyAffectYaw is true, the point at
instruction works the same as a turn to face instruction.) Note that in target games and flight
animations onlyAffectYaw should be false (so as to align on the diagonal with a target object).
When this code is run, the boat moves to the center of the island, as seen in Figure T-2-30.
Of course, the center of the island is located at its center of mass. So, the boat plows right into
the middle of the island!
Summary
This chapter introduced the fundamental concepts of programming in Alice. We began with
reading the scenario and designing a storyboard. A scenario helps us set the stage—that is, it
tells us what objects will be used and what actions they will perform. A storyboard breaks
down a scenario into a sequence of scenes that provide a sense of the order in which actions
will take place.
Some actions in a program will take place in sequence (one after the other) and some
actions simultaneously (at the same time). Once prepared, a storyboard is used as a guide for
implementation (writing the program code). Testing code (running the program) is an impor-
tant step in finding and removing bugs (errors in the program).
Comments are used to document methods, where the purpose of the method or a small
section of a method is not immediately obvious. Comments are considered good program-
ming “style.”
Programming Terms
algorithm instruction state
argument method storyboard
bug nesting syntax
comment (in a program) property (of an object) trial-and-error
control structure pseudocode
design runtime
implement scenario
Questions
1. Creating a computer program can be described as a four-step process using problem
solving techniques. List the four steps and give a brief description of each step.
2. Describe two major differences between a visual storyboard and a textual storyboard.
3. In what way does the design and implementation of a computer program resemble the
process that an artist goes through when creating a painting or an engineer when con-
structing a bridge or other product?
4. Describe the difference between translational motion and rotational motion.
5. Create sketches of an object in an Alice world to illustrate your answer to each of the
following:
(a) What will happen if an object is given an instruction to move right 90?
(b) What will happen if an object is given an instruction turn right 90?
(c) What will happen if an object is given an instruction to roll right 90?
6. Do together and Do in order are each described as “control statements.” Why?
7. Explain how to synchronize the orientation of two objects, in Alice.
8. Explain how to synchronize the motion of two objects, in Alice.
9. What does a method define?
10. (a)Which control statement is used in Alice to create a block of instructions that will
occur in sequence when the program is run?
11. Which control statement is used in Alice to create a block of instructions that will occur
simultaneously when the program is run?
12. What is meant by the phrase “one block of code may be nested in another”?
13. How do you know whether a computer program has a bug?
14. If comments are ignored by Alice then why do we add comments to our programs?
15. Which built-in Alice method is used to:
(a) change the orientation of an object
(b) display a comic-book style text bubble on the screen
(c) synchronize the movement of one object to the movement of another
Exercises 59
16. In a move, turn, or roll instruction, what are the choices of arguments that can be used
for each of the following?
(a) duration
(b) style
(c) asSeenBy
17. Sketch a flowchart for exercise 3 below.
Exercises
2-1 Exercises
1. Creating Storyboards
Create a visual and a textual storyboard (two storyboards) for each of the following
scenarios:
(a) A child’s game: Alice, the white rabbit, and the Cheshire cat enjoy a game of musi-
cal chairs in a tea party scene. One of the characters yells “switch” and they all run
around the table to stand beside the next chair. After the switch, a chair is tipped
over and the character standing next to it is eliminated from the game (moves away
from the table).
(b) A video game: A jet fighter plane is returning to the carrier deck after a training
mission. The plane makes a half-circle around the carrier to get into position for
landing and then gradually descends. The carrier is in motion, so the plane has to
continually adjust its descent to finally land on the deck. After the plane touches
down on the carrier, it continues to move across the deck to finally come to a halt.
(c) An Olympic simulation: An ice skater is practicing her skating routine for the
Olympic trials. She will perform a sequence of jumps and spins, while classical
music is playing.
2-2 Exercises
2. First Encounter—Extended
(a) The worlds used for chapter examples throughout this book can be found on the
DVD. Each world provided on the DVD has the initial scene already set up with the
background scenery and the objects, as shown in the example. In this chapter,
the example world is a first encounter, where a robot meets an alien on a distant
moon. Start Alice. Then, copy the FirstEncounter.a2w world to your computer. In
Alice, use File|Open to open the world. Follow along with the reading in the chap-
ter and recreate the program as described in the chapter.
(b) In the code presented in this chapter, only two legs (backLeft and frontRight) were
animated in a walking action. Add code to animate a walking action for the other
legs. Be sure to save the world.
3. Snowpeople
Create a snow people world as shown in the scene below. Several snow people are out-
doors on a snow-covered landscape.
60 Chapter 2 Program Design and Implementation
A snowman is trying to meet a snowwoman who is talking with a friend (another snow-
woman.) The snowman tries to get her attention. He turns to face the snowwoman and
says “Ahem.” She turns to look at the snowman and he blinks his eyes at her. She
blushes (her head turns red). But, alas, she is not interested in meeting him. She gives
him a “cold shoulder” and turns back to talk with her friend. He hangs his head in dis-
appointment and turns away.
4. Circling Fish
Create an island world with a fish in the water. (You may wish to reuse the island world
created in an exercise for Chapter 1.) Position the fish and the camera point of view so
the scene appears as illustrated below. Write a program that has the fish swim around in
a circle in front of the island. Next, have the fish swim around the island. You may wish
to have the fish move asSeenBy the island (asSeenBy is described in Tips & Techniques 2).
Finally, have the fish jump out of the water and then dive down into the water. The final
scene should look somewhat like the initial scene, with the fish back in roughly the
same position as where it started.
6. Magnet Fun
Create a world where Mana (People) has a magnet (Objects) held out in her left hand.
Add five metallic objects (Objects folder in Local, DVD, or Web gallery) of your choice
to the world and one by one have Mana point the magnet at each object. As Mana points
the magnet toward an object, have the object move to the magnet. Have the last object
be very large (perhaps a car from the Vehicles folder) so when Mana points at it, she
instead is pulled toward the object while saying something like “Whoa!” or “Yikes!”
Hints: See Tips & Techniques 2 for information on how to (1) use the vehicle prop-
erty for help in making the magnet move in coordination with Mana’s hand, and
(2) use the move toward instruction to make an object move toward another object.
Also, you may wish to review the notion of center of an object, as described in
Chapter 1, Section 2, page 12.
Chapter 3
Programming:
Putting Together
the Pieces
In this chapter, you will see how to put together different kinds of program code “pieces” to
make the program do what you want it to do. The pieces of program code include:
instruction—a statement that executes to make objects perform a certain action
control structure—a statement that controls the execution of a block of instructions
function—asks a question about a condition or computes a value
expression—a math operation on numbers or other kinds of values
You have already seen instructions such as:
You have also been using the Do in order and Do together control structures. The Do
in order structure tells Alice to run the instructions sequentially, one after the other. The Do
together structure tells Alice to run the instructions all at the same time.
This chapter presents two additional execution controls: conditional execution
(If/Else) and repetition. This is where programming gets exciting, because you gain control
of how the program is executed. Conditional execution makes use of functions and expres-
sions to check a current condition in the world. For example, “Is the color of the spiderRo-
bot’s head red?” Obviously, this is a question and a function used to ask the question. Often,
checking a condition requires that two or more objects be compared. For example, we
might check whether “the distance of the spiderRobot from a rock is greater than 1 meter.”
An expression is used to compare whether the distance between the two objects is greater
than 1 meter.
Section 3-1 uses short examples to show how to use built-in functions in Alice. We also
look at simple arithmetic operations (addition, subtraction, multiplication, and division) in
expressions.
62
3-1 Built-in functions and expressions 63
Built-in functions
Not all properties of objects are available in its properties list. Only properties most com-
monly used in setting up your world (e.g., color and opacity) are listed. Other properties of
objects (such as height, width, and position) can be determined, however, by asking Alice for
the information. The Alice system provides a set of built-in functions—statements you can
use to ask about properties of objects and relationships of objects to one another. Also, utili-
tarian kinds of questions can be asked of the world—about things like the position of the
mouse and some math operations.
To better understand why we want to use functions, let’s look again at the First
Encounter world, shown in Figure 3-1-1. As you view this scene, you interpret what you see.
For example, you pick up visual clues in the scene that lead you to believe that the spiderRo-
bot is closer to the camera than the rocks. An artist calls this perspective. Of course, it is dif-
ficult to know exactly how far away the rocks are from the spiderRobot. Likewise, it is
difficult to know how far the spiderRobot is away from the lunarLander. The camera angle
simply does not provide enough information.
This is where functions come into play. Functions can be used to get the information we
need. Alice provides several functions that can be used for each object in a world. We call
these built-in functions. To view a list of built-in functions about an object in a world, select
the object in the Object tree, and view the functions in the details area. In this example, you
64 Chapter 3 Programming: Putting Together the Pieces
can view a list of built-in functions for the spiderRobot by selecting spiderRobot in the Object
tree and then its functions tab, as in Figure 3-1-2.
At the right of the functions list, a scroll bar allows you to scroll the window down to
view all the available functions for the spiderRobot. The built-in functions are divided into
subcategories:
Proximity—how close the object is to some other object in the world (such as distance
to, distance above) (the functions in Figure 3-1-2 are proximity functions)
Size—dimensions such as height, width, and depth, and how these compare to the
dimensions of another object in the world
Spatial relation—orientation compared to another object in the world (such as to left
of, to right of)
Point of view—position in the world
Other—miscellaneous items such as the name of a subpart of the object
In our daily conversations, when a question is asked, we expect to receive an answer. In
Alice, the answer is the value of the property you are asking about. What types of values can
you expect? That depends on what question the function is asking. For example, the proxim-
ity function spiderRobot is within threshold of object (is within threshold means “is within a
given distance”) will return a true or false value. But the function, spiderRobot distance to,
returns a number (distance to means “the distance in meters to another object”). In Alice, val-
ues can be of several different types. Four common types of values are:
3-1 Built-in functions and expressions 65
Figure 3-1-3. Code to move the spiderRobot forward as the legs walk
We don’t know exactly how far the spiderRobot is away from the rock where the
alienOnWheels is hiding. The 1 meter distance for the move forward instruction is just a
guess. The problem is that we don’t know exactly how far to move the spiderRobot forward.
One way to find out is to use trial and error—that is, try different distances until we find one
that works best. Another technique to find the distance is to use a function to ask a question:
“What is the spiderRobot’s distance to the rock (where the alienOnWheels is hiding)?” Alice
will return the distance (in meters). Then the spiderRobot can be moved forward that distance.
To use the distance to function, just drag the spiderRobot’s distance to tile into the edi-
tor and drop it on top of the 1 meter distance. Then, select rock as the target object, as shown
in Figure 3-1-4.
Collision
After making such a change to our program, the program should be tested. In this example,
when the program is run the spiderRobot walks right into the middle of the rock! This is
called a collision. In some animations, a collision is exactly what is desired. In this example,
though, we do not want the spiderRobot to collide with the rock. The reason a collision occurs
is that distance to is measured from the center of one object to the center of another object. In
this example, distance to is measured from the spiderRobot’s center to the rock’s center, as
shown in Figure 3-1-5.
Expressions
How can a collision be avoided between these two objects? One way is to adjust the distance
that the spiderRobot moves so it doesn’t move the entire distance. Adjusting the distance
requires the use of an arithmetic expression to subtract a small value from the distance. In this
example, the rock is bigger than the spiderRobot. If the width of the rock is subtracted from
the distance between the two objects, a collision can be avoided.
Alice provides math operators for common math expressions: add 1+2, subtract 1-2,
multiply 1*2, and divide (/). A math expression is obtained by selecting math from the popup
menu of number value in an instruction. For example, to use a math expression to adjust the
distance the spiderRobot moves, click the down icon at the far right of the distance to tile in
the move instruction, then select math : spiderRobot distance to rock - 1, as illustrated in
Figure 3-1-6.
The resulting instruction subtracts 1 meter from the distance. Actually, we want to sub-
tract the width of the rock from the distance (not 1 meter). But, we had to choose something
3-1 Built-in functions and expressions 67
from the popup menu so we arbitrarily chose 1 meter. This is okay to do because we can now
substitute the rock’s width for the 1 meter value, as shown in Figure 3-1-7.
Figure 3-1-7. Substituting the rock’s width function for the arbitrary 1 meter value
Now, the spiderRobot moves forward so it gets close to the rock without a collision. The
completed code is shown in Figure 3-1-8.
Figure 3-1-8. Code to move spiderRobot forward and avoid collision with the rock
Technical Note: The distance expression used in the move instruction of this example works
very well. We should note, however, that this expression is purposely a primitive form of
68 Chapter 3 Programming: Putting Together the Pieces
Conditional execution
A conditional execution control statement depends on a decision. Sometimes life is “one
decision after another.” If the grass isn’t wet, we can mow the lawn. If the dishwasher is full
of dirty dishes, we run the dishwasher. If we are taking the dog out for a walk, we put a leash
on the dog. Programming, too, often requires making decisions. Decisions are useful when
writing programs where some instructions are expected to run only under certain conditions.
When a decision is being made, a question is asked about a current condition in the
world. For example, “Is the spaceship visible?” or “is the color of the hat red?” Clearly the
answer is either true or false. True and false values are known as Boolean values, named after
the 19th century English mathematician, George Boole, who was the first (as far as we know)
to be interested in expressions that can evaluate only to either true or false.
In Alice, an If/Else statement is used as a conditional execution control structure. (For
convenience, we refer to an If/Else statement as an If statement.) Figure 3-2-1 illustrates the
processing of an If statement. The statement checks to see whether a condition is true. If the
condition is true, one set of program instructions is run. If the condition is false, a separate set
of program instructions is run. The section of code that is executed (or not) depends on the
value of the condition.
True Is False
condition
true?
Do this Do something
action else
It is possible that no action would be expected for one of the paths in the flowchart. For
example, Figure 3-2-2 illustrates a single path If statement (Else is not needed). In Alice, the
Else part of the control structure would contain the instruction Do nothing.
True Is False
condition
true?
Do this action
An If statement is created in Alice by dragging the If/Else tile into the editor. A popup
box allows you to select the initial condition (true or false), as shown in Figure 3-2-3.
The green color of this block is a visual clue that an If statement is being used in the pro-
gram. The If statement has two parts (an If part and an Else part). Although an initial condition
(true or false) is selected from the popup menu, Alice allows you to create your own conditional
expression on top of the condition tile. A conditional expression is a function that will evaluate
(at runtime) to either true or false. If the answer is true, the If part is executed and the Else part
is skipped. But, if the answer is false, then the If part is skipped and the Else part is executed.
A simple example
To illustrate the usefulness of an If statement, let’s continue with First Encounter world. As
mentioned before, our sense of perspective can be misleading about distances and sizes of
objects in a world. The spiderRobot walks over to the rock to get a closer look at the
alienOnWheels, but then the alienOnWheels moves down (out of our sight). From this camera
angle, as seen in Figure 3-2-4, the rock appears to be taller than the robot, but we cannot be
sure. So we cannot tell whether the spiderRobot is actually able to see over the rock. If the spi-
derRobot is shorter than the rock, it could move its neck up to look over the rock. Otherwise,
the spiderRobot can still see the alienOnWheels and no additional action is necessary.
70 Chapter 3 Programming: Putting Together the Pieces
Figure 3-2-4. The spiderRobot moves closer, but the alienOnWheels hides behind the rock
The problem is, how do we know which is taller (the spiderRobot or the rock)? One
solution is to use an If statement with the built-in is shorter than question. The storyboard is:
Finally, spiderRobot.neck move instructions are added in a Do together block for the If
part of the If/Else statement. The Else part of the If/Else statement is Do Nothing. The result-
ing code is shown below.
When this code is run, a function is used to ask the question: “Is the spiderRobot shorter
than the rock?” The answer is either true or false (a Boolean result). Then, a decision is made
on the basis of the answer. If the answer is true the spiderRobot’s neck moves up and down (to
peek behind the rock). Otherwise, the Else section kicks in and nothing happens. That is, the
spiderRobot’s neck is not moved up and down. We could have written instructions to make the
spiderRobot do something different in the Else part—like spin the head around—but we
wanted to show that Do Nothing is an acceptable alternative to an action.
Relational operators
In the example above, we used a built-in function to compare the heights of the spiderRobot
and the rock. We frequently take advantage of built-in functions to check a condition in an If
statement. Sometimes, though, we want to write our own condition using a relational operator.
Alice provides six relational operators grouped together in the math category of the World’s
built-in functions, as shown in Figure 3-2-6. The operators work the same as they do in
mathematics. We added labels to the screen capture in Figure 3-2-6 to indicate the meaning of
each operator. For example, “= =” means “is equal to” and “!=” means “is not equal to.”
As an example of using a relational operator to write your own condition, let’s assume
that we know the rock in the First Encounter world is 2 meters tall (2 meters is about 6 feet).
We could write an If statement that checks the spiderRobot’s height against 2 meters. We want
to write a statement for the following storyboard:
The condition of the If statement is “spiderRobot’s height is less than 2 meters.” The
condition must be written as a Boolean expression (is either true or false). Let’s write an If
statement for this storyboard, creating our own Boolean expression with a relational operator.
First, drag the If tile into the editor, as in the examples above. Then, complete the fol-
lowing two-step process:
1. Drag the World function “less than” tile 1a 6 b2 on top of the true tile in the If state-
ment. If you are following along in the text and creating the code as you read, you will
already have an If statement in the editor (from instructions on the previous page). The
previous If statement should be removed (drag it to the trash can) before creating a new
one. A popup menu allows you to select values for a and b, as shown in Figure 3-2-7.
From the popup menu, select 1 for a and 2 for b. The resulting expression looks like
this:
Actually, we want to drag in the tile representing the spiderRobot’s height to use as the
value for a, but we chose 1 from the popup menu as a placeholder to complete this first
step. We will fix it in the next step.
2. Now, drag in the spiderRobot’s height function to replace the 1 (that was put there as a
placeholder). Inside the If part, a Do in order block and instructions to make the spider-
Robot’s neck move up and down are added. The Else part of the statement is left as Do
nothing. If the condition (spiderRobot’s height 6 2) is false, no action will be taken.
The resulting code is shown below.
Figure 3-2-8. The spiderRobot moves forward several meters but legs take only one step
74 Chapter 3 Programming: Putting Together the Pieces
It would be more realistic if the spiderRobot legs walked a step with each meter that the
spiderRobot moves forward. In other words, if the spiderRobot moved forward 3 meters, then
the leg walking action would occur three times. If the spiderRobot moved forward 4 meters,
then the leg walking action would occur four times, and so forth.
We could revise the program code to move spiderRobot forward 1 meter and the legs
would take one step. (You may recall that this is what was in the original code in Chapter 2,
Section 2.) Then, the code would (once again) look like the code shown in Figure 3-2-9.
Figure 3-2-9. The spiderRobot moves forward 1 meter and legs walk once
The problem is that the spiderRobot is now moving forward only 1 meter. We want the
spiderRobot to move forward several (3 or 4) meters. It would be rather tedious to create this
set of instructions three or four times. Also, think about what would happen if we wanted the
robot to move forward say 20 meters!
A possible solution is to use the clipboard. The clipboard is a wonderful tool for copy-
ing a set of instructions from one place to another in the editor. (See Appendix B for instruc-
tions on how to use the clipboard.) In this situation, however, dragging the same set of
instructions from the editor to the clipboard and then from the clipboard back into the editor
several times is still a bit tedious.
When the Loop tile is dragged into the editor, a popup menu offers a choice for the
count (the number of times the loop will execute), as seen in Figure 3-2-11. Alice uses the
term “end” to describe the end of the count. We selected other and then entered the number 3.
Note that a loop can execute only a whole number of times. (A whole number is a number
with no fractional part.)
Finally, drag the Do together block into the Loop statement, as shown in Figure 3-2-12.
Figure 3-2-12. Dragging the Do together block of instructions into the Loop statement
The resulting Loop statement is shown in Figure 3-2-13. The blue-green block encloses
all the instructions in the loop construct. The comment has been updated to show that the
walking steps will be repeated three times.
76 Chapter 3 Programming: Putting Together the Pieces
camera position at the time an initial scene is being created. Of course, the camera controls
are not available while the animation is running. In this section we look at a technique for con-
trolling the movement of the camera at runtime. Also, we offer a tip on how to use the speed
multiplier to speed up (or slow down) an animation at runtime.
point of view to the point of view of the dummy object (essentially placing the camera onto a
dummy tripod). At runtime, the set point of view method effectively moves the camera to the
dummy object (similar to a move to instruction), and the camera viewpoint is now from that
location.
This technique is best illustrated with an example. You may find it helpful to sit at a com-
puter and try this out as you read the description. Figure T-3-2 shows an initial scene with the
camera pointed at a skateboarder (People). The skateboard and the rail-ramp can be found in
the SkatePark folder on the DVD or Web gallery. From our perspective (as the person viewing
the scene), the camera is allowing us to look at the scene “from the front.”
We want to be able to move the camera around to view the skater’s actions “from the
back” of the scene while the animation is running. To prepare for this action, let’s create a
couple of dummy objects for the front and back viewpoints. First, drop a dummy object at the
current location of the camera. To do this, click the more controls button in the scene editor,
as in Figure T-3-3.
The interface expands to show additional controls, including a drop dummy at camera
button, seen in Figure T-3-4.
A click on the drop dummy at camera button creates a dummy object as a tripod at the
current location of the camera. The dummy object is added to the Object tree, as shown in
Figure T-3-5. Alice automatically names dummy objects as dummy, dummy2, etc. In this
example, we renamed the dummy object as frontView (a meaningful name makes it easy to
remember).
The next step is to reposition the camera to view the scene from the back. One technique
that seems to work well is to drag the camera’s forward control (the center camera navigation
arrow) toward the back of the scene. Continue to drag the forward control and allow the cam-
era to move straight forward until the camera seems to move through the scene. When the
camera seems to have moved far enough to be on the other side of the scene, release the
mouse. Select the camera in the Object tree and select a method to turn the camera one-half
revolution, as in Figure T-3-6.
3-2 Simple control structures 79
The camera should now be facing in the opposite direction and you should be able to see
the scene from the back. Click once more on the drop dummy at camera button. We renamed
the dummy marker as backView. Two dummy objects should now be in the Object tree,
frontView and backView. To return the camera to the front view, select frontView from the
dropdown menu of the move camera to dummy button (see Figure T-3-4).
Now instructions can be written to move the camera at runtime. Select camera in the
Object tree and then drag the set point of view instruction into the editor. Select the particular
dummy object for the point of view. Figure T-3-7 illustrates how to create the instruction.
A sample instruction is shown below. At runtime, this instruction will move the camera to
backView and the camera’s point of view will be from that location.
It is also possible to have the camera follow an object by changing the camera’s vehicle
property (which was described in Tips & Techniques 2). A fun exercise is to open the sky ride
animation world (TT3_skyride.a2w, available in the textbook Worlds folder). In running this
world, you will see the movement of a sky ride at an amusement park. This ride can be made
80 Chapter 3 Programming: Putting Together the Pieces
more interesting by adding an instruction to set the camera’s point of view to the first cable
car prior to running the animation, as illustrated in Figure T-3-8.
Figure T-3-8. An instruction to set the camera’s point of view to another object
See the impact of this instruction by running the modified world. To get a different sense
of the ride, try also adding an instruction to change the camera’s vehicle to the first cable car,
as illustrated in Figure T-3-9. See the differences in what happens as the world runs. You may
also want to experiment with “riding” some of the other amusement park rides.
The Speed Multiplier is a slide bar with a thumb. You can grab the thumb with the mouse
and slide it left or right while the animation is running to control the speed of the animation.
(Sliding the thumb has no effect if the animation has stopped.) To return the animation to nor-
mal speed, simply drag the thumb all the way to the left.
Note: The speed multiplier affects only the speed of the animation. If a sound is being
played, the sound is not affected by the speed multiplier (i.e., the sound does not play
faster).
Summary
In this chapter, we looked at how to put together the “pieces” of program code. The “pieces”
that we use to create our programs include the following:
instruction—a statement that executes to make objects perform a certain action
control structure—a statement that controls the execution of instructions
function—asks a question about a condition or computes a value
expression—a math operation on numbers or other kinds of values
Alice provides built-in functions for the World and for objects within it. Functions can
return different types of values (e.g., number, Boolean, or object). Expressions allow you to
compute a value or perform a comparison of some property of two objects. One use of
functions and expressions in an animation program is to help avoid collisions (when an object
moves into the same position as another object).
We can use the built-in functions and Boolean expressions (expressions that have a true
or false value) to check the current condition in the world and make decisions about whether
(or not) a section of the program will be executed. In Alice, the conditional execution control
structure is the If/Else statement. An If statement has two parts: the If part and the Else part. In
the If part, a condition is checked and a decision is made depending on the condition. If the
condition is true, the If part of the If/Else statement is executed. Otherwise, the Else part of the
statement is executed. It is possible that the Else part of the statement may be Do nothing, in
82 Chapter 3 Programming: Putting Together the Pieces
which case no action is taken. (It is also possible for the If part of the statement to be Do noth-
ing—but this is an awkward way of thinking about a condition.)
A simple repetition control structure is the Loop. A Loop statement allows you to repeat
a section of program code a counted number of times.
Programming Terms
Boolean value count If/Else instruction
condition decision loop
conditional execution expression relational operator
control structure function repetition
Animation Terms
collision
Questions
1. What action(s) does a function perform that a method does not?
2. What type of value is returned by each of the following built-in functions?
(a) distance to
(b) is within threshold of
(c) is wider than
(d) width
3. What are the four operations that can be used in a math expression in Alice?
4. List four different control structures used in creating a program in Alice.
Exercises 83
Exercises
3-1 Exercises
1. Robot to Lunar Lander
Use the First Encounter world to recreate the program code as described in Chapter 3,
Section 1. After the spiderRobot moves to the rock, have the spiderRobot turn to face
the lunarLander and then move forward half the distance between the spiderRobot and
the lunarLander.
2. Freestylin’ Snowman
Create a world using the snow template. Add a snowman (People) and a ramp
(Skatepark). Write instructions to move the snowman to the base of the ramp. When the
snowman reaches the base of the ramp, the snowman should turn around and move far
away from the ramp very quickly and say “YIKES!”
84 Chapter 3 Programming: Putting Together the Pieces
3. Hop
Create a world with a crate (Objects) and a kangaroo (Animals). Write a program to
make the kangaroo hop to the top of the box, turning the kangaroo’s legs backward and
forward to make it look like a hop. Use the height function to guide the forward and
upward movements.
3-2 Exercises
5. SpiderRobot’s Walk
In Section 3-2, program code was presented to make the spiderRobot walk forward
three times in a loop. Recreate the program code and test the Loop statement with a
count of 2, 4, and then 5. Which count works best? Why?
Exercises 85
7. Snowman to Stool
This exercise uses a number function as the count for a Loop. Create a world with a
snowman and a stool, as seen below. Use a Loop to make the snowman (People) move
to the stool (Kitchen), one meter at a time. Use a distance to function to determine the
number of times the loop repeats. (The distance to function might return a fractional
distance such as 3.75 meters. The Loop statement truncates the fractional number to the
integer 3 and will repeat three times.) We recommend that you test your solution by
moving the snowman and the stool to different locations on the screen and running the
program with each change, so you can know whether it works no matter where the
snowman and the stool are located.
This page intentionally left blank
Part II
Object-Oriented
and Event-
Driven
Programming
Concepts
Chapter 4 Classes, Objects, Methods
and Parameters
4-1 World-Level Methods
4-2 Parameters
4-3 Object-Level Methods and Inheritance
Tips & Techniques 4: Visible and Invisible
Objects
Summary
Exercises and Projects
87
This page intentionally left blank
Chapter 4
Classes, Objects, Instructions for Making a Strawberry Tart
Methods and 1 crust, baked
3 cups strawberries, hulled
Parameters 1 pkg. strawberry gelatin
1 1冫2 cups of water
2 Tbs. corn starch
Place strawberries in the crust.
Mix gelatin, water, and corn starch in
“The Queen of Hearts, she made some tarts, a small pan.
All on a summer day: Stir, while heating to a boil.
Let cool and then pour over strawberries.
The Knave of Hearts, he stole those tarts, Chill.
And took them quite away!”
When you created your own animations in earlier chapters, you may have started to think
about more complicated scenarios with more twists and turns in the storyline, perhaps games
or simulations. Naturally, as the storyline becomes more intricate, so does the program code
for creating the animation. The program code can quickly increase to many, many lines—sort
of an “explosion” in program size and complexity. Animation programs are not alone in this
complexity. Real-world software applications can have thousands, even millions, of lines of
code. How does a programmer deal with huge amounts of program code? One technique is to
divide a very large program into manageable “pieces,” making it easier to design and think
about. Smaller pieces are also easier to read and debug. Object-oriented programming uses
classes, objects, and methods as basic program components, which will help you organize
large programs into small manageable pieces. In this chapter and the next, you will learn how
to write more intricate and impressive programs by using objects (instances of classes) and
writing your own methods.
Classes
A class defines a particular kind of object. In Alice, classes are predefined as 3D models pro-
vided in the gallery, categorized into groups such as Animals, People, Buildings, Sets and
Scenes, Space, and so on. Figure 4-0-1 shows some of the classes in the Animals folder.
Notice that the name of a class begins with a capital letter.
Each class is a blueprint that tells Alice exactly how to create and display an object from
that class. When an object is created and displayed, we call this instantiating the class
because an object is an instance of that class.
Objects
In Figure 4-0-2, Person and Dog are classes. The people joe, stan, and cindy are instances of
the Person class while spike, scamp, and fido are instances of the Dog class. Notice that the
name of an object begins with a lowercase letter. This naming style helps us to easily distin-
guish the name of a class from the name of an object. All objects of the same class share some
commonality. All Person objects have properties such as two legs, two arms, height, and eye
color. Person objects can perform walking and speaking actions. All Dog objects have prop-
erties including four legs, height, and fur color, and have the ability to run and bark. Although
each object belongs to a class, it is still unique in its own way. Joe is tall and has green eyes.
Cindy is short and has blue eyes. Spike has brown fur and his bark is a low growl, and scamp
has golden-color fur and his bark is a high-pitched yip.
joe spike
stan scamp
Person Dog
cindy fido
In Figure 4-0-3, larry, lila, and louis are all instances of the Lemur class (Animals) in
Alice. We named the lemurs in this world, made them different heights, and changed the color
of lila. The lemurs larry, lila, and louis are all objects of the same Lemur character class and
have many common characteristics. They also differ in that larry is the tallest, lila has rich,
dark fur, and louis is the shortest.
Methods
A method is a coordinated sequence of instructions that will be carried out when requested.
You have already used methods in your animations. Every object in an Alice world has a
repertoire of instructions it knows how to do—move, turn, turn to face, etc. These instructions
are actually primitive methods, built in to the Alice software. The primitive methods can be
organized into a method of your own—to carry out a small piece of the overall program. Each
method performs its own job, but all the methods in a program work together to create the
overall animation.
As your animation programs grow larger, it will become increasingly important to use
many, many methods as a way of organizing the program. Methods divide a program into
small, manageable pieces that work together to create a meaningful whole. Just as paragraphs,
sections, and chapters make a book easier to read, methods make a program easier to read.
Methods also provide a number of advantages. For example, once a method is written it
allows us to think about an overall task instead of all the small actions that were needed to
complete the task. This is called abstraction.
Some methods need to be sent certain pieces of information to carry out an action. For
example, a move method needs a direction (forward, backward, left, right, up, or down) and a
distance (in meters). A parameter acts like a basket to receive information that we send to a
method. In a way, you can think of a method as somewhat like a recipe—a set of instructions
that describe how to perform some action. (As an example, see the recipe at the beginning of
this chapter for making a strawberry tart.) Parameters hold onto the specific items of informa-
tion. In a recipe, a parameter could specify the amount of water. In a method, a parameter
could specify the distance a spaceship is to move.
In Alice, you can define methods for an object acting alone or for two or more objects
interacting with one another. This is similar to the way a director works with the cast of actors
in a play. The director gives instructions sometimes to a single cast member and at other times
to several cast members to coordinate their actions. Methods that specifically reference more
than one object are world-level methods. Methods that define behaviors for a single object
may be considered object-level methods.
In Section 4-1, our focus is on learning how to create and run your own world-level
methods. This section demonstrates how to call your own method. Calling a method causes
Alice to animate the instructions in the method. We revise our storyboard design process to
use a technique of breaking the overall task down into abstract tasks and then break each task
down into smaller pieces and then define the steps in each piece. This design technique is
known as stepwise refinement.
Section 4-2 launches a discussion of parameters. A parameter helps us send information
to a method—a form of communication with the method. The information that gets sent to a
method can be of many different types (e.g., a numeric value, an object, or some property
value such as a color).
Section 4-3 presents an introduction to class-level methods. An advantage of class-level
methods is that once new methods are defined, we can create a new class with all the new
methods (and also the old methods) as available actions. This is a form of inheritance—the
new class inherits methods from the old class.
A problem
In the FirstEncounter world, a spiderRobot has traveled through space to land on the surface
of a distant moon. The spiderRobot surprisingly encounters an alienOnWheels, investigates
the alien, then sends a message back to earth. To construct this first animation program, we
used a rather straightforward technique of designing a storyboard and then writing the pro-
gram instructions all in World.my first method. The code for this program (as written in
Chapter 2) is shown in Figure 4-1-1.
Figure 4-1-1. Program code for First Encounter world (as created in Chapter 2)
As we constructed this program, the code just seemed to grow and grow until we ended
up with a large number of instructions all together. If we continue to write our programs this
way, our program code is likely to grow to hundreds of lines of code all in one big block. The
problem with this is that it becomes difficult to read and even more difficult to find and
remove bugs.
We need a way to better organize the instructions to make it easier to read and debug a
program. One way to do this is to organize the instructions into smaller methods. Once the
method is defined, we can tell Alice to run it from one main method. Another advantage of
using small methods is that the methods can be called from several different places in the
program, without having to copy all the instructions again and again into the editor. The
following illustrates how to organize your program by using methods.
4-1 World-Level methods 93
Do in order
surprise—spiderRobot and alienOnWheels surprise each other
investigate—spiderRobot gets a closer look at alienOnWheels
react—alienOnWheels hides and spiderRobot sends message
The next step is to break down each major task of our storyboard design into simpler
steps. As an example, let’s do this for the surprise task.
Do in order
surprise—spiderRobot and alienOn Wheels surprise each other
investigate—spiderRobot moves closer to alienOnWheels
react—alienOn Wheels hides and spiderRobot sends message
surprise
Do in order
alien moves up
alien says “Slithy toves?”
robot’s head turns around
The steps in the surprise storyboard are the same as the first four instructions in the pro-
gram we wrote in Chapter 2. But now we are thinking of these instructions as one abstract
idea—the spiderRobot and alienOnWheels surprise each other. In a similar way, we can con-
struct storyboards for the investigate and react tasks.
investigate
Do in order
robot turns to look at alien
Do together
robot moves forward (toward the alien)
robot’s legs walk
react
Do in order
alien moves down
robot turns to look at the camera
robot’s head turns red (to signal danger)
robot says “Houston, we have a problem!”
94 Chapter 4 Classes, Objects, Methods and Parameters
The process of breaking a problem down into large tasks and then breaking each task
down into simpler steps is called stepwise refinement—a design technique used in many of
the examples presented in the next few chapters. For our First Encounter example, we have
used stepwise refinement to break the program into three simpler tasks: surprise, investigate,
and react. One way to translate this new version of the storyboard into program code is to
write a method for each of the simpler tasks and then write instructions in World.my first
method that call each of the methods, in sequence. Figure 4-1-2 provides an implementation
strategy diagram for the stepwise refinement design in this example.
Program
(my first method)
Figure 4-1-3. Selecting World’s create new method button and entering the name of the new method
Alice automatically opens a new editor tab, where the code can be written for the new
method. (See Figure 4-1-4.)
Note that the particular method being edited has its tab colored yellow, and that all
other method tabs are grayed out. To switch back and forth between the editor tabs, click the
edit button to the right of the method you want to work on (in the details panel on the left).
96 Chapter 4 Classes, Objects, Methods and Parameters
Now we can add instructions for the World.surprise method, using instructions similar
to those in the program in Chapter 2, as in Figure 4-1-5.
Note: If the Play button is clicked at this time, the animation will not run. Although
the surprise method has been defined, Alice has not been told to execute it. That is,
the method has not been called into action. (Another phrase commonly used for
“calling a method” is “invoking a method”—but in this book we use the phrase
“calling a method.”)
Calling a method
How is your new method called into action? You have no doubt discovered that when you
(as the human “user”) click on the Play button, Alice automatically executes World.my first
method. You can see why this happens by looking carefully at the Events editor, located in the
top right of the Alice interface as seen in Figure 4-1-6. The instruction in this editor tells Alice
When the world starts, do World.my first method. We didn’t put this instruction here—the
Alice interface is automatically programmed this way. So, when the user clicks on the Play
button, the world starts and World.my first method is called.
Figure 4-1-6. When the world starts is linked to World.my first method
4-1 World-Level methods 97
Technical Note: The Events editor (upper right of the Alice interface) can be used to
modify what happens when the world starts. By default (meaning “unless you tell Alice
otherwise”), the user presses the Play button and Alice starts executing World.my first
method. Modifying this event in the Events editor tells Alice to execute a different
method when the user clicks on the Play button.
To modify the When the world starts event, click on the right of the World.my first
method tile in the Events editor. Then, select surprise from the dropdown list, as seen in
Figure 4-1-8. Now, when the world starts, the World.surprise method will run instead of
World.my first method.
A second method
Now that the World.surprise method is complete, we can construct the second method, named
World.investigate. World.investigate is a world-level method because both the spiderRobot
and the alienOnWheels objects are directly referenced in the instructions. Following the same
process as above for the World.surprise method, we created a World.investigate method, as
shown in Figure 4-1-9.
98 Chapter 4 Classes, Objects, Methods and Parameters
Now, we are ready to call each of the methods in World.my first method. The code is
illustrated in Figure 4-1-11.
Compare the revised program code in Figure 4-1-11 to the code in Figure 4-1-1. One
thing that you should notice immediately is that the revised code in Figure 4-1-11 has
fewer lines of code. The overall program has been broken down into methods—small
collections of instructions that carry out specific abstract tasks. World.my first method
acts as a driver that calls the methods. This organization makes the program easier to
read and understand. Also, writing and testing short methods makes it easer to debug
your programs.
4-1 World-Level methods 99
One benefit of writing methods this way is that some methods may be called more than
once. For example, the World.investigate method can be called multiple times to make the spi-
derRobot walk toward the alienOnWheels. This reduces the amount of program code and
saves us time as we create our programs. Figure 4-1-12 illustrates two calls to the
World.investigate method.
Deleting a method
Built-in methods and methods that are predefined for a model should not be deleted. In
other words, delete a method only if you have written the method and want to discard
it. Before deleting a method, delete all calls to the method and then close its edit win-
dow (right click on the method’s edit panel and select “close”), if open. To delete a
method, drag its name tile (from the methods list) to the trash bin, as illustrated in
Figure 4-1-13.
100 Chapter 4 Classes, Objects, Methods and Parameters
4-2 Parameters
It is clear from the examples in the preceding section that one program may be made up of
several methods. Each method is its own small block of instructions, designed to perform a
specific task when requested. We can appreciate that some communication might need to
occur when a method is called. In this section, we look at parameters. Parameters are used to
communicate with a method. We arrange to communicate values (e.g., a number or a color) or
names of objects from one method to another by using parameters in our methods.
Example
An example world will illustrate the creation and use of parameters. For a spring concert, our
entertainment committee has hired a popular music group—the Beetle Band. Our job is to
create an animation to advertise the concert. In the animation, each band member wants to
show off his musical skills in a short solo performance.
Setting the stage: Figure 4-2-1 shows an initial scene. The world is simple to set up.
To a new world, add a table as a stage (Furniture on DVD or Web gallery), georgeBeetle,
lennonBeetle, paulBeetle, and ringoBeetle (Animals). Give each band member a musical
instrument: bass, saxophone, timbalesCowBell, and guitar (Musical Instruments).
Make the vehicle of each musical instrument be the band member who plays the instru-
ment. For example, the vehicle of the bass guitar is georgeBeetle. Using the vehicle property
is a convenient way to make the musical instrument move with the band member as the band
member jumps up and down in his solo.
In the scene in Figure 4-2-1, we used a table to simulate a stage for the band and con-
serve memory. (Worlds that take up less memory load faster.) If you want a fancier scene, you
could use the concert stage (Environments on DVD or Web gallery) as shown in Figure 4-2-2.
Storyboard
The storyline for this animation is that each band member will perform a short solo—the band
member will jump up and down at the same time as a sound plays. (If your computer does not
have sound, you can have the band member say lyrics, rather than play a sound.) Let’s create
a storyboard for each band member’s solo. Because we have four band members (georgeBee-
tle, ringoBeetle, paulBeetle, and lennonBeetle), four textual storyboards can be composed:
Do together Do together
Do in order Do in order
georgeBeetle move up ringoBeetle move up
georgeBeetle move down ringoBeetle move down
play sound play sound
Do together Do together
Do in order Do in order
paulBeetle move up lennonBeetle move up
paulBeetle move down lennonBeetle move down
play sound play sound
Now a method can be written for each storyboard. We begin with a method for the solo
performed by georgeBeetle. Of course, the bass guitar will move with georgeBeetle when he
moves up and down because the bass guitar’s vehicle property is set to georgeBeetle. In a Do
together block, a play sound instruction will be used to play a sound at the same time as
georgeBeetle and the bass guitar instrument move up and down. Before a sound can be
played, a sound file must be imported into Alice. (Alice will play either MP3 or WAV sound
102 Chapter 4 Classes, Objects, Methods and Parameters
files.) Alice provides a few sounds for your use. Many noncopyrighted sound files are avail-
able on the Internet. You can also use sound editing software to record your own sound files
or you can purchase sound recordings on the Internet (for educational projects only).
In this world, a sound is associated with a musical instrument. For this reason, the sound
will be imported for the instrument object. To illustrate how to import a sound file, let’s
import a bass guitar sound for the bass instrument. Click on the bass instrument in the Object
tree and then on the import sound button in the bass object’s property list. A file selection
box appears. Navigate to a directory where you have stored your sound files and then select
the sound file to be used, as shown in Figure 4-2-3. (Note that our sound files have been stored
in a directory we created and named Sounds, but you may have them stored in some other
directory. It may be necessary to navigate through several folders on your computer to find a
sound file you wish to import.) Once the file has been selected, click on the Import button.
The name of the sound file automatically appears in the list of properties for the bass
object, as shown in Figure 4-2-4. The green arrow is a preview button and can be clicked to
test the sound file.
For this world, we used this technique to import four sound files—one for each musical
instrument (bass, sax, timbalesCowbell, and guitar) in the world. Now that the sound files have
been imported, a method can be created for a solo performed by one of the members of the
Beetle Band. The code for a solo by georgeBeetle is shown in Figure 4-2-5. The play sound
instruction is created by dragging the play sound method tile into the editor and selecting the
appropriate sound from a popup menu. The play sound instruction automatically includes the
duration of the sound. The bassGuitar sound used in our example will play for a duration of
1.845 seconds. If you wish to change the duration of the sound, we recommend that you use a
sound editor to modify the sound (rather than modify the duration in the Alice instruction).
To complete the animation, four methods are needed—one for each band member’s
solo. It is quite clear that the four storyboards are strikingly similar and four methods will be
almost exactly the same. The major differences are which band member will solo and which
instrument will play a sound.
Parameters
This is where parameters come in. A parameter allows you to send information to a method
when the method is called. You have been using parameters all along. Most primitive methods
have parameters that allow you to send information to the method. For example, a move
instruction has parameters that allow you to send in the direction, distance, and duration. In
the move instruction shown below, the direction is up, the distance is .25 meters, and the dura-
tion is 0.5 seconds. We say that the values are sent in as arguments to the parameters.
We can use parameters in our own methods. In the Beetle Band example, the four sto-
ryboards are so similar that we can collapse them into one storyboard by using a parameter to
communicate to the method which band member will perform the solo. The storyboard with a
parameter is:
solo
Parameter: bandMember
Do together
Do in order
bandMember move up
bandMember move down
play sound
104 Chapter 4 Classes, Objects, Methods and Parameters
The bandMember parameter name (an arbitrary name) is taking the place of the name of
the specific object that will perform the solo. You can think of a parameter as acting like
someone who stands in a cafeteria line for you until you arrive—sort of a placeholder. For
example, when georgeBeetle is sent in as an argument, then bandMember represents george-
Beetle. But, when lennonBeetle is sent in as an argument, bandMember represents lennon-
Beetle. By creating a parameter, we can write just one method (instead of four methods) and
use the parameter to communicate which band member will perform the solo.
An object parameter
A new world-level method, named solo, is created. The editor creates a new editor tab for the
World.solo method, as seen in Figure 4-2-6. A create new parameter button automatically
appears in the upper right corner of the editor. When the create new parameter button is
clicked, a dialog box pops up as shown in Figure 4-2-7. The name of the parameter is entered
and its type is selected. The type of a parameter can be a Number, Boolean (“true” or “false”),
Object, or Other (e.g., a color or sound). In this example, the name of the parameter is
bandMember and its type is Object.
Figure 4-2-7. Enter the name and select a type for a parameter declaration
When completed, the parameter name is in the upper left of the method panel, as shown
in Figure 4-2-8. Now, whenever the World.solo method is called, an object must be sent as an
argument to the bandMember parameter.
Now, we can translate the storyboard into program code. The first part of the storyboard
is a Do in order block to make the bandMember jump (move up and then down). Intuitively,
4-2 Parameters 105
we look at the Object tree to find bandMember so that its move instruction can be dragged into
the editor, but bandMember is not in the Object tree. (See Figure 4-2-9.) This makes sense
because, as mentioned earlier, bandMember is not an actual object—it is acting as a place-
holder for an object.
Instead of dragging a move method into the editor, drag the parameter tile into the edi-
tor. For example, in Figure 4-2-10, the bandMember parameter tile is dragged into the editor
and move, up, and 1/2 meter are selected from the popup menus.
Using the same procedure, another instruction is written to move bandMember down
0.5 meters. The duration for the move up and move down instructions is selected as
0.5 seconds. The resulting method is shown in Figure 4-2-11.
Multiple parameters
Each bandMember plays a different musical instrument, and each instrument should have a
different sound. (In this example, we want a bass sound for georgeBeetle, saxophone for
paulBeetle, drum for ringoBeetle, and guitar for lennonBeetle’s performance.) Let’s create
two additional parameters: instrument, for the object playing the sound, and music, for the
sound to be played. The type of the instrument parameter is Object (created in the same way
as bandMember, above) and the type of the music parameter is Sound. Figure 4-2-14 illus-
trates creating a Sound parameter named music.
As with the bandMember parameter above, the instrument and music parameters are
placeholders, and do not appear in the Object tree. When a parameter does not represent an
object, the parameter tile often must be dragged into the editor to replace the tile in an exist-
ing instruction. In this example, the instrument tile is dragged in to the editor to create a play
sound instruction, as illustrated in Figure 4-2-15. A popup menu allows the selection of play
sound as the method and music as the sound.
The code shown in Figure 4-2-15 is complete. A Do in order block is used to have the
bandMember move up and then down. And, a Do together block causes the sound to play at
the same time as the bandMember moves up and down.
108 Chapter 4 Classes, Objects, Methods and Parameters
Figure 4-2-15. Dragging the instrument and music parameters in to create a play sound instruction
Note: If alice is slow to load a sound file, you may see an error box several times, the
first time you click Play. Don’t ditch the World. Press restart in the play window and
the error should disappear. Once loaded the error should not occur again.
As mentioned above, this animation can be completed without the use of sound. An
alternate version of the solo method is shown in Figure 4-2-17. A string parameter, songLyric,
is used instead of a sound parameter. (A string is just several text characters or words.) The
songLyric string is displayed using a say instruction. To call this method, an argument for
songLyric could be something like “Oh, yeah!”
The height parameter can then be dragged into the move up and move down instruc-
tions. Figure 4-2-19 shows a revised solo method where the bandMember moves up and down
an amount specified by the height parameter.
Example
Consider the iceSkater shown in the winter scene in Figure 4-3-1. (The IceSkater class is from
the People collection, and the Lake class is from the Environments collection in the gallery.)
We want the skater to perform typical figure-skating actions. She is dressed in a skating
costume and is wearing ice skates, but this does not mean she knows how to skate. However,
all Alice objects “know” how to perform simple methods such as move, turn, and roll. We can
use a combination of these simple methods to “teach” the ice skater how to perform a more
complex action. We begin with a method to make the skater perform a skating motion.
An object-level method
Skating movements are complex actions that require several motion instructions involving
various parts of the body. (Professional animators at Disney and Pixar may spend many, many
hours observing the movement of various parts of the human body so as to create realistic ani-
mations.) To skate, a skater slides forward on the left leg and then slides forward on the right
leg. Of course, the entire skater body is moving forward as the legs perform the sliding move-
ments. The steps in a skating action are put together as a sequence of motions in a storyboard,
as shown next.
4-3 Object-Level methods and inheritance 111
skate
Do together
Move skater forward 2 meters
Do in order
slide on left leg
slide on right leg
Notice that the storyboard breaks down the skating action into two pieces—slide on the
left leg and slide on the right leg. The sliding motions can each be broken down into simpler
methods. Breaking a complex action down into simpler actions is called refinement. Here we
are using a design technique known as stepwise refinement. We first describe general actions,
and then break each action down into smaller and smaller steps (successively refined) until
the whole task is defined in simple actions. Each piece contributes a small part to the overall
animation; the pieces together accomplish the entire task.
The following diagram illustrates the refinement of the slideLeft and slideRight actions.
The actions needed to slide on the left leg are to lift the right leg and turn the upper body
slightly forward. Then, lower the right leg and turn the upper body backward (to an upright
position). Similar actions are carried out to slide on the right leg.
Refinement of slideLeft
Do in order
skate Lift right leg and turn upper body forward
Lower right leg and turn upper body backward
Do together
Move forward 2 meters
Do in order
slideLeft Refinement of slideRight
slideRight
Do in order
Lift left leg and turn upper body forward
Lower left leg and turn upper body backward
Nothing else needs to be refined. We are now ready to translate the design into program
code. We could translate this design to instructions in just the one method, but it would be
lengthy. Furthermore, you can quickly see that we have used stepwise refinement to break the
skate task down into distinct pieces. So, we demonstrate how to write several small methods
and make them work together to accomplish a larger task.
To translate the textual storyboard into program code, we need to think about these
actions in terms of methods. An implementation strategy diagram is shown in Figure 4-3-2.
The diagram is based on the textual story board above. Notice that the diagram has three
levels: World.my first method calls the skate method. The skate method calls the slideRight
method and then the slideLeft method.
Skate is a complex action that is designed specifically for the iceSkater and involves no
other objects. Likewise, the slideLeft and slideRight actions are designed specifically for the
iceSkater. The methods should be written as class-level methods because they involve only
the ice skater. We begin with the slideLeft method. The iceSkater is selected in the Object
112 Chapter 4 Classes, Objects, Methods and Parameters
Program
(my first method)
method
(skate)
method method
(slideRight) (slideLeft)
tree and the create new method button is clicked in the details panel. We enter slideLeft as
the name of the new method. (The result is shown in Figure 4-3-3.) Notice that the editor tab
is labeled iceSkater.slideLeft (not World.slideLeft)—indicating that the method is a class-
level method.
To implement the slideLeft method, we enter instructions in the editor. The idea is to
translate the design into actual program instructions. For example, to translate the design
steps for sliding on the left leg, we use the following:
4-3 Object-Level methods and inheritance 113
Figure 4-3-4 illustrates translating the textual storyboard into instructions for sliding on
the left leg. The instructions for sliding forward on the right leg are similar. So, writing the
slideRight method is rather easy. Figure 4-3-5 illustrates translating the textual storyboard
into instructions to slide forward on the right leg.
With the slideLeft and slideRight methods written, we are now ready to write the skate
method. The skate method is really quite simple: slideLeft and then slideRight at the same
time as the entire skater is moving forward. The skate method moves the skater forward and
calls the slideLeft method and then calls the slideRight method. Note that the calls to the
slideLeft and slideRight methods are enclosed in a Do in order block, nested within a Do
together. The Do together block is needed to ensure that the instruction that moves the skater
forward is performed simultaneously with the left and right sliding motions.
The duration of the forward movement of the skater is the sum of the durations of the
left and right slides. Paying attention to the durations of the instructions in a Do together
block will help coordinate the motions to begin and end at the same time. In this case, we
wanted to coordinate the slideLeft and slideRight motions with the forward motion of the
entire body. When the skate method is called, the skater glides forward in a realistic motion.
Figure 4-3-6 illustrates the skate method.
spin
Parameter: howManyTimes
Do in order
prepare to spin
spin the skater around howManyTimes
finish the spin
4-3 Object-Level methods and inheritance 115
We can use stepwise refinement to design the simple steps for each part of the spin. The
“prepare to spin” step can be written as a method (prepareToSpin) where the skater’s arms
move up and one leg turns. The “finish spin” step can also be written as a method (finishSpin)
to move the arms and legs back to their original positions, prior to the spin. The following dia-
gram illustrates a refinement of the spin method.
prepareToSpin
Do together
spin move arms up
raise and turn left leg
Parameter: howManyTimes
Do in order
prepare to spin
spin the skater around howManyTimes finishSpin
finish the spin
Do together
move arms down
lower and turn left leg
Nothing else needs to be refined. We are now ready to translate the design into program
code. Once again, class-level methods should be used, because we are defining a complex
motion specifically for the ice skater. Figure 4-3-7 shows an expanded implementation strat-
egy diagram for the Skater program. World.my first method calls the skate method and then
the spin method. When the skate method is called, it calls the slideLeft and slideRight meth-
ods to perform the skate. When the spin method is called, it calls the prepareToSpin and the
finishSpin methods to perform the spin.
Program
(my first method)
method method
(skate) (spin)
Figure 4-3-8 illustrates the prepareToSpin method, where the ice skater raises her left
leg as she lifts her arms.
116 Chapter 4 Classes, Objects, Methods and Parameters
Figure 4-3-8. The prepareToSpin method to raise arms and one leg
Figure 4-3-9 presents the finishSpin method to reposition the skater’s arms and leg to
their original positions at the end of her spin.
Now that the prepareToSpin and finishSpin methods have been written, we can write the
spin method, as seen in Figure 4-3-10. The howManySpins parameter is a number that speci-
fies how many times the skater is to turn around (one revolution is one complete spin around).
The order in which the methods are called is important so as to adjust the skater’s arms and
legs in preparation for the spin and after the spin.
The code for the two examples above (the skate and spin methods) is a bit longer
than we have written in previous chapters. It is important that the code is easy to under-
stand, because we have carefully broken down the overall task into smaller methods. The
small methods all work together to complete the overall action. Also, the methods have
been well documented, with comments that tell us what the method accomplishes. Good
design and comments make our code easier to understand as well as easier to write and
debug.
The second step is to save out as a new class: right click on cleverSkater in the Object
tree and this time select save object. In the Save Object popup box, navigate to the
folder/directory where you wish to save the new class, as in Figure 4-3-12, and then click the
Save button. The class is automatically named with the new name, beginning with a capital
letter and a filename extension .a2c, which stands for “Alice version 2.0 Class” (just as the
.a2w extension in a world filename stands for “Alice version 2.0 World”).
Once a new class has been created, it can be used in a new world by selecting Import
from the File menu, as illustrated in Figure 4-3-13. When an instance of the CleverSkater
class is added to a world, she will be just like an instance of the IceSkater class, except that a
cleverSkater object knows how to skate and spin in addition to all of the methods an iceSkater
object can perform.
118 Chapter 4 Classes, Objects, Methods and Parameters
Inheritance—benefits
Creating a new class based on a previously defined class is called inheritance. Inheritance in
most object-oriented languages is more complicated than in Alice. The basic idea is the
same—adding functionality by defining new methods for a new kind of inherited class. Inher-
itance is considered one of the strengths of object-oriented programming because it allows
you to write code once and reuse it in other programs.
Another benefit of creating new classes is the ability to share code with others in team
projects. For example, if you are working on an Alice project as a team, each person can write
class-level methods for an object in the world. Then, each team member can save out the new
class. Objects of the new classes are added to a single team-constructed world for a shared
project. This is a benefit we cannot overemphasize. In the “real world,” computer profession-
als generally work on team projects. Cooperatively developed software is often the way pro-
fessional animation teams at animation studios work.
4-3 Object-Level methods and inheritance 119
Figure 4-3-14. Object-level methods and sounds for the Lion class
2. Play a sound in a object-level method ONLY IF the sound has been imported for the
object (instead of the world). If the sound has been imported for the object and the
object is saved out as a new class, the sound is saved out with the object. Then the sound
can be played anywhere in any world where an object of this class is added. On the
other hand, if the sound is imported for the world, the sound is not saved out with the
object and you cannot depend on the sound being available in other worlds.
3. Do not call world-level methods from within a object-level method. Figure 4-3-15 illus-
trates cleverSkater.kaleidoscope—a object-level method that calls a world-level method
named World.changeColors. If the cleverSkater (with the cleverSkater.kaleidoscope
method) is saved out as a new class and an instance of the CleverSkater class is then
added to a later world where the World.changeColors method has not been defined,
Alice will complain that the World.changeColors method cannot be found. Alice stops
running your program and opens an Error dialog box with a description of the specific
error in your program.
Figure 4-3-15. Bad example: calling a world-level method from a object-level method
120 Chapter 4 Classes, Objects, Methods and Parameters
4. Do not use instructions for other objects from within a object-level method. Object-level
methods are clearly defined for a specific class. We expect to save out the object as a
new class and reuse it in a later world. We cannot depend on other objects being present
in other programs in other worlds. For example, a penguin (Animals) is added to the
winter scene, as in Figure 4-3-16. We write a object-level method named skateAround,
where the penguin object is specifically named in two of the instructions (circled in
Figure 4-3-17). If the cleverSkater with the skateAround method is saved out as a new
class and then a cleverSkater object is added to a later world where no penguin exists,
Alice will open an Error dialog box to tell you about a missing object. The error would
be that the cleverSkater cannot skate around a penguin that does not exist in the world!
Note: Possible exceptions to guideline #4 are the world and camera objects, which are
always present.
Figure 4-3-17. Bad example: instructions specifying another object in a class-level method
can be modified to use a parameter, arbitrarily named whichObject, as shown in Figure 4-3-18.
The whichObject parameter is only a placeholder, not an actual object, so we do not have to
worry about a particular object (like the penguin) having to be in another world. Alice will not
allow the skateAround method to be called without passing in an object to the whichObject
parameter. So, we can be sure that some sort of object will be there to skate around.
Testing
Once you have created and saved out a new class, it should be tested in a new world. The ini-
tial scene was shown in Figure 4-3-16. A sample test program is presented in Figure 4-3-19.
In this test, we have called the skate, spin, and skateAround methods to test each method.
The lilfish is swimming out to lunch, and her favorite seafood is seaweed. Instructions to
point lilfish at the seaweed and then swim toward it are shown in Figure T-4-2. The wiggletail
instruction is a method, shown in Figure T-4-2(b), that makes the fish wiggle its tail in a left-
right motion.
As the fish moves toward the seaweed, she will also move away from the camera. So she
should fade, because water blurs our vision of distant objects. We can make lilfish become
less visible by changing the opacity property. As opacity is decreased, an object becomes less
distinct (more difficult to see). To write an instruction to change the opacity, click on the
lilfish’s properties tab and drag the opacity tile into the editor. From the popup menu, select
the opacity percentage, as shown in Figure T-4-3.
When the world is run, lilfish will become less visible, as shown in Figure T-4-5. At 0%
opacity, an object will totally disappear. This does not mean that the object has been deleted;
it is still part of the world but is not visible on the screen.
Figure T-4-5. The lilfish becomes more difficult to see as opacity is decreased
isShowing to false makes the “You won!” text invisible, as shown in Figure T-4-7. (For this
world, we used the bottle Throw object from the Amusement Park folder in the DVD or Web
gallery.)
Figure T-4-6. The isShowing property is true and “You won!” is visible
Figure T-4-7. The isShowing property is false and “You won!” is not visible
When its isShowing property is set to false, the object is not removed from the world; it is
simply not displayed on the screen. The object can be made to “reappear” by setting its
isShowing property back to true.
In this example, we want the text to appear when the player wins the game. To create an
instruction that sets the isShowing property to true, drag the isShowing property tile into the
world and select true from the popup menu. The result is shown in Figure T-4-8.
126 Chapter 4 Classes, Objects, Methods and Parameters
This is no problem. The pterodactyl will fly around the dragon if we use
asSeenBy = dragon in a turn right instruction for the pterodactyl object. (The asSeenBy
parameter was described in Tips & Techniques 2.)
Summary 127
Suppose that we want the pterodactyl and the dragon to both fly around in a half-turn rel-
ative to each other (facing each other down—sort of a bluffing technique). This would mean
that the dragon should end up at the pterodactyl’s location (facing the pterodactyl’s new loca-
tion), and the pterodactyl should end up at the dragon’s location (facing the dragon’s new
location). A first attempt might be as follows:
When this program is run, each animal ends up where it started, facing in the opposite
direction! The problem is that once each animal has begun to move, its location changes, so
that further moves relative to each other lead to unexpected results! What we need is an object
that does not move, located somewhere between the dragon and the pterodactyl. Let’s add a
sphere object between the dragon and the pterodactyl and make it invisible by changing its
isShowing property to false. Now we can write:
When this code is run, the dragon and pterodactyl exchange places, as seen in Figure T-4-10!
Summary
In this chapter we looked at how to write our own methods and how to use parameters to send
information to a method when it is called. An advantage of using methods is that the pro-
grammer can think about a collection of instructions as all one action—abstraction. Also,
methods make it easier to debug our code.
Two different kinds of methods can be written: world-level methods that involve two or
more objects interacting in some way, and object-level methods that define a complex action
carried out by a single object acting alone.
Parameters are used to communicate values from one method to another. In a method, a
parameter acts as a placeholder for a value of a particular type. The values sent in to a method
are known as arguments. When an argument is sent in to a method, the parameter represents
128 Chapter 4 Classes, Objects, Methods and Parameters
that argument in the instructions in the method. Examples presented in this chapter included
object, sound, string, and number parameters. Parameters allow you to write one method but
use it several times with different objects, sounds, numbers, and other types of values.
In a way, object-level methods can be thought of as extending an object’s behavior. Once
new object-level methods are defined, a new class can be saved out. The new class has a different
name and has all the new methods (and also the old methods) as available actions. It inherits the
properties and actions of the original class but defines more things than the original class. A
major benefit is that you can use objects of the new class over and over again in new worlds. This
allows you to take advantage of the methods you have written without having to write them again.
Some guidelines were provided for writing object-level methods: only sounds imported
for the class should be played in a object-level method; world-level methods should not be
called; and instructions involving other objects should not be used. Following these guidelines
will ensure that objects of your newly defined classes can safely be used in other worlds.
Stepwise refinement is a design technique where a complex task is broken down into
small pieces and then each piece is broken down further—until the entire task is completely
defined by simple actions. The simple actions all work together to carry out the complex task.
Programming Terms
abstraction object-level method object
argument inheritance parameter
by default instance primitive method
calling a method instantiate stepwise refinement
class method world-level method
Animation Terms
isShowing opacity
Questions
1. Alice has hundreds of pre-written classes for instantiating objects in an Alice world.
Where, in the Alice interface, can you find these pre-written classes?
2. Is it possible for your Alice program to have more than one instance of the same class?
Explain your answer.
Exercises and Projects 129
3. When you click on the Play button in Alice, what method is automatically called?
Why?
4. What is another term commonly used for “calling a method”?
5. In Alice, one method may call another method, which may require that one or more val-
ues be communicated to the method being called.
(a) What part of an instruction holds a value to be communicated?
(b) What part of the called method receives the value?
6. List the types of parameters that may be in an Alice method.
7. Why is it useful to test a method by sending in different arguments?
8. What is the distinction between a world-level method and a object-level method?
9. Alice is said to have a very primitive form of inheritance because inheritance is not
“fully defined” as part of the Alice system. Which kind of methods in Alice (world-
level or class-level) can be used as part of its primitive inheritance capability?
10. If sound is being imported in a object-level method, should the sound be imported for
the object or for the world? Explain your answer.
11. If you wish to write a object-level method where another object is involved, what can be
done to allow your code to call the other object’s methods?
12. What is the difference between opacity and isShowing properties of an object, in terms
of effect on visibility of an object in Alice?
13. Sketch a storyboard and an implementation strategy diagram for each of the following:
(a) Exercise 2, below.
(b) Exercise 5, below.
(c) Exercise 11, below.
4-1 Exercises
Reminder: Be sure to add comments to your methods to document what each method does
and what actions are carried out by sections of code within the method.
1. Snowpeople Flip Hats
Write a new world-level method for the Snowpeople world (from Chapter 2, Exer-
cise 3). The new method, named flipHats, will be called when the snowwoman turns
her head to look at the snowman. In the flipHats method, the snowman uses his right
arm to grab his hat and graciously tip his hat to the snowwoman and then returns his
hat to his head. After the snowman flips his hat, the snowwoman flips her hat.
130 Chapter 4 Classes, Objects, Methods and Parameters
2. Confused Kanga
Scrounging for breakfast on the outback, Kanga (kangaroo from Animals) encounters a
rather confusing sign (Roads and Signs folder). Kanga stares at the sign for a few sec-
onds and tilts her head sideways to show that she is confused. Kanga then hops left and
turns toward the sign and then hops right and turns toward the sign and then left and
then right.
Create a simulation that implements this comical story. Write methods hopLeft (Kanga
turns left a small amount and hops, and then turns to face the sign) and hopRight
(Kanga turns right a small amount and hops, then turns to face the sign). With each
hop, Kanga should make some progress toward the sign. In World.my first method,
alternately call the hopLeft and hopRight methods (twice) to make Kanga take a zigzag
path toward the sign.
3. Gallop and Jump
Kelly (People) has entered an equestrian show as an amateur jumper. She is somewhat
nervous about the competition so she and the horse (Animals) are practicing a jump.
Create an initial scene with a horse and rider facing a fence (Buildings), as shown
below.
Write two world-level methods, one named gallop (horse and rider gallop forward one
step) and another named jump (horse and rider jump the fence). In the gallop method,
the horse’s front legs should lift and then go down as the back legs lift and the horse
moves forward. Then the back legs should go back down. The jump method should be
Exercises and Projects 131
similar, but the horse should move up far enough to clear the fence in mid-stride. Test
each method to be sure it works as expected. You will need to adjust the distance
amounts to make each look somewhat realistic.
Hint: If you make the horse a vehicle for Kelly (Tips & Techniques 2), you will only
need to write an instruction to move the horse and Kelly will go along for the ride.
When you think the gallop and jump methods are both working properly, write instruc-
tions in World.my first method that call the gallop method as many times as needed to
move the horse and rider up close to the fence; then call the jump method. Use trial and
error to find out how many times the gallop method must be called to make the anima-
tion work well.
4. Helicopter Flight
Create a world with a helicopter (Vehicles on DVD or Web gallery), airport (Buildings),
and a control tower (Buildings). Create a circleTower method that makes the helicopter
fly toward the control tower and then around it. In my first method, call the circleTower
method twice and then make the helicopter land on the airport landing strip.
4-2 Exercises
5. Beetle Band Duet
In Section 4-2, the Beetle Band example has a method named solo, where each member
of the band jumps and plays a musical instrument. Recreate the Beetle Band example
and write a method named duet, where the solo method is called to have two members
of the band jump together and play their musical instruments. This exercise can be done
with sound (as in Figure 4-2-15) or with lyrics (as in Figure 4-2-17). Parameters must
be used to send in the name of the band member and the music to be played or the lyric
to be said.
6. Frog Escape
At the local lily pond (Environments on DVD or Web gallery), the frogs (Animals)
enjoy climbing out of the water now and then to warm up in the sun. Of course, they get
a bit jumpy when a predator is sighted. On this fine day, a hungry snake (Animals) wan-
ders into the scene. Create a world scene similar to the one below and animate the frogs
jumping into the pond when the snake approaches. Write a method that turns the snake
toward the frog and slides the snake forward. Then, have the frog turn to the pond and
jump in. Your method should use a parameter to specify which frog is escaping.
132 Chapter 4 Classes, Objects, Methods and Parameters
7. Magic Act
A magician is performing a levitation illusion, in which objects seem to rise magically
into the air. The magician (People) points a magic wand (Objects) at his assistant (Girl
from People folder), and she gently rises into the air and then floats back down to her
original position on the table (Furniture on DVD or Web gallery). Then the magician
performs the same trick with the rabbit (Animals). The rabbit, being a lighter object,
floats up higher than the magician’s assistant. Because the magician’s assistant and
rabbit are each to levitate in the same way, use a single method and use parameters to
communicate which object is to float and the distance the object is to move upward
(and back down).
Hint: The magician’s assistant is reclining on the surface of the table. A move up
instruction will cause the assistant to move upward from her point of view, as shown
below. Use the asSeenBy argument to make the magician’s assistant move upward as
seen by the ground.
Exercises and Projects 133
8. Dragons
Legend has it that dragons are distant relatives of chickens. We are not surprised, then,
that a favorite pastime of dragons was a game of “chicken.” The scene below shows a
world with four dragons (Medieval) carefully placed in a diamond like pattern (similar
to baseball players at the four bases). Create a simulation of a game of chicken where
any two dragons face each other and fly upward to a slightly different height above the
ground. Then the dragons fly toward each other, nearly missing one another. Each
dragon should land in the position where the other dragon was located. That is, the two
dragons trade places. Your simulation should use a method named dragonFlight that
has four parameters—the two dragons that will face off in a game of chicken and the
height for each dragon’s flight.
4-3 Exercises
9. Enhanced cleverSkater
Create an even better cleverSkater than the one presented in Section 4-3. In addition to
the skateForward, spin and skateAround methods, create skateBackward and jump
class-level methods. In skateBackward, the skater should perform similar actions to
those in the skateForward method, but slide backward instead of forward. In a jump
method, the skater should move forward, lift one leg, then move upward (in the air) and
back down to land gracefully on the ice and lower her leg back to its starting position.
Save out your enhanced skater as EnhancedCleverSkater.
Test your newly defined class by starting a new world with a frozen lake. Add an
enhancedCleverSkater to the world. Also, add a penguin and a duck.
(a) Call each of the methods you have written.
(b) Then call the skateAround method—to make the skater skate around the penguin
and then the duck. (This will require two calls to the skateAround method.)
10. Lock Combination
Create a world with a comboLock (Objects folder). Create four class-level methods—
leftOne, rightOne, leftRevolution, and rightRevolution— that turn the dial 1 number
left, 1 number right, 1 revolution left, and 1 revolution right, respectively. Then, create
a class-level method named open that opens and another named close that closes the
lock.
Hints: One position on the dial is actually 1/40 of a revolution. (Use the endGently style
to make the motion more realistic.) Rename comboLock as TurningComboLock and
save it as a new class.
134 Chapter 4 Classes, Objects, Methods and Parameters
Projects
We are using the term project to describe advanced exercises that are more challenging than
regular exercises. The projects in this chapter involve motion of human body parts. Profes-
sional animators spend many hours mastering the art of making these movements look realis-
tic. Our focus is on mastering the art (and science) of writing methods in a program.
1. Dance
Technical Note: To assist you in learning how to animate human body parts, this first
project includes some explanations and coding suggestions. The goal of this animation
is to have the couple perform a dance step in a traditional box (square) figure as used in
the waltz and other dances. Create a scene with a sheriff (Old West) and a woman (Peo-
ple) inside a saloon (Old West), as illustrated below.
In the first step of a box figure, the sheriff takes a step forward, leading with his left leg
and (at the same time) the woman takes a step backwards, leading with her right leg.
This is not as simple as it sounds. One way to make an object with legs appear to take a
“step” is to have the object raise one leg some small amount and then move forward as
the leg moves back down. Then, the other leg performs a similar action. Thus, to make
two objects appear to dance together requires coordinated leg lift, move and drop
actions for both objects. The easiest way to do this is to write a method, perhaps named
forwardStep. The forwardStep method will need two parameters: howFar (the distance
forward), and howLongToTake (the time it takes). A possible storyboard is:
forwardStep
Parameters: howFar, howLongToTake
Do in order
Do together
sheriff’s left leg moves up
woman’s right leg moves up
Do together
sheriff moves forward howFar
sheriff’s left leg moves down
woman moves backward howFar
woman’s right leg moves down
136 Chapter 4 Classes, Objects, Methods and Parameters
To help you get started, an example of the code for the forwardStep method is shown
below. The distances used in this code worked well for us in our example. You may
need to experiment with the amount to move the legs up (and down), and with the size
of step forward, backward, and sideways the couple is to take. The distances depend on
the size of the models in your world.
4. Cleanup Robot
The scene below shows a child’s room with toys scattered around on the floor. The gorilla
robot (SciFi) can be programmed pick up things in the room and put them behind the
door in the closetRoom (Environments on DVD or Web gallery). In the initial scene for
this animation, the robot is standing in the middle of the room near several objects scat-
tered around the floor (e.g., a barbell, a piñata, and a teddy bear from the Objects folder).
Write a program to teach the robot to pick up one object at a time and put it in the closet.
Write three methods, named pickup, putdown, and putInCloset. The methods should
have one parameter identifying the object to be picked up or put down. The pickUp
138 Chapter 4 Classes, Objects, Methods and Parameters
method should make the robot pick up an object in its hand. The putDown method
should have the robot put the object down. The putInCloset method should make the
robot turn one-half revolution and move to the door. The door opens and the robot puts
down the object. When these methods have been written, then write instructions in my
First Method to make the robot pick up an object and put it down in the closet.
5. Skater Competition
Add five enhancedCleverSkater objects to a world with a lake (Environments) scene.
See Exercise 9 for a description of the EnhancedCleverSkater. Also, add three people to
act as judges of a skating competition. Write a method for each skater that has her per-
form a skating routine (each skater should perform some combination of skate, spin,
jump and other methods). Each skater (one at a time) will perform her skating routine;
then have the three judges say a score. Scores range from 1 to 9. Then the skater that has
just performed will move out of the way and the next skater will perform.
The real world around us is interactive. A conversation, as between Alice and the Queen
above, is a “give and take” form of interaction. As we interact with objects in our world, we
often give directions to them. For example, we change the channel on a television set by send-
ing a signal from a remote control. We press a button on a game controller to make a charac-
ter in a video game jump out of the way of danger.
We have concentrated on writing programs that were not interactive—we watched the
objects perform actions in a movie-style animation. It’s time we looked at how to create inter-
active programs in Alice—where the objects in the scenes respond to mouse clicks and key
presses. In this chapter we see how programs can be made interactive.
Much of computer programming (and the movie-style animations seen earlier) is
computer-centric. That is, the computer program basically runs as the programmer has
intended it. The programmer sets the order of actions and controls the program flow. How-
ever, many computer programs today are user-centric. In other words, it is the computer user
(rather than the programmer) who determines the order of actions. The user clicks the mouse
or presses a key on the keyboard to send a signal to Alice about what to do next. The mouse
click or key press is an event. An event is something that happens. In response to an event, an
action (or a sequence of many actions) is carried out. We say the event triggers a response.
Section 5-1 focuses on the mechanics of how the user creates an event and how the pro-
gram responds to the event. Naturally, all of this takes a bit of planning and arrangement. We
need to tell Alice to listen for a particular kind of event and then what to do when the event
happens. This means we need to write methods that describe the actions objects should take in
response to an event.
Section 5-2 describes how to pass parameters to event handling methods. In some pro-
gramming languages, arranging events and writing event handling methods is a rather com-
plex kind of programming. We hope you will find that learning to use events and event
handling methods is easy in Alice.
the programmer. The programmer designs a complete storyboard and then writes the program
code for the animated actions. Once the program is constructed and tested, then every time the
program runs, the same sequence of actions will occur. In an interactive program the sequence
of actions is determined at runtime, when:
• The user clicks the mouse or presses a key on the keyboard.
• Objects in the scene move (randomly or guided by the user) to create some condition,
such as a collision.
Events
Each time the user clicks the mouse or presses a key, an event is generated that triggers a
response. Objects in the scene may move to positions that trigger a response. Each time the
program runs, different user interactions or different object actions may occur and the over-
all animation sequence may be different from some previous execution of the program. For
example, in a video game that simulates a car race, where the player is “driving” a race car,
the sequence of scenes is determined by whether the player is skillful in steering the car to
stay on the road through twists, turns, and hazards that suddenly appear in the scene.
Keyboard-control example
We begin with an acrobatic air-show flight simulator. The initial scene, as illustrated in
Figure 5-1-1, consists of the biplane (Vehicles) in midair and some objects on the ground
(house, barn, and so forth from the Buildings and Farm folders). A guidance system will
allow the user to be the pilot. The biplane has controls that allow the pilot to maneuver the
plane forward, left, and right. We want to program the biplane to perform a popular show
stunt—a barrel turn. In the exercises at the end of this chapter, other stunts can be added.
Input
The whole idea of a flight simulator is to allow the user to interact with the biplane. The user
provides input that sends a signal to animate a particular motion, perhaps by pressing a set of
keys on the keyboard. For example, arrow keys can be used, each corresponding to a given
direction of movement. Of course, input can also be obtained from mouse clicks, the move-
ment of a trackball, or the use of a game stick controller. In this text, we rely on the keyboard
and mouse to provide user input for interaction with the animations.
In our flight simulator, the arrow keys and spacebar will be used to provide input from
the user. If the user presses the up arrow key, the biplane will move forward. If the user
presses the left or right arrow keys, the biplane will turn left or right. For the acrobatic bar-
rel turn, we will use the spacebar. The selection of these keys is arbitrary—other keys could
easily be used.
Design—storyboards
We are ready to design the flight simulator program—the set of instructions that tell Alice
how to perform the animations. Each time the user presses an arrow key or the spacebar, an
event is generated. The animation program consists of methods to respond to these events. To
simplify the discussion, let’s concentrate on two possible events: the spacebar press for the
barrel turn and the up arrow key to move the biplane forward. Two storyboards are needed, as
shown below. Note that sound is optional and can be omitted.
Response: Response:
Do together Do together
roll biplane a full revolution move biplane forward
play biplane engine sound play biplane engine sound
rolling the biplane one complete revolution, illustrated in Figure 5-1-3. In the methods
shown here, a sound is played simultaneously with the movement. The duration of the
biplane movement is set to be approximately the same as the length of the sound (in sec-
onds). As noted previously, sound is a nice feature but can be omitted. If sound is used, the
sound should be imported for the biplane. (Importing a sound file was introduced in
Chapter 4, Section 2.)
In Figure 5-1-6, an event for any key pressed has been added to the Events editor. The
“any key” and “Nothing” tiles are placeholders that need to be replaced. To tell Alice that we
want to use the up arrow key, clicking on the any key tile and select Up from the popup menu.
Now that Alice has been notified that an up arrow key event may occur, we need to tell
Alice what to do when the event happens. As shown in Figure 5-1-7, click on the Nothing tile
and then select biplane and flyForward from the popup menu.
The process is repeated to link the spacebar to the barrel method. Figure 5-1-8 shows
the Events editor with both links completed.
You may be questioning how the Alice system works with events. Basically, Alice is in
an infinite loop (one that runs until the program is stopped). The system continuously “lis-
tens” for the user to type a key or mouse click. In this example, if a key is typed then a deci-
sion is made to call the appropriate method, depending on whether the key is the up arrow or
the spacebar. If a different key is typed it is discarded and no method is called. A mouse click
on the Stop button (or on an exit for the runtime window) stops the program. A mouse click
anywhere else in the runtime window has no effect.
Testing
Now the world should be tested. To test the flight simulator, just save the world and press the
Play button. Nothing happens until the up arrow is pressed, which causes the biplane to call
its flyForward method.
Events and methods could be created for the left and right arrow keys, and other acro-
batic stunts could be written. (See exercise 1.) However, it is important to test event han-
dling methods as they are developed. Write a method and test it, write a method and test it,
until the program is completed. This is a recommended program development strategy called
incremental development. Its advantage is in making it easier to debug your program. When
something isn’t working, it can be fixed before it causes problems elsewhere.
Note: An interactive world such as a flight simulator requires that the user know what
keys to press to make the simulation work properly. A startup method could be written
in World.my first method to display 3D text or a billboard for a quick explanation of
the guidance system. After a few seconds, the 3D text (or billboard) can be made to
disappear (by setting its isShowing property to false), and then the simulation can
begin. 3D text and billboards were described in Tips & Techniques 2.
“When” means “listen for this event” and each time it occurs, perform the event handling
action. “While” means “as long as something is true” continue to perform the event handling
action. In the world illustrated in Figure 5-1-10, the bunny will hop each time the user types
“B”. The chicken, however, will peck continuously as long as it is showing.
Figure 5-1-10. The bunny hops only when B is typed; chicken pecks continuously until not showing
For some events, it is possible to change “When” to “While”. A right-click on the event tile in
the Events editor pops up a menu having a “change to” option, as shown in Figure 5-1-11. In
this example, we changed “When B is typed” to “While B is pressed”. Now, the bunny will
hop continuously, as long as the “B” key is held down. The same technique can be used to
change “While” to “When”.
A simple example
The stage manager for an ice show production is testing various lighting effects before the ice
skaters perform. Three lights (Lights) have been positioned around a white cube (Shapes) set
on the ice surface (FrozenLake, in Environments). The lights are carefully positioned so the
red light is reflected on one side of the cube, the blue light on an adjacent side, and the green
light in the middle. The initial scene is shown in Figure 5-2-1. (To create the world with a dark
sky, we used the Space template.) To test the lighting effects, the brightness of the world’s
light is dimmed. This example is to create an animation that allows the user to click on a light
to turn it off. Each time a light is clicked, that light is turned off. When all three lights are
turned off, the world scene will be totally dark. Well, perhaps not totally dark—but as dark
as possible.
Design—storyboard
To design an interactive program storyboard, we must give some thought to what events will
occur and what event handler methods are needed. Let’s allow the user to select the light to be
turned off. In order to turn off a light in Alice, it is necessary to do two things: the light itself
needs to be blackened, and it needs to stop emitting light (which is accomplished by blacken-
ing its emissive color). A textual storyboard is shown below.
148 Chapter 5 Interaction: Events and Event Handling
Responding Method:
Change blueLight color to black
Change blueLight emissiveColor to black
world.turnOffLight
parameter: whichLight
Do in order
Change whichLight color to black
Change whichLight emmissive color to black
The code is presented in Figure 5-2-2. To make the clicked light “turn off,” we set its
color property to Black. Then, we set its emmisiveColor property to Black.
Figure 5-2-3. Three events: one for each object that can be clicked
Testing
When parameters are used in event-driven programming, it is especially important to run
the animation several times, each time causing different events to occur to be sure that
each possible parameter value works as expected. In this example, it is important to test
the program by using your mouse to click each of the three lights. In other programs you
may need to send a numeric parameter. If so, you should test by trying a small value, a large
value, and perhaps even a negative value—just to be sure the program works with a range of
parameter values.
Design—storyboard
To make this animation interactive, we will let the user choose the object that will be the next
victim of Zeus’s anger. When the user clicks on an object, the object will be passed to the
event handling method. What actions need to occur in response to the mouse-click event?
First, Zeus will turn to face the selected object and the thunderbolt will be made visible. Then,
the thunderbolt will flash down to strike the object. Smoke will be used as a special effect to
make the object appear to meet a sad fate. Then, the lightning bolt must be repositioned to
prepare for another lightning strike. (In interactive worlds, the user can click on more than one
object.)
Clearly, the event handling method will involve many different actions. To organize an
event handling method (named shootBolt), let’s begin with a storyboard that summarizes the
overall actions. A parameter (arbitrarily named who) is needed to send in the object that was
clicked.
Do in order
prepare to strike the object that was clicked
thunder plays and lightning strikes the object that was clicked
lightning is repositioned for the next strike
In this storyboard, the first two steps in the Do in order block are actually composed of
many actions. If we were to translate these into code in a single method, it would be many,
many lines of code. A long method (consisting of many lines of code) is often difficult to read
and debug. Let’s use stepwise refinement to break the design down into smaller pieces. We
could write a method, prepareToShoot, for the first step and a second method,
lightningAndThunder, for the second step. In the third step, repositioning the lightning bolt for
another strike can be performed as a single move to instruction. The revised storyboard would
look like this:
Do in order
call prepareToShoot method—send who as the target
call lightningAndThunder method–send who as the target
lightning move to cloud’s position
5-2 Parameters and event handling methods 151
Now the shootBolt method will be easy to write because all it does is call two other
methods and then reposition the lightning bolt behind the cloud. A method that does very lit-
tle other than organizing the calls to other methods is known as a driver. The driver organizes
and calls the methods. The called methods do almost all the work. An important role played
by the shootBolt method is to pass along (to the called methods) the object that was clicked
(who). Each of the called methods will use the object that was clicked as the target of its own
actions.
For now, let’s assume that the prepareToShoot and lightningAndThunder methods have
been written (we will write them later). Then, we can write the shootBolt method, as in
Figure 5-2-5.
Figure 5-2-5. The shootBolt event handling method calls other methods
Now that you have the overall idea of how an event handling method can act as a driver
to call other methods, let’s write the methods that are called. First, the prepareToShoot
method prepares Zeus and the lightning bolt for shooting at the object that was clicked. A
simple storyboard is:
prepareToShoot
Parameter: target
Do together
turn Zeus to face the target
make the lightning bolt visible
A turn to face instruction will make Zeus look at the target. In setting up the world, the
lightning bolt was made invisible by setting its opacity to 0 (0%). To make the lightning bolt
visible (so we can see it flash across the scene), we write an instruction to set its opacity to 1
(100%). The code for the prepareToShoot method is shown in Figure 5-2-6.
152 Chapter 5 Interaction: Events and Event Handling
lightningAndThunder
Parameter: target
Do together
play sound
call specialEffects method—send target as the victim
Now that we have a design, the next step is to translate it into program code. Let’s
pretend that the specialEffects method is already written. Then, the lightningAndThunder
method could be written, as shown in Figure 5-2-7. Playing a sound at the same time as
other actions requires that the amount of time the sound plays must be synchronized with
the amount of time needed for the special effects. In this program, we found it worked best
if we inserted a Wait instruction with the play sound instruction (in a Do in order) to create
a short delay. The call to the specialEffects method passes along target as the victim of the
lightning strike.
5-2 Parameters and event handling methods 153
Finally, it is time to write the specialEffects method. First the lightning should strike,
and then smoke should appear around the targeted object (victim). The victim should show
the effects of a lightning strike—change color and jump up and down. A storyboard for
specialEffects is:
specialEffects
Parameter: victim
Do in order
Do together
lightning bolt move to victim
smoke move to victim
Do together
set smoke to visible
set lightning to invisible
call smoke cycle—built-in method
set victim’s color to black
move target up and down
Do together
set smoke’s opacity to 1
smoke move down 5 meters
parameter), which is easy to do. Just drag the lightning move to tile into the editor and select
expression : victim as the targeted object from the popup menu, as in Figure 5-2-8.
An instruction to move the smoke to the position of the victim is created in a similar
manner. After the lightning strikes, we need to make the lightning bolt invisible and the
smoke visible. This is accomplished using set opacity instructions. Figure 5-2-9 shows the
complete implementation of the specialEffects method. If using Alice 2.2, use isShowing
instead of opacity.
In the specialEffects method, we took advantage of a built-in method for smoke (cycle
Smoke) to create a smoke animation. To animate the effects of the lightning strike, the target
color is set to black and made to move up and down.
5-2 Parameters and event handling methods 155
select the desired body type, hair, skin color, eyes, and clothing. When you have completed
your selections, click on OK to name the object and add it to your world.
It is worthwhile to experiment with using each of these methods in your world. Many of these
methods allow your person object to exhibit various emotions. The walk method is particu-
larly worthy of your attention. This method provides a real advantage, because a walk method
is difficult to write on your own. Note, however, that the walk method causes the person to
158 Chapter 5 Interaction: Events and Event Handling
walk “in place”—not moving forward. Thus, an instruction that calls the walk method should
be paired with a move forward instruction, in a Do together to have the person object walk
forward. Figure T-5-4 illustrates the code to have the person Steve walk forward 2 meters.
Figure T-5-4. Pairing the built-in walk method with a move forward
Note: Alice uses poses (see Tips & Techniques 11) when implementing these built-in
methods. If an object is resized (either during scene setup or at runtime) the built-in
methods will not work properly. We recommend that you do not resize person objects
constructed with the hebuilder/shebuilder. Instead, resize all other objects in your
scene, as you are setting up the world.
Summary
The focus of this chapter was the creation of interactive (event-driven) worlds. Creating
worlds with events will allow you to build significantly more interesting worlds such as game-
like animations and simulations. In many object-oriented programming languages, event-
driven programming requires knowledge of advanced topics. The Events editor allows you to
create events and link them to event handling methods. The event handling method has the
responsibility of taking action each time the event occurs. The Events editor handles many of
the messy details of event-driven programming.
Programming Terms
control of flow incremental development
event interactive
event handling method
Exercises and Projects 159
Questions
1. In what way(s) is an interactive animation program different from a non-interactive
(movie) animation program?
2. How is an event created at runtime?
3. List five different kinds of events that are available in the Alice system.
4. What part of the Alice system is used to link an event to an event handling method?
5. What is the advantage of using one or more parameters in an event handling
method?
6. Why should you test an event handling method that has a parameter several times, call-
ing it with different parameters?
7. What is the advantage of using incremental development when creating an interactive
program?
8. Why are events considered to be world-level in Alice?
9. How is it possible to make one event handling method respond to more than one
event?
10. Suppose an Alice program has the event “When the world starts”. How many times will
this event occur when the program is run?
11. For exercise 8 below,
(a) Create a textual storyboard
(b) Sketch a flowchart
Then, link the biplane, as shown below. Run the flight simulator again to see the effect.
4. Typing Tutor
Learning to type rapidly (without looking at the keyboard) is a skill requiring much
practice. In this exercise, you are to create a typing tutor that encourages the beginning
typist to type a specific set of letters. Use 3D text letters (3D Text folder) to create
a word in the world, (for example, you could create the word ALICE with the letters
A, L, I, C, and E) and create a method for each letter that spins the letter two times.
When the user types a letter key on the keyboard that matches the letter on the screen, the
letter on the screen should perform its spin method. Also include an additional method,
spinWord, which spins all the letters when the user presses the spacebar.
Hint: Use asSeenBy to spin the word.
6. Ninja Motion
A ninja (EvilNinja in People folder) is trying out for a karate movie, and he needs a lit-
tle practice. Create a world with a ninja object in a dojo. The motions the ninja needs to
162 Chapter 5 Interaction: Events and Event Handling
practice are: jump, duck, chop, and kick. If you have not already done so (see Exercise
12 in Chapter 4), write motion methods for the ninja that include the following:
kickRight, kickLeft: allows the ninja to kick his right/left leg, including all
appropriate movements (e.g., foot turning, etc.)
rightJab, leftJab: allows the ninja to do a jabbing motion with his right/left
arms
Create events and event handling methods that provide the user with controls to make
the ninja jump, duck, jab, and kick.
7. The Cheshire Cat
Consider the Cheshire cat (Animals) from the Alice in Wonderland books. Sometimes,
the cat would disappear, leaving only his grin. At other times, the cat would reappear.
Create such a world, where the cat (except for its smile) disappears when the red button
of the switch (Controls) is clicked, then reappears when the green button is clicked.
(The tree is found in the Nature folder.)
5-2 Exercises
8. Zeus Modification
Recreate the Zeus world presented in Section 5-2. In this world, a philosopher has been
zapped by lightning and is scorched to show he has met a tragic ending. The philoso-
pher is still in the scene, however, and the user can zap him again. Revise the program
to make the zapped philosopher fall down below the ground, where he can’t be mouse-
clicked again.
9. Interview with a Computer Scientist
Create a world in which an interview takes place between a talk show host (heBuilder or
sheBuilder from People) and an influential person from the world of computer science
(heBuilder or sheBuilder from People). The scene should look like a television studio
set with a desk (make your own using a Box from Shapes), and a chair (Armchair from
Furniture) for the interviewer. Add a couch (Furniture) for the guest. Find an interesting
picture for the background and import it as a billboard. Use dialogue to tell some inter-
esting facts about the guest. The dialogue can be in the form of the person saying some-
thing or you can create voice recordings and import the sound files. Create an event for
each new question by the interviewer and activate the event using the number keys (1–9).
Challenge: Download a picture of the guest and edit it using a drawing application. In
Alice, make a billboard of the guest’s face and position it on the guest’s body.
Exercises and Projects 163
14. Hockey
Jack (Jock from High School/Students and Teachers folder on the DVD or Web gallery)
is planning to try out for the school hockey team this fall. As a successful athlete, Jack
knows that “practice is the name of the game.” Jack has set up a hockey net (Sports) on
the lake and is going to practice his aim with the hockey stick (Sports) to improve his
chances of making the team.
This animation could be the first phase of developing an interactive ice-hockey game.
To design an interactive program storyboard, some thought must be given to what
events will occur and what event handling methods are needed. Let’s allow the user to
select the power factor behind Jack’s swing of the hockey stick. The power factor will
determine how fast Jack swings the stick and how far the hockey puck travels when
hit by the stick. The power factor will be selected by a mouse-click on one of the
power buttons (GumDrops from Kitchen/Food folder) in the lower right of the scene.
The yellow button will select low, green will select average, and red will select a high
power factor.
15. Slappy
Slappy, an adventuresome squirrel (Animals on DVD or Web gallery), has just gotten
her own squirrel-sized snowmobile (Vehicles on DVD or Web gallery). Create a pro-
gram to animate Slappy’s first ride on the snowmobile. The user controls the forward
and reverse motion of the snowmobile, using a two switch box (Controls). When the
user clicks the green button on the switch, the snowmobile and Slappy move forward
and Slappy screams something like “wahoo!” When the user clicks the red button on
the switch, the snowmobile and Slappy move in reverse and Slappy looks at the camera
and says something like “!oohaw.”
166 Chapter 5 Interaction: Events and Event Handling
Projects
1. Alice Drum Set
In this project, your goal is to create an interactive drum set by using subparts of objects
defined in the gallery.
Hint: To separate a subpart of an object and use it as an object without the rest of the
object, first create an object that has subparts (for example the timbales in the Musical
Instruments folder of the gallery. In the object tree, right-click one of the subparts and
select “save object. . .” from the popup menu. The saved-out object can then be imported
into a new world.
In this project, the kick drum, all the toms, and the snare are timbales (Musical
Instruments) that were separated from the timbales set. The snare stand is made from
the timbales stand. The cymbal stands are poles from a stop sign (Roads and Signs).
The Kick and HiHat pedals are squares (Shapes) put together then angled, the cymbals
are circles (Shapes), and the bumps on the cymbals are bumps (Shapes).
Import the sounds for each piece of the drum set. These sound files are found on
the resource DVD accompanying this book.
Make methods for each object as described below. Create an event that calls the
method when the person clicks the object.
• Kick Drum: play—plays the kick drum
• Snare Drum: play—plays the snare
• Rack Toms: play—plays the rack toms
• Floor Toms: play—plays the floor toms
• Hi Hat: closeOpen—open and closes the hi hat
Exercises and Projects 167
The idea of this animation is to provide a skydiving guidance system to allow the user
to guide the movement of Alice Liddell as she jumps from the platform of the helicop-
ter and glides down to the carrier. When the user thinks Alice Liddell has hit the top of
the carrier, the user can press the Enter key to have Alice Liddell drop her chute.
Guidance system methods (as smooth and lifelike as possible):
jump: jump from the helicopter’s platform
glideForward, glideBack, glideRight, glideLeft: glide in the appropriate
direction
swingLegs: legs swing a bit when gliding or jumping
dropChute: get rid of parachute (to simplify things, just have the chute rotate
as if it were falling and make it disappear)
Keyboard controls:
Space bar—jump off the platform
Up/Down/right/left arrow—glide forward/back/right/left
Enter key—parachute drops
Remember that Alice Liddell should first jump off the platform prior to gliding and
should not drop her chute until she hits the carrier.
3. Turtle Motion Control
In this project, you are to create a turtle motion controller to help the turtle (Animals)
perform exercises for his upcoming race with the rabbit. Create a world that contains
only a turtle and then create motion control methods for the turtle:
headBob: allows the turtle’s head to bob a little
tailWag: allows the turtle’s tail to wag
oneStep: allows the turtle to move forward one step; his legs should move while
he is taking that one step
walkForward: combines the above three methods, to make a realistic step; all
movements should take the same amount of time and occur at the same time
168 Chapter 5 Interaction: Events and Event Handling
turnAround: turns the turtle 180 degrees; he should be walking while turning
turnLeft, turnRight: turns the turtle left/right, walking while he is turning
hide: allows the turtle to hide in his shell (you may assume that the turtle is cur-
rently outside of his shell); remember not to leave the shell hanging in midair
reappear: allows the turtle to reappear from his shell (you may assume that the
turtle is currently hidden)
talk: has the turtle look at the camera and say “hello” (or something different, if
you wish) to the user
Create keyboard controls:
When the up arrow key is pressed, the turtle is to walk forward.
When the down arrow key is pressed, the turtle is to turn around.
When the left arrow key is pressed, the turtle is to turn left.
When the right arrow key is pressed, the turtle is to turn right.
When the letter “H” is pressed, the turtle is to hide in his shell.
When the letter “R” is pressed, the turtle is to reappear from his shell.
When the letter “T” is pressed, the turtle is to talk to the user.
Test the turtle motion control system by running your world and trying all the interac-
tions at least once. Be sure to hide the turtle only when he is already out of his shell and
have him reappear only when he is hiding.
4. Robot Preparing for Competition
In this project, your goal is to create a motion controller for a robot (Ranger from Scifi).
You will create specific methods that allow the robot to perform warm-up actions for its
upcoming competition.
Create the following methods to help the robot warm up for it’s competition:
armSwing: the robot swings it’s arms back and forth across the front of it’s body
headShake: the robot’s visor flips back so it’s head is showing. Then it rocks it’s
head right, left, back, forth. Then rotates its head left and right.
jumpUpAndDown: the robot jumps up and down
Your own method: Think of one other action for the robot and make a method
for it.
Create the following keyboard controls:
When the “A” key is pressed, the robot swings its arms.
When the “H” key is pressed, the robot shakes its head.
When the “J” key is pressed, the robot jumps up and down.
Exercises and Projects 169
Hint: The background effect shown here was created by adding the fire (SpecialEffects)
and changing the skinTexture of the ground to the skin texture of the fire. You can use a
skinTexture image of your own choosing.
5. Alice Piano
In this project, your goal is to create a keyboard that plays notes when you click on the
keys. This is a challenging project, and it is best to plan carefully. A good strategy is to
break the project up into several smaller parts. Remember that often times when making
a program, there is more than one way to do the project. However, you should challenge
yourself to think of the best way to do it!
Hints on making the keyboard: One way to make the keyboard is to add a box
(Shapes) to your world and make copies of it. This works nicely because the copies form
a line and you can adjust the spacing between each one after all the keys are made.
Rename all of the keys (lowC, lowDFlat, etc.) Another way to make the keyboard is to
find an image of a keyboard and crop each key from the image using image editing
software. Be sure to have a transparent background for each key. Then you can import
each key as a billboard.
Import the sound for each piano key: The sound for each key is found on the resource
DVD that came with the textbook. Import each sound for each key and name it
(lowCSound, lowDFlatSound, etc.)
Make the methods to play each key: When someone plays your piano, they will click
on the piano key to make the sound. To make the key more realistic, have the key move
down slightly, then move back to its original position.
This page intentionally left blank
Part III
Using Functions
and Control
Statements
171
This page intentionally left blank
Chapter 6
Functions and If/Else
This chapter presents functions and conditional execution control statements (two key
concepts in programming), as used with methods. Functions allow you to check certain conditions
within a world while an animation is running. While Alice provides some built-in functions that
are useful in methods, in this chapter we look at examples of programs where we want to use a
function that does not already exist in Alice. In such a situation, you can write your own function.
A function is similar to a method in that it is a collection of instructions and (like a
method) is called. The purpose of a method is to perform an animation, but that of a function
is to return a value. What difference does this make? Well, an animation performed by a
method moves, turns, or performs some other action with objects in the world. We call this
changing the state of the world. In a function, however, objects do not move, turn, or perform
some other action. So, functions leave the state of the world unchanged. Mathematicians
say these are pure functions.
An exciting thing about writing your own function is you can then use it (along with
built-in functions) to check out a current condition in the world and make a decision about
whether (or not) a method is called. In Alice, we use an If/Else statement as a conditional exe-
cution control statement that uses a condition for making a decision.
Section 6-1 introduces the use of functions in methods and explains how to write your
own function as a method that returns a value. We need functions as a way of getting infor-
mation about objects as the program is running (at runtime).
In Section 6-2, we use conditional execution (If/Else statement) to make decisions
about whether (or not) to call a method. We will write our own Boolean function (which
returns true or false) to be used as part of the execution control mechanism. In your programs,
you will use decisions to make animations execute in different ways depending on a condi-
tion, such as whether an object is visible or where an object is located. In an interactive world,
we can use If/Else to decide what is done in an event handling method.
6-1 Functions
In writing program code, we often need some information about the objects in the world and
the World itself. The most commonly used properties (such as color and opacity) are listed in
a properties list for the object. To get information about other properties (e.g., height or width)
we use a function to ask a question. The value returned by a function can be a number, an
object, a Boolean (true or false), or some other type.
173
174 Chapter 6 Functions and If/Else
A function may receive values sent in as arguments (input), perform some computation
on the values, and return (send back) a value as output. In some cases no input is needed, but
often values are sent in. The diagram in Figure 6-1-1 outlines the overall mechanism. One
way of thinking about a function is that it is something like an ATM machine. You enter your
bankcard and password as input and click on the button indicating you would like to see your
balance (another input). The ATM machine looks up your account information and then tells
you what your current balance is (as output).
Input values
Function
Abstraction
As with class-level and world-level methods, one important benefit of a function is that it
allows us to think about the overall process rather than all the nitty-gritty little details. When
we use an ATM, for example, we think about getting the balance in our account—not about
all the operations that are going on inside the machine. In the same way, we can call a func-
tion in our program to perform all the small actions, while we just think about what answer we
are going to get. Like methods, functions are an example of abstraction—collecting lots of
small steps into one meaningful idea to allow us to think on a higher plane.
We want to bounce the ball over the tennis net. Do not be deceived. This is not as easy
as it sounds because we cannot easily tell just by looking at the ball what its orientation is. In
other words, we don’t know “which way is up” in terms of the ball’s sense of direction. The
ball should move up and forward and then down and forward.
Actually, we are thinking about the ball’s up and down motion relative to the ground, so
we need to align the ball’s sense of direction with the ground. Orientation is done by using an
orient to method, as shown in Figure 6-1-3.
Figure 6-1-3. Using an orient to method to orient the ball with the ground
Having properly set up the initial scene, we can write a method to bounce the ball over
the net. Since two objects are involved in this action, we will write a world-level method
named ballOverNet.
A storyboard would look like this:
ballOverNet
Do in order
toyball turn to face the net
Do together
toyball move up
toyball move forward
Do together
toyball move down
toyball move forward
176 Chapter 6 Functions and If/Else
We know how far to move the ball forward because we set up the world with the ball
exactly 1 meter from the net. We do not know how far up to move the ball to clear the net. We
can use a built-in function for the tennisNet to determine its height and then use that as the
distance the ball moves up (and then back down). We don’t have to think about what Alice is
doing to figure out the height of the tennis net, we can just call the function and get the height.
This is a two-step process. (1) Drag the toyball’s move tile into the editor and select 1 as a
default distance. (2) Drag the tennis Net’s height function tile on top of the 1. Figure 6-1-4 illus-
trates dragging the tennisNet’s height function onto the move up and move down instructions.
Surprise—the turn instruction simply rotates the ball in place! (It spins the ball
around, but the ball does not move along the ground.) To actually roll, the ball must turn
and also move in the same direction. A storyboard for a method to simulate a rolling action
(realisticRoll) would be:
realisticRoll
Do together
move ball forward 1 meter
turn ball forward 1 revolution
With this in mind, we can write a class-level method named realisticRoll, Figure 6-1-5.
6-1 Functions 177
Our testing of this code, however, is disappointing. The effect of moving and turning the
ball at the same time is that the ball ends up at the same place it started. (The turning action
prevents the ball from moving forward.)
Why is this? Well, the ball is moving relative to itself, not relative to the ground. A
solution to this problem is to use asSeenBy = ground in the move statement. The code in
Figure 6-1-6 moves and turns the ball forward 1 meter, simulating a real-life ball rolling on
the ground.
We guessed that one revolution would look realistic. But when it is run, it is not quite
right. We must now think about how many revolutions the ball needs to turn in covering a
given distance in a forward direction. This presents a challenge because the number of times
the ball needs to turn is proportional to the ball’s diameter. To cover the same forward dis-
tance, a small ball turns more times than a larger ball. In Figure 6-1-7, the larger ball covers
the same distance in one revolution as the smaller ball covers in four revolutions.
Of course, the number of revolutions needed for the ball to roll, say, 10 meters could be
found by trial and error. But then, every time the ball changed size you would have to figure it
out all over again and change the code. A better way is to compute the number of revolutions.
Alice does not have a function for this, so we will write our own.
A popup New Function box (Figure 6-1-9) allows you enter the name of the new func-
tion and select its type. Your new function is categorized by the type of information it returns.
The types of functions include Number, Boolean, Object, and Other (such as String, Color,
and Sound). In this section, we will write functions that return Number values. Examples and
exercises later in the chapter use functions that return other types of values.
A click on the OK button creates an editor panel where you can write the code for the
function, as shown in Figure 6-1-10.
To use this formula, we need three pieces of information: the distance the ball is to roll,
the diameter of the ball, and something named p. To provide this information,
• A parameter will be used to send in the distance the ball is to roll.
• The built-in function toyball’s width will be called to get the diameter.
• The symbol p (also known as pi) is a constant value (it does not change). Pi represents
the ratio of the circumference of a circle to its diameter. We will use 3.14 as the constant
value of pi.
The code shown in Figure 6-1-11 implements the function. The number of rotations is
computed by dividing the distance the ball is to move (the distance parameter) by the product
of the ball’s diameter (toyBall’s width, a built-in function) and pi (described above). The
Return statement tells Alice to send back the computed answer.
The order of evaluation of the values in the function must be carefully arranged. Alice
uses nested tiles and parentheses to emphasize the order in which the values are evaluated.
180 Chapter 6 Functions and If/Else
The innermost expression is computed first. In this example, 3.14 is multiplied by the
toyBall’s width, and then that value is divided into the distance.
Although 10 meters was used as a test value in the example above, we should really be
testing our program by using low distance values (e.g., -2 and 0) and also with high distance
values (e.g., 20). Using a range of values will reassure you that your program code works on
many different values. One way to do this is to parameterize the realisticRoll method so it can
be called with different test values, as illustrated in Figure 6-1-13.
Figure 6-1-13. A parameter for rollDistance allows testing with different distance values
True Is False
condition
true?
Do this Do something
action else
a condition is true. If it is, a set of program instructions are run. If the condition is false, a sep-
arate set of program instructions are run.
First, let’s write a method to hide the canteen. This will be a world-level method, named
hideCanteen. It is world-level because more than one object is involved. First, we choose one
of the tortoises. Then, we can hide the canteen by moving it to the back of the chosen tortoise
and attaching the canteen to the tortoise. An If/Else statement can be used to determine which
tortoise was chosen, as illustrated in the storyboard, here:
World.hideCanteen
Actually, we don’t want the condition to always be true, but in a drag-and-drop editor a
condition must be selected from the pop-up menu in order to complete the drag-and-drop
action. Alice doesn’t know what condition we really want to use but offers a couple of possi-
ble selections in the pop-up menu. Because we want a very specific condition that does not
appear in the menu, we arbitrarily selected true as a placeholder.
Let’s replace the placeholder. In our storyboard, the If statement’s condition was described
as: “sammy is the chosen tortoise”. Our guessing game wouldn’t be much fun if sammy were
chosen every time the game is played. What we want to do is choose sammy in some plays
of the game and tommy in other plays of the game. This is known as random choice. Ran-
domly choosing one of two options is similar to tossing a coin where the toss can be either
“heads” or “tails.” It is random because we can’t predict whether the tossed coin will land
heads-up or tails-up. However, if we toss the coin again and again, repeated tosses will prob-
ably cause the coin to land heads-up about 50 percent of the time and tails-up the other
50 percent of the time.
6-2 Execution control with If/Else and Boolean functions 183
The problem we need to solve is how to write the program code to randomly choose one of
the tortoises. Fortunately, Alice has a world-level function that makes a random choice based on
percent probability. As shown in Figure 6-2-4, drag the random function choose true probability-
OfTrue into the editor and drop it on top of the placeholder condition in the If statement. In the
pop-up menu, select 0.5 (50%). The random function choose true probabilityOfTrue is a Boolean
function because it returns either a true or a false value. By selecting 50% as the probability, it
will return true 50% of the time and return false the other 50% of the time. More information
about random values is provided in the Tips & Techniques section at the end of this chapter.
Figure 6-2-4. Using the world-level random function for probability of true
In our guessing game, sammy is chosen when the condition is true. When the condition
is false sammy is not the choice—instead, tommy is the choice. To complete the hideCanteen
method, statements are created for the If and Else parts of the If/Else code block. Each part is
a Do in order code block, as shown in Figure 6-2-5. The canteen is positioned on the chosen
tortoise’s shell by first setting the canteen’s point of view to the tortoise. Setting the point of
view of the canteen to the chosen tortoise has two effects: (1) the canteen is moved to the cen-
ter of the tortoise (in the middle of its tummy), and (2) the canteen is oriented to face in the
same direction as the tortoise. Now, to move the canteen to the back of the tortoise’s shell, all
that is needed is to move the canteen backward 1⁄2 the depth of the tortoise. In computer ani-
mation, a common way to “attach” one object to another object is to set the vehicle of one
object to another. We used this animation technique to attach the canteen by setting its vehicle
property to the chosen tortoise. Figure 6-2-5 shows the completed hideCanteen method.
Testing
You may have noticed that the duration is 0 seconds for each of the statements that are
used to hide the canteen. A duration of 0 seconds causes the actions to occur so fast that
the user does not see the canteen being hidden. To be sure that the canteen is hidden fast
enough so the user can’t see where the canteen is located, call hideCanteen from world.my
first method.
However, both responses are the same—except which tortoise reveals whether the
user’s guess was correct. Writing two event handling methods is unnecessary. To handle the
two possible events, we will write only one event handling method, named checkGuess. A
parameter will be used to pass the tortoise that was clicked to the event handling method. A
possible storyboard for the checkGuess method is:
world.checkGuess
Parameter: clickedTortoise
To translate the storyboard for checkGuess method, we first create a new world-level
method and then drag in an If/Else control tile. An Object parameter, named clicked, is cre-
ated to represent the tortoise that the user clicks. As can be seen in Figure 6-2-6(a), the next
step is to create a conditional expression in the If statement (to replace the true placeholder).
In the storyboard for checkGuess, the condition is described as “canteen is attached to
clicked.” But, the world’s functions, as shown in Figure 6-2-6(b), do not include a function
that checks whether one object is attached to another object.
6-2 Execution control with If/Else and Boolean functions 185
Figure 6-2-6(a). Need a condition to replace true Figure 6-2-6(b) “is attached to” is not built-in
world.isAttachedTo
First, create a new world-level function by clicking on the create new function button
in the world’s details panel, as seen in Figure 6-2-7. In the New Function dialog box enter
isAttachedTo as the name of the new function and select Boolean as the type of value that will
be returned when this function is called.
In the isAttachedTo storyboard, above, the design includes an If/Else statement to check
whether the canteen's vehicle is the tortoise that was clicked by the user. However, we think
this new function might be useful in other animation programs, not just this one. For example
we might want to know whether a paddle is attached to a boat or whether an invisibility cloak
is attached to a wizard. Let’s revise the storyboard for the function so we could possibly use
the isAttachedTo function with objects other than the canteen and tortoise. Two parameters
186 Chapter 6 Functions and If/Else
will be needed, for the two objects. The revised storyboard, shown below, names the parame-
ters oneObject to represent an object and secondObject to represent another object to which
oneObject might be attached. In our example, the canteen will be represented by oneObject
and the clicked tortoise will be represented by secondObject.
World.isAttachedTo
Parameters: oneObject, secondObject
To write the function, first create two new Object parameters, oneObject and secon-
dObject, and then drag in an If/Else code block with true as the placeholder condition. The
result is shown in Figure 6-2-8.
Now, the true condition (placeholder) must be replaced with a conditional expression
that will determine whether the canteen’s vehicle is the clicked tortoise. In the hideCanteen
method, defined earlier in Figure 6-2-5, a canteen was attached to one of the tortoises by set-
ting the canteen’s vehicle property to a tortoise. All we have to do, then, is check whether
6-2 Execution control with If/Else and Boolean functions 187
oneObject’s vehicle “is equal to” secondObject. In Alice, a check for equality is represented
by the “= =” relational operator.
The condition for the If/Else statement in the isAttachedTo function cannot be written
using one of the world’s math functions because the built-in math relational operators can
only be used to compare numbers, but we need to compare one object’s vehicle to another
object. (See additional detail at the end of this section.)
To create a customized conditional expression for isAttachedTo, click on the canteen’s
properties, and drag the canteen’s vehicle tile onto the top of placeholder true and drop it.
Then, from the cascading popup menus, select expressions, and then world.isAttachedTo.sec-
ondObject as illustrated in Figure 6-2-9(a).
We used the canteen object as a convenience to drag-and-drop the statement shown in
Figure 6-2-9(b), where the condition is now canteen.vehicle = = secondObject. What we
really want, however, is oneObject. vehicle = = secondObject. To modify the statement, click
on the down arrow next to canteen (as shown in Figure 6-2-9(b)). Select from the expressions
menu, world.isAttachedTo.oneObject to replace canteen with the oneObject parameter. Be
careful to only replace canteen, not the entire canteen.vehicle.
Finally, add a return statement to return true if the condition is true and a return state-
ment to return false otherwise. The completed function is shown in Figure 6-2-9(c)
Figure 6-2-10.
An important part of any If/Else statement is the condition. In the examples above, the condi-
tion involved calls to functions (both built-in and our own). One example (see Figure 6-2-9(c)
above) used a Boolean expression with a relational operator. Regardless of how the condition
is written, it must evaluate to true or false. The value of the condition determines whether the
If part or the Else part of an If/Else statement is executed. This is why an If/Else statement is
said to be one way to provide conditional execution in a computer program.
one of the tortoises, the checkGuess method should be called and the tortoise that was clicked
should be passed in as an argument to the parameter, named clickedTortoise. One event is
needed for each tortoise, as shown in Figure 6-2-11.
Figure 6-2-13. The shootBolt method (from Zeus world in Section 5-2)
We had intended that Zeus shoot the thunderbolt only at a philosopher. Unfortunately,
we found that if the user clicks on any other object that happens to be in the world, Zeus zaps
that object as well. We want to control the lightning so that the bolt is shot at an object only if
who is one of the philosophers.
We have four philosophers in this world, so we will need to check whether the object
clicked was one of them. This is an example where a conditional expression contains multiple
conditions. To show how to use multiple conditions, we begin with a single condition to check
for just one philosopher—then expand it to four philosophers.
First, drag an If statement into the top line of the shootBolt method. Next, create a condi-
tion to test whether the object clicked was homer. To create the condition If who = = homer,
drag the who tile on top of the true tile in the If statement. Then select who = = homer from
the popup menu, as shown in Figure 6-2-14.
In Alice, = = means “is equal to.” (We talked about “= =” above as a relational operator.)
The question being asked is: “Is the object sent to the who parameter the same as the object
named homer?” If so, the value is true. If not, the value is false.
Now that the If statement has a condition, we need to supply the instructions to be
carried out when the condition is true. In this example, we need only drag the Do in order
block of the shootBolt method into the true part of the If statement. The result is shown in
Figure 6-2-15. Now, if who is homer, lightning will strike.
Now it is time to expand the If statement’s condition to allow any of the four philoso-
phers. A logical operator “or” is needed (one of three logic operators found in the World
functions list, shown in Figure 6-2-16). The or operation means “either this or that or possi-
bly both.” While this makes sense, the way we actually use “or” in daily life is somewhat dif-
ferent. When you say, “I am going to the movies or I am staying home,” you mean that either
you are going to the movies or you are staying home, but not both. However, the Alice
expression either a or b, or both means that either the first statement is true, or the second
statement is true, or they are both true! (The other two logic operators are discussed at the
end of this section.)
To use the or operator, drag the either a or b or both tile over the condition tile in the If
statement. In this example, the or operator must be dragged into the condition tile three times
to account for all four philosophers. The code below illustrates the modified If statement. (The
statement is broken into two lines to make it fit on the width of this page—but is all on one
line in Alice.)
Figure 6-2-17 shows the revision of the shootBolt method. (Not all of the multiple con-
ditions can be seen, because the code runs off the edge of the window.) Now, clicking on any
one of the four philosophers results in Zeus shooting a thunderbolt at that philosopher, but
clicking on something else in the world causes no action.
Figure 6-2-19. Calling the isPhilosopher function from the shootBolt method
again, we have the problem of using a parameter as an object. (We saw this problem before in
Chapter 5 when we wanted to use a move to instruction with the parameter who.) We will use the
same technique of dragging in an arbitrary object and then replacing the object tile with who.
Here are the steps:
1. Drag an If statement into the method. In this example, drag it into the line immediately
under the first If statement.
2. Select one of the philosophers from the Object tree (we arbitrarily chose plato). Drag its
color property onto the condition tile and select the != operator and the color black. The
result should look like this:
3. Drag the who parameter on top of plato to allow the color of any philosopher object to
be checked. Now the statement should look like the one in Figure 6-2-20.
Code is now added to the If and Else parts of the If statements. The completed code is
illustrated in Figure 6-2-21.
The effect of the nested If statements is that both If statement conditions must be met
before the Do in order block will be run. If the object clicked is a philosopher and the selected
philosopher has not yet been struck by lightning, Zeus shoots his thunderbolt at the philoso-
pher. On the other hand, if the user clicks on an object other than one of the four philosophers,
Zeus says, “I only shoot at philosophers!” Finally, if the user clicks on a philosopher who has
already been hit by a thunderbolt, Zeus now says, “That philosopher is already zapped!!!”
6-2 Execution control with If/Else and Boolean functions 195
Figure 6-2-21. The complete code for the revised shootBolt method
evaluates to true only when who is not homer. In other words, clicking anywhere on the
screen (on one of the other philosophers, on a cloud, etc.) would cause this expression to eval-
uate to true. If the object clicked is homer, the expression evaluates to false.
A third logical operator is and. The and logical operator requires both Boolean expres-
sions to be true in order to evaluate to true. The example
evaluates to true only if who is homer and his color has been set to blue.
It is important to be very careful with expressions containing two or more logical oper-
ators. The following expression evaluates to true only if who is homer and homer’s color is
black or blue.
196 Chapter 6 Functions and If/Else
The reason this expression is different is that the logical tiles are nested differently, so
the order of evaluation is different. These nested tiles represent the expression:
either 1both 1who = = homer2 and 1who.color = = blue22 or 1who.color
= = black2 or both
These examples point out that the level of nesting in logical expressions can be tricky.
In general, we recommend not including more than one logical operator in a Boolean expres-
sion. If more are needed, we recommend using nested If statements. It isn’t that we think
nested If statements are better than combinations of logical operators. Instead, we just realize
it can be quite difficult to understand exactly the order of evaluation when a Boolean expres-
sion has several nested logical operators.
As an example, consider the world scene in Figure T-6-2. An Eskimo (People) and a pen-
guin (Animals) are playing together, sliding around on the ice in a winter world.
6-2 Execution control with If/Else and Boolean functions 197
Suppose you want to write code to make the penguin slide forward a random distance.
This easily is accomplished by first creating a move instruction and then dragging the random
number function tile into the distance parameter. The result is shown here:
The random number function returns a fractional value between 0 and 1. When the above
instruction is executed, the penguin will slide forward some fractional amount between 0 and
1. Although you know the range of values (somewhere between 0 and 1) you don’t know the
exact number. Also, each time the program is executed the distance is likely to be different.
This unpredictability is what makes it random.
Now, each time the program is executed, the penguin will slide forward 3.8 meters or 2.3
meters or some other random amount between 1 and 4.999. We suggest that you test this out
by creating and running the world. Press the Restart button several times to observe the slid-
ing motion.
Random motion
If the random number function is combined with the move instruction, a form of random
motion is created where objects move to a random location. Random motion is essential in
many different kinds of games and simulations. As an example, consider the world in
Figure T-6-4. The goldfish (Animals) is to swim in a random-like movement. We want to
restrict the movement to a nearby position. Otherwise, successive moves would make the
goldfish jump around here and there on the screen—not at all like a goldfish swimming.
Figure T-6-4. The goldfish in a water world, for a random motion animation
Because Alice objects live in a three-dimensional world, you can write a move instruction
that moves the goldfish in any of six possible directions (forward, backward, left, right, up,
and down). Combining the random number function with six move instructions might be a bit
clumsy. Let’s try to make our work easier by taking advantage of negative numbers. If a neg-
ative number is used as the distance in a move instruction, the object is to move in the oppo-
site direction. For example, the instruction shown next is to move the goldfish left -1 meters.
When executed, this instruction will actually move the goldfish right 1 meter.
If we use both positive and negative distance values, only three move instructions are
needed. We will use up, left, and forward directions. With this idea in mind, let’s write a sto-
ryboard for a randomMotion method:
randomMotion
The Do together block executes the move up, move right, and move forward all at the
same time. As a result, the goldfish will move to some random location within a cube of space
defined by the minimum and maximum random number distances.
Once the randomMotion instruction has been written, it should be tested. To call the
randomMotion method, min and max arguments must be passed to the method, as shown
below. In this example, the min 1-0.22 and max (0.2) arguments will restrict the movement of
the goldfish to a random location near the current location.
Summary
Examples in this chapter presented ways to use functions and If statements in methods. In
Alice, an If statement allows for conditional execution of a section of code (based on the value
of a Boolean condition, true or false). The Boolean condition is used to determine whether the
If part or the Else part of the statement will be executed at runtime. Thus, an If statement
allows us to control the flow of execution of a section of our program code.
Built-in functions do not always meet the particular needs of a program. In this
chapter, we looked at how to write your own functions that return different types of values.
The benefit of writing your own functions is that you can think about the task on a higher
plane—a form of abstraction. Functions that compute and return a number value make
200 Chapter 6 Functions and If/Else
program code much less cluttered and easier to read, because the computation is hidden in
a function. Such functions will be useful in many situations. For example, we might want
to write a function to return the number of visible objects on the screen in an arcade-style
game. The function would be called to keep track of how many objects the user has elimi-
nated (made invisible). When only a few objects are left, we might decide to speed up the
game.
Parameters can be used to allow a function to be used with different objects. As with
class-level methods, you can write a class-level function and save it out with the object. This
allows the function to be reused in another program.
Programming Terms
Boolean expression function random number
conditional execution If/Else statement range
conditional expression integer relational operator
abstraction logical operator return statement
Questions
1. What is the purpose of a conditional expression in an If/Else statement?
2. A conditional expression in an If/Else statement must evaluate to what type of value?
3. What type of value is obtained by evaluating each of the following expressions?
(a) height 6 3
(b) 15 + 12 * 10
(c) who = = plato
4. In Alice, where can you find the built-in random number functions?
5. Alice provides many built-in functions. Why would a programmer want to write her/his
own function?
6. Why must a function have a Return statement?
7. Is it possible to have more than one Return statement in a function? Explain your
answer.
Exercises and Projects 201
8. What is the difference between the types of parameters (explained in Chapter 4) used in
methods and the types of values that can be returned from a function?
9. In Alice’s drag-and-drop interface, nested tiles and parentheses are automatically
inserted in the expression. What is the purpose of nested tiles and parentheses in an
expression?
10. In a Boolean expression containing multiple conditions, what operators may be used to
connect the conditions?
11. A Boolean expression containing multiple conditions is often difficult to understand.
What alternative structure can be used to achieve the same results?
3. Bee Scout
It has been a hot, dry summer and a hive of bees is in desperate need of a new supply
of pollen. One bee (Animals/Bugs) has ventured far from the hive to scout for new
pollen sources. A natural place to look is near ponds in the area. Set up the initial
scene with a circle (Shapes) flat on the ground and colored blue to look like a pond.
Add plants, trees, and other natural scenery including some flowers (Nature). Be
sure the bee is located somewhere around the edge of the pond, as shown in the
screen shot here.
Write a program to animate the bee scouting the edge of a pond for flowers
that are in bloom. The bee is to fly around the perimeter of the pond (circle). Write a
method to move the bee scout around the perimeter of the pond in which the circum-
ference of the circle is used to guide the motion. (Yes, asSeenBy could be used—but
that is not the point of this exercise.) The formula for computing the circumference
of a circle is p * the diameter of the circle. p is 3.14 and the diameter is the
object’s width. Write a function that computes and returns the circumference of the
circle. Then have the bee fly around the perimeter of the pond by moving forward
the amount of meters returned by the circumference function while turning left one
revolution.
4. Pyramid Climb
On spring break, a student is visiting the land of the Pharaohs. The student (e.g., ran-
domGuy 1 from the People folder on the DVD or Web gallery) decides to climb one of
the pyramids (Egypt), starting at the bottom and moving straight up the side. Set up an
initial scene consisting of a person and a pyramid, as shown in the screen shot below.
Write a method to animate the climb so that the person’s feet are always on the side of
the pyramid.
Exercises and Projects 203
Begin by pointing the person at the pyramid and walking him/her up to edge.
Then, turn the person about 1/8 of a revolution so as to lean into the climb. (Play with
this leaning movement until you get a reasonable angle for the person to climb the
pyramid.) After reaching the top, the person should stand up straight.
To determine how far the person must move to complete the climb, the climb
method must call a function. The function computes the side length of the pyramid. The
formula for computing the distance up the side of the pyramid is based on the
Pythagorean theorem 1a2 + b2 = c22. The value of c will provide a rough estimate of
how far the person should move (in a diagonal direction) up the side of the pyramid.
The formula is:
5. Baking Lessons
In this exercise, a woman (People) is learning how to make rolled cookies. Before she
can cut out the cookies, she needs to roll the dough with her rolling pin (Kitchen). Cre-
ate a function that determines how much the rolling pin is to roll as she slides it along
the table, flattening the dough. Use the function in a world that animates rolling pin
rolling across the table (Furniture on DVD or Web gallery).
204 Chapter 6 Functions and If/Else
6-2 Exercises
6. Modifications to the Zeus World
(a) Modify the Zeus world to make each philosopher say something different when
clicked.
• Euripides says, “Come on guys, I want to take a bath.”
• Plato says, “I call it Play Doe” and then extends his right hand to show the other
philosophers his Play Doe.
• Homer says, “By my calculations, pretzels are the optimum solid food.”
• Socrates says, “Like sands in the hour glass, so are the days of our lives.”
Use an If statement to determine which philosopher was clicked.
(b) Modify the Zeus world so that if homer gets clicked and zapped by the thunderbolt,
he falls over, says “d’oh”, and then stands back up again (instead of turning color).
Allow repeated clicking on homer, which should result in his repeated falling down
and getting back up.
7. Practice Turns
Create a skater world, as illustrated below. Import an enhancedCleverSkater object, as
designed and created in Chapter 4, Exercise 9. (If you have not created the Enhanced-
CleverSkater class, an iceSkater can be used from the gallery, but you will have to write
your own methods to make her skate forward and skate around an object.)
For this world, write a program to make the skater practice her turns on the ice.
First, place the skater 1 meter from the second cone, facing forward. She then skates
forward toward the first cone (a sliding step). When she gets close, she should skate
halfway around the cone and end up facing the other way to skate back toward the other
cone. Next, have the skater skate toward the other cone and when close enough make a
turn around it. In this way, the skater should complete a path around the two cones.
Hint: To find out whether the skater has gotten close enough to do a half-circle turn
around the cone, you can use the is within threshold of object function for the enhanced-
CleverSkater. (The phrase is within threshold of object evaluates to true if the second
object is within the specified distance of the first object.) Another possibility is to use
the distance to function and the relational operator a 6 b (available as a world-level
function) to build the logical expression “Is the skater’s distance to the cone less than
2 meters?”
8. Figure-Eight
This exercise is an extension of Exercise 7. Modify the world to have the skater com-
plete a figure-eight around the cones.
Exercises and Projects 205
9. Ice Danger
For this exercise, you can begin with a world completed in either Exercise 7 or 8—or
create a new skater world from scratch. Add a hole in the ice (a blue circle).
Make the world interactive to allow the user to use the mouse to move the hole
around on the icy surface. Now, as the skater is moving across the surface of the ice, the
user can move the hole into the skater’s path. Modify your method that skates the skater
forward to use an If statement that checks whether the skater is skating over the hole. If
she is on top of the hole, she will drop through it. If you have sound on your computer,
you may want to add a splash sound.
10. Flying between Two Trees
Create a world with a lichenZenspider (Fantasy/Fairies) between two trees (Nature).
Animate the lichenZenspider flying back and forth between the two trees. Make the
world interactive so that lichenZenspider flies forward a short distance each time the
user presses the enter key. LichenZenspider should move forward until she reaches a
tree, then turn around to fly back toward the other tree. When she gets to the second
tree, she should turn around to fly back toward the first tree. Be sure to avoid lichen-
Zenspider’s colliding with a tree.
the cat. The user is expected to click on the correct Spanish word for cat. A click on any
other object will not work. Write a function (isGato) that returns true if the word (a 3D
text object) selected is “gato,” and false otherwise. The function will use one parameter
(objectClicked) to send in the 3D text word clicked by the user. If the user clicks on
“gato,” the cat will say “Si, si!” Otherwise, the cat should turn its head left and right
(indicating that the choice was incorrect).
12. Switch
Create a world using a Switch object (in the Controls folder of the gallery). Write a
method called flipSwitch that handles the “when the Switch is clicked” event. It the
switch is clicked, its handle will flip from up to down or down to up. Also, write a
Boolean function isHandleUp which returns true if the handle is up and false if it is
down. (flipSwitch will call isHandleUp to decide whether to turn the handle forward
one-half revolution or backward one-half revolution.)
Hint: To write isHandleUp, some reference point is needed to test the handle’s position.
One way to do this is to put a small invisible circle (Shapes folder) on the center of the
switch plate. When the handle is up, the handle is above the circle. When the handle is
turned down, the handle is below the circle. (See Tips & Techniques 4 for details on
moving an object relative to an invisible object.) Do be careful to place the circle imme-
diately below the handles center of gravity, as illustrated below.
13. Lightbulb
Create a world with a lightbulb (Lights) and a method turnOnOff that turns the lightbulb
on/off depending on whether it is already on/off. When the lightbulb is on, its emissive
color property has a value of yellow. When the lightbulb is off, its emissive color is
Exercises and Projects 207
black. Write a Boolean function isLightOn that returns true if the light bulb is on and
false if it is off. When clicked, the lightbulb should turn on/off.
Projects
1. Help the Snowman get Home
Create a game where the goal is to move the snowman through a forest to get him
home to his igloo. The hazard in this game is that if the snowman gets too close to a
tree, he moves back 10 meters. Add the snowman (People), a snowboard (skateboard
from Skatepark - change the isShowing for the wheels to false), an igloo (Buildings),
and eight pineTrees (Nature). Set the vehicle for the snowman to be the skateboard.
Create an event so that the skateboard can be controlled by game player, by typing the
arrow keys.
Create a method for the skateboard named checkForCollisionWithTrees. If the
skateboard’s distance to the pine tree is less than 3.75 meters, then move the skateboard
back 10 meters. In this method, you will need to check each tree in the scene. When you
have the If/Else working for one tree, then copy it for each of the other trees.
Exercises and Projects 209
To have Alice constantly check for collisions with the trees, create a When the
World Starts event. Then change it to While the World is Running (a right click on the
event pops up a menu so it can be changed). In the during section of the While the World
is Running event, call the checkForCollisionWithTrees.
In order to check whether the player has won the game, create a method named
checkIfHome for the skateboard. If the skateboard gets close to the igloo, display a 3D
text object that proclaims “I’m Home!” To make the 3D text flash, add a loop that
repeatedly sets the 3D text isShowing property to false and then true.
2. Binary Code Game
Build a world with three switches (Controls) and a lightbulb (Lights), as seen below. Set
the emissive color property of the lightbulb to black (turned-off).
In this game, the positions of the levers on the switches represent a binary code.
When a lever is up, it represents 1 (electric current in the switch is high) and when
down, 0 (electric current in the switch is low). In the above world, all three levers are
up, so the binary code is 111. The correct binary code is chosen at the beginning of the
game. (You can enter a given code, and then have a friend try to guess it, or you can use
the world-level random number function, as described in Tips & Techniques 6.) The
idea is to have the user try to guess the correct binary code that will light up the light-
bulb (its emissive color will be yellow). To guess the binary code, the user will click on
the levers to change their position. Each time the user clicks on a lever, it moves in the
opposite direction—up (if currently down) or down (if currently up). When all three
switches are in the correct position for the binary code, the bulb will turn on.
Each switch should respond to a mouse-click on the switch. If the handle is down,
flip it up. If the handle is up, flip it down. To track the current position of a handle, an
invisible circle can be placed on the switch and used as a point of reference. When the
handle is above the circle, turn it down. When the handle is below the circle, turn it up.
See Exercise 12 for more detail.
Your program must include a Boolean function that determines whether the
Boolean code is correct.
Hint: You can use the color of the circles (even though they are invisible) as a flag that
indicates the correct position of the lever.
Create a world and add the Cafeteria, the LunchLady, two CafeteriaTables, and
several CafeteriaChairs (all from High School). Add the EvilNinja (from People).
The first goal is to get the Ninja to move around to random locations within the cafe-
teria. Create a method named moveAround for the EvilNinja. This method should
move the ninja a random distance from where it currently is, without moving off the
screen.
To check whether the player has successfully clicked on the Ninja, create a
method named checkIfNinja for the Ninja. The checkIfNinja method will need an
object parameter named who. Create an event When the mouse is clicked on anything,
and have it call the checkIfNinja method, sending the object clicked to the who
parameter
4. Phishy Move
Phishy fish (Animals) has just signed up at swim school to learn the latest motion, the
sineWave. Your task is to write a method to teach her the sineWave motion. The initial
scene with a fish and water is seen here.
Note: This world is provided on the DVD that accompanies this book. We recommend
that you use the prepared world, as setting up the scene is time consuming. If you are
an adventuresome soul, here are the instructions for setting up the world on your own:
Use popup methods to move the fish to the world origin (0, 0 and 0) and then turn the
fish right one-quarter revolution. Because Phishy is partially submerged, set the opac-
ity of the water to 30% so the fish can be seen in the water. Now, use camera controls
to reposition the camera (this takes a bit of patience as the camera must be moved hor-
izontally 180 degrees from its default position). Then, adjust the vertical angle to give
a side view of the fish in the water, as seen above. The fish should be located at the far
left and the water should occupy the lower half of the world view, as seen in the screen
shot above.
Exercises and Projects 211
Alice has a sine function that can be used to teach Phishy the sineWave motion.
(The sine function is often used to determine the relationship between the lengths of the
sides of a right triangle. For the purposes of this animation, that relationship is not really
important.) If the sine function is computed over all angles in a full circle, the sine value
starts at 0, goes up to 1, back through 0 to -1 and returns to 0:
This function is continuous, so if sine values are plotted some multiple of times, we will
see the curve repeated over and over:
1.5
0.5
⫺0.5
⫺1 Sine wave
⫺1.5
Sine wave
For the sineWave motion, Phishy is to move in the sine wave pattern. In the
world provided on the DVD, Phishy has been positioned at the origin of the world. In
a 2D system, we would say she is at point (0,0). To simulate the sine wave pattern,
she needs to move up to height that is 1 meter above the water, then down to a depth
of 1 meter below the surface of the water 1-1 meter2, back up to 1 meter above the
water, and so on, at the same time as she moves to the right in the water. The Alice
sine function expects to receive an angle expressed in radians (rather than degrees).
Write a function, named degreesToRadians, which will convert the angle in degrees
to the angle in radians. To convert from degrees to radians, multiply the angle
degrees by p and divide by 180. The degreesToRadians function should return the
angle in radians.
212 Chapter 6 Functions and If/Else
Now, write a method to have Phishy move in the sine wave pattern. Remember
that in the world provided on the DVD, Phishy has already been positioned at the origin
of the world. So, Phishy is already at the position for 0 degrees.
Hint: One way to create the sine wave pattern is to use move to instruction (Tips &
Techniques 2). A move to instruction should move Phishy to a position that is (right, up,
0), where right is the radian value and up is the sin(radian value). After adding a move
to instruction, the built-in world level function (right, up, forward) can be dropped onto
the target of the move to, allowing individual specification of each coordinate. Use
move to instructions for angles: 45, 90, 135, 180, 225, 270, 315, and 360. For a
smoother animation, make each move to instruction have style = abruptly. Using
style = abruptly seems counter intuitive to making an animation run more smoothly.
The reason is that animation instructions begin slowly (gently) and end slowly (gently)
by default. If we wish to have two instructions appear to behave as a single instruction,
we do not want each instruction to slow down as the instruction starts/ends. Hence we
use the abrupt option.
In example programs, we have used If statements to make a choice about whether to execute
a section of program code. In this way, If statements can be used to control program execu-
tion. This is why an If statement may be thought of as a control statement. In this chapter, we
look at control statements where instructions and methods are repeated.
In Section 7-1, examples are presented where a Loop statement is used to execute a
block of instructions again and again. The Loop statement can be used when we know exactly
how many times a block of instructions should be repeated (i.e., a definite number of times).
We use the word count to describe the number of times a loop repeats. For this reason, a Loop
statement is referred to as a counted loop.
In Section 7-2, the While statement is introduced for repeating a block of instructions
where we do not know exactly how many times it should be repeated (an indefinite number
of times). A While statement corresponds naturally to the way we say and think about certain
actions in our everyday conversation. For example, we might say, “While I am driving, I will
continue to keep my hands on the wheel and my eyes on the road,” or perhaps something like,
“While I am a member of the baseball team, I will practice batting.” The While statement is
intuitive—a way to think about actions that repeat while some condition remains true.
7-1 Loops
As our worlds become more sophisticated, the code tends to become longer. One reason is
that some animation instructions and methods must be repeated to make the same action
occur over and over. Perhaps you have already written programs where you needed to write a
call to a method several times. In this section, we look at using a Loop statement to call a
method repeatedly.
213
214 Chapter 7 Repetition: Definite and Conditional Loops
The bunny in our example world is eight hops away from the broccoli. One possible
way to animate eight bunny hops is given in Figure 7-1-3. In this program, a Do in order block
is placed in the World.my first method. Then, a turn to face instruction is used to make the
bunny turn to look at the broccoli. Finally, the call to the bunny.hop method is dragged into the
editor eight times.
Of course, the code in Figure 7-1-3 will perform the task of making the bunny hop over
to the broccoli. It was tedious, though, to drag eight bunny.hop instructions into the program.
We want to look at a way to make our job easier by using a Loop statement. To create a Loop
statement, drag the Loop tile into the editor. The popup menu offers a choice for the count (the
number of times the loop will execute), as shown in Figure 7-1-4. In this example, the number
8 is entered as the count. Note that a loop can execute only a whole number of times.
Next, a call to the bunny.hop method is placed inside the Loop statement, as shown in
Figure 7-1-5. When the program is run, the bunny will turn to face the broccoli and then hop
eight times. That is, the loop will call the bunny.hop method eight times. The benefit of using
a Loop is immediately obvious—the Loop is quick and easy to write. Although eight calls to
the bunny.hop method is not a big deal, there are program situations where methods have to be
repeated 20, 30, or even 100 times. It would be much easier to use a single Loop statement if
the bunny had to hop 100 times!
In this simple example, we placed a single call to a method (bunny.hop) in the Loop
statement. We could have dragged several instructions and method calls into the block, and all
would have been repeated. A Do in order or Do together block can be nested inside the loop
to control how the instructions are repeated; otherwise, Alice will assume the instructions are
to be done in order.
Nested loops
Each of the examples above used only one Loop statement. Of course, it is possible to have
several Loop statements in the same program. In fact, a Loop statement can be nested inside
another Loop statement. In this section, we take a look at a world where this is an appropriate
way to write the program code.
Consider an initial scene with a two-wheeled Ferris wheel (Amusement Park folder on
the DVD or Web gallery), as in Figure 7-1-6. An animation is to be written that simulates the
running of this Ferris wheel. The double wheel will turn clockwise (roll right) while each of
the individual wheels will turn counterclockwise (roll left).
Figure 7-1-7 is code for a Loop to roll the Ferris wheel 10 times. The style = abruptly
parameter has been used to smooth out the rotating of the entire double wheel over each rep-
etition. (We chose the abrupt style because the default style, gently, slows down the animation
instruction as it begins and ends. Because we are repeating the instruction within a loop,
we want to avoid having the wheel go through a repeated slowdown, speedup, slowdown,
speedup Á kind of action.)
With the motion of the entire Ferris wheel accomplished, instructions can now be writ-
ten to rotate each of the inner wheels counterclockwise (roll left) while the outer double
wheel is rotating clockwise (roll right). The code to rotate the inner wheels is presented in
Figure 7-1-8.
Now the rotations can be combined. To increase the excitement of the ride, we will have
the inner wheels rotate more frequently, perhaps twice as often as the outer wheel. So, each
time the double wheel rotates one revolution clockwise, the inner wheels should rotate twice
counterclockwise. Figure 7-1-9 shows the modified code.
In previous programs you have seen that actions in a Do together block need to be syn-
chronized in duration. In this example the inner wheels need to rotate twice while the outer
wheel rotates once. So, the duration of rotation for the outer wheel (doublewheel) is
made to be twice the duration of rotation of the inner wheels (doublewheel.wheel1 and
doublewheel.wheel2). Each time the outer loop runs once, the inner loop runs twice. This
means that the double wheel takes 2 seconds to complete its rotation, and the inner wheels
218 Chapter 7 Repetition: Definite and Conditional Loops
require 1 second (the default duration) to complete their rotations, but rotate twice. In all, the
inner wheels rotate 20 times counterclockwise as the outer wheel rotates 10 times clockwise.
Optical Illusion: Instructions within a Do together block can sometimes cancel each
other out (in terms of the animated action we can observe). For example, in the First
Encounter world described in Chapter 2, Section 2, turning the backLeftLegUpperJoint
backward and forward at the same time made the animation look as though the leg was
not turning at all. In the Ferris wheel example above, since the outer loop is set to exe-
cute only one time and the inner loop two times, the inner wheel will look as though it
rotates only once.
Infinite loop
One option in the popup menu for selecting a Loop count is infinity. (See Figure 7-1-11.) If
infinity is selected, the loop will continue on and on until the program stops.
Ordinarily, we advise that you avoid infinite loops. However, in animation programs an
infinite loop is sometimes useful. Consider an amusement park animation where a carousel is
one of the objects in the scene, as in Figure 7-1-12. To make the carousel go around in the
background, call the carousel’s built-in method carouselAnimation in an infinite loop, as
shown in Figure 7-1-13.
The instruction performed inside the while statement can be a single action or several
actions enclosed in a Do in order or Do together block. The condition used in a While state-
ment is a Boolean condition (the same type of condition used in If statements). The Boolean
condition acts like a gatekeeper at a popular dance club. If the condition is true, entry is gained
to the While statement and the instructions within the While statement are executed, otherwise
the instructions are skipped. Unlike the If statement, however, the While statement is a loop.
The diagram in Figure 7-2-1 illustrates how the While statement works as a loop.
220 Chapter 7 Repetition: Definite and Conditional Loops
Is No exit
Condition
loop
true?
Yes
Execute instructions
If the condition is true, the instructions are performed; then the condition gets checked
again. If the condition is still true, the instructions within the loop are repeated. If the condi-
tion has become false, the loop ends and Alice goes on to execute the next statement in the
program. A While statement is useful for situations where we do not know how many times
the loop should be repeated. All we need to know is the condition that determines whether the
loop will be repeated.
Chase scene
Let’s look at an example of a situation where we do not know (ahead of time) how many times
a block of code should be repeated. This animation is a “chase scene” simulation. Chase
scenes are common in video games and animation films where one object is trying to catch
another. In this example, a shark is hungry for dinner. The shark is going to chase after and
catch a fleeing goldfish (Animals). OK, so this is not a gracious animation—but sharks have
to eat, too! Figure 7-2-2 shows a very simple initial world.
Problem
Our task is to animate the shark chasing the goldfish, as it tries to get close enough (say,
within 0.5 meters) to gobble the goldfish down for dinner. Naturally, as the shark chases it, the
goldfish is not standing still. Instead, it is trying to escape by moving to a random position. Of
course, we want the fish to look like it is swimming (not jumping all around on the screen), so
we will move it to a random position that is close to the current position.
7-2 While—a conditional loop 221
Storyboard solution
The basic idea is that if the goldfish is more than 0.5 meters away from the shark, the shark is
going to point at the goldfish and swim toward it. Meanwhile, the goldfish is moving away to
a random position nearby. If the goldfish is still more than 0.5 meters away, the shark will
change course and swim toward it and the goldfish will try to swim away. Eventually, when
the shark finally gets within 0.5 meter of the goldfish, the chase is over and the shark can
catch and eat the goldfish.
Let’s plan a method for the chase animation using the While statement. Think about it
like this:
“While the shark is more than 0.5 meters away from the goldfish, move the shark
toward the goldfish and, at the same time, move the goldfish to a random position nearby”
The condition in our While statement will be “the goldfish is more than 0.5 meter away
from the shark.” If this condition is true, the chase is on. A storyboard is shown here.
chase
Do in order
While the goldfish is more than 0.5 meters away from the shark
Do in order
shark point at the goldfish
Do together
shark swim (toward the goldfish)
goldfish flee (away from the shark)
shark eat (the goldfish)
The condition must be true to allow entry into the loop. After running the instructions
within the While statement, the condition will be evaluated again, and if the condition is still
true, the instructions within the While statement will run again. This process continues until
the condition finally evaluates to false.
In the storyboard, the shark swim, goldfish flee, and shark eat steps will each require
several instructions. These actions will be written as methods.
chase
While the goldfish is more than 0.5 meters away from the shark
Do in order
shark point at the goldfish
Do together
shark swim
goldfish flee
shark eat (goldfish)
For now, let’s pretend that these methods have already been written (we can write them
next). A chase method to implement the overall storyboard is illustrated in Figure 7-2-3.
222 Chapter 7 Repetition: Definite and Conditional Loops
Now, let’s look at how to write the shark.swim, goldfish.flee, and shark.eat methods that
are called from the chase method. We can use stepwise refinement to complete the storyboard,
as shown next. Please note that a duration of zero causes the instruction to occur instanta-
neously, without a gradual animation of the action.
The shark.swim method moves the shark forward and then turns the torso of the
shark right and left to simulate a swimming motion through water. Figure 7-2-4 illustrates
shark.swim.
chase
Do in order
While the goldfish is more than 0.5 meters from the shark
Do in order
Point the shark at the goldfish
Do together
shark swim
goldfish flee
shark eat (goldfish)
swim flee
Do in order Do together
turn torso left and move forward wiggle tail
turn torso right and move forward move to random location
turn torso left and move forward
eat
Parameter: what
Do in order
shark points at what
shark opens jaw and moves forward
shark closes jaw
The goldfish.flee method moves the tail of the goldfish to simulate a swim-like motion
and calls the randomMotion method (previously defined in Tips & Techniques 6) to move the
fish to a nearby random location. The goldfish.flee method is shown in Figure 7-2-5.
After the While statement ends, the shark.eat method is executed, as is illustrated in
Figure 7-2-6. The method uses a parameter to specify what object in the scene is on the menu.
224 Chapter 7 Repetition: Definite and Conditional Loops
In this example, shark.eat was invoked with the goldfish object as the parameter. The shark
moves forward 1 meter to completely swallow the goldfish. The opacity of the goldfish is
faded to 0% so that the goldfish becomes invisible (disappearing into the shark’s mouth).
Infinite While
As a general rule, a While statement should contain instructions that change conditions in the
world so the While statement will eventually end. Otherwise, the loop would continue to exe-
cute in a never-ending cycle—an infinite loop. (An infinite loop is often a program error that
makes the program seem to be “spinning its wheels.”) In the shark chase example above, we
avoided an infinite loop by carefully planning the distance the shark and the goldfish move
with each execution of the loop. Although the goldfish is moving randomly, we set the maxi-
mum value to 0.2 meters in any one direction (forward, up/down, right/left). A bit of 3D
geometry is needed to show that the total distance the goldfish travels must be less than .35
meters, as illustrated in Figure 7-2-7.
0.35
0.2
0.2
0.2
Figure 7-2-7. Maximum distance the goldfish can travel in one move
The goldfish, then, never moves more than 0.35 meters away from the shark, and the
shark always moves 0.4 meters closer to the goldfish. The shark’s distance advantage guaran-
tees that the shark is eventually going to catch up to the goldfish and the loop will end.
7-2 While—a conditional loop 225
We highly recommend that you carefully check the condition for a While statement to
be sure the loop will eventually end. On the other hand, there are some kinds of programs
where an infinite loop is desirable. This is particularly true in games and simulation anima-
tions, where an action should occur until the program shuts down.
This animation has two repeated actions: a helicopter circling an island and a rabbit mov-
ing his head to watch the helicopter as it circles. Also, an action should occur as soon as the
helicopter can no longer be seen by the rabbit: the rabbit looks back at the camera. The prob-
lem is how to make actions repeat (within a loop) but also make an action occur each time the
loop ends. We have seen this situation before in working with interactive worlds and events.
Perhaps we can create a solution to our problem by using events. In fact, Alice has a built-
in While statement event for linking events to repeated actions. The event, highlighted in
Figure T-7-2, is While something is true.
226 Chapter 7 Repetition: Definite and Conditional Loops
As was described in Chapter 5, Section 5-1 selecting the While something is true event
from the pull-down menu causes a While event block to be added to the Events editor, as
shown in Figure T-7-3. The event block automatically contains a Begin–During–End (BDE)
block that allows you to specify what happens when the loop begins, during the execution of
the loop, and when the loop ends. Up to this time, we have only used the “During” part.
To create a BDE behavior, we need to specify up to four pieces of information (any or all
may be left as Nothing):
A conditional expression/function (evaluates to true or false)—The While statement
condition is 6None 7 by default, but you must replace it with a Boolean expression or
function.
Begin—An animation instruction or method that is to be done once, at the time the
condition becomes true.
During—An animation instruction or method that is to be done repeatedly, as long as the
condition remains true. Note that as soon as the condition becomes false, the animation
instruction or method ceases running, even if it is in the middle of an instruction!
End—An animation instruction or method that is to be done once, at the time the condition
becomes false.
In the above example, the helicopter is flying around the island. We would like to have
the white rabbit’s head look at (point at) the helicopter as soon as the helicopter is in front of
the rabbit (Begin). Then, as long as the helicopter is still in front of the rabbit (During), we
want the rabbit’s head to continue to look at the helicopter. As soon as the helicopter is no
longer in front of the rabbit (End), the rabbit should look back at the camera. The code in
Figure T-7-4 accomplishes this task:
7-2 While—a conditional loop 227
The constrain to point at instruction is a built-in method that adjusts the position of an
object to point at some other object. In this example, constrain to point at is used to make the
rabbit’s head continuously point at the helicopter as long as the While statement condition
(helicopter is in front of whiteRabbit) is true.
Note: Using multiple Do together control structures within a BDE may cause a run-
time error if the BDE ends but one or more of the Do togethers are still trying to run.
A “While” event can be changed to a “When” event. In the example shown in Figure T-
7-5, the While event causes the chicken to continuously peck as long as its opacity is less than
one. Changing the event to “When something becomes true” causes the chicken to peck each
time its opacity falls below one (but not continuously). For this reason, the Begin and End
parts of a “While” event are not needed in a “When” event. That is to say, a “When” event
does not have a BDE code block.
Summary
Loop and While were introduced in this chapter as control structures for repeating an instruc-
tion or block of instructions. A counted Loop allows you to specify exactly how many times a
block of code will be repeated, and a While statement allows you to repeat a block of code as
long as some condition remains true. The advantage of using loops is immediately obvious.
Loops are fast and easy to write and also easy to understand. Of course, it is possible to write
loop statements that are complicated. Overall, though, loops are impressive programming
tools.
Programming Terms
count indefinite loop nested loops
definite loop infinite loop While
Animation Terms
Begin-During-End event
When something is true event
Questions
1. Unless nested within a repeating control statement, Do in order, Do together, and
If/Else control statements are expected to be executed exactly how many times?
2. Give two examples of control statements that are generally expected to execute
repeatedly.
Exercises and Projects 229
Loop 4 times
Loop 3 times
bunny.hop
turn left 1>4 revolution
3. Saloon Sign
An old saloon (Old West) is being converted into a tourist attraction. Use 3D text to cre-
ate a neon sign to hang on the front of the balcony. Then use a loop to make the sign
blink 10 times. (Tips & Techniques 1 provides instructions on using 3D text. Tips &
Techniques 4 shows how to make an object visible or invisible.)
4. Lock Combination
Exercise 10 in Chapter 4 was to create a new class of combination lock with four class-
level methods—leftOne, rightOne, leftRevolution, and rightRevolution—that turn the
dial one number left, one number right, one revolution left, and one revolution right,
respectively. Also, the lock has a method named open that opens it, and another named
close that closes it. The purpose of this exercise is to reuse the methods created in the
previous exercise. Revise the previous world. Use a loop instruction to turn the dial left
25 times. Then use a loop to turn the dial right and finally use a loop to turn the dial
back to the left three times. (The combination is 25, 16, 3.) Then, pop open the latch,
close the latch, and return the dial to zero.
Hint: Use Wait to make the lock pause between each turn of the dial.
Exercises and Projects 231
7-2 Exercises
5. Frog and Ladybug
Create a world with a frog (Animals) and a ladybug (Animals). Write an interactive pro-
gram to allow the user to drag the ladybug around the scene. (Use a let the mouse move
objects event.) As the ladybug is dragged around, make the frog chase after it by mov-
ing one hop at a time without colliding with the ladybug. If the user moves the ladybug
within 2 meters of the frog, have the frog look at the camera and say “ribbit”—then end
the animation.
6. Bumper Cars
Create a simulation of the bumper car ride (Amusement Park), where the cars move
continuously around within the bumper arena. Add two bumper cars inside the arena. In
this animation, each car should be moving forward a small amount until it gets too close
to another car or to the wall, then turn the car a quarter of a revolution clockwise (to get
a different direction) and continue moving forward. Use a switch (Controls) to stop and
start the ride. As long as the switch is on, the ride should continue.
232 Chapter 7 Repetition: Definite and Conditional Loops
Hint: To create new bumperCar objects, select one of the bumperCar objects in the
object tree and then click on the copy icon in the mouse control palette. Be sure to click
on the white arrow mouse control icon when finished creating copies (to turn off copy).
To avoid a car driving through a wall of the arena, a simple form of collision detection
is needed. One way to check for a possible collision is to use the distance to function to
compute the distance of the car to the arena. Remember that distance to is measured
“center-to-center.” In this world, a measurement from the center of the car to the center
of the arena is exactly what you need. (When a car gets too far from the center of the
arena, it will collide with a wall.) It is also possible to write a function that returns
whether two cars are about to collide with one another. What should be done in this
case?
8. Spinning Stars
This exercise provides a world in which to explore using world-level functions to con-
trol the execution of a loop. A knight has been thrown from his horse and stars are spin-
ning above him. We want to allow the user to control how the stars start and stop
spinning by moving the mouse cursor near the left or top edge of the window. While the
mouse is near the top or left edge of the window, the stars will start and continue spin-
ning. However, when the mouse is moved back towards the center of the world, the stars
should stop spinning.
To create this world, add a horse, a knight (both from Medieval), and a see-
ingStars object (from Special Effects). Create a new method named spin for the see-
ingStars object. A “spin” is 2 revolutions, turning either left or right. In the spin method,
the stars should spin left about half the time and spin right the other half. Create a
world-level function named nearTheEdge that returns true if the mouse is within
1 meter of the top or the left edge of the screen. Then, write a world-level method
named outOfBounds that uses a while loop to spin the stars as long as the mouse is near
the top or left edge of the screen. Use a While the world is running event to call the
outOfBounds method.
Hint: The world has functions that return the distance of the mouse from top edge and
from the left edge of the screen. Also, the world has a random probability function that
can be used to choose whether the stars turn right or left.
Exercises and Projects 233
To create the clock, add an alarmClock (Objects) and a katana (Objects). Position
the katana on the clock to be used as a second hand. The world's functions include sev-
eral time functions that access your computer's built-in clock. Use the world functions
hour of AM or PM, minute of hour, and second of minute to roll the hands to their cor-
rect starting positions. Then, use a while loop to continuously update the second hand
and If/Else statements to decide when to move each of the minute and hour hands.
Hint: Repeated turn and roll motions will eventually make the bucking bronco assume
very unrealistic positions. To avoid this result, carefully position a reference object at
the peak of the cone on which the bronco is suspended. Make it invisible and then mod-
ify the motion statements to use asSeenBy the reference object.
Projects
1. Drinking Parrot
A small toy popular with children is a drinking parrot. The parrot is positioned in front
of a container of water and its body given a push. Because of the counterbalance of
weights on either end of its body, the parrot repeatedly lowers its head into the water.
Create a simulation of the drinking parrot (Objects). Use an infinite Loop statement to
make the parrot drink.
Hint: We used the blender object (Kitchen gallery), pushed the base into the ground,
deleted the lid, and changed the color of the blender to blue to simulate a bucket of water.
the elevator is currently located. A dummy marker can be used to remember the loca-
tion of the glassCage when it was on the ground floor. Create and use a function to com-
pute the current floor.
4. Juggling
Create a world with an object that has arms (the picture below shows an ant) and three
juggling balls. (A juggling ball is easily created by adding a sphere or a tennis ball to the
world, resizing it, and giving it a bright color.) To juggle the balls, the object must have
at least two arms and be able to move them in some way that resembles a tossing
motion. Write a method to animate juggling the balls in the air. Use a loop to make the
juggling act repeat five times, after which the juggling balls fall to the ground.
Exercises and Projects 237
6. Carrier Landing
Create a water world with a carrier in the ocean and a navyJet (Vehicles) in the air, as
shown below. Write an interactive program to allow the user to use keyboard controls to
land the jet on the deck of the carrier. Up, down, and forward controls are needed. Use
a function to determine when the jet has landed (gotten close enough to the carrier’s
deck) and a While statement to continue the animation until the jet has landed.
7. Moonwalk
Write a program that will make the astronaut (Space) perform a moonwalk. The lunar
lander (Space) and flag (Objects) are used to decorate the Space template scene.
To perform the moonwalk, the astronaut should turn right and then walk backward in a
sliding sort of motion where one leg slides backward and then the other leg slides back-
ward. The astronaut’s entire body must move backward at the same time as the moon-
walk leg motions are executed. Use a loop to make the astronaut repeat the moonwalk
steps five times.
Chapter 8
Repetition: Recursion
This chapter introduces a third form of repetition known as recursion, in which a method (or
a function) calls itself. This is an extremely powerful technique that greatly enhances the
types of problems that can be solved in Alice. Recursion is often used where we do not know
(at the time the program is written) the number of times a block of code should be repeated.
(This is also true for the While statement, covered in Section 7-2.)
In Alice, there are two major situations where we do not know (even at runtime, when
the program first starts to run) the count of repetitions. The first is when random motion is
involved. As you recall, random motion means that an object is moving in a way that is some-
what unpredictable. In Section 8-1, we explore the technique of writing methods where repe-
tition is implemented with recursion.
In Section 8-2, we look at a famous puzzle and present a solution using a second flavor
of recursion. This form of recursion is useful when some complex computation is to be done
that depends on an ability to break a problem down into smaller versions of the same problem
(subproblems). The solutions to the smaller subproblems are used to cooperatively solve the
larger problem.
A game-like example
To illustrate recursion, we use a simple version of a horse race in a carnival game (Amuse-
ment Park). The initial scene is shown in Figure 8-1-1. Unlike a traditional horse race, where
horses run around an oval-shaped track and each horse breaks to the inside of the track, horses
in a carnival game move straight ahead in a mechanical track. In a carnival game, you win a
prize if you pick the right horse. In this example, we won’t worry about picking the right
horse. We will simply have the winning horse say, “I won!!!” This is not a realistic end to the
game—but it will serve the purpose of signaling the end of the race.
239
240 Chapter 8 Repetition: Recursion
The problem is how to make this simulate a real carnival game, where the horses move
forward again and again until one of them finally reaches the finish line. At each move, the
horses move forward different amounts. To keep the game honest, each horse must have an
equal chance of winning the race. This means that over several runs of the game, each horse
should win about the same number of times as the other horses.
A possible solution is to randomly choose one horse to move forward a short distance.
If none of the horses has won (gotten to the finish line), we will once again randomly choose
one of the horses to move forward. This action (a randomly chosen horse moves forward a
short distance) will be repeated again and again until one of the horses eventually gets to the
finish line and wins the race.
An essential step is how to decide when the race is over. In this example, if one of the
horses reaches the finish line, the horse wins the race and the game is over. An If statement
can be used to check whether one of the horses has won. If so, the game is over. Otherwise
(the Else part), we randomly choose another horse to move forward and do it all again. A sto-
ryboard for this animation could look something like this:
race
If one of the horses has won
the winner says, “I won!!!”
Else
randomly choose one horse and move it forward a small amount
do everything again
In the storyboard above, the line “do everything again” means that the entire method
should be repeated. How do we write a program instruction to “do everything again”? We
simply have the method call itself! Let’s modify the storyboard to show the recursive call:
race
If one of the horses has won
the winner says, “I won!!!”
Else
randomly choose one horse and move it forward a small amount
call the race method
8-1 Introduction to recursion 241
A close look at the modified race storyboard shows that the method is calling itself!
This is known as recursion. A method that calls itself is said to be recursive. The effect of a
recursive call is that the method will repeat. Repeated execution of a method may occur again
and again until some condition is reached that ends the method. In this example, the condition
that ends the recursive calls is “one of the horses has won.”
Now, all we have to do is translate the storyboard into program code. To write the code
for the race, we have three problems:
1. How to determine when the race is over.
2. How to randomly select one of the horses to move forward for each execution of the loop.
3. How to figure out which horse won the race and have it say, “I won!!!”
These problems can be solved using stepwise refinement, creating functions and/or
methods to solve each.
race
If one of the horses has won
the winner says, “I won!!!”
Else
randomly choose one horse and move it forward a small amount
call the race method
For now, let’s pretend that the functions isRaceOver and whichHorseWon along with the
moveRandomHorseForward method have already been written. (We will write them next.) For
now, we created the functions and method tabs in the editor but did not write the code. This
allows us to call the functions and method but delay the coding. If the functions and method
were already written, we could write the race method as shown in Figure 8-1-2. The If part
checks to see whether the game is over. If so, the game ends with the winning horse saying “I
won!!!” Otherwise, the Else part kicks in and a horse is randomly selected to move forward a
short distance. The last statement, racehorseGame.race, recursively calls the race method. The
overall effect of the recursive call is repetition until some condition occurs that ends execution of
the method.
Now that you have the overall idea of how recursion works, we can look further at the
details of implementing isRaceOver, moveRandomHorse, and whichHorseWon.
Random selection
If the game is not over, we need to randomly choose a horse and move it forward a short dis-
tance. In this problem we need to give each horse a “fighting chance” to win the race. Let’s
use the world-level random selection function, choose true (probability of true) of the time.
This function will return true some percentage of a total number of times (probability of
true is a percentage). For example, saying “choose true 0.5 of the time” means that
50 percent of the time the function will return a true value, the other 50 percent of the time it
will return a false value.
It seems reasonable to use a value of 0.33 (one-third) for probability of true, so that each
horse will be chosen 33 percent (one-third) of the time. The other two-thirds of the time, that
horse will not move. As shown in Figure 8-1-4, we start the random selection with the first horse,
whose name is racehorse1. Racehorse1 will be selected one-third of the time. But, what if
racehorse1 is not selected? Then the Else-part takes over and a selection must be made from race-
horse2 or racehorse3. Once again, to decide which horse should move, choose true (probability of
true) of the time is used. Figure 8-1-4 illustrates the code for the moveRandomHorseForward
method.
8-1 Introduction to recursion 243
and found the following very surprising results: racehorse1 won 7 times, racehorse2 won
3 times, and racehorse3 won 10 times! Something is very wrong. The results for racehorse1
are reasonable (it won about a third of the time). But racehorse2 didn’t win nearly enough,
and racehorse3 won far too often.
The problem is within the second (nested) random selection of which horse should
move. We used 33% as the percentage of probability for choosing each horse. What we didn’t
think about was that if racehorse1 was not selected, then we have only two choices: racehorse2
or racehorse3. So, after racehorse1 has been eliminated, we should select racehorse2 to move
50 percent of the time to give racehorse2 an equal chance with racehorse3. The modified code
is presented in Figure 8-1-6. Now, each horse wins approximately one-third of the time!
Collectively, each friend lends $10 back up the stream of requests, and the problem of bor-
rowing enough money is solved. (Of course, you now have the problem of paying it back!)
Notice that each friend has a problem similar to your problem—but the amount of money
each friend needs to borrow is successively smaller. This is what we mean by breaking
the problem down into smaller and smaller subproblems. When the smallest problem (the base
case) is solved, the solution is passed back up the line, and that solution is passed back up the
line, and so on. Collectively, the entire problem is solved. To illustrate this form of recursion in
terms of designing and writing a program, it is perhaps best to look at an example world.
In setting up this world, careful positioning of cones and measurement of disks will
make the animation easier to program. We positioned each cone exactly 1 meter from its near-
est neighbor, as labeled in Figure 8-2-2.
Each disk is placed exactly 0.1 meter in height above its neighbor, as illustrated in
Figure 8-2-3.
To make it easier to describe our solution to the puzzle, let’s give each disk an ID num-
ber and a name. The disk with ID number 1 is disk1, ID number 2 is disk2, ID number 3 is
disk3, and ID number 4 is disk4. The smallest disk is disk1 at the top of the stack and the
largest disk is disk4 at the bottom. Also, let’s name the cones cone1, cone2, and cone3 (left to
right from the camera point of view). The goal in the puzzle is to move all the disks from the
leftmost cone, cone1, to another cone. In this example, we will move the disks to the right-
most cone (cone3).
246 Chapter 8 Repetition: Recursion
Figure 8-2-3. Each disk is 0.1 meter above its neighboring disk (measuring from top down)
A first attempt to solve the problem might be to use a while loop. The textual storyboard
might look something like this:
Unfortunately, it is not easy to figure out what needs to be done inside the “Do.”
The problem can be solved using a While loop, but it takes much thinking and insight into the
problem. Recursion makes the problem much easier to think about and solve, so we will use
recursion.
Two requirements
We want to solve this puzzle for four disks using the second form of recursion, where the
problem is broken down into smaller and smaller subproblems. To use this form of recursion,
two requirements must be met.
The first requirement is that we must assume we know how to solve the problem for a
smaller subproblem. Let’s assume that we do know a solution for solving the problem for three
8-2 Another flavor of recursion 247
disks. If we know how to solve the problem of moving three disks, it would be quite easy to
write a program to solve it for one more disk (four disks). The following steps would work:
1. Move the three disks (imagining the solution for the puzzle with only three disks is
already known) from cone1 to cone2. See Figure 8-2-4(a).
2. Move the last disk, disk4, from cone1 to cone3. See Figure 8-2-4(b). (Remember that
this move is now safe, as all of the three smaller disks are now located on cone2.)
3. Move the three disks (again, imagining the solution is already known) from cone2 to
cone3. The final result is shown in Figure 8-2-4(c).
The second requirement is that we must have a base case. A base case is the simplest possible
situation where the solution is obvious and no further subproblems are needed. In other
words, when we get down to the base case, we can stop breaking the problem down into sim-
pler problems because we have reached the simplest problem. The obvious “base case” in the
Towers of Hanoi puzzle is the situation where we have only one disk to be moved. To move
one disk, we can just move it. We know that there are no smaller disks than disk 1. So, if it is
the only disk to be moved, we can always move it to another cone!
248 Chapter 8 Repetition: Recursion
towers
Parameters: howmany, source, target, spare
If howmany is equal to 1
move it (disk 1) from the source to the target
Else
Do in order
call towers to move howmany-1 disks from source to spare (using
target as spare)
move it (disk # howmany) from the source to the target
call towers to move howmany-1 disks from the spare to the target
(using the source as the spare)
We know this looks a bit complicated; but it really is not too difficult. Let’s break it
down and look at individual pieces:
First, the If piece:
if how many is equal to 1
move it (the smallest disk) from the source to the target
This is simple. The If piece is the base case. We have only one disk to move, so move it!
Second, the Else piece:
Else
(1) call towers to move howmany-1 disks from source to spare
(using target as spare)
(2) move it (disk # howmany) from the source to the target
(3) call towers to move howmany-1 disks from spare to target
(using the source as the spare)
All this is saying is:
1. Move all but one of the disks from the source to the spare cone.
2. Now that only one disk is left on the source, move it to the target cone. This is ok,
because all smaller disks are now located on the spare cone, after step 1.
3. Now, move all the disks that have been temporarily stored on the spare cone to the
target cone.
8-2 Another flavor of recursion 249
Notice that the If piece and the Else piece in this storyboard each have a substep that
says “move it” (move a disk) from the source cone to the target cone. The moveIt substeps are
highlighted in the storyboard below. Moving a disk from one cone to another is actually a
combination of several moves, so we will need to use stepwise refinement to break down our
design into simpler steps.
towers
Parameters: howmany, source, target, spare
If howmany is equal to 1
move it (the smallest disk) from the source to the target
Else
Do in order
call towers to move howmany-1 disks from source to spare
(using target as spare)
call towers to move howmany-1 disks from the spare to the target
(using the source as the spare)
moveIt:
Exactly what does the moveIt method do? Move it must lift the disk upward to clear the
top of the cone it is currently on. Then, it must move the disk (forward or back) to a location
immediately above the target cone. Finally, it must lower the disk down onto the target cone.
Figure 8-2-5 illustrates a possible sequence of moves.
To write the moveIt method, we need to use three parameters because it needs to know:
(1) which disk is to be moved (whichdisk—the disk ID number), (2) the source cone
(fromcone), and (3) the target cone (tocone). A storyboard for moveIt could be:
moveIt
Do in order
Lift the disk up above the top of the fromcone
Move it (forward or back) to a location above the tocone
Lower the disk down onto the tocone
250 Chapter 8 Repetition: Recursion
Two methods are to be written: (1) the towers method and (2) the moveIt method. Let’s
start by writing the towers method, as shown in Figure 8-2-6. The code is a straightforward
translation of the storyboard.
If whichdisk is 1 then
Move disk1 up 0.4 meters
Else
If whichdisk is 2 then
Move disk2 up 0.5 meters
Else
If whichdisk is 3 then
Move disk3 up 0.6 meters
Else
Move disk4 up 0.7 meters
We thought about this for a while, realizing that the nested If statements might seem a
bit awkward. We noticed that the distance each disk has to move up is 0.3 meters more than
0.1* the ID number (whichdisk). Thus, a nifty mathematical expression could be used to move
a disk upward. Using an expression to compute the distance would allow the storyboard to be
just one step:
Sometimes it is helpful to come up with an elegant idea like this one. We want to point out,
however, that condensing the code into a more compact form may lead to other problems. In this
case, using an expression to compute the distance leads us to a problem of how to write the state-
ment. Notice that the one-statement storyboard uses the phrase “appropriate disk” because we
don’t know exactly which disk is to be moved. All we have is whichdisk—an ID number, not a
name. Think of it like this: you have a name and a social security number. When someone talks to
you, she says your name, not your social security number. Writing a move instruction is a similar
situation. A move instruction uses the name of the object, not its ID number.
Conversion function
“How is Alice to be told the name of the disk object to be moved when only the disk ID num-
ber is known?” One solution is to write a conversion method that takes the ID number as a
parameter and returns the appropriate name of the disk object to move. Such a conversion
method can be written using a function. The which function is illustrated in Figure 8-2-8. In
this code, each If statement includes an instruction containing the keyword Return. As you
know, the Return statement sends information back to the method that called it. For instance,
suppose which1i = 22 is called; the information that will be returned is disk2. The which
function provides a way to convert an ID number (the whichdisk parameter) to an object
name. (We named the function which to make it easy to mentally connect the which function
to the whichdisk parameter.)
252 Chapter 8 Repetition: Recursion
An instruction can now be written in the moveIt method that calls the which function to
determine which disk to move and uses a mathematical expression to compute the distance, as
illustrated in Figure 8-2-9. In this instruction, which1i = whichdisk2 is a call to the which
function. When executed, which1i = whichdisk2 will select the appropriate disk and return its
name. That disk will then be moved upward the computed amount, as explained in the earlier
expression.
moveIt
Do in order
Lift the disk up above the top of the fromcone
Move it (forward or back) to a location above the tocone
Lower the disk down onto the tocone
8-2 Another flavor of recursion 253
For the second instruction, we want to move the disk forward or backward so as to posi-
tion it immediately over the target cone. How far should the disk be moved? As previously
illustrated (Figure 8-2-2), the cones are purposely positioned exactly 1 meter from one
another. There are six possible moves, as shown in Table 8-2-1.
Table 8-2-1. Six disk moves from source cone to target cone
Forward moves forward distance Backward moves forward distance
from cone1 to cone2 1 meter from cone2 to cone1 -1 meter
from cone1 to cone3 2 meters from cone3 to cone1 -2 meters
from cone2 to cone3 1 meter from cone3 to cone2 -1 meter
Notice that moving forward a negative 1-1 meter2 distance is the same as moving
backward 1 meter. After examining the six cases in detail, we see that the forward distance
can be computed using an expression 1tocone - fromcone2. For example, to move a disk
from cone1 to cone3, move it 2 meters 13 - 12 forward. With this insight, an instruction can
be written to move the disk to the target cone, as shown in Figure 8-2-10.
The last step in the moveIt method is to move the disk downward onto the target cone.
This instruction should simply do the opposite of what was done in step 1. The complete
moveIt method appears in Figure 8-2-11.
Now, with the towers and the moveIt methods completed, all that remains is to call the
towers method when the world starts. A link in the Events editor can be used, as seen in
Figure 8-2-12.
The second form of recursion (presented in this section) depends on the structure of
a problem and its solution, breaking a problem down into smaller and smaller subprob-
lems. Many mathematicians (and computer scientists interested in logic) often prefer this
form of recursion because it is easy to show that the program does end—and that it ends
with the correct solution. For example, with the Towers of Hanoi, we reasoned that we
could:
move four disks, if we can move three disks and then one disk (we know how to move
one disk)
move three disks, if we can move two disks and then one disk
move two disks, if we can move one disk and then one disk
move one disk (base case—we know how to move one disk)
Clearly, the problem has been broken down into smaller and smaller subproblems. We
know that the program will end, because we know that eventually the problem size will get
down to the base case, which is moving one disk.
Texture maps
Objects displayed in Alice are covered with texture maps to provide a sense of realness. For
example, consider the plate (Kitchen) on a table (Furniture on DVD or Web gallery) scene,
shown in Figure T-8-1.
A texture map named ground.GrassTexture covers the ground surface, and a texture map
named plate.TextureMap covers a plate, as can be seen in Figure T-8-2.
8-2 Another flavor of recursion 255
A graphic file (.gif, .bmp, .jpg, or .tif) can be used to give an object a different look. The
Internet is a good place to look for graphic files—just be sure the images are not copyrighted!
As an example, let’s change the appearance of the plate to look like a cookie instead. Two steps
are required. The first step is to import a texture map that we intend to use for that object. In
this example, we selected the plate object, clicked the import texture map button, and then
selected cookie.gif to be used as the texture. (The cookie.gif file is not part of Alice. We created
the graphic image using a paint program.) Figure T-8-3 illustrates the importing step. The
second step is to set the skin property to use the new texture map, as in Figure T-8-4. The result
is seen in Figure T-8-5.
To add fog, click on World in the object-tree and select properties, as shown in Figure T-8-7.
Then, click on the image to the right of fogStyle and select density. Density refers to the thickness
of the fog. To adjust the fog density, click the fogDensity tile and adjust the density value to
achieve the desired effect. A larger density value produces a thicker fog.
Figure T-8-7. The fogStyle and fogDensity properties are used to create a foggy scene
Summary
This chapter introduced the concept of using recursion as a mechanism for repetition. Recur-
sion is a powerful tool for building more complex and interesting worlds.
The horse race example in this chapter demonstrates a kind of recursion where more
executions of a section of program code are “generated” each time the result of the previous
decision is true. The famous Towers of Hanoi puzzle is an example of a second flavor of
recursion, where a complex problem is broken down into simpler and simpler versions.
A comparison of repetitions
Chapters 7 and 8 presented three ways for accomplishing repetition in a program: Loop,
While, and recursion. You might ask, “Which one should I use, and when?”
The choice depends on the task being completed (the problem being solved) and why
you need the repetition. If you know how many times the repetition needs to be performed
(either directly or via a function), the Loop statement is generally easiest. In most program-
ming that you do, you will want to avoid infinite loops. In animation programming, however,
an infinite Loop statement can be used to create some background action that continues to run
until the program is shut down.
Otherwise, use the While loop or recursion. Some programmers prefer While and others
prefer recursion. Put two programmers in the same room and they are likely to disagree over
this issue. The underlying difference between the two is how you think about solving a prob-
lem. We say, “Try both.” Some problems are easier to solve with a While loop and others are
easier to solve with recursion. With experience, you will discover which works best for you.
The important thing is that you learn to write code that uses repetition.
Programming Terms
base case
recursion
random selection
Animation Terms
texture map
Questions
1. Give an explanation for the following statement: “Recursion is more appropriately
described as a programming technique rather than as a control construct.”
2. In what way(s) is a recursive method similar to a While loop?
3. A programmer who wishes to write a recursive method will use a statement that
evaluates a condition that determines whether the method will call itself again. In
Alice, what is the control construct that is used for the decision-making statement?
4. One “flavor” of recursion is generative, where actions build up and up until some
conditional goal is met. Describe the second “flavor” of recursion.
5. At least one of the cases in an If statement must not include a recursive call. Why?
2. Butterfly Chase
Use recursion to make the white rabbit (Animal) chase a butterfly (Animals/Bugs). The
butterfly should fly to a random, nearby location (within 0.2 meters in any direction).
Exercises and Projects 259
The white rabbit, however, must always remain on the ground (rabbits do not fly). Each
time the butterfly moves, use turn to face to make the rabbit turn toward the butterfly
and then move the rabbit toward the butterfly 0.5 meters. When the rabbit gets close
enough, have him catch the butterfly in his net (Objects).
Hint: To move the butterfly to a random nearby location, you can adapt the
randomMotion method presented in Tips & Techniques 6. It is necessary to keep the
butterfly from flying too high or too low. (The butterfly could disappear below the ground
or fly too high, so that the rabbit would never get close enough to catch it.) To limit the
up–down direction of the butterfly’s movement, use an If statement to check the butterfly’s
distance above the ground and then move the butterfly up or down accordingly. The
butterfly’s distance above the ground should always be within the range of 0 (ground
level) and 1 (meter above the ground).
3. Midas Touch 1
In the story of the Midas Touch, a greedy king was given the gift of having everything
he touched turn to gold. This exercise is to create a simulation of the Midas Touch. In
the initial scene shown below, a woman is facing a candy cane (Holidays/Christmas).
(Use turn to face to make this alignment.) Write a recursive method, named
checkCandy, that checks whether the woman’s right hand is very close to the candy
cane. If it is, the woman should touch the candy cane. After she touches the candy cane,
the candy cane turns to gold (color changes to yellow). If the woman is not yet close
enough to the candy cane to be able to touch it, she moves a small distance forward and
the checkCandy method is recursively called.
4. Midas Touch 2
Create a second version of the MidasTouch1 world. This new version will be interac-
tive. The idea is to allow the user to guide the movement of the woman toward a candy
cane. To make this a bit more challenging, the woman should not be facing the candy
cane in the initial scene. This will require the checkCandy method be modified so that
whenever the woman is close enough to the candy cane to touch it, she first turns to
point toward the candy cane before bending over to touch it.
260 Chapter 8 Repetition: Recursion
Use the left and right arrow keys to turn the woman left or right. Create two
methods: turnRight and turnLeft. The methods should turn the woman 0.02 revolutions
to the right or left when the user presses the right or the left arrow key. These methods
will allow the user to guide the woman toward a candy cane.
Hint: It is possible that the woman will wander out of the range of the camera. There
are two possible solutions. One is to make the camera point at the woman each time she
moves. The other is to make the camera’s vehicle be the woman.
8-2 Exercises
5. Towers of Hanoi
Create the Towers of Hanoi puzzle as described Section 8-2. When you have it working,
modify the event-trigger link that calls the towers method so that it moves the disks
from cone1 to cone2 (instead of cone3).
6. Towers of Hanoi Modified
We do not need to pass around the spare cone as a parameter. The spare cone is always
6 - fromcone - tocone.
Modify the towers method to use this new approach.
7. On the Hour
Place a cuckoo clock (Objects) in a new world. The idea of this animation is to have the
cuckoo clock keep time (not in real time, of course). The minute hand should go around
on the face of the clock (perhaps one complete revolution should take about 30 seconds
in real time) and the pendulum should swing back and forth. When the minute hand has
made one revolution (from 12 back to 12 on the face of the clock), then the hour hand
should advance to the next hour, the doors should open, and the cuckoo bird (on the
clock arm) should come out and chirp once. Then the bird should retreat inside the
clock and the doors should close until the next hour has gone by. “All is well” as long as
the clock is running—which should continue until the user stops the animation. Use a
recursive method to implement the animation.
Projects
1. Why Did the Chicken Cross the Road?
A popular child’s riddle is, “Why did the chicken cross the road?” Of course, there are
many answers. In this project, the chicken (Animals) has a real sweet-tooth and crosses
the road to eat the gumdrops (Kitchen/Food) along the way.
Exercises and Projects 261
Write a game animation where the player guides the chicken across the road to get to
the gumdrops. Cars and other vehicles should move in both directions as the chicken tries
to cross to where the gumdrops are located. Use arrow keys to make the chicken jump left,
right, forward, and back. Use the space bar to have the chicken peck at the gumdrop. When
the chicken is close enough to the gumdrop and pecks, the gumdrop should disappear.
A recursive method is used to control the play of the game. If the chicken gets hit
by a vehicle, the game is over (squish!). The game continues as long as the chicken has
not managed to peck all the gumdrops and has not yet been squished by a vehicle. If the
chicken manages to cross the road and peck at all the gumdrops along the way, the
player wins the game. Signal the player’s success by making 3D text “You Win” appear
or by playing some triumphant sound.
2. Reversal
In the world below, the row of skeletons (Spooky) is guarding the gate (Spooky). Every
so often in this world, the row of skeletons is to reverse order. This project is to animate
the reversal using the second form of recursion. The storyboard goes something like the
following:
reverse
If the row of skeletons not yet reversed is more than one then
reverse the row of skeletons starting with the second skeleton (by recursively
calling reverse)
move the head skeleton to the end of the row
The base case is when there is just one skeleton in the row (that has not yet been
reversed). Of course, a row of one skeleton is already reversed! The recursive case (for
n skeletons, where n is larger than 1) says to first reverse the last n - 1 skeletons and
then move the first skeleton to the end of the row.
Implement the Skeleton reversal storyboard given above. The program you write
should be quite similar to the Towers of Hanoi program, including the which function.
up a new world with a square (Shapes) as the screen, the slide projector (Objects) on a
table (Furniture on DVD or Web), and a lightbulb (Lights) in front of the screen, as
shown in the image below left. The lightbulb is for the purpose of lighting up the screen
(simulating light from the projector). Then, make the lightbulb invisible by setting its
isShowing property to false.
For an added sense of realism, start with the world’s light on and them dim the
light before turning on the projector. The slide show in your project must display at
least three different slides. Numbering the slides and using an If statement may help
you create a method to change slides. Between each slide, the screen must go blank,
the projector light must flicker (change the color of the light), and the slide projector’s
tray of slides must rotate. (The blank slides below show the screen going blank
between one slide and the next.) The slides are to change continuously (meaning once
all three have been seen, the show should go back to slide 1 and start over). The
sequence of images is a sample slide show. (The cat pictures are of Muffin, one of our
graduate student’s cats.)
4. Click-a-Cow
Let us design a game where the goal is to click on an object that is appearing and then
disappearing on the screen. If the user successfully clicks on the object while it is visi-
ble, some visual action should happen so the user will know he/she has managed to
“click” the object with the mouse. In our sketch of a storyboard below, a cow (Animals)
is the object and a windup key (Objects) is used to signal success. (Of course, you can
creatively choose a different object and a different way to signal the fact that the user
has clicked on the object.)
We assume that the cow and wind-up key have been added to the world and both
have been made invisible by setting their isShowing property to false. A storyboard for
a method, check, will look something like this:
Exercises and Projects 263
When the user finally manages to click the mouse on the object, a method should
be called that signals success. In our example, the wind-up key would become visible.
Once the key is visible, the game ends.
Hint: The most challenging part of this project is to move the object to a random loca-
tion on the ground (perhaps between -3 and 3 in the forward–back and right–left direc-
tions). Also, you will find it helpful to experiment with a Wait instruction to find out
how long to wait while the object is visible (not too fast, not too slow) before making it
invisible again.
This page intentionally left blank
Part IV
Advanced
Topics
265
This page intentionally left blank
Chapter 9
Lists and List
Processing
9-1 Lists
A list is one of the most popular ways to organize information. We use lists in our everyday
lives. For example, you might have a grocery list or a list of homework assignments. Pro-
grammers use lists to organize objects and information about objects in their programs.
Examples of specialized lists can be found in thousands of software applications. In Alice, a
list (generally) contains items of a similar type. (For example, we might want a list of objects
or a list of colors.) In this section we look at how to create a list and then how to iterate
through the list, to look for a particular item or to take some action with each item in the list.
Creating a list
In the initial scene shown in Figure 9-1-1, five rockettes (People) have been added to the world.
The rockettes are famous for their holiday dance routines. We want to create an animation where
267
268 Chapter 9 Lists and List Processing
the rockettes will perform the kick-step from one of their dances. In a kick-step routine, the
dancers each perform a kick, one after the other down the line. Then, they all perform the
same kick-step at the same time. This is an example of an animation where a list can be used
to organize objects to act as a group.
Before a list can be used in a program, the list must be created. Five rockette dancers
have been added to the scene and positioned to form a dance line. Just adding the objects to the
world and then positioning them next to one another, however, is not enough to create a list.
To actually make a list, a list variable must be created (to give the list a name) and then
the objects (already in the world) must be added to the list. To create a list variable, select the
properties tab for the World and then click the create new variable button, as shown in
Figure 9-1-2. (The list is created at the world-level rather than at the class-level because it will
contain several different objects.)
When the create new variable button is clicked, a popup dialog box allows you to enter
the list variable name, as shown in Figure 9-1-3. In this example, we used the name dancers
and selected its Type as Object. The key action here is to check the box marked make a List.
Then you can click the button labeled new item to add an object to the list. In the example
9-1 Lists 269
shown in Figure 9-1-3, the new item button was clicked five times to enter each rockette.
Finally, click the Okay button. The list variable name can now be used in instructions where
we want to have the dancers perform as a group.
kickUpRightLeg
Parameter: whichRockette
Do in order
For all dancers in order
Do together
item_from_dancers kickUpRightLeg
whichRockette right thigh turn back
whichRockette right calf turn forward
whichRockette right calf turn back
270 Chapter 9 Lists and List Processing
Now we can translate the design into a world-level method named World.kickUpRightLeg,
where the whichRockette parameter acts as a placeholder for an item from the dancers list. (At
first glance, we might think the kickUpRightLeg method should be a class-level method. How-
ever, several different objects may be used in the dancers list.) The kickUpRightLeg method is
shown in Figure 9-1-4.
An object parameter in a method requires that you perform more than one step to create
instructions that use the parameter. In this example, we want to move parts of the right leg
(subparts) of the rockette. Alice has no way of knowing which kind of object is actually going
to be sent in to whichRockette and also does not know whether the object has a right leg. (Sup-
pose we had added a snowman to the list of dancers. Sending in a snowman to whichRockette
would be a problem, because snowmen do not have right legs, or any legs for that matter!)
What all this means is that we must use a part named function to specify the exact subpart of
whichRockette is involved in the turn instructions.
As an example, let’s look at the steps we used to create the first turn instruction in
kickUpRightLeg.
1. Create an instruction to turn one of the rockettes backward 0.25 revolutions.
2. Then, drag in the part named function for the rockette and drop it on top of the rockette
tile. The result should look like this:
3. Click to the right of part named and enter the exact name of the part (Alice is case sen-
sitive, so type it correctly). Now, we have this:
4. Now, drag the whichRockette parameter tile down to drop it on top of the rockette. The
final instruction should look like this:
9-1 Lists 271
Now that the kickUpRightLeg instruction has been written, a For all in order statement
can be used to create the animation. The For all in order tile is dragged into the editor, and the
expression World.dancers is selected as the name of the list, as illustrated in Figure 9-1-5.
An instruction is written inside the For all in order statement to call the World
.kickUpRightLeg method, as illustrated in Figure 9-1-6.
When the program is run, each item from the dancers list is sent as an argument to the
kickUpRightLegs method, one at a time. Each dancer kicks up her right leg one after the other,
down the dance line. The screenshot in Figure 9-1-7 was captured after the first two rockettes
have already kicked their right leg in the air and the third rockette has just started to do so.
Figure 9-1-7. Running the dance animation using For all in order
call—everyone who is connected to the conference call is on the phone line at the same time
and everyone can talk and interact at the same time.
In any dance group, the dancers perform some steps sequentially and others at the same
time. Let’s have all the rockettes kick up their right leg at the same time. To do so, drag the For
all together tile into the editor, as shown in Figure 9-1-8.
The World.kickUpRightLeg method is called from within the For all together statement.
The resulting instruction is shown in Figure 9-1-9.
Now, when the code is run, the dancers all kick up their right legs at the same time, as
illustrated in Figure 9-1-10.
9-2 List search 273
Figure 9-1-10. Running the dance animation using For all together
progress. The second is to increase the player’s score each time the player manages to actually
click on one of the moles that pops up. In storyboard form,
execution, the code for starting the game and keeping it in progress will be written in
World.my first method.
A While loop can be used to provide continuous action in the game. While the player-
Score column has not yet moved above the ground (meaning that the player hasn’t yet won the
game), calls will be repeatedly made to a popMole method. So, we need a method to pop up a
mole. We have 12 moles, so we will use a parameter whichMole to represent one of them. The
method is illustrated in Figure 9-2-3.
Of course, the first thing to do after this method is written is to test it. (We don’t have to
wait until the program is written!) Just call the method from World.my first method.
Whichever mole is passed to whichMole is the mole that pops up. The popup action makes the
mole move up, stay up for 0.3 seconds, and then move back down.
Now we need to figure out how to pass a random mole to the popMole method. Our solu-
tion is to organize the moles into a list structure and then randomly select a mole from the list.
A list of moles is created, as previously described in Section 9-1. The name of the list variable
in this example is moles—not a very creative name, but it has the advantage of being obvious!
Now that the popMole method has been written (Figure 9-2-3) and the moles list cre-
ated, the code for keeping the game in progress can be written in World.my first method, as in
Figure 9-2-4. To send a random mole from the list to the popMole method each time it is
called, we dragged the mole list into the parameter tile and then selected random item from list
from the popup menu. When this code is run, a random mole from the list is passed as an
argument to the popMole method each time the While statement is repeated.
Wait a second! When the code shown in Figure 9-2-4 is tested, it keeps playing and
playing and playing. The While loop is supposed to end when the playerScore column moves
up above the ground. Of course, the playerScore column does not move upward because we
have not yet written the code to make that happen. Our program is not yet complete Á we
have one more step to accomplish.
276 Chapter 9 Lists and List Processing
Second subtask—scoring
A score method needs to be written to visually display the player’s success in the game. Each
time the player actually clicks the mouse on a mole that pops up, the playerScore column
should be raised. The score method is shown in Figure 9-2-5. The object clicked by the mouse
will be sent to the clicked parameter. In this method, a For all in order statement is used to
iterate through the list of moles. The condition in the if statement checks a mole to determine
whether it is the object clicked. The conditional expression is created by dragging in clicked
(the parameter tile) and dropping it into the condition position in the if statement. A menu
pops up from which you can select the == operator and item_from_moles as the operand.
Because the if statement is nested with in a For all in order, the if checks each mole in
the list. This is how the list search takes place! If one of the moles in the list is the object
clicked, the player’s score is increased (by raising the playerScore column,) and the mole that
was clicked makes a popping noise.
Critical to scoring is the event When the mouse is clicked on something. To use this
event, a When the mouse is clicked on something event is created. Then the World.score
method tile is dragged into the editor and dropped on top of 6Nothing 7. From the popup
menu, we selected object under the mouse cursor as the argument for the clicked parameter.
The result is shown in Figure 9-2-6.
In response to the mouse being clicked on something (anything), the score method is
called. This event notifies Alice the mouse has been clicked, and Alice can then determine
what object is under the mouse cursor. The object under the mouse cursor will be passed to
the clicked parameter for the score method.
Of course, it is possible that the player clicked too soon or too late and the object under
the cursor was the top of the WhackAMole game booth (because the mole had disappeared
back underneath). The player may move the cursor too quickly and click on the grass or the
9-2 List search 277
sky. In such situations, the search for a mole that has been clicked fails, so the player’s score
is not increased and no pop sound is made.
In summary, the important concept illustrated by the WhackAMole example is that of
searching a collection of items to determine whether one of them has a particular property.
Other techniques for searching can be used, but the overall idea is the same. In this example,
the collection of items is a list of moles. The search is conducted using a For all in order state-
ment to iterate through the list. The For all in order statement goes through each mole in the
list and checks whether one of them has been clicked by the player.
As you have certainly experienced, when you add several objects into a world in Alice,
the Object Tree fills up quickly. It would be convenient to somehow create a grouping for
some of the objects in a given scene. This would make the Object Tree look less cluttered.
And it would reduce the need for scrolling when trying to either position the objects during
initial scene set-up, or when dragging methods of an object into the program editor.
Alice allows the grouping of objects in the Object Tree. To create a group, simply right mouse-
click anywhere on the white space in the Object Tree panel. Figure T-9-2 shows the resulting pop-up.
Figure T-9-2. Clicking with the right mouse button on the white space in the Object Tree
A left mouse-click on the “create new group” button creates a new group in the Object
Tree. To give the group a name, right mouse-click on the Group tile in the Object tree, select
278 Chapter 9 Lists and List Processing
“rename,” and then enter a name for the group. In this example, the Group folder has been
renamed to Fairies, as illustrated in Figure T-9-3.
Note that there is a thin black line immediately below the Fairies folder, with a slight ver-
tical part indicating that the drop is going to occur into the Fairies folder. Repeating this
process for all of the fairie objects yields the result shown in Figure T-9-5.
It is important to note that adding such a group is for appearance purposes only. It is not
possible to save out this group of fairies as a single .a2c file. Additionally, unlike the list cre-
ation process in the earlier parts of this chapter, there is no list created as a result of this group-
ing. It only makes the Object Tree less cluttered and easier to navigate.
Summary
In programming, many different kinds of organizing structures can be used to create a collec-
tion of objects or information about objects. Each kind of structure offers different capabili-
ties or features. In Alice, lists are used as organizing structures (data structures). A list is a
collection of several items of the same type (such as Object or Color).
In this chapter we looked at creating a list as well as iterating through a list. Alice pro-
vides two mechanisms for iterating through a list: sequentially (using For all in order) and
simultaneously (using For all together). The For all in order iteration is similar to “walking”
(or traversing) through each item in the list, one at a time. The For all together iteration is like
setting up a multiway telephone conference call—everyone is on the line at the same time.
The For all in order statement is similar to Do in order in that actions are performed in
sequence, and the For all together statement is similar to Do together in that actions are per-
formed simultaneously. A common application of lists is searching for an item in a list. A list
search walks through each item in the list, one at a time, until we find the one we want.
Programming Terms
data structure list list variable
iterate through a list list search
Animation Terms
For all in order For all together group
Questions
1. If an Alice world contains six penguin objects, is it necessarily the case that the six pen-
guins are items in a list of penguins? Explain your answer.
2. What is the purpose of creating a list of similar items in a program?
3. For the programmer, what is the advantage in using a list in a program?
4. The list examples in this chapter illustrate lists where the items are all objects. What
other types of items could have been used?
5. Which control construct is used to iterate through a list of items in sequence?
6. Which control construct is used to iterate simultaneously (all items in the list at once)?
7. To which of the repetition loop constructs (Loop or While) is the For all in order itera-
tion construct most similar? Explain your choice.
280 Chapter 9 Lists and List Processing
2. Room Remodel
Sometimes the hardest decision to make when repainting a room is choosing the color.
Create a world that helps a person decide what color they should choose for their walls
and carpeting. Make a room scene by using three squares (Shapes) as the walls and add
furniture (Furniture) to it. To get the look and feel of carpeting, add the moonSurface
(Space) and use its texture for the floor. Create a list named wallColors (a list of type
Color) and add five colors to the list. Create a second list of colors named floorColors
and add five colors to the list. Use nested For all loops with the lists to show every pos-
sible combination for the wall and floor colors. Use a wait statement to allow the viewer
to see a color combination a couple seconds before showing the next color combination.
3. Spring Flowers
If you have a copy of that world created in Chapter 5, Exercise 13, you can revise that
world. Otherwise, build the world using a box (Shapes) and flowers (Nature). Five
flowers (your choice) are hidden inside the box.
Exercises and Projects 281
Hint: The flowers can be hidden inside the box by using the mouse to position them out
of sight.
Create a list, where each flower is one item of the list.
(a) Make each flower “grow” upward (out of the flowerbox) one at a time using For all
in order.
(b) When you have that working well, create a second version where all flowers grow
out of the flowerbox at the same time, using For all together.
9-2 Exercises
4. Casting a Beach Scene
A casting director is selecting people to act as extras for a beach scene in a film. Create
a world in which the user is the casting director. Allow the director to mouse-click on a
person to be cast in the scene. When the casting director clicks on DONE, the camera
changes to view the beach scene and all the people that were cast for the scene move
into the water and face the camera.
To create this world, use the grass template and add 10 different people using
models from the gallery. Use 3D text to create the “Cast an actor” sign and the “DONE”
control object. Use a dummy marker to mark the location and orientation of the camera
for the initial scene. Then, add the oasis (Environments) in a different location and use
a dummy marker to mark the location and orientation of the camera for the beach scene.
Make an object list named cast and leave it empty (do not add objects at this
time). Create a world method named castActors, having an object parameter named
who. Each time an actor is cast, the castActors method should add that person to the
cast list. Use a For all together statement to move each person to the oasis a random dis-
tance and then have them face the camera.
Note: People objects used in this world should have their center point in the middle
of the body, rather than at their feet. Any people who have their center point at their
feet will appear to be standing on the water, rather than standing in the water.
282 Chapter 9 Lists and List Processing
5. Ship Motion
To create a realistic animation of ships at sea (Vehicles), ships must appear to move as
if responding to the motion of the waves. A response amplitude operator (RAO) ship-
motion approach is commonly used by animators. Create a simulation of ship motion
with a world containing four ships. Make a list of the four ship objects. Animate all
ships moving at the same time but by different amounts. Use a randomly generated
RAO to determine the amount of movement in a random direction for each ship in the
list. Because the ships are moving with the waves, the movements tend to be symmetri-
cal. That is, a forward (left, up) movement is followed by a backward (right, down)
movement in approximately the same amount. Use a loop to continue the motion simu-
lation until the user stops the animation.
To animate the floating action of all seven buoys, create a world-level list named
allBuoys and add each of the seven buoys to the list. Then create a method named sway.
In the sway method, use the allBuoys list to roll all the buoys right and left. Create an
event that continues to call sway while the world is running.
Create an event that allows the player to steer the boat using the arrow keys. Have
the camera follow the sailboat to always keep it in view. To determine when the boat
gets close enough to pick up a buoy, create a world-level method named checkIfClose-
ToBuoy that checks whether the sailboat is within 3 meters of any one of the buoys in
the allBuoys list. Create another method named pickUpBuoy, having an object parame-
ter named whichBuoy. The whichBuoy parameter represents the buoy to be picked up.
The picked up buoy should be moved to the back of the boat, where it will ride until the
game ends (see picture below). When the sailboat is within 3 meters of any buoy, check-
IfCloseToBuoy calls pickUpBuoy. Use an event that continuously calls checkIfCloseTo-
Buoy while the world is running.
284 Chapter 9 Lists and List Processing
To determine when the game is over, you need a way to know when all the buoys
have been picked up. To track the buoys that have been picked up, create a second
world-level list, this one named pickedUpBuoys and leave it empty. In the pickUpBuoy
method, create a statement that adds the picked up buoy to the pickedUpBuoys list. Cre-
ate a world-level method named checkIfGameIsOver and call it every time a buoy is
picked up. When the size of pickedUpBuoys is equal to seven, the player wins the game
and a 3D text object is used to display “You did it!”.
Projects
1. Game: Got Me!
In this project, you will create a game in which the goal is to click on objects that are
moving across the screen. When the player clicks on an object, that object says, “Got
me!” The objects should alternately move from left to right and right to left on the
screen.
To create the world, add 12 different objects to the world and have them all facing
in the same direction. Be sure to choose 12 objects that have a center point at their base
(where they touch the ground). Then, add two axes (Shapes) objects to the scene. Posi-
tion one axis on the far left and the second axis on the far right of the scene. The “For-
ward” axis of each axes object should be directly facing the other. The axes will act as a
starting point for the objects on each side. Two screen captures are shown below. The
picture on the left shows the full scene with the axes on the far left and right and the 12
objects clustered in between. The picture on the right shows the initial scene for the
game, where the camera is moved in to get a closer view of the 12 objects and the axes
are not in view of the camera.
To organize the twelve objects for playing the game, create four world-level lists.
The first list, named allObjects, should contain all 12 objects that will move across the
screen. The second list, named objectsOnTheLeftSide, should contain 6 of the 12
objects. The third list, named objectsOnTheRightSide, should contain the other 6 of the
12 objects (those not on the left side are on the right side). The fourth list, named objects-
ThatWereClicked, is initially empty.
To prepare the objects for moving across the screen one at a time, create a world-
level method named setUpGame. This method should set the point of view of each
object in the objectsOnTheLeftSide list to that of the axes object on the left of the scene.
And, the method should do the same for objectsOnTheRightSide, using the axes object
on the right of the scene.
To create the code for playing the game, create three methods:
(1) playGame loops through the size of the objectsOnTheLeftSide list and uses the
index of the loop to move each of the objects forward (across the screen), one at a
time. This loop should work to alternately move an object from the left side and
Exercises and Projects 285
then from the right side, until all objects have moved across the screen once. Use a
random value for the duration as each object moves across the screen.
(2) addObjectToList checks whether an object that the user has clicked is one of the 12
valid objects. If the object is a valid object, then it is added to the objects-
ThatWereClickedOn list and the object says “Got me!” To make this method work,
create a mouse-click event that listens for a mouse click and calls this method, send-
ing in the object that was clicked.
(3) showWhoWasClickedOn, which (after all objects have moved once across the
screen) provides an end-of-game report by moving all of the objects that were
clicked to the center of the screen. Each of them should move forward and say “Got
Me!”
2. Monty
A famous mathematical problem (the Monty Dilemma) goes something like this:
Suppose you’re on a game show, and you’re given the choice of three doors. Behind one
door is a car, behind the others, toy monkeys. You pick a door, say number 1, and the
host, who knows what’s behind the doors, opens another door, say number 3, which has
a toy monkey. He says to you, “Do you want to pick door number 2?” Is it to your
advantage to switch your choice of doors?
One way to find an answer to this question is to create a simulation of the game
where the objects are placed randomly behind the doors. Play the game 25 times where
you do not switch and 25 times where you do switch. Keep track of your success rate
when you switch and your success rate when you do not switch. Then you will know the
answer to the question!
To set up the initial world, add three doors (Furniture), a car (Vehicles), and two
toy monkeys (Animals) to a new world. Position the car and the two monkeys behind
the three doors, as shown above. Each door should be 2.5 meters to the left (or right) of
its neighbor door. Position the door in front of the car and then do the same for each
monkey and its respective door. (When the door moves, the object behind will move
with it.) Also create a 3D text object that asks the player to “Select a Door.” Make the
text object invisible by setting its isShowing property to false.
286 Chapter 9 Lists and List Processing
To program the game, make a list containing the three doors. When the animation
begins, randomly pick two doors and swap them. Use a method called swap that takes
two doors as parameters. Swap the two doors by having them move 2.5 meters in oppo-
site directions.
Important: Two doors should swap only if they are different (a door cannot swap
places with itself). Repeat the swap 10 times. (The idea is to make it difficult for the
player to know what object is behind what door.)
Display the 3D text to ask the player to select a door. After the player clicks on
one of the doors, pick another door that hides a monkey and open that door. Then ask
the player whether he/she wants to switch the choice. If the object behind the door
(selected by the player) is the car, the player has won. Open the door and declare the
player a winner. Otherwise, the player has lost. Use sound or 3D text to indicate the win
or loss.
3. Frog Crossing the Pool
Add a rectangle (Shapes) to a new world and change its color to blue. This will serve as
a swimming pool. Add seven circles (Shapes) to the world—five yellow along the long
side of the pool (each one meter apart), one green at the nearest side, and one red at the
far edge. The yellow circles are lily pads that float back and forth across the pool. Add
a frog, and place it on the green circle. The goal is to make the frog jump from lily pad
to lily pad until it gets all the way across the pool. If the frog lands on the water (not on
a lily pad), the frog sinks into the pool and the game is over. If the frog jumps all the
way across the pool and lands on the red circle at the far edge, the player wins.
Your program must place the five yellow circles in a list. Write a method that uses
an infinite loop to repeatedly move each of the five yellow circles in the list across the
pool and back at different speeds. (The easiest way to do this is to pass a random num-
ber to the method to specify the duration for the circle to move across the pool.) Create
event handling methods that have the frog jump forward 1 meter if the player presses
the c key, move left if the player presses the ; key, and move right if the player
presses the : key. Connect each event handling method to an event.
4. Game: Follow The Leader
In this project, you will create a clicking game where the goal is to click the cubes in the
same order that they were flashed (using a random sequence of colors). The player
should watch the cubes flash (a random sequence of five flashes) and then try to click
on the cubes in the same sequence. If the player is able to click on the cubes in the exact
sequence that the cubes were flashed, then the player wins the game.
To create the world for this game, you will create three sets of objects. The first
set is four cubes (Shapes) where you give each cube a different color. The second set of
Exercises and Projects 287
objects is five gloves and the third set of objects is five keys (gloves and keys from
Objects gallery). The cubes are arranged in the middle of the scene. The keys and
gloves are arranged in five pairs, each pair consisting of of one key and one glove, with
the key on top of the glove, as shown here:
The keys and gloves should initially be invisible (set the is Showing property for
each key and glove to false). Next, create three text objects. Two text objects are used to
provide instructions to the player, “Watch the Cubes” and “Click on the cubes in the
same order.” The third 3D text object should be the phrase, “Check Answer!”
Three lists are needed to manage the cubes, keys, and gloves. Create a list named
allCubes and add each of the four cubes to the list. Create a list named keyList and add
each of the five keys to the keyList. Create a list named gloveList and add each of the
five gloves to the gloveList.
Two additional lists are needed to play the game. Create a list named randomSe-
quence and leave the list empty. Create a second list named playerSequence and leave
this list empty, as well. Objects are to be added to these two lists when the game is being
played. The randomSequence list will hold a random sequence of five cubes (at least
one of the cubes will be flashed more than once). The playerSequence list will hold the
sequence of the five cubes that the player mouse-clicks in an attempt to reproduce the
exact same sequence.
To create the code to play the game, the following world-level methods are needed:
• createRandomSequence—adds five cubes in random order to randomSequence
• oneCubeFlash—“flashes” one cube (quickly sets is showing to false and then true)
• flashCubesInSequence—“flashes” each of the cubes in the order that they appear in
randomSequence
288 Chapter 9 Lists and List Processing
Note: Events are needed to call the addToPlayerSequence method, sending in the clicked
cube. Also, an event is needed to call checkForWin when the player clicks on “Check
Answer!”
Chapter 10
Variables
and Revisiting
Inheritance
This chapter introduces the concept of mutable variables and revisits classes and inheritance,
as used to create new classes. A mutable variable is a piece of storage that holds onto a value
(a piece of information) while a program is running. We say it is mutable because we can
change the value as things happen during program execution.
In Section 10-1, mutable variables are introduced as properties that can be changed at
runtime using a set instruction. We look at how to add new properties to an object (as class-
level variables). The object and its new properties can be saved out in a new class. An instance
of the new class has all the old properties of the original class but also has the new properties.
You have seen this technique before (in Chapter 4), where we defined new methods for an
object in the world and then saved out the object as a new class.
In Section 10-2, an array visualization is created. An array is a structure that organizes
a collection of items. Each item is located in a certain position in the array structure. In work-
ing with an array, we use an index variable to keep track of the position of each item in the
array.
10-1 Variables
From Alice’s perspective, a mutable variable is a property that can be directly changed using
set (or some other methods, as will be shown below). The word “mutate” means “to change,”
and we use “mutate” to describe what happens when a property is changed. For simplicity, we
often drop the word “mutable” and just say “variable.”
What makes mutable variables worth learning about? They allow you to keep track of
changes. In the same way that we need to track the balance of money in a checking account or
the amount of gasoline in the tank of a car, we often need to keep track of changes in position,
color, opacity, and other properties of objects in our programs. In a game, we might want to
keep track of the number of times the player has put a basketball through the hoop or how
much time is left on the clock. The mutable variables in our examples are class-level vari-
ables, designed to keep track of a property for a specific kind of object. But, we are getting
ahead of ourselves. Let’s begin with a quick recall of properties of objects and how properties
relate to state. Then, we can look more closely at mutable variables.
289
290 Chapter 10 Variables and Revisiting Inheritance
An object’s property values are the information we know about the object. We call this
set of information the state of the object. Instructions in our programs generally change the
state of the object. For example, a move instruction changes an object’s position and a turn to
face instruction changes its orientation. Some of the state can be changed directly, using a set
method (available by dragging a property tile into the code window). For example, the color
property of the basketball is set to orange in Figure 10-1-2. You have probably used a set
method to change opacity, isShowing, and other properties of objects in programs.
Example 1: A timer
A common component in games is a timer. A timer is used to keep track of how much time the
player has left to play the game. For example, in a basketball game a timer (clock) begins with
12:00 minutes at the beginning of each period. As the game is played, the timer counts down
to 0:00. When the timer reaches 0:00, the period ends. Another common component of games
is a scorekeeper. A scorekeeper is similar to a timer, but it increases the score when a player
scores a point (or points).
In this example, we construct a timer that counts down in seconds. Figure 10-1-3 shows
a world with a timer object. The timer is actually a 3D text object, displayed in the lower left
of the scene. The string stored in the 3D text object has been set to 0.0 (to indicate that the
timer is inactive). Our task is to set the timer to an initial number of seconds for a game (say,
10.0 seconds) and then count down the seconds remaining in a game. The number of seconds
remaining will be displayed and will be updated with each passing second.
Because the timer has a default timeLeft of 0 seconds, it would be helpful to create a
parameterized method that can be used to initialize the timer to some number of seconds
appropriate for any game. A class-level method is created named initialize. A storyboard for
the initialize method is:
initialize
parameter: amountOfTime
The code for the initialize method is shown in Figure 10-1-6. The set instruction is cre-
ated by dragging the timeLeft variable into the editor and selecting amountOfTime as the
value.
The next step is to create a method that causes the timer to count down by seconds and
update the 3D text to display the new time with each passing second. A simple storyboard for
a countDown method is:
10-1 Variables 293
countDown
Do in order
While timeLeft is greater than 0
Do in order
update the 3D text to show the remaining number of seconds
decrease timeLeft by 1
update the 3D text to display 0 seconds
You may be puzzled by the last line of the storyboard. Think about it like this: the While
statement runs again and again, as long as the value of timeLeft is greater than 0. When the
value of timeLeft becomes 0, the While statement ends and the 0 does not get displayed! We
added the last line to display the 0, thereby showing that the time on the clock has run out.
Now, the storyboard is translated into the corresponding code in the countDown
method for the timer. First, a While statement tile is dragged into the editor and then the
World function 1a 7 b2 is dragged in as the condition, as shown in Figure 10-1-7. We selected
timer.timeLeft as the value for a. (Recall that the variable timeLeft stores a number value, as
set by the initialize method.) To complete the condition 1a 7 b2, select other as the value for
b. A popup number pad is used to enter 0 as the value for b.
Instructions can now be written within the While statement. First, a Do in order block is
dragged in and then an instruction is created to update the 3D text display to show the remain-
ing time. Select the timer 3D text object in the Object tree and then drag its text property tile
into the editor. Select the default string from the popup menu, as shown in Figure 10-1-8.
Figure 10-1-8. Dragging the text property into the editor to create a set instruction
The default string is just a placeholder. We want to replace the default string with the
number of seconds remaining. The problem is that the value stored in the timeLeft variable is
a Number but we want to display it as a 3D text string. To solve this problem, a World-level
function can be used to convert a Number to a string. Select World in the Object tree and then
click on functions. Drag the what as a string function over the default string tile and select
timeLeft from the popup menu, as illustrated in Figure 10-1-9.
Figure 10-1-9. Dragging the what as a string function into the editor
The code created, thus far, is shown below. Notice that the duration of this instruction is
0 seconds, meaning that updating the 3D text string is done instantaneously.
10-1 Variables 295
Now, the count down instructions can be created. One way to do this is wait 1 second
and then decrease the value stored in timeLeft by 1 second, as illustrated in Figure 10-1-10. As
with the set instruction, the decrement instruction has a duration of 0 seconds. Because we
used a Wait 1 second instruction and made the other instructions occur in 0 seconds, we can
be sure the timer decreases 1 second.
Finally, the last statement is added to display 0 seconds on the clock after the While
statement ends. The completed code is shown in Figure 10-1-11. Notice that the last line of
code is created outside the While statement, to display 0 seconds.
To demonstrate how the timer is used, we created the code shown in Figure 10-1-12.
First, timeLeft is initialized to 10 seconds, by passing 10 as the argument to the amountOfTime
parameter. Then, a Do together block is used to play a game while the timer counts down.
The critical technique in using the timer is to control the length of time the player is
allowed to play the game so that when timeLeft decreases to 0, the game is over. This means
296 Chapter 10 Variables and Revisiting Inheritance
Figure 10-1-12. Code to play a game at the same time as the timer counts down
the playGame method must be able to find out how much time is left on the clock. We created
a class-level function howMuchTimeIsLeft for the timer, as shown in Figure 10-1-13. This
function allows the playGame method to check the time left on the clock, as needed.
Figure 10-1-13. The timer’s howMuchTimeIsLeft function returns the value of timeLeft
The playGame method is created using a While statement that makes use of the
howMuchTimeIsLeft function in its conditional expression, as illustrated in Figure 10-1-14.
The code in this example is not really a game—just a demonstration of some code that repeats
until the time left on the clock reaches zero. Nonetheless, it illustrates how a block of game
instructions can be controlled by the timer.
Figure 10-1-15 illustrates an initial scene, with a city terrain (City) and a corvette added to
an initial world.
We want to allow the user to steer the car using the left, right, up, and down arrow keys.
Alice has a built-in event Let the arrow keys move 6object7 but this does not work the way
steering a car works in the real world. Using the built-in event, the left arrow moves the car
left sideways and the right arrow moves the car right sideways—not a very realistic motion.
To steer the corvette, we will turn its front wheels right and left in response to a right or left
arrow key-press, and the corvette should move forward and back up in response to an up or
down arrow key-press.
To design and write the program code for this animation, it is important to understand
that the left and right arrow keys will be used to steer the car left and right and the up and
down arrow keys move the car forward or back. (In other words, the left and right arrow keys
do not move the car—they only turn the steering wheel.) This is true in a real car, as well;
turning the steering wheel left or right does not actually cause the car to move. You must press
the gas pedal and put the car in gear to make it move forward or back. So, think of the left and
right arrow keys as steering and the up and down arrow keys as a gear/gas mechanism that
moves the car forward or back. Four object-level methods will be needed: turning left and
right and moving forward and back.
One problem we need to figure out is how to keep track of which way the front wheels
have been turned. This is needed because when the corvette moves and the wheels have been
turned right or left, the corvette should move and turn right or left at the same time. Also, we
need to keep track of how much the wheels have been turned. For example, if the wheels
have been turned sharply to the left, a move forward should be sharply toward the left. We
can create a class-level variable, direction, that will track the amount the wheels have been
turned and whether they have been turned right or left, using a linear scale, as shown in
Figure 10-1-16.
⫺10 0 10
Left Right
Figure 10-1-16. Linear scale for tracking the amount the car has turned left or right
298 Chapter 10 Variables and Revisiting Inheritance
The direction variable value will begin at 0, meaning that the wheels are aligned straight
ahead with the front of the car. If the direction is 0 and the up arrow is clicked, the car will
move straight. When the left arrow key is clicked, the direction will be decremented by 1
(decrementing subtracts 1 from the current value). When the right arrow key is pressed, the
direction will be incremented by 1 (incrementing adds 1 to the current value). In other words,
a direction value 6 0 means the wheels are turned to the left, and a direction value 7 0
means the wheels are turned to the right.
As with real cars, you can turn the steering wheel only just so far. We arbitrarily chose
a linear scale of -10 to +10. This means the direction variable can store a minimum value of
-10 and a maximum value of 10. The minimum value limits how far left and the maximum
value limits how far right the car can turn.
Now, we can design the methods to make use of the direction variable for steering and
moving the corvette. The four storyboards are shown below. The left and right arrow story-
board design is to keep track of how much the wheels have been turned by incrementing or
decrementing the direction value. The condition of the If statement for the left arrow ensures
that the direction will never be less than -10 for a left turn and never greater than 10 for a
right turn.
Response: Response:
If direction > -10 If direction < 10
Decrement direction by 1 Increment direction by 1
The design of the up arrow storyboard is to move the corvette forward 1 meter and at the
same time turn the corvette based on the value of the direction. The down arrow storyboard
does the same thing, but in reverse. Each turn of the steering wheel is 2 degrees. (A complete
revolution is 360 degrees, so 2 degrees is 2/360 of a revolution. A maximum value for a direc-
tion of 10 would correspond to 20 degrees, a reasonable turn of the steering wheel in a fast-
moving corvette.)
Implementation
The first step in writing the code is to create the direction variable. Then the methods can be
written to make use of the variable. To create the class-level variable, select the corvette in the
Object tree, and then its Properties tab. Click on the create new variable button. Then, enter
the name direction and select Number as its type with an initial value of 0, as illustrated in
Figure 10-1-17.
The simplest methods to write are those to steer the wheels right and left. The
corvette.right method is illustrated in Figure 10-1-18 and the corvette.left method in Figure
10-1-19. In each method the direction variable has been used twice. The first occurrence is in
the If/Else statement—if the wheel has turned right less than 10 times, it is okay to turn it fur-
ther to the right. The second occurrence of the direction variable is in the increment (for
corvette.right) and the decrement (corvette.left) method calls. The forward and backup meth-
ods are illustrated in Figures 10-1-20 and 10-1-21.
10-1 Variables 299
Figure 10-1-18. The corvette.right method uses the direction class-level variable
You may have noticed that the forward and backup methods only use a turn right
instruction. The reason a turn left instruction is not needed is that the direction variable stores
negative values for a left turn. A negative direction for the turn right method will cause the
corvette to turn left instead of right.
To use the corvette in other worlds, rename it (we chose the name steerableCorvette)
and save out as a new class. An instance of the new steerableCorvette class will have its own
direction variable and right, left, forward, and backup methods.
The term access describes the action of “getting at” an individual element of the array.
We access individual elements in the array directly, using special array operations. Let’s use a
“real-world” analogy. An array is somewhat like a music CD. The CD contains a collection of
songs. The label on the CD lists the order of the songs. A CD player will allow you to use a
location index to select (access) a specific song to play. For example, if you want to play song
#5 on the CD, you can just select song #5 and play it. (Of course, you can also play the entire
CD from beginning to end, if you wish.)
Creating an array
To create an array, we begin by adding several objects to a world. (Just adding the objects to a
world does not create an array, but it is the first step.) Next we add an instance of the array
Visualization class (in the Visualizations folder of the local gallery). The Array Visualization
class defines properties and actions for an object especially designed to represent an array
structure. (Arrays are not actually visible objects. We created this visual representation to
make it easy to show you how an array works.) The last step is to add each object to the array
structure. The objects become elements of the array.
To demonstrate the steps in creating an array, let’s say that we want to create an array of
bugs, using five different bugs (from the Animals collection in the gallery). (You may find it
helpful to sit at a computer and try these steps as you read.) First, we select five different kinds
of bugs and add an instance of each to the world. Figure 10-2-1 shows a world with a beetle,
mantis, scarab, bee, and ladybug (Animals/Bugs).
Now add an instance of the ArrayVisualization class to the world. The ArrayVisualiza-
tion class is in the Visualizations folder in the local gallery, as seen in Figure 10-2-2.
A dialog box pops up, where you can add each object to the array, as seen in Figure 10-2-3.
A click on the new element button creates an entry named item0 in the editor. Click on
6None7 and select the object to be added to the array, as in Figure 10-2-4.
As each bug is added, it moves into its position in the array. Note that arrays start at loca-
tion 0. This step is repeated for each of the bugs. Figure 10-2-5 shows the completed array.
We number the locations in the array 0, 1, 2, 3, and 4. The location number is known as
an index. The beetle is in location 0, and we say it is “at index 0.” Likewise, the mantis is at
index 1, the scarab at index 2, and so on. (If you look closely, you can see the index number in
the blue box under each bug in Figure 10-2-5.) An important note about elements in an array:
an individual element cannot be in two locations at the same time! In other words, do not add
the same instance of a class to two different places in the array. For example, the mantis can-
not be in position 1 and also in position 3. Of course, you could have two different mantis
instances (mantis and mantis2), and both could be in the array (at different locations).
10-2 An array visualization using an index variable 303
Figure 10-2-5. The completed array—bugs are now elements in the array
The arrayVisualization structure has a variable named elements that contains a listing of
all the objects that have been added to the array, as illustrated in Figure 10-2-6. The order of
the elements in the elements variable matches the order of the objects in the arrayVisualiza-
tion structure. The elements variable keeps track of the location of each object in the array.
Figure 10-2-6. The elements variable maintains a listing of ordered elements in the array
But wait a minute! This instruction will turn the whole arrayVisualization structure
around. This is not what we intended. What we really want is the element at index 3 to spin
around. The instruction must be modified to access the specific element at index 3. This is
where we can use the elements to specify the index of the element we want. Drag the elements
tile into the editor and drop it in place of arrayVisualization in the turn left instruction. From
the popup menu, select the index 3, as shown in Figure 10-2-8.
Now that the statement is complete, the program can be run to test the statement.
Repeated runs should make different bugs in the array spin around.
With a temporary holding space now available in the world, a method can be designed to
perform the three steps in a swap. Two number parameters will be needed to identify the index
position of the elements to be swapped. The indexOne parameter will be the index of the first
element and indexTwo the index of the second element. A storyboard for the method could be:
306 Chapter 10 Variables and Revisiting Inheritance
swap
Parameters: indexOne, indexTwo
Do in order
relocate element at indexOne to objectVisualization temporary location
relocate element at indexTwo to indexOne
relocate element from objectVisualization to indexTwo
The only thing left to do is translate the storyboard into program code. The curious
thing about this storyboard is that the three steps within the Do in order do not use move
instructions. The term relocate is used to indicate that more is involved than just moving an
object from one place to another. A special let instruction is used to relocate an element in an
array. The let instruction moves the element and also updates the elements variable to keep
track of the change in location index.
To write the code for this method, first we need to relocate the element at indexOne to
the objectVisualization temporary location. Select objectVisualization in the Object tree, click
on its methods tab, and drag the let instruction into the editor. In the popup menu, select
arrayVisualization. This process is illustrated in Figure 10-2-13.
Figure 10-2-13. Drag in let instruction and select item from popup menu
Of course, we do not want the entire arrayVisualization structure to move into the tem-
porary location, so we use the arrayVisualization’s function the value at to select an element
from the array. The indexOne parameter is selected as the index location. Figure 10-2-14
shows the result.
Figure 10-2-14. A let instruction to relocate an element to the temporary holding space
10-2 An array visualization using an index variable 307
Finally, create the instructions to relocate the elements in the array. This is done by
dragging the let instruction for the arrayVisualization into the swap method and selecting the
indexOne and indexTwo parameters, as needed. Figure 10-2-15 shows the completed swap
method.
To test the program, create an instruction to call the swap method. Pass in the position
of the two elements to be swapped. For example, calling the swap method, as shown in Figure
10-2-16, swaps the beetle (at index 0) with the mantis (at index 1). Figure 10-2-17 illustrates
the beetle and the mantis in swapped positions.
As the beetle and mantis are swapped around, the elements variable is automatically
updated. Figure 10-2-18 shows the elements variable before and after swap is run.
Figure 10-2-18. Elements swap locations and the elements variable is updated
308 Chapter 10 Variables and Revisiting Inheritance
The loop executes five times—the loop count (index) starts at 0 and increases by 1 each
time (0, 1, 2, 3, 4). The first execution of the loop, the index is 0 and the beetle (at index 0)
turns one revolution. The second execution of the loop, the index is 1 and the mantis (at index 1)
turns around, and so forth. Eventually, each element in the array is accessed in succession.
Creating a watch
Creating a watch is like hiring a private investigator to snoop on someone. The “private eye”
sets a “tail” on that person and keeps a constant watch on his/her activities. In Alice, a watch
creates a small window where the value in the watched variable is constantly displayed at run-
time. Every time the value changes, it is immediately updated in the watch window.
As an example, let’s create a watch on the direction variable used in the corvette steering
example presented in this chapter. To create a watch, right-click on a variable and select watch
this variable, as illustrated in Figure T-10-1.
After a watch has been created, a run of the animation is displayed in a split window. One
panel displays the animation while another panel displays the value of the watched variable.
10-2 An array visualization using an index variable 309
You may recall that the direction variable is used to track the amount the corvette’s steering
wheel has been turned left or right. The direction amount is then used to guide the movement
of the corvette. In Figure T-10-2(a), the value stored in direction is 0, and the corvette moves
straight ahead. In Figure T-10-2(b), the value stored in direction is -2 and the corvette is
steering toward the left. Viewing the direction value and the resulting motion of the corvette
in the animation confirms that the animation is working as designed.
Text output
The print instruction in Alice is another way to keep an eye on the value stored in a variable
at runtime. As with the watch feature, the print instruction causes the animation to be dis-
played in a split window. One panel displays the animation, while another panel displays out-
put in a text console.
As an example, let’s modify the steering corvette program to use print instructions to dis-
play the value in the corvette’s direction variable. In this program, the direction variable is
incremented each time the right arrow key is pressed and decremented each time the left arrow
key is pressed. All that needs to be done is to add a print instruction to the corvette.right and
corvette.left methods. Figure T-10-3 illustrates dragging a print instruction into the corvette.left
method. From the popup menu, we selected object : expressions : corvette.direction.
The modified corvette.left method is shown in Figure T-10-4. A print instruction is also
created for the corvette.right method. After the print instructions are created, a run of the ani-
mation and a text console are displayed in a split window. The first left or right arrow press
causes the text console to appear. Thereafter, the mouse can be used to activate/deactivate the
text console. Clicking the mouse on the animation panel activates the text console; moving the
mouse elsewhere on the screen deactivates the text console. A sample run is illustrated in
Figure T-10-5. (On some machines, the runtime window must be resized to make it large
enough to view the text console.)
If the text console is active, each left arrow or right arrow key-press causes the value
stored in the direction variable to be displayed on the next line in the text console. In this way,
a text console provides a history of the changes in a variable’s value.
310 Chapter 10 Variables and Revisiting Inheritance
Figure T-10-2. (a) and (b) Screen captures of a watch window at runtime
Summary
In this chapter we reviewed the use of properties to store information about an object in a
world. We call this state information. Then we introduced the term mutable variable to
describe those properties that can be changed at runtime. The mutable variables we presented
were class-level. Class-level variables keep track of information about a specific object.
We added a new class-level variable to an object and then saved out the object and its
new variable to create a new class. This is a form of inheritance similar to the technique used
in previous chapters, where we defined our own methods and saved out the object and its new
methods as a new class. The difference is that previously we extended a class by adding
behavior (methods), while in this chapter we extend a class by adding state information.
An array visualization was created to illustrate the concept of an array structure. In
Alice, an arrayVisualization object has a built-in elements variable that tracks the index (posi-
tion) of each element in the array.
Programming Terms
access mutable variable state of an object
array property of an object
index variable size of an array
Animation Terms
array visualization
Questions
1. List two built-in properties of an object that are indirectly changed by instructions such
as move or turn to face.
2. Which button in the details panel of an object allows you to create your own property
for an object?
3. What instruction can be used to directly change the value of a property?
4. What does it mean to say that a variable is mutable?
5. List two ways to modify a class and save it out as a new class.
6. What is the difference between an object-level variable and a world-level variable?
7. In what way(s) is an array similar to a list (as described in Chapter 9)?
8. What is the purpose of an index variable in an array?
9. In Alice, an arrayVisualization may be created by clicking on the arrayVisualization
thumbnail image in the Visualizations folder of the Gallery. If you add an
arrayVisualization to your world, is it an object or is it an array? Explain your answer.
10. Name the built-in method for an arrayVisualization that allows your program to access
an individual element in the array being visualized.
Exercises and Projects 313
3. Binary Switches
Digital electronics is based on the use of high and low currents to represent binary val-
ues. A high current flowing through a circuit represents the digit 1 and a low current the
digit 0. Thus, a single circuit represents a single binary digit (a bit). A nibble is a com-
bination of four circuits (4 bits) put together to represent numbers in base 2 (binary
numbers). A byte is eight circuits (8 bits).
As a review, let’s compare our base-10 number system to the base-2 number system. A
base-10 number is created using digits 0 through 9. The following example breaks
down the base 10 number 5932:
Like base-10 numbers, the first column from the right represents 20 or 1, the second col-
umn represents 21 or 2, the third 22 or 4, and the fourth 23 or 8. Here is an example of
how the base-2 number 1001 is converted to its base 10 equivalent:
23 22 21 20
1 0 0 1
11 * 232 + 10 * 222 + 10 * 212 + 11 * 202
11 * 82 + 10 * 42 + 10 * 22 + 11 * 12
8 + 0 + 0 + 1
= 9
This exercise is a simulation of a byte of computer memory. Create a world with four
switches, each with an onOff Boolean variable. Above each switch, insert 3D text for
the number 0, and centered above these, four 0s. Then add an additional 0, as shown
below. Create an event handling method to set the 3D text above a switch to 0 when the
switch is off (down) or to 1 when the switch is on (up).
The top-level 3D text digit is to be the base-10 representation of the binary num-
ber represented by the zeros and ones below it. Write a method called findResult that
converts the base-2 number represented by the switches to a base-10 number and
change the top-level 3D text to this base-10 number each time a switch is clicked and
switched. The easiest way to make this work is to create a number variable for each 3D
text object that represents the digit value to which its text is set. Also, modify the on–off
event handling method so that in addition to changing the 3D text above it to 0 or 1, it
also sets its value variable to the corresponding 0 or 1 and then calls the findResult
method.
Hint: Use the following formula: 1a * 82 + 1b * 42 + 1c * 22 + 1d * 12, where a, b,
c, and d represent the 0s and 1s in the appropriate columns. In the World’s functions
under String you will find the option 6what7 as a string. This will convert the integer
result to text that can be displayed by the base-10 3D text.
10.2 Exercise
6. All Possible Permutations
A permutation is a rearrangement of a set of objects. For example, a permutation of the
numbers 1, 2, 3 could be 2, 1, 3 or it could be 2, 3, 1. How many possible permutations
are there?
Create an array containing three 3D text number objects, as shown below. Write
the swap method as illustrated in Chapter 10, Section 2. Then write a program that calls
the swap method to show the numbers moving around to create a permutation of the
numbers. Call the swap method with different parameters so that all possible permuta-
tions can be seen.
When a field goal kicker kicks a football, the football moves through the air in a
parabolic path because the motion of the ball is effected by gravity. As the ball travels
upward, gravity slows it down until it stops (briefly) at its peak height. Then, the ball
starts to come down and gravity speeds it up until it hits the ground. Two major factors
influence the path of the ball: velocity (the speed of the ball) and the angle of the kick.
The diagram below illustrates the effect of the angle of the kick.
316 Chapter 10 Variables and Revisiting Inheritance
80 degrees
(1.396 radians)
30 degrees
(0.524 radians)
Ask the player to enter the angle of the kick (in degrees) and the initial velocity of the
kick (in meters per second). Together, the velocity of the ball and the angle of the kick
determine how long the ball will remain in the air (the “hang time”), how high the ball
will go (the “peak height”), and how far the ball will go (the “range”).
To compute the path of the football, first break the velocity down into two compo-
nents: horizontal (speed along the x-axis) and vertical (speed along the y-axis). The for-
mulas for computing horizontal and vertical velocity are shown below. Note that the
angle of the kick must be converted from degrees to radians.
horizontal Velocity = cos(angle of the kick, in radians) * initial velocity
vertical Velocity = sin(angle of the kick, in radians) * initial velocity
To compute the hang time, use the formula:
hang time = 2 * vertical Velocity / 9.8
Once you have the horizontal velocity, the vertical velocity, and the hang time,
you can then animate the football’s motion by repeatedly computing the position of the
ball (at each instant in time during the hang time ) and moving the ball to the new posi-
tion at that time in the flight. For example, compute the position after 0.2 seconds has
elapsed and move the ball to that position, then compute the position after 0.4 seconds
has elapsed and move the ball to that position, then compute the position after 0.6 sec-
onds … and so forth. To compute the position of the ball (in x and y coordinates) after a
specific lapse in time during the hang time, use the formulas:
x = horizontal velocity * elapsedTime
y = 0.5 *-9.8 * (vertical velocity * elapsedTime2) + (vertical velocity * elapsedTime)
Sample test data: With an angle of 30 degrees and a velocity of 27 m/sec (about
90 ft/sec), the hang time should be approximately 2.8 seconds and the ball should travel
about 66 meters forward from its original position on the ground.
Hints: We recommend using a loop that repeats while the elapsed time is less than the
hang time. Each time the loop repeats, increase the lapsed time by a very small amount
such as 0.2 seconds. Update the position of the ball each time through the loop, by mov-
ing the ball forward the change in x position and up the change in y position.
Projects
1. Record and Play a Song
The goal of this project is to allow users to record their own song and play it back. This
project is an extension of project 5, from Chapter 5. If you already created the AlicePi-
ano project, reuse it for this project. Otherwise, please refer back to project 5, Ch. 5, and
create the project, as described. To the AlicePiano world created in Ch. 5 project 5, add
four control “buttons.” These buttons can be created using different shapes and 3D text,
as shown in the screen capture below.
In a carnival game, you win a prize if you pick the winning horse. In this game,
the player will pick the horse by clicking one of the circles at the beginning of the track.
For example, if the player clicks on the green circle, the player picks the horse in the
nearest track. Create a class-level Boolean variable named isClicked for each of the cir-
cles. The isClicked variable should be false. When the player clicks on the circle,
change isClicked to true and start the game.
When the game begins, use a Do together to move all three racehorses forward a
short random distance. This action should be repeated until one of the horses gets to the
finish line and wins the race. You can use either a While loop (Chapter 7) or recursion
(Chapter 8) to repeat the action until the race is over.
An essential step is to know when the game is over. Write a function named
isGameOver that asks: “Is a horse within 0.5 meters of the finish line?” We suggest 0.5
rather than 0 meters because the distance between the finish line and the horse is meas-
ured from the horse’s center, not from the tip of its nose. (You may need to adjust this
distance, depending on how much you resized the raceHorseGame object in setting up
the initial scene.)
Exercises and Projects 319
Write a function named whichHorseWon that returns the horse that is closest to
the finish line. When the loop ends, determine whether the player picked the winning
horse (use the circles’ isClicked variable). If the player has selected the winning horse,
display the message “You won!” If not, display “Try again!” Because of the random
distances used in this program, different horses should win the race if the program is run
several times.
3. Game: Freestlylin’ Frostee
This project is an extension of Project 1, from Chapter 6 “Help the Snowman Get
Home.” If you did not complete Chapter 6. Project 1, please refer to that project’s
instructions on creating the original world scene. For this project, modify the original
scene by removing the igloo and adding at least 20 more pine trees (Nature). Also add
12 ramp objects (Skate Park) positioned here and there between the trees.
The object of this game is to challenge the player to use keyboard control keys to
steer Frostee over as many ramps as possible before the clock runs out, while avoiding
collisions with the trees. The player earns points by going over the ramps and landing
on the other side. The player loses points each time Frostee collides with a tree.
When the world starts, display game instructions using a billboard. Create a but-
ton (located in front of the billboard) to allow the user to click on the button to start the
game. The rules of the game are:
• Use the arrow keys to steer the snowman through the woods and over the ramps.
• Each ramp jump earns 1 point; 6 or more points wins game.
• Collision with a tree takes away 1 point.
• Passing through a lightening bolt boosts Frostee’s speed.
• When time runs out, the game is over.
Create while key is pressed (BDE) events for each of the arrow keys to move the
snowboard (with the snowman along for the ride). Create methods to have the snow-
man’s body tilt at the beginning and return to upright at the end of each snowboard
right/left move actions.
Use 3D text objects to display the player’s score and the number of seconds
remaining in the game. If the player scores 6 or more points before time runs out, dis-
play 3D text to say the player won the game. Otherwise, display 3D text to say the
player lost and to please try again. The camera should follow the snowman as he winds
down the slopes, and the player should be able to see the score and the timer while the
game is being played.
320 Chapter 10 Variables and Revisiting Inheritance
Create world-level lists to organize the pine trees, one list for each 12 trees. You
can then check whether the snowman has collided with a tree by using For all together
to determine whether the snowman is within 2 meters of any tree in each list. If so, then
the snowman should blush and say OUCH!!. Be sure to return the snowman’s color to
normal and reduce the score by 1 point.
Similarly, create a list of the ramps. Then, create an event that continuously calls
a method to check the ramps while the world is running. The checkRamps method can
use a For all together loop to check whether the snowboard is near enough to a ramp to
ski over it. If so, call a method named jumpRamp that has the snowboard (with Frostee
on board) ski up, over, and then drop down to the other side of the ramp. Also, add 1
point to the score.
To allow the player to choose whether the stingray or the shark will be the taxi,
add two cones and label each with 3D text indicating a choice of either shark or stingray
taxi. If the player clicks on the shark cone, show the shark and hide the stingray. If the
player clicks on the sting ray cone, show the sting ray and hide the shark.
Exercises and Projects 321
After the player makes a choice of which taxi scubaDiver will ride, display a start
sign, that the player must click to start the game. Create a gameStart method that is
called when the start sign is clicked. The gameStart method should make the start sign,
shark cone, sting ray cone, and 3D text labels disappear. Then, scubaDiver (and the taxi)
should turn one-half revolution to begin the game, as shown in the screen captures here:
ScubaDiver gets paid for each fish that he picks up and drops off. To keep track of
the number of fish passengers, create a 3D text transportCount object that will be used
to display the count of the number of fish scubaDiver has successfully picked up and
transported to a remote destination. Display the transportCount in the upper left of the
scene. Additionally, create a 3D text tankMeter object that will be used to display the
number of seconds of air remaining in Steve’s scuba tank. Display the tankMeter in the
upper right of the scene. The camera should follow scubaDiver as he rides around the
underwater world. During the play of the game, the transportCount and the tankMeter
should always remain in sight of the camera.
To give the illusion of an underwater scene, create a method for the scuba diver
(and the taxi) to continuously move up and down 0.15 meters. Create two world-level
lists to organize the lilfish and the seaweed objects and then create methods to have
each seaweed object sway gently in the water and each fish to swim around randomly.
The random swim can be a simple move forward and turn (min –0.2 to max 0.2) at the
same time. The seaweed should sway continuously while the game is running.
Use the arrow keys to guide the taxi around the scene looking for a passenger (as
do taxi drivers in a real-life city). Create two world-level methods named pickUpFish
and dropOffFish. If scubaDiver is near to a fish and the player presses the letter “P”,
then a lilfish hops in the taxi. scubaDiver can carry only one passenger at a time, so
immediately help scubaDiver by steering to the remote destination. While the fish is in
the taxi, it should not be swimming away from the taxi. When scubaDiver gets close
enough to the destination and the player presses the letter “D”, the fish is dropped off
and should start swimming away randomly once again.
To win the game, scubaDiver needs to drop off at least five fish at the destination
target within two minutes to have enough money to buy food for the shark and stingRay.
The game continues until the tankMeter reaches zero. Create an endGame method that
uses a 3D text object to display whether the game is won or lost.
Hints: You may find it helpful to use Boolean variables to track when a fish is in the taxi
(so another fish cannot be picked up at the same time) and when the game is over (so the
player cannot continue to play the game after the tankMeter counts down to zero.)
Chapter 11
What’s Next?
We expect that many students who are using this book as a text will decide to take another
course in programming. If you are one of these people (and we sincerely hope you are), you
will need to make a transition from Alice to another programming language.
As we write this book, the most likely language you will learn next is Java, C++, or C#.
These are all object-oriented languages. This is great, because the Alice programming lan-
guage has a distinct object-oriented flavor. Alice does, however, differ in some ways from the
so-called “real-world” languages. The reasons for the differences are clearly the underlying
goals of the languages. Java, C++, and C# are designed for general-purpose programming of
workhorse applications in a world of commerce, Internet communication, and scientific
research. Alice was designed to achieve two very different goals: (1) to provide a program-
ming environment for 3D graphic animations, and (2) to provide a high-impact visualization
tool that can enjoyably be used for learning to write computer programs.
It is not within the scope of this book to introduce another programming language.
What we can do, however, is summarize the concepts you have learned with Alice that pre-
pare you to learn another language. Also, we can point out a major change you will encounter
as you move from Alice’s drag-and-drop editor to a text editor, where details of writing a
statement in a program become important. This chapter demonstrates a feature of Alice that
will help you make that change.
2. Design: Although simple programs require only small amounts of planning, large and
more complex programs require that some thought be put into how the program will be
written. One design technique you have learned is a textual storyboard, which is much
like a to-do list. Another technique you have learned is stepwise refinement, which
allows you to start thinking about the overall process and progressively break the steps
down into simpler and simpler actions. These same design techniques are commonly
used in planning Java programs. Other techniques can be used, as well. But, the overall
idea is the same—plan before you begin writing code.
3. Implement: Writing program code takes some organization in an object-oriented lan-
guage such as Java. Classes and methods must be written. Objects must be instantiated.
Methods must be called and arguments sent to parameters. The control statements used
in the program code are decisions (If/Else), loops (For and While), and recursion. Exe-
cution can be sequential or simultaneous. As you have learned to program in Alice, you
have gained experience and understanding of these concepts.
4. Test: Testing is one thing we definitely respect as part of the programming process. No
doubt you have discovered that testing often reveals a bug in a program. Then the pro-
gram has to be revised, which sends us back into the design and implementation steps.
This is OK. No one is expected to sit down and write perfect code on the very first try.
In fact, we often learn from our mistakes!
A major change
A major change you will encounter is the move from using Alice’s drag-and-drop editor to
a text editor. To write a program in Java, for example, you will use a text editor and type in
your program. Figure 11-1-1 shows a simple Java program, as written in a text editor.
Although we are not trying to introduce how to program in Java, a quick explanation of the
program will be helpful. A Java program is made up of one or more class descriptions, where
properties (variables) are declared and methods are defined. This example has one class,
named SimpleProgram. In the SimpleProgram class, one method, main, is defined. In this
very simple example, the only statement in the main method is to print a line (println) of text:
“This is a simple Java program!” (Java does have graphics—but are much more complicated
to use than graphics in Alice.)
As you look at this Java program, you may realize that moving from a drag-and-drop
editor to a text editor involves more than just typing the program instructions (as compared to
simply dragging in the instruction tiles). As you write the program statements, you will need
to type various symbols such as curly brackets, parentheses, commas, quotes, and semicolons.
Also, you will use some Java words such as public, static, and void.
Syntax
The symbols and words you saw in the simple Java program above are part of the syntax of
the Java programming language—the rules about how a Java statement can be written. All
languages, both human and computer, have rules about how to write statements. Statements
must begin with certain kinds of words, which are followed by other kinds of words, which
324 Chapter 11 What’s Next?
are followed by other kinds of words, and so on. Furthermore, punctuation marks such as
commas, quotes, semicolons, and parentheses are sprinkled liberally throughout. For exam-
ple, in the English language we can write a statement:
The panda moves forward 1 meter.
The statement begins with a capitalized word and ends with a period. The noun phrase
of the statement (“The panda”) is followed by the verb phrase (“moves forward”). To write a
statement like this:
forward 1 panda the moves meter
is an error because the order and punctuation do not follow the rules. Figure 11-1-2 illustrates
the syntax of a typical statement in Alice. The tiles and colors give visual clues to the differ-
ent parts of the statement.
object method
arguments
Syntax rules can be frustrating because you have to learn where all the punctuation
marks go and the order in which the words must be positioned. In Alice, the editor for writing
statements is purposely designed to reduce the frustration for beginning programmers. You
drag and drop the parts of a statement into the editor, and it enforces the rules of the language,
so you have not had to worry about syntax errors.
Syntax switch
To help you prepare for learning a real-world language (such as Java), you can turn on a Java-
style switch in Alice. The style switch is a setting in the Edit/Preferences menu. To turn on
Java-style, first select Edit from the main menu bar at the top of the Alice interface and then
the Preferences menu item. In the General tab of the Preferences menu, select the Java Style
option, as illustrated in Figure 11-1-3. The style switch acts as a toggle switch that can be
turned on and off to suit the programmer’s preferences. To return to the default Alice-style
display, simply set the style switch back to the Alice Style setting.
Technical Note: On your computer, setting the style switch may require that Alice be shut
down and then restarted for the switch setting to take effect.
Once the syntax switch has been set, statements in the editor are more detailed and
include symbols and words like those that appear in a Java program. The statement from
Figure 11-1-2 is displayed using Java-style in Figure 11-1-4.
Syntax details
Let’s take a look at some of the details of Alice instructions displayed using Java-style syn-
tax. First look at the method signature, circled in Figure 11-1-5. A method signature
always begins a method definition in a Java program. The name of the method contains no
blank spaces. Alice’s my_first_method is similar to the main method in Java—it is the first
method executed when the program runs. The word public means that it can be called from
anywhere. (In Alice, all methods are public.) The word void means that it does not return
326 Chapter 11 What’s Next?
any information. In other words, it is not a function that sends back some information to a
calling method.
A second detail to notice is the use of punctuation symbols. We have circled some punc-
tuation symbols in Figure 11-1-6. A dot (.) has been placed between the object named panda
and the method named move. The arguments are enclosed in parentheses and separated by
commas (UP, 1 meter), and the entire statement now ends with a semicolon (;). This is exactly
how these punctuation symbols are used in Java statements. Finally, notice that two curly
brackets have been added to enclose statement(s) within the method, as circled in Figure 11-1-7.
As you know, a method is a block of code (possibly several instructions), and blocks of code
in Java are marked by enclosure in matching curly brackets.
You can look at the Alice programs you have already written to get an idea of what sim-
ilar statements would look like in Java. This will give you a head start in learning Java or
another programming language.
11.2 Alice 3 327
11.2 Alice 3
In addition to the transition mechanisms described in the previous section, the Alice develop-
ment team has been working on building Alice 3. At this writing, Alice 3 is currently in beta
version, so it will not be covered in great depth in this book. “Beta” software means that it is
still undergoing development and that there are likely many bugs that early users of the soft-
ware will identify, and that the development team can then fix. For those of you who are dar-
ing, and willing to help the Alice development team, please go to www.alice.org, and
download the latest version of Alice 3 and its accompanying NetBeans plugin. Be sure to
carefully follow the download instructions, which also require that you download the latest
version of Oracle’s Java Development Kit (JDK) as well as the NetBeans Integrated Develop-
ment Environment (IDE). Both the JDK and NetBeans are free and should be downloaded
and installed prior to installing Alice 3 and the plugin for NetBeans.
One of the main purposes of Alice 3 is to ease the transition from programming in Alice
to programming in Java. Alice 3 does so by allowing students to learn the fundamental concepts
in Alice 3 and then re-create and expand the same animation programs in Java, by typing actual
Java instructions, including Alice animation instructions. The intended result is a transfer of
concepts learned in Alice to the same concepts in Java. Let’s look at how this works by using a
simple Alice 3 world as an example. Consider the following scene, shown in Figure 11-2-1.
Suppose that we wanted to teach the chicken how to peck. Consider the code that could
be written in Alice 2.2. A method such as the one illustrated in Figure 11-2-2 could suffice.
Now, you can write the same code in Alice 3. Please note that Alice 3 is regularly undergoing
changes. It is possible that the beta version of Alice 3 used in the creation of this example may
be slightly different from the version that you download. Within the Alice 3 environment, the
code for the chicken to peck appears as Figure 11-2-3.
However, the code can also be generated in Java by saving the project (including the code for
the peck method for the chicken) and then opening the Alice 3 project in NetBeans. Alterna-
tively, it is possible to simply set up the initial scene in Alice 3, save the project, and then open
the project in NetBeans. This will allow you to directly type the Java code corresponding to
the peck method. The Java code for the peck method is shown in Figure 11-2-4.
– import org.alice.apis.moveandturn.gallery.animals.Chicken;
import org.alice.apis.moveandturn.*;
– public MyChicken() {
}
In summary, while this section of the text is not intended to provide a tutorial on how to use
Alice 3, it is intended to illustrate the possibilities that Alice 3 does and will provide in helping
you transfer the programming concepts learned in Alice directly into Java!
The ballerina’s body is upright, the arms are outstretched, the feet are positioned with the heels
together, and each foot is turned outward.
Suppose a program is written to have the ballerina begin in a first-position pose and then
perform several ballet movements. Once the animation has been played (and the arms and
legs of the ballerina are now in different positions), a click on the Restart button will cause the
ballerina to resume her initial location and pose, so that the animation can play again.
330 Chapter 11 What’s Next?
You can use the scene editor to arrange an object in other poses and ask the object to
remember them. Use the mouse and object methods to position the body parts of the object into
the desired pose. Then click on the capture pose button in the object’s Details panel and enter
a name for the pose. Figure T-11-2 illustrates the capture of an onToe pose for the ballerina.
Now you can write instructions to make the ballerina assume the pose during an anima-
tion. To create an instruction using a pose, drag the pose tile into the editor, as illustrated in
Figure T-11-3.
Note: A few words of caution about poses: resizing an object may have an unpredictable
effect on poses. For this reason, we recommend that capturing a pose be the last step in cre-
ating an initial world. Also, we suggest avoiding poses if objects are being resized during
the animation.
Appendix
331
Figure A-1-1. Alice shortcut icon on the desktop of your computer
Figure A-1-5. Opening AppendixA_FirstWorld from Textbook examples in the dialog box
Select AppendixA_FirstWorld and click the Open button. The bee and hare objects
are displayed in the world that opens, as shown in Figure A-1-6. The Object tree lists the
objects in the world.
Click Play to run the world.
Figure A-1-6. Play button at top, Object tree on left, First World initial scene on right
Take a close look at the controls at the top of the animation window (Figure A-1-7).
Some buttons, such as Pause and Restart, are obvious. The Take Picture button will take a
single snapshot of the animation and save it as a graphic image file. (A popup dialog box
states where the image was saved. You can change the default location for saving images in
the Edit/Preferences/Screen Grab menu.) The Speed slide control allows you to adjust the
speed of the animation.
334 Appendix
Of course, the speed of the animation is affected by the capabilities of your computer
hardware. A helpful hint is that the size of the window in which the animation runs (the
World Running window) affects the speed of an animation. If your animation is running too
slowly, make the window smaller. (Grab the lower right corner of the window with the mouse
and drag the window to the size you want.) After the window size is changed, Alice will
remember it the next time you play an animation.
Close the animation window for the FirstWorld (use a mouse-click on the X at the
upper right of the animation window or click the Stop button).
World 2
World 1 (FirstWorld) is a “movie” style of animation. A movie runs from beginning to end
while you, as the human “user,” view the animation. Let’s look at a world that is interactive
where you can make choices as to how the animation works.
Use File : Open World to open the dialog box.
In the dialog box, select Textbook and then AppendixA_Dancing Bee, as shown in
Figure A-1-8.
Click Play.
Then, try each of the two choices (keys can be pressed in any order):
1. Press the up arrow key
2. Press the space bar
When you have finished viewing the animation, close the window.
This world uses the same initial scene as in the first world, viewed above, but the program
has been changed to be an interactive, event-driven animation. Pressing the up arrow key cre-
ates an event. Alice responds to the up arrow event by making the hare jump. Pressing the space
bar creates a different event. Alice responds to the space bar event by making the bee perform a
pirouette in flight. This world is an example of an interactive, event-driven animation.
Summary
Here’s a recap of what we just covered with Worlds 1 and 2. If you’re not comfortable with
any of these topics, go back to the start of this section and go through it again.
Appendix A: Using Alice 335
Saving a world
Each time a new world is created, it is a good idea to save the world. Then, if the computer
crashes or loses power (it can happen, even on the best of machines!), your work will be safe
to reload when the computer is rebooted. A world can be saved to any one of several different
locations (desktop, file server space, hard drive, or a memory stick).
336 Appendix
Navigate to the folder (directory) where you plan to save your world, as shown in
Figure A-1-11. We recommend that you create a folder named AliceWorlds where you will
save all your animations.
Make up a name for your world—we recommend a single word name, such as Snow-
manExercise, that uses upper- and lowercase characters. Enter the name for your world and
then click the Save button, as shown in Figure A-1-12.
Your world will be saved with the .a2w extension (an Alice version 2 world).
Appendix A: Using Alice 337
As you work on your world, Alice will periodically prompt you to save your world. We
recommend that you save the world every half hour or so. Alice automatically makes backup
copies of your world when you save it. The folder is named “Backups of. . . .”
Alice opens the Scene Editor. A visual directory to the Local and Web galleries is pro-
vided for access to 3D models. A Search Gallery button allows you to search for a particular
kind of object. (See Appendix B for more details on searching for an object.)
Figure A-1-16. Two options: drag and drop or click to add an object (instance)
Note: Drag and drop works relative to the ground. If the ground is deleted from a world,
the drag-and-drop technique cannot be used to add an object to the world.
Appendix A: Using Alice 339
Note: The models in the Web Gallery may take longer than the models on the DVD to
load, depending on the speed of your connection.
Follow the same procedure as outlined above to add a snowman object from the
online People collection of 3D models.
This illustrates an important point—you don’t have to worry about messing things up.
Use Undo to get back to a previous position.
On the far right of the scene editor is a toolkit of buttons that allow you to select the way
the mouse moves an object in 3D space. By default, the horizontal (left–right, forward–back)
movement is selected.
One at a time, select each of the mouse control buttons and experiment with the
snowman using that control, as shown in Figure A-1-19.
For your reference, Figure A-1-20 identifies the actions of the mouse control buttons for
objects in a scene. The default button, labeled “move objects freely,” allows the mouse to
move an object left, right, forward, or back in the scene.
340 Appendix
2. Actually, a copy is somewhat like a ghost of the original object—not completely inde-
pendent. In most worlds, we prefer to add new objects. Delete the second snowman—
right-click on the second snowman and choose Delete from the popup menu.
3. Finally, click the mouse cursor in the mouse control buttons to stop copying objects.
Note: If the ground is deleted in a world, new objects can only be added using the
“Add instance” button (rather than a drag-and-drop action).
The world view window changes to a four-pane quad view. The four panes show Cam-
era, Top, Right, and Front viewpoints. Note that the vertical mouse control button is no
longer available because the Front and Right panes automatically have vertical movement.
The toolbox now displays a second row of mouse control buttons, containing a scroll and a
zoom button, as labeled in Figure A-1-24.
In the quad view shown above, the snowwoman is partially out of sight in the Top view.
(Your world may appear somewhat different than ours.) The scroll tool can be used to reposition
the viewpoint in a pane. As shown in Figure A-1-25, we used the scroll control to reposition
the Top view pane.
Another useful feature is the zoom tool. The zoom tool can be used to zoom in or out in
a pane. As shown in Figure A-1-26, we have used the zoom tool to zoom out in the pane that
shows the view from the top.
Click single view to return to a single pane in the scene editor, as shown in Figure A-1-29.
Click and drag on the camera controls to get an idea of what each camera control does.
You can always use Undo to return to a previous camera position.
Summary
Here’s a recap of what you just learned with World 3. If you’re not comfortable with any of
these topics, go back to the beginning of this section and try it again.
Appendix A: Using Alice 345
Figure A-1-31. (a) All objects near center of world; (b) Objects rearranged in the scene
As seen in the Figure A-2-2, the frog is a bit small and it seems to fade into the grass,
making it somewhat difficult to see. This situation is great for camouflaging the frog from its
enemies but is not so good for an animation. You can use a resize method to make the frog larger.
Note: Resizing an object may have some unexpected results. An object standing on the
ground may sink into the ground. Reposition the object using the mouse, as needed.
The turn method makes an object turn in a given direction (forward, back, left, right)
by a given amount (in revolutions). An object moves relative to its own sense of direction
(orientation).
Use a turn method to turn the frog left 1/4 revolution, as shown in Figure A-2-4.
The roll method rolls an object left or right.
Use a roll method to roll the tree left 1/4 revolution, as shown in Figure A-2-5.
The stand up instruction makes an object’s vertical axis line up with the vertical axis of
the world. In other words, the object stands up!
Use a stand up instruction to put the tree back into an upright position, as shown in
Figure A-2-6.
Appendix A: Using Alice 347
The turn to face method makes an object turn to look toward another object.
Use turn to face to make the frog face the tree, as shown in Figure A-2-7.
Figure B-1-5. Drag instructions from the clipboard into the editor
Note that a clipboard can hold only one set of instructions at a time. If instructions were
previously copied to the clipboard, copying a new set of instructions to the same clipboard
will overwrite (destroy) what was already there. As originally installed, Alice displays only
one clipboard. The number of clipboards can be increased by selecting the Edit menu and
Appendix B: Managing the Alice interface 353
then the Preferences menu item. In the Seldom Used tab of the Preferences window, modify
the number of clipboards, as in Figure B-1-6.
Deleting code
What if you make a mistake or want to change some code that you have created? The easiest
way to remove a line of code is to drag it to the wastebasket at the top of the Alice window.
An entire block of code can be deleted by dragging the block to the wastebasket, as illustrated
in Figure B-1-7.
Figure B-1-7. Dragging a block of code to the wastebasket to delete the entire block
354 Appendix
If you want to remove a Do together or Do in order block but keep the lines of code,
right-click on the block and select dissolve, as seen in Figure B-1-8. The lines of code
will be promoted one level and the previously enclosing block will be erased, as shown in
Figure B-1-9.
Figure B-1-9. After dissolve, the Do together block has been erased but the instructions remain
Figure B-1-10. Selecting the Export Code For Printing menu item
Appendix B: Managing the Alice interface 355
A Save World for the Web dialog box allows the entry of a title, width and height of
the world window to be displayed in a browser, and a location where the Web files will be
saved, as illustrated in Figure B-1-13. (The location in the Save Location box cannot be a
URL.) A click on the Save button causes Alice to save three files to the directory you select:
the usual .a2w file, an .html file, and a Java archive (.jar) file.
To allow others to view your world via the Internet, you must store the three files on a
Web server. All three files must be in the same directory. The first time someone downloads a
page, it will take a few seconds (depending on the speed of their Internet connection) because
of the size of the Java archive file. The viewer’s computer must have a Java-enabled browser,
and the viewer must also have downloaded and installed Java 3D and Java Media frameworks,
available from Oracle’s Sun Developer Network Check the Alice 2.2 downloads page at
www.alice.org for links to the Java 3D and Java Media Frameworks download sites.
356 Appendix
Export a video
Alice version 2.2 has implemented an export video option. If you have this version installed
on your computer, you may use it to create a video in QuickTime™ format.
The example world shown in Figure B-1-14 will be used to illustrate the steps for using
Alice 2.2 to create a video.
Open the File menu and select Export Video, as shown in Figure B-1-15.
Appendix B: Managing the Alice interface 357
A “save as” dialog box will open, asking you to save your Alice world. Create a new
folder (on the desktop or some other location) and save the world in the new folder. This is to
allow Alice to store the video and any sound clips in the same folder. When the world has
been saved in its own folder, a video capture window will open, with the opening scene of the
current world displayed, as shown in Figure B-1-16. The video capture window is an expanded
version of the runtime window (the popup window that displays a world running when you
press Play in Alice). Two new rows of buttons are at the top of the video capture window.
The top two rows of new buttons allow you to control the creation of a video. The bot-
tom row (containing the Speed slider, Play, Pause, Restart, and Stop buttons) is the same row
of buttons displayed in the runtime window. In the video capture window, these buttons allow
you to preview the world before creating a video.
Creating a video has two parts. First, record the video. The top row of the video capture
window contains buttons for recording the video. Second, export to a video file. The second
row of the video capture window contains a textbox (for naming a video file), a pull down
menu (for selecting file format), and a button (for exporting as a file in the selected format).
The Export Video button is disabled until you have recorded a video.
To start the video capture, click the Record button, as shown in Figure B-1-17. The
world will start playing and Alice will capture the video (and, if needed, any sounds). While
recording, a red dot will appear in the upper right corner of the window and a timer will be
running to display the number of minutes and seconds being captured. In other words, the
timer shows the progress of the recording.
If you are creating a video of the play of an Alice game, you might want to skip the in-
structions at the beginning of the game before starting to record. To skip a couple of seconds
at the beginning, first click the Play button. The world will start to run but the video recording
will remain inactive. When you are ready to start the video recording, click the Record button
and the video capture will pick up from there.
As the world is being recorded, temporary screen captures are created and stored in a
folder named “frames.” If you click the Record button and Alice seems to “freeze up” or seems
to be taking a VERY long time to complete the recording, it may be that Alice is having a
problem trying to create the frames folder. This can happen because you are out of space on a
Appendix B: Managing the Alice interface 359
flash drive (or memory key) or because the folder you want to use is in a “read only” loca-
tion. Close the video capture window and then save the world to a different folder in a different
location on your computer. With the world in a different location, start over to create the video.
To stop recording, click the Stop Recording button, as shown in Figure B-1-18.
If something went wrong, you can click the Clear button, as shown in Figure B-1-19.
Clear will remove all temporary screen captures in the frames folder. Then, click the Reset
button to start recording from the beginning.
Once the recording step is completed, you are ready to export the recorded frames (and
sound, if any) as a video. First, enter a name for the video in the textbox, labeled “File name,”
as shown in Figure B-1-20. As can be seen, the MOV format has been pre-selected because
Alice 2.2 has only one option (MOV), which is a QuickTimeTM video. The pull-down menu is
provided as an option for future versions, which may have additional formats.
To complete the video creation, click the Export Video button, as shown in Figure B-1-21.
When the Export Video button is clicked, the temporary screen captures are encoded and
merged to create the video. As soon as the video exporter is closed the frames folder should
be automatically removed. However, if Alice does not remove the frames folder, you may
delete it without harming the video.
The video file should be in the same folder as your saved world. Figure B-1-22 shows a
folder window with the video created in this example world.
Notes: It is possible to recapture and write over the existing video. If you are recreat-
ing a video file, however, make sure that the current video file is not being used else-
where. (This means you should close QuickTimeTM, if you have not already done so.)
Also, if the frames folder still exists, delete it before recapturing the video.
360 Appendix
Figure B-1-21. Click Export Video button to save the video file
The use of sound in your Alice world tends to make a video file much larger. Try using
shorter-length sound files, if possible.
The video capture window is pre-sized to provide a reasonably sized video file. You can
resize the window before recording the video, but be aware that the larger the window, the
larger the size of the video file. Also, do not change the size of the window after the recording
has started, as this disrupts the size of the frames and the video will not turn out right.
Note: Alice, as an educational tool, provides this video export feature to support the
creation of short movies (less than 2 minutes) with short sound clips. If you need to
create a more expansive video, we recommend you try a commercial package such as
jing (PC), Camtasia (PC) or videoCapture (Mac).
362 Appendix
!=, not equal to operator, 72, 189 Animation, 14–15, 76–81. See also Movement; Special
( ), argument parentheses, 326 effects
*, multiplication operator, 72 frame sequence, 14–15
-, subtraction operator, 72 point of view, 76–80
., dot symbol, 326 runtime speed, 80–81
/, division operator, 72 Arguments, 34, 39, 52–54, 103, 106–107, 199, 326
//, comments, 42–43 asSeenBy, 53–54
;, semicolon statement ending, 326 duration, 53–54, 103
{ }, method statement enclosure, 326 implementation of, 34, 39
+, addition operator, 72 method requirements, 34
<, less than operator, 72, 189 min and max, 199
<=, less than or equal to operator, 189 parameters and, 103, 106–107
==, equal to operator, 72, 187, 189, 190–191 parentheses ( ), 326
>, greater than operator, 189 popup menus for, 39
>=, greater than or equal to operator, 189 random choices and, 199
style, 53
A trial-an-error strategy, 39
Arrays, 289, 300–308
Abstraction, 91–92, 174
access elements, 301, 303–305
Actions, see Instructions; Movement
creating, 301–303
Algorithms, 22, 28
elements, 300–301, 303–307
Alice, 3–21, 39, 322–330, 331–362
index variables in, 289, 300–308
animation, 14–15
permutation of elements, 305–306
clipboards, 351–353
random elements, 304–305
deleting code, 353–354
relocation of elements, 306–307
exporting, 354–361
swapping elements, 305–307
flowchart design, 7–8
visualization, 289, 300–308
Gallery searches, 350–351
walking through, 308
graphic images, 17–18
asSeenBy argument, 53–54
interface management, 350–362
At runtime, 41
Java transition, 322–328
object-oriented programming concepts, 8–18
B
objects, 9–14
pop-up menus, 39, 345–350 barrel method, 142–145
poses, 328–330 Base case, 247
printing, 354–355 Begin-during-end (BDE) events, 225–227
programming with, 3–8 Billboards, 17–18
sound files, 362 Boolean functions, 180–196, 242
templates, 9–10 calling, 188
text, 15–17 create new function button, 178, 185–186
3D models, 10 events and, 188–189
video creation, 356–362 IfElse statements using, 180–196
virtual worlds, 9, 331–345 isAttachedto, 185–189
Web displays, 355–356, 362 logical operators and, 191–192, 195–196
Alice 3 development, 327–328 random choices using, 182–183, 196–198
and logical operator, 191–192 recursion using, 242
363
364 Index
Design, 22, 23–28, 31–32, 323 built-in functions and, 62–63, 66–68
flowcharts for, 31–32 distance comparison using, 62–63, 66–68
Java programming and, 323 IfElse statements and, 63, 189–192
programming and, 22, 23–25 logical operators for, 191–192, 195–196
textual storyboards, 27–28 math operators for, 66–68
visual storyboards, 25–27 multiple condition, 189–196
Details panel, 13–14 relational operators for, 187, 189, 190–191
Details properties tab, 255–257
Direction of an object, 44–46 F
direction variable, 297–298
Flowchart design, 7–8, 31–32
Distance and objects, 11–12, 198–199, 243, 253
flyForward method, 142–145
distance to function, 65–68
Fog special effect, 256–257
Driver methods, 151
For all in order (sequential iteration), 269–271
duration argument, 53–54
For all together (simultaneous iteration), 271–273
Duration of instructions, 40–41, 103
Frame sequence, 14–15
Functions, 6, 63–68, 157–158, 173–212, 218, 242–243,
E
251–253
Edit/Preferences menu, 324–325 abstraction, 174
Egocentric direction, 45 Boolean, 180–196
Elements of arrays, 300–301, 303–307 built-in, 63–68, 157–158, 174–176, 187, 189
access, 301, 303–305 calling, 6, 180, 188, 218
permutation of, 305–306 conversion methods using, 251–252
random, 304–305 counted loops called by, 218
relocation of, 306–307 create new function button, 178, 185–186
swapping, 305–307 distance, 243, 253
Evaluation, programming and, 28 expressions and, 62–63, 66–68, 189–196
Events, 141–156, 184–189, 225–227 IfElse statements and, 180–196
begin-during-end (BDE), 225–227 math (relational operators), 187, 189
Boolean functions and, 184–189 methods and, 174–176
create new event button, 143–146 new, 178–179, 185–186
event handling methods, 141, 147–156, 184–189 pure, 173
IfElse statements for, 184–189 random choices, 182–183, 196–199
interactive programming, 141–146 random selection, 242–243
linking methods to, 141, 143–145, 148–149 recursion and, 242–243, 251–253
multiple responses to, 149–156 Return statement for, 179–180
multiple with one event handling method, 148–149 testing, 184, 188–189
parameters and, 147–156 3D people models, 157–158
testing, 155–156, 188–189 types of, 178–179
when versus while for, 145–146 values returned by, 173–174, 178–180
When changed from While, 227 which, 251–252
While loops for, 225–227 writing, 176–179, 185–188
world-level methods, as, 145
Events editor, 143–145 G
Execution control, 180–196. See also Conditional
Gallery searches, 350–351
execution; IfElse statements
Graphic files for special effects, 255–256
Exporting from Alice, 354–361
Graphic images, 2D, 17–18
HTML files, to, 354–355
program code (printing), 354–355
H
video, 356–361
worlds (Web display), 355–356 hebuilder 3D models, 156–158
Expressions, 62–63, 66–68, 189–196 hideCanteen method, 185–189
Boolean functions and, 189–192 hop method, 213–216
366 Index