An Introduction To Programming Using Alice 2.2, 2nd Edition
An Introduction To Programming Using Alice 2.2, 2nd Edition
An Introduction To Programming Using Alice 2.2, 2nd Edition
to Programming
Using Alice 2.2
Second Edition
pi
ii ' H i '
Charles W. Herbert
m to Programming Using A
« COURSE TECHNOLOGY
ond Edition Herbert «• C t N i j A G E Learning"
Leilehua Maly graduated from the University of Hawaii
at Hilo in 2003 with a B.S. in Computer Science. After
graduation, he moved to Seattle to work as a software
engineer at Amazon.com. Leilehua is currently
employed as a software engineer in the Windows
Mobile and Embedded division of Microsoft.
J
You knew you were headed for a career in Computer Science when...
I realized how much fun it was to make a computer do what I want.
AN INTRODUCTION
PROGRAMMING
2.2
S E C O N D EDITION
by Charles W. Herbert
; COURSE TECHNOLOGY
t% CENGAGE Learning-
Purchase any of our products at your local college store or at our preferred
online store www.cengagebrain.com
Some of the product names and company names used in this Course Technology, a part of Cengage Learning, reserves the
book have been used for identification purposes only and may right t o revise this publication and make changes f r o m t i m e t o
be trademarks or registered trademarks o f their respective t i m e in its c o n t e n t w i t h o u t notice.
manufacturers and sellers.
The programs in this book are for instructional purposes only.
Any fictional data related t o persons or companies or URLs used
throughout this book is intended for instructional purposes only. They have been tested w i t h care, but are not guaranteed for any
At the time this book was printed, any such data was fictional particular intent beyond educational purposes. The author and
and not belonging t o any real persons or companies. the publisher do not offer any warranties or representations, nor
do they accept any liabilities w i t h respect t o the programs.
CHAPTER T W O
Methods 31
CHAPTER THREE
Events 63
CHAPTER FOUR
Algorithms 97
C H A P T E R FIVE
C H A P T E R SIX
CHAPTER SEVEN
C H A P T E R EIGHT
C H A P T E R NINE
CHAPTER TEN
APPENDIX A
APPENDIX B
APPENDIX C
GLOSSARY 321
INDEX 327
Table of Contents
PREFACE ix
FOREWORD TO THE FIRST EDITION xv
CHAPTER ONE
A n Introduction t o Alice a n d O b j e c t - O r i e n t e d P r o g r a m m i n g 1
Object-Oriented Programming and Alice 2
Tutorial 1A—Exploring the Alice Interface 4
The Main Work Areas of the Alice Interface 7
Other Elements of the Alice Interface 9
Menus 9
Tutorial 1 B — P l a y i n g an Alice World 10
Tutorial 1 C — C r e a t i n g Your First Alice World 12
Adding Objects to an Alice World 14
Object Classes and Instances in Alice 15
Positioning Objects 17
Adding Some Action 18
Closing and Reloading a Saved World 22
Tutorial 1 D — P r i n t i n g Code from an Alice World 22
Tutorial 1 E — S a v i n g an Alice World as a Movie File 23
Chapter Summary 26
Review Questions 26
Exercises 27
CHAPTER TWO
Methods 31
Top-Down Design and Modular Development 32
The Software Development Cycle 36
Designing Methods 36
Coding Methods in Alice 37
Testing and Debugging Alice Methods 37
Tutorial 2 A — W o r k i n g with Primitive Methods in Alice 39
Running Primitive Methods Directly 41
Using Primitive Camera Methods to Find a Lost Object 43
Tutorial 2 B — C r e a t i n g New Methods in Alice 45
Setting the Scene 46
Designing a Method 49
Coding the J u m p Methods 50
Creating the Main Method 52
Testing (and Debugging) Your Finished Software 53
Tutorial 2 C — M e t h o d s With Parameters 54
Creating a Parameter 55
Using a Parameter 56
Chapter Summary 58
Review Questions 59
Exercises 59
Table of Contents V
CHAPTER THREE
Events 63
Event-Driven Software 64
Three-Dimensional Space 65
Tutorial 3 A — E v e n t s in Alice 70
Exploring Events 70
Creating a Sample World for Event Exploration 71
Alice Event Types 74
The When a Key is Typed Event 76
The While a Key Is Pressed Event 78
The When the Mouse Is Clicked on Anything Event 78
Additional Notes About Mouse Events 79
Tutorial 3 B — B u i l d i n g Camera Controls with Events 80
Open an Existing World 80
The Let the Mouse Orient the Camera Event 82
The Let the Mouse Move the Camera Event 82
The Let the Arrow Keys Move the Camera Event 83
Tutorial 3 C — B u i l d i n g a Flying Machine in Alice 84
Software Specifications 84
Refining Specifications 84
Code the World—Specification 1 , Create a World with a Seaplane 87
Code the World—Specification 2, Animate the Seaplane 89
Code the World—Specification 3, Add Turn Controls 89
Code the World—Specification 4 , Add a Find Control 90
Test the World 90
Debug the World 91
Chapter Summary 92
Review Questions 93
Exercises 94
CHAPTER FOUR
Algorithms 97
Elements of Logical Structure 98
Flowcharts 99
Flowcharting Template 100
Flowchart Symbols 100
Linear Sequences 101
Selection S e q u e n c e s — B r a n c h i n g Routines 103
Binary and Multiple Branching 103
Binary Branching 104
Pseudocode 104
Repetition S e q u e n c e s — L o o p i n g 105
Pretest and Posttest Loops 106
Count-Controlled and Sentinel Loops 108
Parallel Algorithms 110
Tutorial 4 A — B r a n c h i n g in Alice Methods 110
User Functions in Alice 111
Tutorial 4 B — A Simple Count-Controlled Loop 116
Tutorial 4 C — U s i n g the While Instruction 118
VI An Introduction to Programming Using Alice 2.2
CHAPTER EIGHT
Lists a n d A r r a y s in Alice 213
Data Structures in Alice 214
The Need for Different Data Structures 214
Lists in Alice 217
Arrays in Alice 219
Tutorial 8 A — E i g h t Ballerinas 220
Exploring the Ballerina Movement Methods 221
Creating a List of the Ballerinas 222
Creating a Dance Routine for the Ballerinas 224
Tutorial 8 B — M a r c h i n g Toy Soldiers 227
The Toy Soldiers World 227
Creating a Marching Routine 229
Tutorial 8 C — S a l u t i n g Toy Soldiers 232
Creating a Generic Salute Method 232
Making All of the Soldiers Salute 237
Tutorial 8 D — S o r t i n g an Array of Sixteen Ballerinas 238
Chapter Summary 241
Review Questions 242
Exercises 243
CHAPTER NINE
M a k i n g A n i m a t e d M o v i e s with Alice 245
Introduction 246
The Moviemaking Process 247
Tutorial 9 A — R e c o r d i n g a Movie from Alice 248
Preproduction 250
Movie Types 252
Movie Topics 253
Outlining the Plot: Scenes, Shots, and Storyboarding 254
Tutorial 9 B — S t o r y b o a r d i n g 257
Camera Placement And Shot Transitions 258
Tutorial 9 C — S i m u l a t i n g Multiple Cameras 259
Tutorial 9 D — R e c o r d i n g Camera Positions for a Multi-Shot Scene 261
Postproduction 266
Chapter Summary 267
Review Questions 268
Exercises 269
CHAPTER TEN
Video G a m e Programming 271
What Is a Video Game? 272
Video Game Careers 274
Game Development Project Management 274
Game Design 275
Script Writing 275
Graphics Arts 275
Music and Sound Engineering 276
Programming 276
Quality Assurance 277
viii An Introduction to Programming Using Alice 2.2
Three things have been changed in this new edition of the text:
Alice 2.2
The second edition of this book is based on Alice 2.2 because this is the best current version
of Alice for learning introductory programming for most students. Some of the features that
did not work well, or at all, in Alice 2.0 now work in Alice 2.2, such as the ability to export
movie files. Alice 3.0 is still not yet ready for prime time, and when it is it may not be the
best vehicle for a general introduction to programming. It is significantly more complicated
and more difficult to use than Alice 2.2. Alice 3.0 will probably be a better vehicle for a
course in which students wish to develop more sophisticated programming skills, or for stu-
dents who wish to dive deeper into things like the nature of events or human computer inter-
action in second-level Java courses. Because it is not as easy to use as Alice 2.0 or Alice 2.2,
Alice 3.0 could be a barrier to getting started with programming for many students.
Therefore, this book, which is intended to introduce students to the nature of computer pro-
gramming, is based on Alice 2.2.
New Chapters
The two new chapters on making animated movies and video game programming aren't
included to displace any of the previous chapters, but rather to extend them. The chapters
should provide students with a good foundation in each area. The animated movie chapter
teaches students about things like camera angles, fades, and transitions so that they can use
An Introduction to Programming Using Alice 2.2
these in programming virtual worlds or in making movies. The video game chapter discusses
careers in the video game industry and exposes students to the kinds of programming needed
for video games.
These chapters aren't intended for courses in filmmaking or game development, but to intro-
duce these areas to students learning programming because these are things that many mod-
ern professional programmers need to learn. Moviemaking and gaming are also areas of
interest to most students, which could spark an interest in computer programming and
related math and physics.
Many years ago, Galileo and others explored the most fundamental concepts in the universe—
optics, heat, mechanics, and so on—as a foundation for understanding and developing the
newest technologies of the day. And so it is with modern computer science. The more we
understand things that don't change, the more we can explore and affect things that do
change. Conversely, the more we wish to know about today's newest and hottest technologies,
the more we find ourselves learning about the immutable foundations of the universe in
which we live. Today's emerging technologies that motivate people to learn include personal
moviemaking and interactive gaming. It may seem like they have been around forever, but
moviemaking and video gaming are relatively new topics that are becoming increasingly
important for computer programmers, are motivating for students, and are just beginning to
appear in most introductory computer programming courses.
R e v i s i o n in E x i s t i n g C h a p t e r s
The chapters that were in the first edition have been revised for this new edition in response
to feedback from instructors and students. More images are included, the language of the text
has been clarified in places, and some of the examples and exercises have been changed. The
fundamental goals and approach of the text remain the same.
O r g a n i z a t i o n o f t h e Text
Each lesson in this text is composed of two parts—lecture and lab. The lecture part of the les-
son includes reading material for the student and lecture material for the teacher that
parallels the reading material. For the most part, the reading material is relatively brief and is
intended to establish a foundation for the lab component. The new chapter on video game
development contains a bit more reading material than most chapters, providing students
with an overview of video game development careers and the kinds of programming used in
video games.
The lab component includes hands-on tutorials in Alice, and sometimes related work intended
to help them explore the concepts of the lesson. The lab component consists of one or more
hands-on step-by-step tutorials, followed by review questions and open-ended exercises the
students should be able to complete on their own, either individually, or in groups, once they
Preface
understand the step-by-step exercises. The exercises contain notes directing the students'
attention to what they should be learning as they carry out the exercise. It is not enough to com-
plete the steps in the exercise, each student should understand what was done, why it was
done, and should be able to repeat the exercise without the directions.
This edition of the book is organized in ten chapters, with goals as follows:
The notion of objects is introduced in the first chapter. Understanding the nature of an object
as a collection of properties and methods that can manipulate those properties is critical in
modern computer programming. The text mentions but does not explore more sophisticated
concepts of object-oriented programming, such as inheritance and polymorphism. In that
sense, like Alice, it is not truly object-oriented, but might better be described as object-based.
I have found that attempts to introduce students to a complete understanding of objects upon
their first exposure to programming is counterproductive. Students can learn more about
inheritance and polymorphism after they have some experience with objects and program-
ming. This approach actually enables students to develop a better grasp of important funda-
mental concepts, like Boolean logic and the nature of algorithms, and to more deeply explore
in a second course how inheritance—with public, private, and protected properties, sub-
classes, super-classes, and so on—really works.
Chapters 7 and 8 present topics that are not covered by everyone in an introductory pro-
gramming course. They are intended to provide students with a first exposure to recursion
and to data structures. Some preliminary work with developmental math and English stu-
dents has shown that the chapters work in making this material accessible to them.
Lesson plans, course outlines, and additional instructional materials for all three approaches,
as well as a complete proposal for a course based on Alice, can be found on the Web site for
the text.
Acknowledgements
May people are responsible for the production of this book, and I am grateful to them all.
Mary Pat Shaffer was the Development Editor, who worked most closely with me in creating
the book's second edition. I appreciate her hard work, and thank her for her patience and
guidance in working with me. This is a much better book because of her efforts.
The book's copy editor was Harold Johnson. Copy editors are the unsung heroes of the pub-
lishing world; guardians of language and thought who painstakingly sift through material
with a fresh eye, finding things that others miss. Chris Scriver and Serge Palladino served as
quality assurance testers, checking each of the tutorials and exercises in the manuscript to
make sure that the final text, the student data files, and the solutions for instructors are cor-
rect. Course Technology stands out among publishers in part because of their attention to
such details.
I am grateful to Alyssa Pratt, Senior Product Manager and Amy Jollymore, Acquisitions
Editor for Computer Science & Programming, two key people at Course Technology who
helped make this edition of the book possible. Thanks also to Melissa Panagos, Content
Product Manager, who guided this book through the production process, and to Marissa
Falco, Art Director, who led the efforts to create the new cover and update the interior design
for this edition.
The original manuscript for the second edition of this book was reviewed by:
I am grateful for their time and the influential insights they offered. Many improvements
were made because of their efforts.
I'd like to thank Walt Johnson, one of my colleagues at Community College of Philadelphia,
who provided the IBM flowchart template shown in chapter 4. Walt is retired now, but for
years I had the opportunity to teach with him and learn much about programming from him.
Early in his career, Walt worked with some now-primitive IBM equipment, like the 1401 and
360 series, and became a master at improvising and inventing new techniques to get a pro-
gramming job done. Many things change rapidly in the world of computing, but one thing that
will never change is the need for people like Walt, filled with intelligence, enthusiasm, and
the ability to work well with computers and with the people who use them.
This book is dedicated to my father, George William Herbert, Jr., who passed away during the
week when the first edition of the book went to press. He was the athletic director for the
Maplewood School District in Colonie, NY for more than 30 years, but spent most of his sum-
mers driving our family around the country to visit as many of America's national parks as
possible. There are many heroes in the world, but few as important as a good father.
The Alice software can be found at www.Alice.org, the official Alice Web site.
Each chapter of this book has clearly stated objectives, one or more readings related to those
objectives, and several hands-on tutorials. A chapter summary, review questions, and further
exercises are included at the end of each chapter. Note that Appendix A of this text contains
technical information about the Alice software, which is easy to install and use.
Note that the text was quality assurance tested using Alice v. 2.2 on Windows 7 Ultimate.
Student Data Files These are provided on the Course Technology Web site at www.cengage.com/
coursetechnology. The student data files contain all of the Alice worlds, image files, and so on
that are needed within the tutorials.
Solution Files Solutions to the review questions and exercises found in the book are
provided for instructors on the text's Companion Site at www.cengage.com/coursetechnology.
The solutions are password protected. The solution files contain the completed Alice worlds
that are the final product of each tutorial.
Foreword to the First Edition
Note from the author: I asked Randy Pausch, Dennis Cosgrove, and Caitlin Kelleher to tell us
about the development of Alice, the current state of affairs regarding Alice, and where things
seem to be headed in the future. The sections that follow are what they wrote in reply. We've
also included their individual bios at the end of this foreword.
All A b o u t A l i c e
So far there have been three distinct phases in the development of Alice, the Goggles and
Gloves phase, the "rapid prototyping 3D graphics phase," and the Teaching Introductory
Programming phase.
The Goggles and Gloves phase started in the early 1990's at the University of Virginia, where
Randy was on the faculty, heading a 20-person User Interface Group investigating the bound-
ary where people and technology interact. We were trying to make virtual reality more acces-
sible by developing improved interfaces and lower-cost human computer interaction
hardware and software. The paper Virtual Reality on Five Dollars a Day, which was pub-
lished in the April 1991 edition of the ACM SIGCHI's journal Human Factors in Computing
Systems, describes some of our work. It's available online through www.alice.org, where we
provide links to publications related to our work on Alice.
We call that first phase the Goggles and Gloves phase because we really were focusing on the
development of virtual reality systems in which the participant (the term user really doesn't
seem to capture the sense of it; Disney Imagineering uses the term "guest") enters a virtual
world by putting on a VR helmet and gloves. One mantra was "If it doesn't have a glove, it's
not VR." At the time, virtual reality was in its infancy. So, in addition to developing VR inter-
faces, we were working on software systems to test the interfaces. One of our early reseach
projects was SUIT, the Simple User Interface Toolkit, to which Matt Conway and Rob DeLine
contributed heavily. Matt was instrumental in recognizing that vocabulary matters—that the
choice of names for behaviors is critically important in a system for novices. His work was
very influential in shaping the direction of the development work that led to the Alice sys-
tem we have today. His doctoral dissertation, Alice: Easy-to-Learn 3D Scripting for Novices
should be required reading for people interested in how to design systems for novices. It's
available on the Web at www.alice.org.
The language for programming VR systems required one to think in terms of X,Y,Z coordi-
nates, and to use terms like translate, scale, and rotate to describe things happening in a vir-
tual world. On the early Silicon Graphics machines, angles were measured in integers
representing tenths of a degree, so commands like rotate -3600 were common. A person
needed fairly advanced mathematics skills to program graphical objects in a 3D system.
An Introduction to Programming Using Alice 2.2
Engineers and physicists had the keys to get in, but many other intelligent, talented and cre-
ative people, such as artists, and filmmakers, did not. Matt saw that the language of VR was
a part of the problem and that if we could change the language, then VR systems would be
easier to use, and thus more accessible for novices and more powerful for experts at the same
time. In his dissertation he wrote that "the tradeoff between power and simplicity is often a
false one." He led us in discovering that using more everyday terms terms like move, turn,
and resize instead of technically-oriented terms like translate, rotate, and scale could go a
long way toward achieving the powerful simplicity that would become one of the hallmarks
of Alice. Turn left 1 revolution makes sense to a lot more people than rotate X -3600.
The first version of Alice emerged as an easy-to-use scripting system for building virtual
worlds. The system itself was a combination of C and Python code, with which one could
rapidly create virtual worlds by iterating Python scripts. Over the years, the programming
features of Python have been replaced with dragging and dropping code elements.
It's important to note that even early versions of Alice could not have been created without
the efforts of a dedicated team of people. In particular, PhD student Rich Gossweiler, was
responsible for the implementation of the very early versions of Alice, and its co-system
DIVER. Tommy Burnette was also responsible for a great deal of the early Alice software
implementation. A complete listing of people who have contributed to the Alice project over
the years is available at www.alice.org .
At about this time (the mid 1990's) our work was funded by a variety of sources, including
the National Science Foundation (NSF) and the Defense Advanced Research Projects Agency
(DARPA). These are two of the most amazing agencies in the federal government, when it
comes to return on investment of public money. A while back, NSF and DARPA asked for
funding to explore using computers as tools for communication among educators, scientists,
and engineers, and the result is the Internet. We believe that any time they ask for money,
Congress should jump at the chance to spend public funds so wisely. One day one of the peo-
ple from the Department of Defense who was overseeing our project said that we should for-
get about the virtual reality hardware and concentrate on the software we were building. He
argued that our most important contribution was the way in which our software could be
used as a rapid development system for 3D graphics prototyping.
During the summer and fall of 1995, Randy spent a sabbatical at Walt Disney Imagineering's
Virtual Reality Studio working on the "Aladdin" project which was featured at EPCOT
Center and, later, at DisneyQuest. The experience working with the Imagineering team
helped to make it clear that we were moving into a realm of work that would require both
artists and engineers. In the spirit of bringing artists and engineers together, Randy created a
course called "Building Virtual Worlds" in which teams of artists and engineers work together
Foreword to the First Edition xvii
to create interactive virtual worlds. In the Spring of 1997, the research group moved to
Carnegie Mellon University, in order to take advantage of the fairly unique cross-disciplinary
focus at CMU. However, no story of the Alice system would be complete without acknowl-
edging how gracious the University of Virginia was in allowing us to continue work on Alice
seamlessly, by allowing us to transfer our funding and research to another university, and we
are very grateful for their support. We have fond memories of the University of Virginia and
highly recommend it to students looking for a great place to go to school.
Over the next few years we gradually moved into the third phase of our work as we devel-
oped better ways to build virtual worlds. Alice became a workhorse for the "Building Virtual
Worlds" course, which was then being taught at Carnegie Mellon, for several years, finally
realizing our dream of allowing "a 1,000 creative flowers to bloom." However, with respect to
making 3D graphics programming easier, we slowly began to realize that we had the problem
inside-out. Instead of thinking about how to improve programming to make 3D graphics
more accesible, it started to become clear that 3D graphics could make programming more
accesible. A seminal event occured one day when Randy was on a family trip to
DisneyWorld. His ten year old nephew Christopher spent the day working with Alice on a
laptop as they drove. Chris programmed 3D graphics for eight hours straight, never really
having trouble with the 3D part, but constantly asking for help about "where the commas and
semicolons had to go." In Randy's words: "I immediately realized that this was a problem we
could solve." Some work had already been done on the drop and drag interface, but now the
creation of a drag and drop interface for creating Alice programs became a priority.
Wanda Dann and Steve Cooper both became important contributors to the future of Alice at
about this time. Wanda, who teaches Computer Science at Ithaca College, and Steve, who
teaches at St. Joseph's University, have long been interested in how visualization can be used to
teach object-oriented programming concepts. They began to work with us to shape Alice as a
better tool to teach introductory programming. We were all beginning to recognize that Alice
works well for teaching introductory programming for three primary reasons: minimization of
the problems of syntax, the ability to see the results of object-oriented programming in a live
virtual world, and the motivation provided by working in such an exciting environment.
Since 1999 Steve and Wanda's efforts developing educational materials based on Alice, test-
ing Alice in the classroom, and providing feedback to Dennis and company as the software
was refined have been instrumental in shaping the current look and feel of Alice.
In addition to helping students with the technical hurdles, Alice is allowing us to begin
changing the ways in which we introduce students to computer programming. The way we
teach computer programming hasn't changed much in the past 50 years, despite the fact
that the way we use computers has. The first computers that appeared in the middle of the
20 th
century were literally used to help bombs hit their targets. The early high-level pro-
gramming language, FORTRAN, was designed to help scientists and engineers with their
An Introduction to Programming Using Alice 2.2
number crunching. Today, how many high school students are excited about writing code
to generate the first 10 Fibonacci numbers? Using Alice, students learn the basics of pro-
gramming while creating animated stories and games. Wanda Dann has been a strong pro-
ponent for using Alice to introduce programming through storytelling at the college-level,
and Caitlin has been studying using the activity of storytelling in Alice to interest middle-
school girls in learning to program. In addition to being more motivating than assignments
like sorting a list of numbers, creating animated stories helps to make computer program-
ming seem less foreign. Not many people are familiar with the concept of mathematical
algorithms, but everyone is familiar with storytelling. By using Alice to tell story in a vir-
tual world, young people become engaged in linear sequencing, modular development,
and planning before implementation—three of the most important skills for early success
in computer programming.
One highly desirable side effect of using Alice to introduce programming through story-
telling is that more young women are attracted to the discipline. It's no secret that Computer
Science, unlike Law and Medicine, has failed to attract women in significant numbers.
Currently, women constitute less than one-third of all Computer Science majors in the US,
and less than one-fourth of those earning Ph.Ds in Computer Science. According to Caitlin s
research (her dissertation, when completed, will be available at www.alice.org), Alice has the
power to begin to change that; thereby changing the culture of the Computer Science class-
room and workplace.
So where do things stand now? Well, Chuck Herbert's programming textbook is only the second
book to use Alice as a tool to teach programming. The Dann, Cooper and Pausch book was the
first. Course Technology's Alice CourseCard is the first widely available reference material for
Alice 2.0. More material is sure to follow as the number and type of schools using Alice
increases. Last year we knew of approximately 30 colleges and universities using Alice. This
year we are aware of about 60 colleges and universities and at least that many high schools, as
well—and there are probably more folks using Alice that we don't know about.
Currently most people who use Alice seem to be doing so to teach introductory program-
ming, although it is starting to be used in other disciplines. The most widespread educa-
tional model for the use of Alice is to use Alice for the first half of an introductory
programming course, followed by the use of Java or a similar commercial programming
language in the second half of the semester. That model seems to be working remarkably
well in places like Duke University, the University of Mississippi, Haverford College, and
here at Carnegie Mellon.
Foreword to the First Edition xix
Within the past three years other models for the use of Alice have emerged, particularly in
the community colleges, and in courses other than computer programming. Here are just a
few of the efforts we know about:
The most common question people ask us these days is about the future of Alice. Right now,
the 04/05/2005 Version of Alice 2.0 is reasonably stable and reliable, and runs on Windows and
the Macintosh. There are no plans develop it further. Instead, work is beginning on Alice 3.0.
How will Alice 3.0 be different? Well, to start with, one thing about it will be the s a m e —
it will continue to be provided free of charge to the public from Carnegie Mellon University.
The University has been very gracious in supporting us, and we are committed to maintain-
ing Alice as an open source, non-commercial, piece of software. This "purity" is important;
many students have worked hard over the years to contribute to the Alice effort, and we
believe it must continue to be "for the people." All of Randy Pausch's royalties from the
Dann, Cooper and Pausch book are donated by him to Carnegie Mellon, to help support the
software development. We are glad to hear that Chuck Herbert has also pledged a portion of
his royalties from this book to the Alice effort. We had various corporate sponsors over the
years, most notably Intel and Microsoft, and we are pleased to say that Electronic Arts (EA) is
a major sponsor of Alice version 3.0.
xx An Introduction to Programming Using Alice 2.2
We expect that Alice 3.0 will be a pure Java implementation, and that you will be able to dump
the Java code for an Alice 3.0 world and then work with it in Java. That's a big change from
Alice 2.0, which does not create Java code, but works more like an interpreter that directly exe-
cutes Alice methods. This should serve several purposes, including helping to make the transi-
tion form Alice to Java smoother in introductory programming courses.
You can expect the new version of Alice to be more truly object-oriented than the current
version. Alice 2.0 is a good tool to introduce the concept of an object as a collection of prop-
erties and methods, but it does not provide the ability to create true class-level methods, true
inheritance, or the overriding necessary for polymorphism. Alice 3.0 should have some, if
not all, of these features.
Caitlin's work has shown that users, especially young people, can do more and learn more
with objects that have higher order primitive methods, such as walk, sit, and touch instead of
just move, turn, and so on. There will probably be more methods that manipulate objects and
their sub-parts together, and the gallery of available objects will probably be richer that the
current Alice gallery.
The overall look and feel of Alice will also probably be less toy-like. Anyone who has used Alice
for more than a few minutes knows it's not a toy, but it looks like a toy. The new version should
still be easy to use, but people probably won't think "Fisher Price" when they first see it.
The team that started working on virtual reality interfaces years ago at the University of
Virginia had no idea that our work would lead to Alice and that it would become such an
important tool in Computer Science education. As is the case with many NSF funded projects,
the taxpayers have gotten more than their money's worth, but just not in the way one would
have thought reading the original proposals. Such is the path of science and exploration. Now
that we know where we are headed, our goal is to make Alice the vehicle of choice for some-
one's first exposure to computer programming, for everyone—worldwide—from 5 th
grade
through college.
Randy Pausch
Dennis Cosgrove
Caitlin Kelleher
Carnegie Melon University,
December 2005
Foreword to the First Edition
Dennis Cosgrove is a Human Computer Interaction Project Scientist (formerly Senior Research
programmer) at Carnegie Mellon University, where he has spent the last several years as the pri-
mary software architect and implementer for Alice 2.0, 2.2, and 3.0. He was one of the principal
developers of the earlier PC/Windows 95 Alice implementation at the University of Virginia.
In addition to his work on Alice, he has contributed to the development of an eye-tracking sys-
tem that allows quadriplegics to interact with a computer.
Run the Alice software and locate and describe the following components of the Alice
interface: World window, Object tree, Details area, Editor area, Events area, menu bar,
Trash can icon, Clipboard icon, Play button, Undo button, and Redo button
Create a new Alice world by adding objects to a blank world, positioning them, and
using simple methods to animate those objects
An object can be something in the physical world or just an abstract idea. An airplane, for
example, is a physical object that can be manipulated by an autopilot—a computer that can
fly the plane. To the computer, the airplane is an object.
Most objects that computers manipulate are not physical objects. A bank transaction is an
example of an object that is not physical. There is usually a paper record of a transaction;
however, the transaction itself is simply a concept. It is an object, but not a physical object.
Whether an object exists in the physical world doesn't matter much in terms of what hap-
pens inside a computer. To a computer, an object is simply something that can be repre-
sented by data in the computer's memory and manipulated by computer programs. The data
that represents the object is organized into a set of properties. Each property describes the
object in some way. For example, the weight of an airplane, its location, the direction in
which it is facing, and so on are all properties of the airplane. A computer manipulates an
object by changing some of its properties or some of the properties of parts of the object. For
instance, the autopilot might change the angle of a wing flap, which in turn affects the
entire airplane.
Sometimes the hardware in a computer translates these changes in properties into actions
that affect the physical world—as an airplane's autopilot does—and sometimes the changes
in an object only affect information in the computer's memory and have no direct effect on
the physical world. For example, when a bank deposit is recorded on a computer, the
amount of money in the bank balance property of the bank account object is changed, but
there is no other immediate effect on the physical world.
The programs that manipulate the properties of an object are called the object's methods.
An object is a collection of properties along with the methods that are used to manipulate
those properties. The values stored in the properties of an object at any given time are col-
lectively called the state of an object. This modern approach to computer programming is
known as object-oriented programming, or OOP for short.
Object-Oriented Programming and Alice 3
Learning to program a computer is often a difficult task because it requires learning about
programming concepts and the language of programming at the same time. It's also difficult
because people find it hard to visualize all of the changes that are occurring as a computer
program runs. Alice can make it easier to learn to program a computer by helping with both
of these problems.
Alice uses an object-oriented style of programming. The objects in Alice exist in a three-
dimensional virtual world, much like a modern video game. In fact, the virtual world itself
is an object in Alice—it has properties and methods that can be used to manipulate those
properties. Alice is similar to other modern object-oriented programming languages, such as
Java, C++, or Visual Basic. However, as you will see, Alice is constructed so that you don't
need to memorize the grammar and syntax of the language to write computer programs. As
you are learning Alice, you can concentrate on learning about the ideas of computer pro-
gramming, such as the logic of your algorithms, instead of having to worry about the
spelling and grammar of a new language at the same time.
The virtual world of Alice is one that you can see. Like the real world, it has three-dimensional
space (and time), and each object has properties just like physical objects have properties;
these include color, size, position, the direction in which the object is facing, and so on. Alice
has a camera that allows you to see its virtual world on a computer screen, just as you might
view a movie or a video game. This ability to see what happens to objects in your virtual world
makes it easier to learn computer programming with Alice than with almost any other system
of programming. For instance, if you try to program a white rabbit to run around in a circle,
and instead he simply stays in one spot and spins, you can see that happening on the screen.
You can get instant feedback from viewing the way Alice runs the programs you have created.
Not every programming system is so easy to use.
For more information on computer programming languages, see Appendix C of this book.
Chapter 1 • An Introduction to Alice and Object-Oriented Programming
In summary, there are three things about Alice that make it a more effective tool for learning
programming than almost any other system of programming:
You will also find that Alice is fun and interesting to use, which never hurts when one is
trying to learn something new.
Anyone attempting this exercise should have experience using a computer. You certainly
don't need to be an expert, but you should have some experience with things like word pro-
cessing and accessing the Internet so that you are familiar with Windows, a mouse, a key-
board, and a printer.
1. Start the Alice software. You will see the Welcome to Alice! dialog box
open in front of the Alice Integrated Development Environment (IDE), as
shown in Figure 1-1. If Alice opens without showing you the Welcome to
Alice! dialog box, click File, and then click New World to open this win-
dow. An Integrated Development Environment (IDE) is a computer pro-
gram that is used to write other computer programs. Most modern
programming languages have IDEs with everything you need to create and
run computer programs. Alice is no exception, but its IDE is simpler than
most. The Alice IDE is often called the Alice interface.
The Show this dialog at start check box appears in the lower-left corner o f the Welcome
H W I * to Alice! dialog box. It should be checked so that the Welcome to Alice! dialog box will
appear when Alice starts.
Tutorial 1 A—Exploring the Alice Menace
FIGURE 1 - 1 : The Alice interface with the Welcome to Alice! dialog box
j lit
ft"*" Alice
H Tutora
il "(Recent Wod
rls T
(empa
ltes "| Examp
e
ls ( O p a n a world
Vcfeli*! m
[ ethods f rations create new variable
myfNSt method
DoUiotdtrr ftjtotjother l*Hu> Loop wti.le Foradmorder Fo. allio.jettier Wad prmt
2. Notice that the Welcome to Alice! dialog box has five tabs: Tutorial, Recent
Worlds, Templates, Examples, and Open a world. You can return to this
dialog box at any time while using Alice by clicking File on the menu bar,
and then clicking New World or Open World. Let's look at each of these
tabs before continuing.
3. Click the Tutorial tab and you will see four Alice tutorials. You won't use
the tutorials now, but you may want to come back to them later as an exer-
cise on your own. When you are ready to use the tutorials, either click the
tutorial you would like to run, or click the large Start the Tutorial button to
follow them in order. They are quite easy to follow.
Dr. Caitlin Kelleher from Washington University in St. Louis created the original version
of these tutorials while she was a graduate student at Carnegie Mellon University.
4 . Click the Recent Worlds tab. You will see thumbnail sketches of the most
recently saved Alice worlds. If no worlds have been saved since the Alice
software was installed on your system, this tab will say No recent worlds.
6 Chapter 1 • An Introduction to Alice and Object-Oriented Programming
5. Click the Templates tab. Alice comes with six blank templates for starting a
new virtual world—dirt, grass, sand, snow, space, and water. Each of the
templates includes a texture for the surface, which is called the ground in
Alice, and a background color for the sky.
6. Click the Examples tab. Several example worlds created by the Alice devel-
opers are provided with the Alice software. We'll return to the Examples
tab later in this tutorial.
7. Click the Open a world tab. This tab is used to access Alice worlds saved
on your computer. Click the Browse button to open the Open dialog box, as
shown in Figure 1-2. This dialog box is very similar to the Open File dialog
boxes seen in other programs, such as Microsoft Windows, with navigation
icons across the top, a list of folders and Alice worlds from the current
directory in the middle, and some controls to view and open files at the
bottom. Notice that the Alice world files end with the extension .a2w. This
extension indicates that the files were created with either version 2.0 or
version 2.2 of the Alice software, the two most recent versions. Alice uses a
generic interface that looks the same when using the Windows, Apple, or
UNIX operating systems. Click the Cancel button to return to the Open a
world tab when you are ready to move on.
w
Jim Watson's Worlds
Recent Ray Sweeney's Worlds folders
Walt Johnson's Worlds
airport.a2w
baseball.a2w
Desktop boat game.a2w Alice worlds
chicken is tasty.a2w
cows.a2w
My haunted house.a2w
Documents tiny dancer.a2w
toy soldiers.a2w
My
Computer controls
8. Next, you will look at the Alice interface with an Alice world open. Click
the Examples tab, click the lakeSkater thumbnail, and then click the Open
button to open the lakeSkater Alice world. It will take a few seconds for
Alice to load all of the elements of the world. The name of each element
will briefly appear in a small window in the center of the screen while this
happens. When Alice is finished loading the world, your screen should
resemble Figure 1-3.
FIGURE 1-3: The Alice interface after loading the lakeSkater world
World window
Events area
Object tree
T h e M a i n W o r k A r e a s of t h e Alice Interface
The Alice interface has five main work areas, as shown in Figure 1-3: the World window, the
Object tree, the Details area, the Editor area, and the Events area. There are also several ele-
ments across the top of the interface—a menu bar, three control buttons, a Trash can icon,
and a Clipboard icon. Let's look at each of these before playing the lakeSkater world.
The World window contains a view of the lakeSkater virtual world. The set of blue arrows
below the window controls the Alice camera, which provides you with the view in the win-
dow. Next to the arrows is a large green ADD OBJECTS button, which you will use in
Tutorial l C when you create your first Alice world.
8 Chapter 1 • An Introduction to Alice and Object-Oriented Programming
The Object tree appears to the left of the World window. It shows the objects in the current
Alice world organized as a tree of tiles, with a tile for each object. The plus sign next to an
object shows that it has sub parts, which may be seen by clicking the plus sign. Click the plus
sign to see the parts of the IceSkater object, and then click the minus sign to hide its parts.
T h e Details A r e a
The Details area of the Alice interface is located below the Object tree. It has tabs to show
properties, methods, and functions for the currently selected Alice object. Properties con-
tain information about an object, such as its color and position in the world. Methods are
programs that manipulate an object. A function is a method that returns a value, such as the
distance between two objects.
You may select an object by clicking that object in the World window or by clicking its tile in the
Object tree. Information about the currently selected object will be displayed in the Details area.
Click the World tile in the Object tree to see the World's details in the
Details area.
Click the lake tile to see the lake's details in the Details area.
Click the IceSkater tile in the Object tree and then the properties tab in
the Details area to see the IceSkater's properties.
• Click the methods tab to see the IceSkater's methods.
Click the functions tab to see the IceSkater's functions.
T h e Editor A r e a
The largest area of the Alice interface is the Editor area, which appears to the right of the
Details area. Here, you assemble and edit methods by clicking and dragging tiles from other
parts of the interface. The bottom of the Editor area has a row of logic and control tiles that
can be used to put branching, looping, and other logical structures into the algorithms that
will make up an object's methods. Most of the time that you spend working with Alice will
be spent using the Editor area.
The Events area in Alice is above the Editor area. The Events area shows existing events
and is used to create new events. An event consists of a condition, called an event trigger,
and a method, called an event handler. Whenever the event trigger occurs, the event han-
dler is called into action. For example, you might want the sound of a splash to occur if an
ice skater falls through the ice. Falling through the ice would be the event trigger, and the
method that makes the splash sound would be the event handler.
Tutorial 1A—Exploring the Alice Interface
Some events, such as causing a method to run when a key is pressed, provide user interac-
tion for an Alice world. The flight simulator world that can be accessed through the
Examples tab is an interactive world that you might want to take a look at after finishing
this chapter. Events are very important for interactive simulations and gaming and are cov-
ered in detail in Chapter 3.
O t h e r E l e m e n t s o f t h e Alice I n t e r f a c e
In addition to the main work areas that you have just explored, the Alice interface also has
two icons, three buttons, and a menu bar near the top of the screen.
The Trash can icon and the Clipboard icon are used for editing Alice worlds.
You can delete an item in an Alice world, such as an object or instruction tile, by dragging
and dropping it in the Alice Trash can. You can also right-click an object or tile, and select
delete from the menu that appears.
You can copy any object, event, or method in the Editor area by dragging and dropping its
tile onto the Clipboard icon in the top-right corner of the interface, and then dragging it
from the Clipboard icon to a new location. You can also duplicate a method tile by right-
clicking it and selecting make copy from the menu that appears; however, this does not
work with Alice objects or events.
The Undo and Redo buttons near the top-left corner of the interface are also useful for edit-
ing an Alice world. You can undo the last change you made by clicking the Undo button.
The effects of the Undo button can be reversed by using the Redo button. Alice can remem-
ber the last several dozen changes that you made. The Ctrl+Z and Alt+U shortcut keys can
be used for Undo. The Ctrl+Y and Alt+R shortcut keys can be used for Redo. There are no short-
cut keys for cut, copy, and paste.
Menus
The Alice interface has a menu bar at the top of the screen with four menus: File, Edit,
Tools, and Help. The menus in Alice are used much less frequently than in many other
computer programs. For now, you will look at only a few of the items on these menus. All
of the features on the Alice menus are listed in Appendix B.
File M e n u The Alice File menu has commands for opening and saving Alice worlds, and
for exiting Alice. It also has several other items that you will explore later, including options
for exporting an Alice world as a Web page or as a video, and exporting code from an Alice
world for printing. You will use these options in later tutorials throughout this book.
10 Chapter 1 • An Introduction to Alice and Object-Oriented Programming
Edit M e n u Currently the only option on the Alice Edit menu is Preferences, which is
used to change settings for the Alice software. Appendix B of this book lists and describes
these settings. The most important thing to know for now is that the Alice Edit menu is not
used to edit Alice methods in the same way that an Edit menu might be used in other soft-
ware. Instead, Alice emphasizes the use of a drag-and-drop interface, which uses the editing
icons and buttons described throughout this book.
T o o l s M e n u The Alice Tools menu contains three options: Text Output, Error Console,
and World Statistics. The Text Output option allows you to see system messages generated
as you play Alice worlds, and the Error Console can be used to look at detailed Alice error
messages. Both of these are rather sophisticated, and are not very useful for novice program-
mers. The World Statistics option allows you to see statistics, such as the number of objects
in a world, the time the world has been open, and many other useful items. Only some of
the information here will be meaningful to you until you learn more about Alice and com-
puter graphics.
H e l p M e n u The Help menu does not contain an option to look up the features of Alice as
you might expect. By not providing a way to look up features, the developers of Alice were
hoping to encourage people to learn about Alice by experimenting with it.
The Help menu does have three options: Tutorials, Example Worlds, and About Alice.
Example Worlds and Tutorials will both take you back to the Welcome to Alice! dialog box.
The About Alice option provides general information about Alice and the Alice Web site,
www.alice.org.
Mil From time to time you may encounter errors while using the Alice software. The Alice
error message box contains a button to copy the error message to the clipboard. You can then
paste the message into programs such as Word or Notepad, although they are often too sophis-
ticated for novice programers to read. You may submit bugs and suggestions about Alice
through the Alice Web site. The Alice team wants to hear from the users of Alice.
In this tutorial, you will experiment with playing an Alice world. Alice worlds fit into one
of two different categories—some Alice worlds are interactive in the way a video game is;
others are simply run and viewed like a movie. In either case, experienced Alice users refer
to "playing" an Alice world the way most software developers talk about "running" a com-
puter program.
The Alice world you will play in this tutorial is the lakeSkater world discussed in Tutorial 1 A.
It is not an interactive world; rather, it is more like watching a movie of an ice-skater's
Tutorial 1B—Playing an Alice World
performance. If you have just finished Tutorial 1A and still have the lakeSkater world open,
then continue with the steps that follow. If not, you will need to run the Alice software and
open the lakeSkater world before starting this tutorial.
1. There are three buttons near the top of the Alice interface, labeled Play,
Undo, and Redo. Undo and Redo are used for editing, as described in
Tutorial 1A. The Play button is used to play the current Alice world. When
this button is clicked, the world will play in a larger version of the World
window, with player controls at the top of the window, as shown in
Figure 1-4. Click the Play button now and watch the show unfold. Let the
world play through to the end at least once before proceeding.
2. Notice that the new window has a speed slider control and five buttons
across the top of the window in which the Alice world plays. The buttons
are labeled Pause, Play, Restart, Stop, and Take Picture.
3 . The Restart button is used to begin playing the current world again from the
beginning. The Pause and Play buttons work like the pause and play buttons
on a DVD player. Click the Restart button now to restart the lakeSkater
world, and then experiment with the Pause and Play buttons.
4. The speed slider is used to change the speed of the world while it is play-
ing. Restart the world, and experiment with the speed slider control.
12 Chapter 1 • An Introduction to Alice and Object-Oriented Programming
5. The Take Picture button captures an image of the currently playing world
and saves it in a data file. Restart the world and click the Take Picture but-
ton to take a picture of the world. An Image captured and stored dialog box
will appear, showing you the full path name of the file that was saved. The
stored image file can be viewed and used as any other computer image file
can be. By default, the images are saved as JPEG files to the desktop.
Appendix B has more information on changing the settings for Alice's
screen capture feature. Click OK to close the dialog box.
6. The Stop button stops the world that is currently playing and returns you
to the standard Alice interface. Once the Stop button is pressed, you will
need to click the standard interface's Play button to replay the world. Try
this now. After you have finished experimenting, click the Stop button one
last time to return to the standard Alice interface.
Alice is a graphics-intensive program that can use a lot of a computer's memory, so you
should exit the Alice program when it is not in use. Now that you are finished with this
tutorial, you should exit the Alice program.
While you are viewing or editing an Alice world, a dialog box will appear every 15 min-
utes, warning you that you have not saved your Alice world. If this happens while you are
playing an Alice world, such as in Tutorial 1B, then it's probably safe to ignore the warn-
ing. If it happens while you are creating or editing your own Alice world, then you should
save your world.
In this tutorial, you will create, play, and save a new Alice world. You should finish
Tutorials 1A and I B before starting this tutorial. You will create an Alice world in which a
bunny will move from the right side of the screen to the center, turn to face the camera, and
then say "Hello, World!" This is an Alice equivalent of the Hello, World! program that stu-
dents traditionally write as their first program in a new programming language.
This tutorial begins with the Alice software closed. If you have an Alice world open, then
exit Alice before continuing.
Tutorial 1C—Creating Your First Alice World 13
FIGURE 1-5: The Templates tab with six templates for new Alice worlds
3. Thumbnail sketches for the six new world templates are now available—
dirt, grass, sand, snow, space, and water. The templates appear to be very
simple, but looks can be deceiving. There is actually a great deal of com-
puter programming behind a new Alice world, with a camera, ambient
light, and other elements already in place. Click the grass thumbnail, and then
click the Open button.
A new Alice world based on the grass template is now open, and you can see the standard
Alice interface that you used earlier in the chapter. Notice that the Object tree in the upper-left
part of the interface contains the four tiles that appear in every new Alice world: world,
camera, light, and ground, as shown in Figure 1-6. You can see from the way the tree is
organized that the other objects are subobjects of the world object.
world
iff camera
C n light
ground
14 Chapter 1 • An Introduction to Alice and Object-Oriented Programming
The new world also has the default event—When t h e world s t a r t s , do world.my first
method—in the Events area, and a blank default method—world.my f i r s t method—in the
Editor area.
A d d i n g O b j e c t s t o a n Alice W o r l d
The next several steps will introduce you to the Alice object galleries and the process of
adding objects to an Alice world. Many people get carried away with creating big worlds
with many objects when they first start to use Alice. In this tutorial, you will start with a
very small Alice world with a minimum number of objects. Objects are added to an Alice
world in Scene Editor mode.
1. Click the large green ADD OBJECTS button in the bottom-right corner of
the World window to enter Alice's Scene Editor mode, which is used to
add objects and position them in an Alice world.
2. Note that the Alice interface now looks different, as shown in Figure 1-7.
The Object tree and the Details area are still visible on the left, but there is
a new area on the right side of the screen. This new area is called the
Scene Editor.
Tutorial 1C—,
tin Crea
9 Your First Alice
Web
nection
Gallery maintained
to use the Web Gallery.)
Scene Editor mode, as shown
by Carnegie
in Figure
Mellon
The Local
1-7.
VmveVSlty.
Gallery is the (N>U
visible at
The galleries are organized
IW
the bottom Ot
as a tree of folders
SCTWU
containing related ob)ects. You can navigate the tree of galleries by clicking a gallery folder
to enter that gallery, or by using the gallery navigation bar, which is just above the galleries.
You will explore the galleries a bit before preparing to add objects to your new world.
1. Click the folder icon on the gallery navigation bar to move up one level in
the tree of galleries, so that you can see the top level in the tree, as shown
in Figure 1-8. Two icons are visible: one for the Local Gallery and one for
the Web Gallery.
Home
2. Click the Local Gallery icon to go back to the Local Gallery. Scroll left and
right through the Local Gallery using the scroll bar below the gallery fold-
ers, and you will see some of the many categories of objects available in Alice.
3. Find and click the Animals folder icon to open the folder. Scroll left and
right through this gallery to see some of the animal objects available in Alice.
O b j e c t C l a s s e s a n d I n s t a n c e s in Alice
Each of the tiles in the Animals folder represents a class of objects. A class is a group of
objects with the same properties and the same methods. Objects in the same class are virtu-
ally identical to each other, except that the values stored in some of their properties may be
different. For example, you could have an Alice world with two Penguin objects. They
16 Chapter 1 • An Introduction to Alice and Object-Oriented Programming
would both have the same methods and the same properties, but the values of some of those
properties, such as location or color, might be different.
Each copy of an object from a particular class is called an instance of the object. As you use
Alice, you will notice that the object class tiles in the object galleries have the word class in
their title and each begins with a capital letter, such as Class Bunny or Class Chicken, but
once an instance of an object is placed in a particular Alice world, its name begins with a
lowercase letter. Of course, it is possible to rename objects, so this distinction is not always
maintained.
The act of adding an instance of an object class to an Alice world is called instantiation.
The same terminology—classes, instances, and instantiation—is used in most object-
oriented programming languages.
You are going to add an instance of an object from the Animals folder in the Local Gallery
to your new Alice world. You are going to instantiate a Bunny class object.
1. Click the Class Bunny icon. A window with information about Bunny class
objects, like the one in Figure 1-9, should appear.
* Bunny X
2. Click the Add instance to world button to put a bunny into the world. This is
sometimes called dropping an object into the world. You should see a bunny
appear in the center of the World window.
3. You can also add an object to an Alice world by clicking an object class tile
and dragging it into place in the World window. Try this now: drag and
drop a chicken tile into your Alice world. This approach lets you place the
new object wherever you would like on the ground in the World window;
however, it does not show you the object's information window first.
4. You should now have an Alice world with two objects—a bunny and a
chicken. Notice that tiles for the new objects have also been added to the
Object tree. You really don't need the chicken for the rest of this exercise.
Tutorial 1C—Creating Your First Alice World 15
The Scene Editor has new controls, a larger World window, and object galleries on the bot-
tom. The Scene Editor replaces the Events area and the Editor area when you are in Scene
Editor mode.
There are two Alice object galleries: a Local Gallery provided with the Alice software, and a
Web Gallery maintained by Carnegie Mellon University. (You need an active Internet con-
nection to use the Web Gallery.) The Local Gallery is visible at the bottom of the screen in
Scene Editor mode, as shown in Figure 1-7. The galleries are organized as a tree of folders
containing related objects. You can navigate the tree of galleries by clicking a gallery folder
to enter that gallery, or by using the gallery navigation bar, which is just above the galleries.
You will explore the galleries a bit before preparing to add objects to your new world.
1. Click the folder icon on the gallery navigation bar to move up one level in
the tree of galleries, so that you can see the top level in the tree, as shown
in Figure 1-8. Two icons are visible: one for the Local Gallery and one for
the Web Gallery.
Home
2. Click the Local Gallery icon to go back to the Local Gallery. Scroll left and
right through the Local Gallery using the scroll bar below the gallery fold-
ers, and you will see some of the many categories of objects available in Alice.
3. Find and click the Animals folder icon to open the folder. Scroll left and
right through this gallery to see some of the animal objects available in Alice.
O b j e c t C l a s s e s a n d I n s t a n c e s in Alice
Each of the tiles in the Animals folder represents a class of objects. A class is a group of
objects with the same properties and the same methods. Objects in the same class are virtu-
ally identical to each other, except that the values stored in some of their properties may be
different. For example, you could have an Alice world with two Penguin objects. They
16 Chapter 1 • An Introduction to Alice and Object-Oriented Programming
would both have the same methods and the same properties, but the values of some of those
properties, such as location or color, might be different.
Each copy of an object from a particular class is called an instance of the object. As you use
Alice, you will notice that the object class tiles in the object galleries have the word class in
their title and each begins with a capital letter, such as Class Bunny or Class Chicken, but
once an instance of an object is placed in a particular Alice world, its name begins with a
lowercase letter. Of course, it is possible to rename objects, so this distinction is not always
maintained.
The act of adding an instance of an object class to an Alice world is called instantiation.
The same terminology—classes, instances, and instantiation—is used in most object-
oriented programming languages.
You are going to add an instance of an object from the Animals folder in the Local Gallery
to your new Alice world. You are going to instantiate a Bunny class object.
1. Click the Class Bunny icon. A window with information about Bunny class
objects, like the one in Figure 1-9, should appear.
ftiBunny X
4
M M
u..,rl.-l.-.HV
ii4i«ed by-
pans:
a o
2. Click the Add instance to world button to put a bunny into the world. This is
sometimes called dropping an object into the world. You should see a bunny
appear in the center of the World window.
3 . You can also add an object to an Alice world by clicking an object class tile
and dragging it into place in the World window. Try this now: drag and
drop a chicken tile into your Alice world. This approach lets you place the
new object wherever you would like on the ground in the World window;
however, it does not show you the object's information window first.
4. You should now have an Alice world with two objects—a bunny and a
chicken. Notice that tiles for the new objects have also been added to the
Object tree. You really don't need the chicken for the rest of this exercise.
Tutorial 1C—Creating Your First Alice World
To delete the chicken, right-click the object or the object's tile in the Object
tree and select delete from the menu that appears.
Positioning Objects
The layout tools to the right of the World window in Scene Editor mode can be used to
manipulate objects. This area contains the seven standard tools listed in Table 1-1.
n Pointer tool Selects an object and moves the object parallel to the ground
m Turn tool Turns an object along its X-Y plane parallel to the ground
4 . After the bunny is in position, click the large green DONE button to close
the Scene Editor and go back to the standard Alice interface.
Adding S o m e Action
The next step is to add some motion to your world. You can start with something s i m p l e —
making the bunny move across the screen—and then add a little more action. To make
things happen in your world, you need to use methods for the objects. In the Editor area,
you already have the default method, which is world.my f i r s t method. The full name of
every method has two parts: the name of the object associated with the method (which
comes before the period) and the name of the method itself (which comes after the period).
1. Click the World tile in the Object tree in the upper-left corner of the interface.
2 . Click the methods tab in the Details area. You will see that the name of the
method in the Details area is simply my f i r s t method, but in the Editor,
you see the full name, world.my f i r s t method.
The default event can be seen in the Events area on the top-right side of the
interface. In Figure 1-11, you can see the tile for the default event, which
shows that the event trigger is When t h e world s t a r t s , and the event han-
dler is w o r l d , my f i r s t method. Any instructions you add to world .my
f i r s t method will be executed when the world starts to play.
Tutorial 1C—Creating Your First Alice World 19
3. Click the bunny tile in the Object tree. Now you can see information about
the bunny in the Details area. You should be able to see the bunny's meth-
ods in the Details area. You create new code for Alice objects by dragging
tiles for objects, other methods, and control structures into the method you
are currently editing. You get object tiles from the Object tree, method tiles
from the methods tab in the Details area, and logic and control tiles from
the bottom of the Editor area.
4. Make sure that the methods tab is selected in the Details area, and then find
and drag the bunny move tile into the middle of world.my f i r s t method
in the Editor area.
5. A short menu will appear asking you to choose the direction and amount
you want the bunny to move. Select forward for the direction, and then
1 meter for the amount.
Information that you must give to a method whenever you use the method is called
a method p a r a m e t e r . Direction and amount are two parameters for the move method.
6. To test your world, click the Play button near the upper-left corner of the
Alice interface. You will see the bunny move. It's not much, but it's a start.
Click the Restart button to play the world again, and then click the Stop
button to return to the standard Alice interface.
7. To change the amount the bunny moves, click the 1 meter parameter in the
move tile in your new method, and then choose one of the values in the
drop-down menu. You can also click other and then enter a number on the
calculator-style keypad that appears. Try changing the amount a few times
and then playing the world after each change until you can make the bunny
move to approximately the middle of the screen.
8. Let's add a few more instructions. First, find the bunny turn to face method
tile. It's in the Details area about 11 or 12 tiles below the bunny move tile
that you just used. You will probably need to scroll down to see it. The
parameter for this tile will be the object you want the bunny to face. Click
and drag the bunny turn to face tile into the Editor area and drop it below
the bunny move tile, and then choose camera as the object you want the
bunny to face.
20 Chapter 1 • An Introduction to Alice and Object-Oriented Programming
9. Next, you are going to add two tiles to make the bunny speak, and then you
will save the world. First, find and drag the bunny say tile into the Editor
area and drop it below your other two instructions. The parameter for this
method is the phrase you want the bunny to say. This parameter is a string
parameter, which contains a string of characters from the keyboard. When
the parameter menu appears, click other, and then type Hello, World! in the
Enter a string input box that appears, and then click OK.
Why "Hello, World!"? One of the most useful and popular programming languages ever cre-
ated was the C programming language developed at AT&T labs in the 1970s. The Hello,
World! program first appeared in a C language book written by two AT&T software develop-
ers, Brian Kernighan and Dennis Ritchie. Dr. Kernighan, who later became a professor at
Princeton University, actually wrote the first Hello, World! program for a tutorial on an ear-
lier programming language. Ever since then, it has been the custom for someone program-
ming in a new language to write a version of the Hello, World! program as his or her first
program. Congratulations, you've just done that in a new language! Let's add one more
instruction before saving the program.
1. Add another bunny say tile to make the bunny say "Hello, Dr. Kernighan!"
2. Now play your world again (several times if you'd like), and when you are
finished, click the Stop button to return to the Alice interface.
3. To save the world you created, click the File menu and then click Save
World. Notice that Alice has File menu options to Save World and to Save
World As. The first time you try to save a new world, you will see the
Save World As dialog box, as shown in Figure 1-12. This dialog box looks
similar to Save As dialog boxes in Windows programs, such as Microsoft
Word; the dialog box contains a navigation bar and other controls.
Whenever you want to make a copy of an Alice world, particularly if you
have made changes to it and want to keep the old world, use the Save
World As feature, and give the new copy a different name.
Tutorial 1C—Creating Your First Alice World
3
airport.a2w
baseball.a2w
boat game.a2w
j
chicken is tasty.a2w
cows.a2w
My
Desktop haunted house.a2w
Documents keyboard tutorial.a2w
Shackleton's penguins.a2w
titry dancer.a2w
My toy soldiers.a2w
Computer
4. Decide where you want to save the world, and then navigate to the
correct folder.
You may save Alice worlds wherever you wish. If you are in a course using Alice, please
find out where your instructor would like you to save your files, because this may depend
on how your classroom computers are configured. If you are working on your own, you
should save them someplace where they will be easy to find; remember (or write down)
where you saved each file. Appendix B contains more information about changing the
default settings for the save command.
5. Type the name hello world, with no punctuation, in the File name box.
Notice that the file type shown below the File Name box is A2W (Alice
World Files). This indicates that the file you save will end in the extension
,a2w. You should not change this. Click the Save button to save your world.
Whenever you want to make a copy o f an Alice world, particularly if you have made
changes to it and want to keep the old world, use the Save World As feature, and give the
new copy a different name.
22 Chapter 1 • An Introduction to Alice and Object-Oriented Programming
Next, close the Alice program and then open your saved world.
1. Click File on the menu bar, and then click Exit. The Alice program will close.
2. Reopen the Alice software. Click the Recent Worlds tab in the Welcome to Alice!
dialog box, and then open the hello world world that you created. If the name of
a world you want to open does not appear on the Recent Worlds tab, you can
click the Open a world tab and look for your world in the tree of folders.
The code from methods and events in an Alice world can be saved on an HTML Web page,
which you may then print, send as an e-mail attachment, or view like any other Web page.
You can also cut and paste items from the resulting Web page to other programs, such as
Microsoft Word or PowerPoint.
The steps in this tutorial show you how to save the code from your Hello, World! project as
an HTML file in the root directory on the C: disk drive. If you are a student in a course
using Alice, it is best to ask your instructor whether you should use the C: disk drive or
another location.
1. Click File on the menu bar. Notice that there are menu options to export an
Alice world as a Web page and to export code from an Alice world for printing.
You are going to use Export Code For Printing, which will put the code from
your Alice world as text on a Web page, rather than putting the Alice world
itself on a Web page as a Java Applet. These options on the hie menu are dis-
cussed in more detail in Appendix B. Click the Export Code For Printing
option. The Export to HTML dialog box, as shown in Figure 1-13, should appear.
jfti E x p o r t t o HTML...
What to export:
| world Select AH
Author's name;
2. Notice that you need to tell the computer what to print. In Figure 1-13, you
can see that you have only two items in your world that you can print. The
first is the default event, when t h e w o r l d s t a r t s , do world.my first
method, and the second is the default method, my f i r s t method. The
code for an Alice world consists of the code for all of its events, and for all
of its methods, but Alice lets you decide what parts of that code you want
to print. In this exercise, you will print everything because you only have a
small amount of code, but with large Alice worlds you may choose to print
just a few items at a time. Make sure that the boxes in front of both items
are checked, as shown in Figure 1-13.
3. You now need to tell Alice where you want to save the HTML file. This is the
tricky part. Use the Browse button to select the folder where the HTML file
will be saved, or enter the file name of the new HTML page in the Export to:
input box, as shown in Figure 1-13. Use the full path name, such as "C:\hello
world.html" (or another name, if directed to do so by your instructor).
4. You also need to add your name as the author of the code. Type your name
in the Author's name input box.
5. Click the Export Code button to create the new HTML document. Now you
can find the document where you saved it and open it in a Web browser to
look at your code. You can print the HTML page to print your code, cut and
paste from the page into Word or PowerPoint, copy the HTML page to
another location, send it as an e-mail attachment, or do anything with it
that you can do with any other HTML page.
T U T O R I A L 1 E — S A V I N G A N A L I C E W O R L D A S A M O V I E FILE
Alice 2.2 allows you to record the view in the World window while an Alice world is play-
ing as a QuickTime Movie file {*.mov}. You can view QuickTime movies on a computer
with QuickTime-compatible video player software, or via a Web browser equipped with a
QuickTime plug-in. Many computers and most Web browsers are equipped with such facili-
ties. QuickTime movies can also be e-mailed, burned on a CD or DVD, and posted to Web
sites, such as YouTube. You can convert QuickTime movies to other formats and edit them
with video-editing software, such as Adobe Premiere or Apple's iMovie. Chapter 7 of this
book discusses this further.
In this tutorial, you will record as a movie file the hello world Alice world that you created
in Tutorial 1C.
24 Chapter 1 • An Introduction to Alice and Object-Oriented Programming
1. Start Alice, and open the hello world Alice world that you created in
Tutorial 1C.
2 . Click the Play button and watch the world as it plays so that you are more
familiar with how long it takes to play. This world should take about three
seconds to play, so the movie you save will be short.
3. Click the Restart button if you wish to view the world again. Then, click
the Stop button to return to the standard Alice interface.
4. Click File on the Menu bar, and then click the Export Video option. You
may be surprised to see that the Save World As dialog box appears. This is
because you must save the world again as a part of the process of recording
a video. Type the the name of your world in the File Name box.
5. Click the Save button to save the world. When Alice finishes saving your
world, the video recording window will appear, as shown in Figure 1-14.
f
Alice World
File name:
Speed: 1x Klyvldeo i Play |MOV |»J
Restart Stop | Take
ExportPicture
Video |
r>
-
—, Pause!
You will only use a few of the items in the video recording window to
record this video. The rest are discussed in Chapter 7. Begin by typing the
name of your movie file in the File name box. It does not need to be the
same as the name of the Alice world.
Now you will actually record the video. You will click the Record button to
start recording. The world will start playing and recording when you press
the Record button. You will need to press the Stop Recording button to
Tutorial 1E—Saving an Alice World as a Movie File 25
finish recording; the recording does not stop automatically when the world
finishes playing. Do this now—click the Record button to start recording
and then click the Stop Recording button to finish recording. You will need
to pay attention and be quick; this movie is only about three seconds long.
8. Next, you will export the recorded video to a file. The file will be saved in
the same folder as the Alice world file [*.a2w) for this world. Click the
Export Video button. If the button is dimmed, then wait—Alice is not yet
finished rendering the video.
9. When you click the Export Video button, Alice will first encode the video
and then the audio. Next, Alice will merge the sound and video.
Information boxes will appear telling you that this is happening, as shown
in Figure 1-15. Alice renders and saves the movie file frame by frame. This
process takes a few seconds for a short video and much longer for long
videos, so be patient. When the information boxes stop appearing, then the
video has been saved.
0:00
10. Click the Stop button to close the window, and then close the Alice soft-
ware. Your video file should be in the same folder as the Alice world you
recorded.
Chapter 1 • An Introduction to Alice and Object-Oriented Programming
Chapter Summary
This chapter consisted of an introduction followed by five hands-on tutorials. The introduction discussed the following:
• Most modern computer programming languages are object-oriented languages in which programs are
organized as sets of methods that manipulate the properties of objects stored in a computer.
• An object is a collection of properties and methods that can be used to manipulate those properties,
• The values stored in the properties of the object at any given time are called the state of the object.
• A class of objects is a collection of all objects that have the same properties and methods,
• Alice uses an object-oriented style of programming; in Alice, objects exist in a three-dimensional virtual
world, which can be seen on a computer screen.
• Alice makes it easier to learn programming because it requires minimal memorization of syntax and it
provides visualization and rapid feedback.
In Tutorial 1 A, you explored the Alice interface, which has five main work a r e a s — t h e World window, the Object tree,
the Details area, the Editor area, and the Events area, as well as a menu bar, a Play button, an Undo button, a Redo
button, a Trash can icon, and a Clipboard icon.
In Tutorial 1B, you learned to load and play an Alice world, and to use the speed slider control and the Pause, Play,
Restart, Stop, and Take Picture buttons that appear when a world is playing.
In Tutorial 1C, you learned to create your own simple Alice world. You learned how to add objects from the object
gallery, position them in the virtual world with the Scene Editor layout tools, and add instructions to the default method
that is initiated by the default event.
In Tutorial 1D, you learned that Alice code may be exported to an HTML Web page and then viewed or printed from the
Web page.
In Tutorial IE, you learned how to export a playing Alice world as a QuickTime movie file.
Review Questions
3. Describe the role of each of the five main areas of the Alice interface: the World window, the Object tree, the
Details area, the Editor area, and the Events area.
6. What is the difference between the Pause and Stop buttons in the window for a playing Alice world?
8. What is the difference between the standard Alice interface and Scene Editor mode?
9. List and describe the function of the following Scene Editor layout tools: the Pointer tool, the Vertical tool, the
Turn tool, the Rotate tool, and the Tumble tool.
10. Alice methods have full method names, such as r o b o t . d a n c e . Describe the meaning of the t w o different
parts of the full method name.
Exercises
1. It can be very difficult for people to write clear and complete algorithms, such as a set of directions. People
often take things for granted when writing directions; however, individuals are usually able to interpret poorly
written directions. For example, directions often contain phrases like "turn left at the third red light." But, what if
one of the lights is green? Does it count? Would a person even ask this question, or would he or she just make
an assumption about what the writer meant? How would a computerized robot handle such a problem? Try
writing a detailed set of directions for a simple everyday process, such as making a pot of coffee, and then
exchange your directions with another student. Critique each other's directions to see if they are clear and c o m -
plete. Did the writer make assumptions that caused steps to be left out of the algorithm?
2. Comments can appear in the code for Alice methods to identify the author and purpose of the method, and to
describe any parameters or special techniques used in the method. You can add comments to a method by drag-
ging the c o m m e n t tile, shown in Figure 1 - 1 6 , and dropping it into the method where you want the comment to
appear. You can edit the comment tile by clicking it, and then editing the text.
Chapter 1 • An Introduction to Alice and Object-Oriented Programming
Open the hello world Alice world that you saved as part of Tutorial 1C, and add t w o comments at the beginning
of the method, as shown in Figure 1 - 1 6 .
—
w o r l d . m y f i r s t method Noparameters | create nt
Do in order Oo together if U s e Loop While For all in order for all together delay print comment tile
3. Open the hello world Alice world that you saved as part of Tutorial 1C, and add some additional animation t o
the world. You may want to experiment with the methods to make the bunny move, turn, and roll. See if you can
do the following:
What is the difference between turn and roll? What difference does it make if you change the order of instruc-
tions in a particular world? When you are finished, click Tools on the menu bar, and then click World Statistics to
see how long your Alice world has been open.
4. The methods available for the Bunny class of objects are called primitive methods and are available for all Alice
objects. Certain classes of objects, such as the Penguin class, have additional methods available. Try starting a
new world with a penguin and experiment with some of its user-created methods. These methods include
wing_flap, glide, jump, jumping, walk, a n d walking.
5. Try creating, playing, and saving another Alice world on your own. While doing so, follow these t w o pieces of
advice:
a. Follow McGinley's Rule for New Programmers: K.I.S.S.—Keep it Small and Simple. You should experiment,
but be careful about getting in over your head. Try a f e w simple things with only a few objects to get started.
b. Try to plan what you will do in the world before you start working on it. Keep in mind the Rule of the Six P's:
Proper Prior Planning Prevents Poor Performance. Many developers of Alice worlds like to outline or story-
board their work first. They draw a series of a f e w simple sketches of what they would like to try to make
the objects in the world do. Professional programmers also use pseudocode and flowcharts, which you will
learn about in later chapters, to design the algorithms that methods will follow.
Exercises 29
6. Try planning and creating a simple Alice world as part of a team of students. How does this experience differ
from working on your own?
7. In Alice, tool tips appear if you place the mouse pointer on one of the tools, buttons, or tabs on the Alice inter-
face and leave it still for more than two seconds. Table 1 -1 in Tutorial 1C shows how the Scene Editor tools can
be used to manipulate objects, but the table doesn't tell you everything. The tool tip for the pointer tool in the
Scene Editor mode lists several additional ways to use the Alice pointer. See if you can find out what they are.
8. There are many Web sites that contain useful information about c o m p u t e r technology. Here are t w o for you
to try: www.webopedia.com and www.wikipedia.com. Both are free online encyclopedias. Webopedia
focuses on computer technology and provides a brief definition of terms and links to other sites. Wikipedia is
more general. Wikipedia is a free Web-based encyclopedia written collaboratively by volunteers. Pick a f e w
of the terms f r o m this lesson, such as algorithm, object-oriented p r o g r a m m i n g , or IDE, and see what you can
find out. You can also look up people, such as Brian Kernighan. The Wikipedia page at http://en. wikibooks.org/
wiki/Computer_programming/Hello_world\ia.s the Hello, World! program in dozens of different computer
languages.
9. A class is often called "a blueprint for instances of an object." What does this mean with regard to object-
oriented programming?
10. Alice lacks some of the features of a true object-oriented programming system, such as polymorphism and true
inheritance. See if you can find out what the terms inheritance and polymorphism mean with regard to object-
oriented programming, and describe them in your own words.
Methods
Describe the processes known as top-down design and modular development, and
discuss why they are often used together, how organizational charts are used in these
processes, and some of the advantages of modular development of new software
Describe the difference between primitive methods and user-created methods in Alice,
and demonstrate how to run primitive methods to directly position objects and manipu-
late the camera in an Alice world
Create new methods in Alice in a manner that demonstrates good top-down design
and modular development
Create and demonstrate the use of methods in Alice that contain method parameters
31
32 Chapter 2 • Methods
Engineers are the people who design and build things, and just as civil engineers design and
build roads and bridges, software engineers design and build computer software. Computer
programming is part of the software engineering process, which usually involves newer
object-oriented design, combined with more traditional methods of algorithm development.
Object-oriented software engineering starts with understanding what the new software must
do. Software engineers decide what objects will be needed for the program, and then use
existing objects and build new ones to create the software. You will use Alice to develop new
software—in this case, small virtual worlds—using objects from Alice's galleries of objects.
You will focus on creating methods and events for the objects in your virtual worlds. Since
each method is an algorithm, a step-by-step process, this chapter focuses on the design of
algorithms. You will learn some techniques for designing and building methods so that you
can begin to design and build your own computer programs.
The language of problem solving is often used in engineering. Working to complete a task that
is part of an engineering project is seen as building a solution to a problem. The process starts
with problem specification. Once you have a clear understanding of the problem, you can
start to solve it.
It's easier to solve smaller problems than it is to solve big ones, so good engineers often start
solving a problem by trying to break it into more manageable parts. This process of decom-
position is sometimes referred to as a divide-and-conquer approach to problem solving. In
this approach, a problem is broken into parts, those parts are solved individually, and then
the smaller solutions are assembled into a big solution. Computer programmers and software
engineers do the same thing when developing new software.
This process, also known as top-down design or top-down development, starts at the top
with one concept or big idea, which is then broken down into several parts. If those parts
can be further broken down, then the process continues. The end result is a collection of
small solutions, called modules, which collectively contain the overall solution to the origi-
nal problem.
Here is an example of top-down development from the world of business. Imagine that you
want to write a computer program to process the payroll for a large company. Your big idea
is named "Payroll." What would you need to do if you were going to process a payroll?
Generally, you would need to get some data, perform some calculations, and output some
results. Figure 2-1 shows Payroll broken down into these three modules.
Top-Down Design and Modular Development 33
PAYROLL
You can go further in breaking down the problem. There are two different sets of data—old
data, such as a list of employees, and new data, such as the number of hours each person
worked during a specific week. The old data will probably come from a database, while
the new data will be entered into the system for the first time. Therefore, the Get Data
module can be broken down further into Get Old Data and Get New Data. If the Perform
Calculations and Output Results modules are broken down in a similar manner, and then the
submodules of those modules are broken down, and so on, then the final design might look
something like the one in Figure 2-2. Such a diagram is called an organizational chart.
PAYROLL
PERFORM OUTPUT
GET DATA
CALCULATIONS RESULTS
GET OLD DATA GET NEW DATA GROSS PAY DEDUCTIONS NET PAY CHECKS CHECK
(FROM A FILE) (ENTERED) REGISTER
FEDERAL HEALTH
INCOME TAX INSURANCE UNION DUES
STATE LIFE
INCOME TAX INSURANCE UNITED WAY
FICA
34 Chapter 2 • Methods
Organizational charts show how separate units are organized to form a single complex entity.
The upper levels are broken down into the parts at the lower levels, and the parts at the
lower levels are layered together to form the upper levels. In Figure 2-2, you can see how the
specific modules are combined to form the overall payroll program. A programmer, or a team
of programmers working together, can create each of the modules as software methods, and
then put them together to build the entire payroll program.
The process of top-down design leads to modular development, in which parts, or modules,
are developed individually and then combined to form a complete solution to a problem.
Modular development of computer software has the following advantages, especially for
larger projects:
The last point in this list is one of the most important concepts in all of computer program-
ming. Reusable code makes programming easier because you need to develop the solution
to a problem only once; then you can use that code whenever you need it. You can also save
the modules you have developed and reuse them later in other projects, modifying them if
necessary to fit new situations. Over time, you can build libraries of software modules for
different tasks. All computer programs, from the lowest levels of an operating system that
directly control hardware to the most complex user applications, are made up of layers of
short programming modules that are constantly reused in different situations.
Top-Down Design and Modular Development 35
Figure 2-3 shows a portion of the methods tab for the iceSkater from the lakeSkater world
seen in Chapter 1. Methods to perform simple tasks, such as s p i n , b l i n k E y e s , and jump,
are reused as necessary to form the overall routine in this Alice world. The entire skater
object can be reused in other worlds where different routines might be assembled from
these simple methods. As you create Alice worlds, you should keep this concept in mind
and try to write small reusable methods as often as possible. This approach to programming
will serve you well in any language you use and is one of the driving principles behind much
of the modern object-oriented approach to programming. Good computer software is filled
with reusable code, and Alice is no exception.
FIGURE 2 - 3 : The methods tab for the iceSkater from the lakeSkater world
IceSkater's details
properties ["methods ["functions
skate howManySteps edit I
spin | edit |
blinkEyes |edit|
setBlink shouldBlink [ edit |
lookAndWink |edit|
simpleSpin [edit |
circleAround whichObject j edit |
skateBackwards howManySteps edit j
jump [edit |
go wireframe edit j
go solid | edit |
create new method
IceSkater move
IceSkater turn
IceSkater roll
36 Chapter 2 • Methods
* Design
Design
Debug Code
Test
Designing Methods
Software design begins by writing clear specifications for what the software is supposed to
do. Before you can design something, you must have a clear understanding of what it is
supposed to do. Top-down development and modular design are used from the beginning of
the design process and help designers break a complex problem into parts that can be more
easily understood. The parts can then be coded and tested as individual methods, each with
its own specifications for completing a single task.
Techniques for describing the design of software methods, such as the use of flowcharts,
pseudocode, and storyboards, will be discussed in subsequent chapters. In this chapter, to
begin, you simply list or outline what your new software is supposed to do, and then break
down your design into smaller parts that can be developed as individual methods perform-
ing single tasks.
The software design process does not depend on a particular programming language,
although it does help to know what language will be used to implement the software. That
way, your design can take advantage of the features of that language. This is difficult for
new programmers, who are trying to learn about software design and a new language at the
same time. In this chapter, you will gain some more experience using Alice, which will
help you become a better designer of Alice software.
The Software Development Cycle 37
C o d i n g M e t h o d s in A l i c e
One of the unique features of Alice is its drag-and-drop interface, in which tiles containing
existing instructions or logic and control structures can be dragged into place to create a new
method. Recall from Chapter 1 that tiles for existing methods can be found on the methods
tabs for various objects, while logic and control tiles can be found at the bottom of the Editor
area, as shown in Figure 2-5. Logic and control tiles will be discussed in Chapter 3.
FIGURE 2 - 5 : Logic and control tiles can be found at the bottom of the Editor area
J w o r l d . m y first m e t h o d
w o r l d . m y first m e t h o d No parameters create new parameter
No variables create new variable
Do Nothing
logic and
control tiles
Do in order Do together If Else Loop While For all in order For all together Wait print
In more traditional programming languages, such as Java, C++, or Visual Basic, the coding
phase of software development includes carefully translating a software design into a partic-
ular language, and then entering that language into the computer. Dragging Alice's language
tiles into place to create new methods, however, is a little different. Alice programmers are
able to focus their attention on the logic of how new methods will operate rather than on the
syntax of the language.
T e s t i n g a n d D e b u g g i n g Alice M e t h o d s
Software testing is a specialized branch of software engineering. The techniques that profes-
sional software developers use to test newly developed methods are varied and can be com-
plex, but generally they involve answering a few simple questions, such as the following:
Does the new method do what it is supposed to do? This is known as a test
for correctness. Tests for correctness measure whether the program meets
the original specifications.
38 Chapter 2 • Methods
Is the method reasonably efficient? How much time does it take for the
method to complete its task, and how much storage space does it use? If a
program takes two hours to sort a list that another program can sort in two
seconds, then it is not a very time-efficient program. Similarly, one pro-
gram might use more or less storage space than another program. Typically,
time efficiency is more critical than space efficiency as computer memory
chips and disk drives become larger and less expensive.
Does the method have any undesirable side effects? For example, if a method
to print a long document also erases the hard disk drive, then the method has
an undesirable side effect. Side effects can be related to how methods change
stored data, how one method affects another method, or even how two
instructions in the same method affect each other. For example, Alice meth-
ods to move and turn an object at the same time can produce unexpected
results if the programmer failed to consider that the object's direction was
changing as it turned.
Software testers must develop a testing plan that examines new software under all possible
circumstances. If the program will perform operations on data sets, such as sorting a list or
performing a numerical analysis of the data, the software testers need to develop sample data
sets that test the program under all possible scenarios.
Software developers perform two general types of tests: unit tests and integration tests. A
unit test checks to see if the method works as expected all by itself. An integration test
checks to see if the method works when it is placed into a larger program in combination
with other methods.
Sometimes a unit test can be performed by running a newly developed method all by itself,
and sometimes it is necessary to create another method, called a testing shell. A testing
shell is a short method that simulates the environment in which a newly developed method
will be used.
In the lakeSkater demonstration that you have already seen, the iceSkater's s p i n method
could be tested without a testing shell. The method could be run all by itself, and the tester
could observe the action to see if the method performs according to specifications.
Once a method has been unit tested and debugged, it can be integration tested. That is, it
can then be put in position in the overall program, which is then be run to see if it works
with the new method in place.
This chapter only scratches the surface of testing and debugging, which can be quite com-
plicated and detailed. For now, just try to keep the following questions in mind:
Has the program been tested under all possible circumstances? This is
especially important if the program has numeric input. For example, what
happens if you tell a method to move forward a negative amount? What
happens if you tell a method to turn a negative number of revolutions?
If any problems are discovered when the software is tested, then the cause of the problem
needs to be isolated. Here unit tests are most helpful, especially if the software has been
developed as many smaller modules, rather than as a few larger modules. Once you know
what is causing the error, you can develop a plan to fix the problem, modify the necessary
method or methods, and then test again.
TUTORIAL 2A—WORKING W I T H P R I M I T I V E M E T H O D S IN A L I C E
Alice objects have two kinds of methods—primitive methods and user-defined methods.
Primitive methods are built-in, predefined methods that are part of each Alice object. They
provide simple basic behaviors, such as move, turn, and roll. User-defined methods are
written by people who use Alice. Some of the objects in the Alice object galleries already
include user-defined methods in addition to the standard set of primitive methods. For
example, the Penguin class has a w i n g _ f l a p method. You can use primitive methods and
user-defined methods to write new methods of your own.
Primitive methods are also encapsulated methods. Encapsulation means that the details of a
method are hidden from the user; the user cannot see or edit the details of the method. All
primitive methods are encapsulated. In Alice, user-defined methods are not encapsulated.
1. Start Alice, click the Templates tab when the Welcome to Alice! dialog box
appears, and begin an Alice world using the snow template.
2. Once the new world is open, click the large green ADD OBJECTS button in
the lower-right corner of the World window to enter Scene Editor mode.
3 . Now you can see the object galleries at the bottom of the screen. Click the
Animals gallery, and then find and click the Class Penguin tile.
40 Chapter 2 • Methods
You should see the Information window for the Penguin class of objects, as shown in
Figure 2-6. It contains information about the designers who modeled and painted the
Penguin class, specifies how much memory is required for an instance of the object, and
lists user-created methods that the designers included to give the penguin additional
behaviors, such as flapping its wings, turning its head, and walking.
Let's add the penguin to the new world and then look at its methods tab.
1. Click the Add instance to world button, and then click the DONE button.
This will return you to the standard Alice interface.
2. Click the penguin tile in the Object tree and the methods tab in the Details
area. You can now see the methods tab for your instance of the Penguin
class of objects, which is shown in Figure 2-7.
Tutorial 2A—Working with Primitive Methods in Alice 41
penguin's details
" : 1
["properties [methods [functions 1
-
wingjlap times | edit [
lumping height edit |
turn_head_right [ edit |
tumjieadjeft | edit |
glide edit |
jump times edit |
walk m o v e j i m e edit |
walking x e di<|
penguin move
penguin turn
penguin roll
penguin resize
Tiles for the penguin's user-created methods appear above the create new method button
and are each followed by an edit button. Notice that this set of methods matches the list in
the Penguin's Information window. The tiles below the create new method button are the
primitive methods that come with each Alice object. They have no edit button because they
are encapsulated.
R u n n i n g Primitive M e t h o d s D i r e c t l y
Primitive methods may be used to build more complex methods, or they may be run
directly. You can run a primitive method directly by right-clicking an object or an object tile
in the Object tree, and then selecting the method you want to run from the list that appears.
42 Chapter 2 • Methods
One of the penguin's primitive methods is the t u r n t o f a c e method. Let's run this method
directly to make the penguin face the camera.
1. Right-click the penguin tile in the Object tree, and then select methods on
the small menu that appears. Now you should see a list of the penguin's
primitive methods, as shown in Figure 2-8.
penguin
methods
rename
Camera get a good look at this
capture pose
delete
penguin say
save object...
penguin think
penguin's details ramete
penguin play sound
properties [methods [functions penguin move to
wing_flap times dit| penguin move toward
e
This is an example of how you can run primitive methods directly, without saving them as
part of a program in the Alice world. This is a good technique to use to manipulate objects
when setting the scene for an Alice world, or simply to learn how certain methods work.
Sometimes in Alice, an object is off-camera, and you may not be sure exactly where the
object is. Off-camera means that an object cannot be seen on the screen with the camera in
its current position. Often it can be difficult to find an off-camera object by manually
manipulating the camera. There are several primitive methods that you can run directly to
help find the lost object.
1. First, using the blue arrow controls at the bottom of the World window,
manipulate the camera so that you cannot see the penguin anymore. Now
the penguin is off-camera.
2. Now you can find the penguin. Right-click the camera tile in the Object
tree, select methods on the menu that appears, and then select camera
point at. On the target menu that appears, select penguin, and then select the
entire penguin, as shown in Figure 2-9. On your screen you will see that the
camera is now pointing at the penguin. Can you see how this might be a
useful method to run directly?
Chapter 2 • Methods
A A |2 I 8/1/2009) [Modified]
File Edit loots Help
I
nghtWing
camera play sound
leftWing
camera get a good look at
3 . Using the blue arrows, again move the camera so that the penguin is
off-camera.
4. This time, run the camera g e t a good l o o k a t method on the entire
penguin. Do you see how this is a little different than the camera p o i n t at
method?
5. Try experimenting by running a few more of the penguin's methods
directly before moving on to the next tutorial. For example, determine the
difference between the t u r n and r o l l methods by running them directly.
Tutorial 2B—Creating New Methods in Alice 45
T U T O R I A L 2 B — C R E A T I N G N E W M E T H O D S IN A L I C E
In this tutorial, you will practice some of the techniques discussed earlier in the chapter to
create an Alice world with several new methods. You will create a world with three objects
from Lewis Carroll's Alice's Adventures in Wonderland—the Cheshire Cat, the White
Rabbit, and Alice, and you will write methods to make them jump up and down. The Alice
software really has no connection to Lewis Carroll's story except for the name Alice, but it
might be more interesting to use these characters in this exercise.
It's easy to find objects for Alice and the Cheshire Cat in the object galleries, but you need to
be careful with the White Rabbit—there are classes for Bunnies, Rabbits, and Hares, in addi-
tion to the WhiteRabbit class. You want the White Rabbit with the waistcoat and pocket
watch on a chain, as described by Lewis Carroll in Alice's Adventure's in Wonderland.
Alice started to her feet, for it flashed across her mind that she had
never before seen a rabbit with either a waistcoast-pocket, or a watch
to take out of it, and burning with curiosity, she ran across the field
after i t . . .
Setting the S c e n e
The first step in creating a new world is to set the scene by opening a template, adding neces-
sary objects, and positioning things. In long programs, a naming convention is needed to make
it easier to read the names of the many objects, methods, and variables used within the pro-
gram. As you work with Alice, you will notice that the names of classes and objects in Alice
follow a pattern called the CamelCase naming convention, which is used with most program-
ming languages and is recommended by many software developers, such as Microsoft.
CamelCase is the practice of writing compound names without using blank spaces, but capi-
talizing the first letter of each name that forms the compound name, like the name CamelCase
itself. In Alice in Wonderland, the proper name of the character is Cheshire Cat, while the
name of the class of characters in the Alice object gallery is CheshireCat. You will also notice
that the very first letter of object class names begin with capital letters, whereas the names of
instances of a class begin with lowercase letters. The class name is CheshireCat, with a capital
C at the beginning; the first instance of the class is named cheshireCat with a lowercase c.
1. Start the Alice software, select the grass template from the Templates tab,
and then click the Open button. Next, click the ADD OBJECTS button to
enter Scene Editor mode.
2. You need to add the three characters to this Alice world and position them
so they appear as shown in Figure 2-10. Start with the Cheshire Cat. Click
Local Gallery, and then click Animals. Click the CheshireCat tile, and then
click the Add instance to world button. A cheshireCat should appear near
the center of the world window, and a cheshireCat tile should appear in the
Object tree.
Tutorial 2B—Creating New Methods in Alice 47
3 . Drag the cheshireCat over to the left side of the World window, as seen by
the camera.
4 . Next, you will make the cat turn to face the camera. Right-click the
cheshireCat tile in the Object tree, and then point to methods from the
small menu that appears.You should see a list of the cheshireCat's primi-
tive methods, similar to Figure 2 - 1 1 .
Chapter 2 • Methods
3 ^TCI
camera
flight
uf^) ground
ffl Ift cheshireCat . ~r~~
cheshireCat
ffl Q whrteRabWti methods cheshireCat m o v e
u?^ aliceLiddell rename cheshireCat turn
C a m e r a get a good look at this cheshireCat roll
capture p o s e cheshireCat resize
delete
cheshireCat s a y
save olriect...
cheshireCat think
world's details cheslnreCat play sound
About halfway down the list, find and point to the cheshireCat turn to face
method, and then click camera as the target object. On the screen you should
see the cheshireCat turn to face the camera.
6. The WhiteRabbit class is in the same animal gallery as the CheshireCat
class. Note that you will have to scroll to the far right in the Animals
gallery to see it. Add an instance of the WhiteRabbit class to your world.
After you have added an instance of the WhiteRabbit class to the world,
you will need to position it on the right side of the world window, facing
the camera, just as you positioned the cheshireCat on the left. To do this,
Tutorial 2B—Creating New Methods in Alice 49
drag the whiteRabbit over to the right, and then run the method to make it
face the camera as you did with the cheshireCat.
8. Finally, add an instance of the AliceLiddell class to your world. The
aliceLiddell object can be found in the People gallery. Alice Liddell was the
young daughter of a friend of Lewis Carroll's for whom the story Alice's
Adventures in Wonderland was named. Leave Alice in the center of the
scene, and make her turn to face the camera, as you did with the other two
objects. You are finished setting the scene, so exit the Scene Editor Mode by
clicking the large green DONE button.
Designing a Method
The design of a new method begins with specifications. In the simple case in this tutorial,
the specifications are given: the three characters will first appear on a grass background,
and then they will jump. The White Rabbit jumps, the Cheshire Cat jumps, and then Alice
Liddell jumps. Alice's programming language has no primitive instruction to make an
object jump up and down, so you will need to use the move up and move down methods to
make each character jump. Figure 2-12 contains the organizational chart for the program.
TRIPLE JUMP
And finally, an expanded outline for the program would resemble Figure 2-14.
FIGURE 2 - 1 4 : An expanded outline for the jumping program showing more detail
1. whiteRabbit jump
a. whiteRabbit move up
b. whiteRabbit move down
2 . cheshireCat jump
a. cheshireCat move up
b. cheshireCat move down
3 . aliceLiddell jump
a. aliceLiddell move up
b. aliceLiddell move down
Top-down design and modular development suggest that separate jump methods should be
written for each object rather than placing all of the code into a single method. By using
proper programming techniques as you begin to write short programs like this one, you will
develop good habits that will help you when you write larger programs, whether in Alice,
Java, Visual Basic, or another language.
C o d i n g the J u m p M e t h o d s
To make an object jump, you will simply move the character up one meter and then move
the character down one meter.
1. Start by creating a jump method for the whiteRabbit. Click the whiteRabbit
tile in the Object tree, and then click the methods tab in the Details area.
2 . Click the create new method button, and a small New Method dialog box
will appear asking you to name the method. Type jump as the name for the
new method, and then click the OK button. In the Editor area, a new tab
appears for a blank method with the name w h i t e R a b b i t . jump, as seen in
Figure 2 - 1 5 .
Tutorial 2B—Creating New Methods in Alice 51
FIGURE 2 - 1 5 : A n e w m e t h o d t a b w i t h t h e n a m e w h i t e R a b b i t . j u m p
Do Nothing
Do in order Do together rf Else Loop While For all in order For all together Wait
print
The new blank method in the Editor area has several components. The name of the method
appears on a tab at the top of the method and again on the method's first line of text, fol-
lowed by the phrase No parameters. To the right of this is a create new parameter button. On
the next line of text is the phrase No variables, with a create new variable button on the
right. Your method will not have any variables or parameters, so for the moment, you can
ignore these buttons. (You will learn more about variables and parameters later in this chap-
ter.) The lines of text at the top of the method can be considered a method header, which
gives us information about how the method works. From the header information, you can
see that you can run this method without any parameters, and that there are no variables in
the method.
You can see a box with rounded corners containing the phrase Do Nothing below the header
for the method. This part of your method is sometimes called the instruction zone. Right
now there are no instructions in the method, so the zone has the text Do Nothing.
You now want to add an instruction to your method to make the whiteRabbit move up one
meter, followed by an instruction to make the whiteRabbit move down one meter, as shown
by the specifications in Figure 2-14.
1. Drag the whiteRabbit move tile from the left side of the screen and drop it
on the Do Nothing phrase. The tile will be surrounded by a red border as
you drag it. The border will turn green when you reach the right place.
2. When you drop the tile into the instruction zone, a menu will appear asking
you the direction in which you want to move the object. Select up for the
direction, and then select 1 meter for the amount. Direction and amount are
52 Chapter 2 • Methods
• whiteRabbit.jump
w h i t e R a b b i t . j u m p Mo parameters
No variables
You are finished with the w h i t e R a b b i t . jump method. Now you need to create a jump
method for the cheshireCat, just as you did for the whiteRabbit.
1. Select the cheshireCat tile in the Object tree, and then click the methods
tab in the Details area.
2. Click the create new method button, and then name the method jump.
3. Add an instruction to make the cheshireCat move up 1 meter.
4. Add an instruction to make the cheshireCat move down 1 meter.
5. Create a jump method for aliceLiddell in a similar manner.
Next, you need a method that calls all three jump methods in the order in which you want
the characters to jump. This method will be your main method, at the top of the organizational
chart. World.my f i r s t method is often used as this top-level method, and you will use that
here. This is a world-level method, associated with the world itself rather than with any
particular object in the Alice world.
1. Start by clicking the world tile in the Object tree, and then click the methods
tab, to view the methods in the Details area. Things look a little different
here than when you looked at an object's methods. There are no primitive
methods listed below the create new method button, but my f i r s t method
already exists as a user-created method.
Tutorial 2B—Creating New Methods in Alice 53
2. Click the edit button. This will open up the method for editing in the Editor
area. It begins as a blank method with no parameters, variables, or instructions.
Your plan calls for the whiteRabbit to jump, followed by the cheshireCat, and
then by aliceLiddell.
3. First, you want the whiteRabbit to jump. Click the whiteRabbit tile in the
Object tree, and then click the methods tab in the Details area. Notice that
there is a tile for the jump method above the create new method button
because this is a user-created method that can be edited.
4. Click the jump tile and drag a copy of it into the instruction zone of world.my
f i r s t method.
5. Next, you need to add a cheshireCat. jump method. Click the cheshireCat
in the Object tree and drag and drop the cheshireCat's jump method into
world.my first method. Make sure that you drop it just below the
whiteRabbit. jump instructions in the desired sequence.
6. Finally, you need to add the aliceLiddell. jump method by clicking
aliceLiddell in the Object tree and then dragging and dropping its jump
method below the cheshireCat. jump instruction. Your screen should
resemble Figure 2-17.
FIGURE 2 - 1 7 : A d d i n g t h e t h r e e j u m p m e t h o d s
• w o r l d . m y first m e t h o d 1
w o r l d . m y first m e t h o d No parameters create new parameter
whiteRabbit .jump
cheshireCat.jump
aliceLiddell.jump
Do in order Do together If.'Else Loop While For all in order For all together Wait print
If you have done everything correctly, then your Alice world should be ready for testing.
A parameter is a v a r i a b l e w h o s e v a l u e is p a s s e d f r o m one m e t h o d to a n o t h e r — j u s t l i k e a
baton is p a s s e d f r o m one r u n n e r to a n o t h e r in a r e l a y r a c e . A v a r i a b l e is a v a l u e that can
c h a n g e i n s i d e a m e t h o d , and a p a r a m e t e r is a v a r i a b l e w h o s e v a l u e is p a s s e d f r o m one
method to a n o t h e r . In the l a s t t u t o r i a l , you had to tell the w h i t e R a b b i t . m o v e m e t h o d the
direction and a m o u n t you w a n t e d the whiteRabbit to m o v e in y o u r j u m p m e t h o d . These
v a l u e s are p a r a m e t e r s for the p r i m i t i v e w h i t e R a b b i t . m o v e m e t h o d . In t h i s t u t o r i a l , you
will add a height parameter to the w h i t e R a b b i t . jump m e t h o d .
Tutorial 2C—Methods With Parameters 55
Creating a P a r a m e t e r
You need to give your parameter a name, and declare what data type the parameter will be.
Remember that the computer stores different data types in different formats, so you need to
tell the system what data type to use for this new parameter. The data type can be an Alice
object, a number, a Boolean value (true or false), or any one of more than a dozen types built
into Alice, such as a string of text, a color, a sound file, a direction, and so on.
1. First, open the triple jump Alice world from the previous tutorial.
2. Save the world with the new name triple jump with parameters before you
begin editing. This will ensure that you do not change the original triple
jump world.
3. Next, select the whiteRabbit tile in the Object tree, and then click the
methods tab in the Details area. Click the edit button, and the
w h i t e R a b b i t . jump method will appear in the Editor area.
4. Click the create new parameter button on the right side of the jump
method's header information, and a Create New Parameter dialog box
appears, as seen in Figure 2-18.
Type: • Number
Boolean
Object
', Other...
Li make a
Cancel
5. Type height as the name of your new parameter and select Number as the data
type. Make sure that the make a List box is not checked, and then click the OK
button. Now you should see a tile appear after the name of the method showing
you that this method has a number parameter, as shown in Figure 2-19. The
height parameter may now be used like a variable within the method, and its
value must be specified whenever this method is called from another method.
Chapter 2 • Methods
Do in order Do together If Else Loop While For all in order For all together Wait print
Using a Parameter
Notice in Figure 2-19 that the whiteRabbit.move instruction tiles in the whiteRabbit. jump
method in the Editor area each say up 1 meter and down 1 meter. These are the values passed
to the primitive whiteRabbit.move method as it is called from the whiteRabbit. jump
method. You are going to replace 1 meter in each of these instructions with the new height
parameter that you just created. Then, whenever the whiteRabbit. jump method is used, the
programmer will be able to specify how high the whiteRabbit should jump.
1. Drag the height parameter tile and drop it in the whiteRabbit move up
instruction tile in place of 1 meter.
2. Drag the height parameter tile and drop it in the whiteRabbit move down
instruction tile in place of 1 meter. The whiteRabbit. jump method in the
Editor area should now look like Figure 2-20.
Do in order Do together If Else Loop While For all in order For all together Wait print
Tutorial 2C—Methods With Parameters
3. Now click the world.my first method tab in the Editor area to see that
method. Notice that the whiteRabbit.jump tile now uses the height parameter
and that its value is set to 1. The jump method tiles for the cheshireCat and
aliceLiddell do not yet have this parameter.
4. Click the height parameter tile in the whiteRabbit.jump tile and a menu
should appear as shown in Figure 2-21. Select 2 from the menu.
FIGURE 2 - 2 1 : A m e n u t o c h a n g e t h e v a l u e of a p a r a m e t e r
whiteRabbit.jump hetgitt = 1
cheshireCat.jum|] 0.25
aliceLiddell.jump 0.5
• 1
2
math •
other...
Do in order Do together If.Else Loop While For all in order For all together Wait print
5 . Now play the world and watch how the height that the whiteRabbit jumps is
higher than the height that the cheshireCat and aliceLiddell jump.
6. Change the value of the height parameter several times and try the world
again. Remember to save the world and exit Alice when you are done.
The set of parameters that appear in the method header at the top of a method is called the
formal parameter list. The values that are used when the method is called from another
method are called the actual parameters. Actual parameters are very much like argu-
ments o f a function in mathematics, such as the value 45 degrees in the expression
X = SIN (4 5 degrees).
Chapter 2 • Methods
Chapter Summary
This chapter consisted of discussions of top-down development, modular design, and a simple software development
cycle, followed by three hands-on tutorials involving Alice methods. The section on t o p - d o w n design and modular
development discussed the following important points:
• Computer programming is part of the software engineering process, which usually involves newer meth-
ods of object-oriented design, combined with more traditional methods of algorithm development.
• Good engineers often break a large problem into more manageable parts. This process, also known as
top-down design or top-down development, starts at the top with one concept or big idea, which is then
broken down into several parts.
• The process of top-down design leads to modular development. In modular development, parts, or
modules, are developed individually and then combined to form a complete solution to a problem.
• Modular development makes a large project more manageable, is faster for large projects, leads to a
higher-quality product, makes it easier to find and correct errors, and increases the reusability of your
solutions.
• Saving solutions to small problems so that they can be applied elsewhere creates reusable code. Object-
oriented programming encourages the development of reusable code.
• Programmers follow a software development cycle, in which they design, code, test, and debug methods.
• Software testers need to be able to develop a testing plan that examines new software under all possible
circumstances. They examine the correctness of a method, its time and space efficiency, and whether or
not it has any undesirable side effects.
• Unit tests check to see if methods work as expected individually. Sometimes a testing shell is used in
unit testing to simulate the environment in which a method will operate.
• Integration tests check to see if larger methods work after newer methods are incorporated into them.
In Tutorial 2A, you explored the primitive methods that come with every Alice object. Sometimes it is desirable to run
primitive methods directly, such as when you need to position objects to set up a scene or find a lost object. You also
saw that some methods come with user-created methods to provide them with additional behaviors, such as the walk
method in the Penguin class.
In Tutorial 2B, you applied some of the methods discussed earlier in the chapter to create an Alice world with a t o p -
level method and separate sublevel methods to make three characters from Alice's Adventures in Wonderlandjump up
and down on the screen.
In Tutorial 2C, you learned to create and use a parameter for a method. You learned that a parameter can be used to
pass a value to a method when the method is called.
Exercises
Review Questions
2. Describe the processes known as top-down design and modular development, and explain how they are used
together.
3. How do organizational charts help with top-down design and modular development?
5. How does the practice of object-oriented programming encourage the development of reusable code?
7. What is the difference between a unit test and an integration test? Why are they both used in software
development?
8. What are the differences between primitive methods and user-defined methods in Alice? Which of these are
encapsulated methods, and what does that mean?
9. Describe two different primitive methods that can be used to find objects that are off-camera. What are the dif-
ferences between using these methods?
10. Describe what parameters are, and how they are used in Alice methods.
Exercises
1. Create an organizational chart showing a top-down, modular design for each of the following:
a. Baking a cake
b. Traveling from your house to Buckingham Palace in London
c. Sorting a list of names alphabetically by last name
d. The plot of your favorite film or television show episode
e. The solution to your favorite math problem
2. Modify the triple jump with parameters world from Tutorial 2C, by adding height parameters in the j u m p meth-
ods for the cheshireCat and aliceLiddell just as you did for the whiteRabbit. Run the world a few times using dif-
ferent values for the parameters.
60 Chapter 2 • Methods
3. Create an Alice world with a bunny in it. Create a hop method for the bunny that has the object move forward
while jumping up and down. (Hint Use the do together logic and control tile.) Create and test a generic hop
method that has three p a r a m e t e r s — who, how high, and how far.
4. Modify the triple jump world from Tutorial 2B, so that it functions as follows:
a. The three characters appear on the screen in the same position as before.
b. Alice says, "Simon says, J u m p ! "
c. Alice jumps.
d. The White Rabbit jumps.
e. The Cheshire Cat jumps.
f. The Cheshire Cat disappears, but his smile stays visible. (Hint.There is a property named opacity. Dragging a
property into a method will create an instruction to set the property to a new value. The cat should disap-
pear, but his smile should not, so you may have to program a part of the object. Clicking the plus sign next
to an object's tile in the Object tree will give you access to the object's parts.)
g. Alice and the White Rabbit both turn their heads to look at the Cheshire Cat.
Save your new world with a different name so that the triple jump world is preserved. You might also try printing
the code from the methods in your world, or saving the world as a movie file.
5. Clicking m o r e . . . on a method tile in the Editor area will reveal additional parameters for a method. Open the
triple j u m p w i t h p a r a m e t e r s world from Tutorial 2C, and then click the w h i t e R a b b i t in the Object tree and
the edit button for the w h i t e R a b b i t . j u m p method in the Details area. The method will open in the Editor
area. Find and change the duration parameter to make the rabbit j u m p more quickly or more slowly.
6. Some Alice method names do not follow the CamelCase naming convention. How should w o r l d . my
first m e t h o d be renamed so that it is in CamelCase? What about the names of user-
created methods that are supplied with the Penguin class of objects?
7. Examine the code in the lakeSkater world that is provided with the Alice software as an example world and
that was used in Chapter 1.
a. Describe how the organization of the iceSkater's object-level methods are related to the concept of reusable code.
b. While the world exhibits good modular design in many of its methods, the method w o r l d . m y first
a n i m a t i o n could be improved. Create an organizational chart showing an improved design for
world.my first a n i m a t i o n that exhibits better modular design.
8. The American Film Institute's list of The 100 Greatest Movie Quotes Of All Time appears on the Web at
http://connect.afi.com/site/DocServer/quotes100.pdf. Pick one of the quotes and create a short Alice world in
which one of the characters uses the quote. Make sure that your world exhibits good modular design.
Exercises
Every method for an object is an algorithm. On the surface of the moon there is a crater, named
al-Khwarizmi. It was named after Abu Ja'far M u h a m m a d ibn Musa al-Khwarizmi, who lived in the ninth century.
See if you can find out why he is important enough in the history of mathematics to have a crater on the moon
named after him. What does his work have to do with computer programming and developing software methods?
Select one of the themed folders in the Alice galleries, such as the Japan, Egypt, or Old West folders. Select
several objects from the folder and develop an outline for a short story using those objects. Create an organiza-
tional chart that shows the modules in the story, and develop a list of the Alice methods that you would need to
write to implement your story as an Alice world. Which of these methods do you think would be reusable for
other stories? If you have high-speed Internet access, you can to look in the Web Gallery, which is more exten-
sive than the Local Gallery.
Events
Describe what is meant by an object's point of view, and list and describe the six
object-relative directions and six object-relative positions in Euclidean 3-space
i Describe basic camera operations, including move, pan, tilt, and zoom, and how to
implement these in Alice
Create Alice events to allow the user to manipulate objects moving in three-
dimensional space
64 Chapter 3 • Events
There are two topics in this chapter. The first topic is relatively short, describing event-
driven programming. The second, which is a bit longer, discusses the nature o f three-
dimensional space. They are combined in this chapter because events in Alice often are
used to manipulate objects in three-dimensional space.
EVENT-DRIVEN SOFTWARE
One of the most important places in the history of computer technology is the Xerox Palo
Alto Research Center (Xerox PARC) in California. Xerox PARC was established as a research
lab where some of the world's best computer scientists and designers could work to improve
modern computer technology. We see their innovations almost every time we use a modern
computer. Local area networks, the laser printer, and the Graphical User Interface (GUI)
were all developed or refined at Xerox PARC.
n > • i i
For more information on X E R O X PARC, see www.parc.com.
A GUI has icons on the computer screen and a mouse to control a pointer that can be used to
operate the computer. Most modern software, such as word-processing and spreadsheet pro-
grams, Internet browsers, and computer games, depends on the use of a GUI. Before GUIs
existed, people had to control a computer by typing commands into what was called a com-
mand-driven interface. Often it was necessary to write or run a computer program to complete
tasks that involved more than a few steps, such as formatting the output for a document.
It's no coincidence that the use of personal computers really took off after the introduction
of the Graphical User Interface. The Apple Macintosh approach to computing and the
Microsoft Windows operating system both incorporate a GUI based directly on develop-
ments at Xerox PARC.
any method can serve as an event handler. When the event listener detects an event trigger,
an event handler is called into action. Everything from word-processing software to com-
puter games depends on event-driven programming, because events allow for keyboard and
mouse controls for interactive software.
There are nine different event types in Alice, as described in Appendix B. In this chapter,
you will use some of those events to manipulate objects moving in three-dimensional space.
Before we begin, let's look at the nature of three-dimensional space.
THREE-DIMENSIONAL SPACE
A dimension is a way of measuring something. The word dimension is derived from the
ancient Latin word demetiri, meaning to measure out. It is an abstract idea, a concept
invented by people to help us understand something. We create a dimension whenever we
assign a value on a continuous scale to some property. This process is called quantification.
For example, a survey might contain the question, "On a scale of 1 to 10, how much do you
like chocolate ice cream?" Someone has created a scale to quantify the popularity of choco-
late ice cream, making popularity a dimension of the chocolate ice cream.
If you want to measure the location of a point on a straight line, then you only need one
number. You could mark a starting point on the line, and then measure distance—how far a
point is from the starting point. By using negative and positive numbers, you could also
indicate which direction the distance spans. Figure 3-1 shows a line marked with a scale to
help us quantify the location of each point on the line.
- 4 - 3 - 2 - 1 0 1 2 3 4
In addition to the concepts of distance and direction, we also have the concept of orientation,
which means the direction an object is facing. If an object is facing the positive direction on
the line, toward higher numbers, its orientation would be forward. An object facing the nega-
tive direction, toward lower numbers, would be facing backward.
Location and orientation together are known as the point of view of an object. Figure 3-2
shows three people in a straight line with the point of view for each of them.
66 Chapter 3 • Events
FIGURE 3 - 2 : Three people in a straight line with the one-dimensional point of view for each person
i t ) Alice World
Speed: 1x
Pause Restart Stop Take Picture
0=
Alice
- 4 - 3 - 2 - 1 0 1 2 3 4
Actually, there are two ideas of direction. A direction can be in relation to a scale of mea-
surement, called absolute direction, or from the point of view of another object, called
object-relative direction. In Figure 3-2, the absolute direction of the boy on the bicycle is
backward, but the direction he is facing in relation to Alice is forward. Object-relative
position can also be considered. From the coach's point of view, Alice is behind the boy,
while the coach is in front of the boy. In front of and behind are two object-relative positions.
On a flat surface, like a sheet of paper, you need two values to specify an object's position.
That is, you need two scales of measurement, each called an axis. The first would measure
the object's position along a straight line, and the second how far away that object is from
Three-Dimensional Space 67
that straight line along a second straight line. A flat surface is two-dimensional. Such a flat
two-dimensional surface is called a plane.
The French mathematician Rene Descartes developed a system of quantification for two
dimensions called Cartesian coordinates. Cartesian coordinates have an X-axis and a Y-axis.
The location of each point is referenced by an ordered pair of the form (x, y), in which x rep-
resents the point's location along the X-axis, and y represents its location along the Y-axis. An
ordered pair is any pair in which one dimension is always listed first, and another dimen-
sion is always listed second. For example, a set of numbers showing the temperature at vari-
ous times throughout the day might be given in the form of ordered pairs with the format
(time, temperature). The data set would look something like this: (8:00 am, 54°), (9:00 am,
56°), (10:00 am, 59°), (11:00 am, 61°), and so on. In Cartesian coordinates, the X-axis value is
always listed first. Figure 3-3 shows several points marked on a Cartesian plane.
Y-axis
(0,2)
(2,1)
X-axis .(-2,0)
-4 -3 -2 -1
Moving up or down off a flat plane requires a third axis and a third number to indicate how far
a point is above or below the plane. In other words, a third dimension is needed. So, instead of
an ordered pair to indicate location, an ordered triplet is used, with three values. Each point
has x, y, and z coordinates. Figure 3-4 shows three buildings with an x-axis, a y-axis, and a
z-axis for orientation in three-dimensional space. You can think of the x-axis as running east
and west, the y-axis as running north and south, and the z-axis as running up and down.
FIGURE 3 - 4 : These buildings sit on a plane with an X-axis (east-west), a Y-axis (north-south);
and a Z-axis (up-down); unlike the curved surface of the Earth, the X-Y plane in
Euclidean 3-space is flat
Up
South
Down
Three-Dimensional Space 69
You saw that on a straight line, an object can be facing forward or backward, either
absolutely or in relation to another object. You also saw that on a straight line, there were the
two object-relative positions: in front of and behind. In Alice's Euclidean 3-space, there are
six object-relative directions, one opposing pair of directions for each axis. There are also
six object-relative positions. Figure 3-5a shows the six object-relative directions—forward
and backward, left and right, and up and down. Figure 3-5b shows the six object-relative
positions—in front of and behind, to the left of and to the right of, and above and below.
FIGURE 3 - 5 : Object-relative directions in 3D space are shown on the left (Figure 3-5a);
object-relative positions are shown on the right (Figure 3-5b)
Above
Is there a four-dimensional space? Albert Einstein pointed out that time is a dimension, and
suggested what he called a four-dimensional space-time continuum. Many important devel-
opments in the field of physics during the past 100 years have been based on Einstein's
work. So, you see, the simple idea of quantification, of applying a system of measurement to
something such as the location of a point in space, can lead to some very sophisticated
results. In fact, almost all of modern science is based on dimensioning—quantifying the
properties of objects, and then studying how those quantities change and affect one another.
The goal of this chapter is to learn about events and computer programming in the three-
dimensional space of Alice. Even though the text refers to direction and movement, we will
try to do so without getting too caught up in the mathematics of it all.
Chapter 3 • Events
T U T O R I A L 3 A — E V E N T S IN A L I C E
In this tutorial, you will explore events in Alice and create several simple events. Before
starting, you should understand the nature of event-driven programming, as discussed
earlier, especially the terms event trigger and event handler. You should also have an under-
standing of methods, as discussed in Chapter 2.
Exploring Events
1. Start the Alice software and open the amusementPark example world. In
the Events area of the Alice interface, you see seven event tiles, as shown in
Figure 3 - 6 .
The first tile contains an event to let the user move the camera with the
four arrow keys on the keyboard. The other six event tiles are of the form
When the world starts, do <event handler>. These events run methods to
animate the amusement park rides when the world starts.
t]
L e , «_ move C a m e r a
If you cannot see all seven events at once, then you might need to adjust the size of the
areas in your Alice interface. You can do this by clicking the background space between
j areas and dragging the pointer to resize the areas. To lengthen the Events area, click
between the Events area and the Editor area and drag the pointer down the screen.
2 . Play the world and use the arrow keys to move the camera around to look
at the various parts of the amusement park. You can see the effects of the
six events that animate the amusement park rides. Also notice that the
camera moves down slightly when it moves forward, and up slightly when
it moves backward. This is because the original camera position was tilted
slightly downward. Take a few minutes to look around the amusement park
before continuing. If you restart the world, the camera will move back to its
original position.
You are going to start a new Alice world with two objects—a blue ballerina and a pink
ballerina—to explore the different Alice event types.
1. Exit Alice and restart the Alice software with a blank world using the grass
template. The amusementPark world uses a lot of memory, and exiting and
restarting Alice is a good way to be sure that it is cleared from the memory
before continuing.
2 . You are going to build a world with two objects, a blueBallerina and a
pinkBallerina. Click the green ADD OBJECTS button and add a
blueBallerina and a pinkBallerina to the world from the People folder in
the Local Gallery.
3 . Move the ballerinas apart from each other and turn them to face the camera,
as seen in Figure 3 - 7 . When you are finished setting up this simple world,
click the DONE button to exit Scene Editor mode and return to the standard
Alice interface.
72 Chapter 3 • Events
4. Next, you are going to create a world-level method to make both ballerinas
spin at the same time. Click the world tile in the Object tree, and then click
the methods tab in the Details area. Now click the create new method but-
ton, and when the dialog box appears, name the method bothSpin, and then
click OK.
5. You now need to add instructions to the b o t h S p i n method to make the two
ballerinas spin. The code in the Editor area in Figure 3-8 shows what this
will look like when you are finished. First click and drag a Do together tile
from the bottom of the Editor area into the instruction zone to replace the
phrase Do Nothing in the w o r l d . b o t h s p i n method.
Tutorial 3A—Events in Alice
No variables
Do together
blueBallerina turn left 1 revolution more...
pinkBallerina turn left 1 revolution more...
Do in order Do together If/Else Loop While For all in order For all together
6 . Click the blueBallerina tile in the Object tree and then the methods tab in
the Details area. Drag and drop a blueBallerina turn method tile from the
Details area into the do together tile in the w o r l d . both spin method.
Choose left and 1 revolution as values for the direction and amount
parameters.
7. Click the pinkBallerina tile in the Object tree and drag and drop a
pinkBallerina turn tile into the world.bothSpin method below the
blueBallerina turn tile. Choose the same values, left and 1 revolution, for
the direction and amount parameters.
8. You are finished creating your new method; now you need to add it to the
default event tile as the event handler. Make sure that world is selected in
the Object tree and that the methods tab is selected in the Details area. Drag
the bothSpin tile from the methods tab into the Events area and drop it in
place of world.my first method in the default event.
9. You no longer need world.my first method, so drag the world.my first
method tile from the methods tab and drop it in the trash can; the method
is removed from the world.
10. Now play the world; you should see both ballerinas spin together. Before
proceeding, save the world using the name two ballerinas. If you want to
save a copy of the world during the rest of this tutorial, save it with a differ-
ent name, so that your basic ballerina world is saved.
Chapter 3 • Events
Alice E v e n t T y p e s
In the Events area, you can see only the When the world starts, do world.bothSpin default
event. Whenever the create new event button is clicked, a list of the nine event types in
Alice appears, as shown in Figure 3-9.
Next, you will experiment with a few of the event types. Figure 3-10 shows what the Event
area will look like when you are finished. Remember, your goal is to learn something about
events and building object controls with events, not to learn everything there is to know about
events in Alice. A discussion of the nine event types in Alice is included in Appendix B.
FIGURE 3 - 1 0 : The Event area with the events to be added in this tutorial
earner
i^)i|iriuiul
wr.ll.l s (1.1,1.1-.
Arties Jmelhods |r\ji
- Do together
bhieBallerrna turn i.-n 1 revolution more-
Do m order Do together Ifffrse Loop WMe For art in order For altogether Wart print
Tutorial 3A—Events in Alice 75
1 . Click the create new event button, and then click When the world starts. A
new event tile of that form will appear in the Events area, as shown in
Figure 3 - 1 1 .
W h e n t h e world s t a r t s , do Nothing
This event functions the same as the default event. It will cause a method to
run whenever the world starts. You can change the form of the When the world
starts event to make a method run continuously while the world is playing. To
do so, right-click the new event tile. (Make sure you click the blue background
of the tile itself, and not a parameter within the tile.) On the menu, three items
will appear: delete, change to, and disable. The delete option will remove an
event from your world. The disable option will keep the event, but it will not
function until you again right-click the event and enable it. You need to change
the form of the event, so click change to, and then click While the world is
running. Now you can see a more sophisticated version of an event handler, as
shown in Figure 3 - 1 2 .
During: <None> —
End: <Nune>
3. The While the world is running event now has places for three different
event handlers. You can tell the world what methods to run when the
world begins to run, during the time that the world is running, and when
the world ends running. This format for an event in Alice is called the BDE
76 Chapter 3 • Events
event format, for Before, During, and End. There are BDE formats for sev-
eral different events. What you see in Figure 3-11 is only one of several
event types with the BDE format. You are going to make the pink ballerina
spin to her right while the world is running.
4. Click the pinkBallerina tile in the Object tree, drag a pinkBallerina turn
tile from the methods tab, and drop it into the event tile in place of None
following the phrase During. Choose the values left and 1 revolution for the
direction and amount parameters.
5. Now play the world again. Notice two things—first, the pink ballerina con-
tinues to spin while the world is running, and second, when the world
starts, she spins more quickly. Restart the world, and you will see this hap-
pen. Why does she spin more quickly when the world starts? The default
event handler causes the pink ballerina to spin left. Combined with the
spin from the new event you just added, she spins twice as fast the first
time around. This is an example of a side effect, an unintended result
caused by two methods running at the same time.
6. Change the direction of the spin to right in the w h i l e t h e world is
running method and then run the world again. Now what happens? The pink
ballerina doesn't spin at all the first time, because the two methods triggered
by the two events cancel out each other. After the first method stops, she
spins to her right. This is another example of a side effect. Professionals who
test computer software routinely check for such side effects.
Alice has a When a key is typed event that will cause a method to run whenever a particular
key is pressed. The event trigger will be the press of a key, and the event handler can be
almost anything that can be coded in an Alice method.
1. Click the create new event button again, and this time click When a key is
typed from the menu that appears. This event takes two parameters: the
first is the key that will trigger the event, and the second is the method that
will serve as the event handler. The event tile is shown in Figure 3-13.
Tutorial 3A—Events in Alice 77
The default menu choice in the When a key is typed event tile is any key. which can be
changed to a specific key.
2. Let's set up an event and give it a try. Click the any key box and you will be
allowed to select a key from a drop-down menu, as shown in Figure 3-13.
The small arrowheads show us menu items that lead to submenus, with the
various letter and number keys listed on the submenus.
3. Select letters from the menu and then the letter B for blue as the trigger key
for this event. Click the blueBallerina tile in the Object tree and then click
the methods tab in the Details area. Drag a blueBallerina turn method tile
from the Details area and drop it into the event tile in place of Nothing;
choose right and 1 revolution as values for the direction and amount
parameters. This is one of the events shown in Figure 3-10.
4. Now play the Alice world. Wait at least one second until the opening move
is complete, and then try the B key a few times. Each time you press it, the
blue ballerina spins to her right. If you hold down the B key, notice that she
will not continue to spin. Note that Alice event triggers are not case sensi-
tive—this event will be triggered by an uppercase B o r a lowercase b. Stop
the world when you are finished experimenting.
78 Chapter 3 • Events
You can change the form of the When a key is typed event to make a method run continu-
ously as long as the triggering key is held down.
While B
i is pressed
mm
Begin: <None>
During: <None>
E n * <None>
2 . Notice that the B key is still in place as the trigger, but that the three event
handlers are now all empty. Drag and drop a blueBallerina turn tile into
place after During, as you did before, with the values right and 1 revolution
as parameters.
3. Now play the world again. After the opening move is complete, try pressing
and holding down the B key a few times for different durations. Notice that
even though the method calls for the ballerina to turn one complete revolu-
tion; when you let go of the key, the method stops, even if the ballerina is
in midturn.
Alice has an event type that will cause a method to run whenever the mouse is clicked on
an object. Let's experiment with it.
1. Click the create new event button, and select When the mouse is clicked on
something from the menu that appears. A new tile of this type will be added
to the Events area. New events are added to the bottom of the Events area, so
it might be necessary to scroll down in the Events area to find the new event.
Tutorial 3A—Events in Alice 79
2 . You're going to create an event to make the blueBallerina roll one revolu-
tion whenever the mouse is clicked on her. First, click the word anything
in the new event tile, and a menu of the objects in this Alice world will
appear, as shown in Figure 3 - 1 5 . Select blueBallerina, the entire
blueBallerina as the target object. Next, make sure that the blueBallerina is
selected in the Object tree, and that the methods tab is selected in the
Details area. Drag the blueBallerina roll tile from the methods tab and
drop it to replace Nothing in the event tile. Choose the values right and
1 revolution for the direction and amount parameters.
3 . Now play the world and try the new method. After the opening move, click
the blue ballerina and watch her roll. The B key event is still active, so you
can try that also. Experiment a little. What happens if you click the blue
ballerina while holding down the B key to make her turn? T h e two meth-
ods combine to cause unexpected results. If things get really messed up,
you can restart the world and try again.
You can change the When the mouse is clicked on anything event to be While the mouse is
pressed on anything, with the BDE format. This change will be similar to what you did with
the When a key is typed and While a key is pressed event types.
80 Chapter 3 • Events
Alice also has an event type to let users change the position of an object while a world is
running. This event type is Let the mouse move <objects>. However, this event type
requires the use of a data structure called a list, which isn't covered until Chapter 9, so
we'll look at it when we get there.
In this tutorial, you are going to build controls to allow the user to manipulate the camera
while a world is running. The tutorial will be brief because Alice has several event types
with built-in event handlers for camera control.
O p e n a n Existing W o r l d
You are going to add some camera controls to the lakeSkaterDemoStart world that is
included with the Alice software.
1. First, start the Alice software. If it is already open, then close it and open it
again to make sure that the old Alice world has been cleared from the com-
puter's memory. When the Welcome to Alice! dialog box appears, open the
lakeSkaterDemoStart world from the Examples tab. This is not the same
lakeSkater world that you saw in Chapter 1, but a similar world named
lakeSkaterDemoStart. The lakeSkaterDemoStart is a nice world to use for
experimenting with camera controls because it contains some interesting
winter scenery with a frozen lake, hills, and trees.
2 . Note that once the world loads, you can see the world window with three sets
of blue arrows below it to manipulate the camera, as shown in Figure 3-16.
Tutorial 3B—Building Camera Controls with Events 81
FIGURE 3 - 1 6 : The lakeSkaterDemoStartworld window with the camera controls at the bottom
The curved arrow on the right is the camera's tilt control. It is used to tilt the camera up or
down, just as you might tilt your head up or down. The center control is a mixed control, to
zoom and pan the camera. A camera can zoom in and zoom out, and pan left and pan right.
Zooming in means the camera moves in closer to get a tighter shot of something, so that it
fills more of the screen. Zooming out means the camera moves out farther to get a longer
shot of something, so that it becomes smaller on the screen. Panning means turning the
camera left or right without moving the position of the camera, although it is possible to
pan and move at the same time.
Most cameras have a lens that will allow the photographer to zoom in and zoom out with-
out moving the camera. In Alice, you zoom in and zoom out by actually moving the camera
forward and backward.
Remember, an object in 3D space can move in six different directions: forward, backward,
left, right, up, and down. The left set of arrows at the bottom of the world window is the
move control, which provides controls to move the camera left and right, and up and down,
while the vertical arrows in the center set move the camera forward and backward.
Take a few minutes to experiment with the camera controls and explore the landscape in
this Alice world. Try to see if you understand the concepts of tilt, zoom, pan, and move.
Pick an object, such as a particular tree, and see if you can frame it in the world window. To
frame an object means to position the camera so that the object fills the screen. You could
frame an individual object, a group of objects, or a particular scene.
82 Chapter 3 • Events
The blue arrows can be used to control the Alice camera before a world starts, but they
don't work once a world is running. There are three Alice events designed to let us manipu-
late the camera once a world is running:
1. Click the create new event button, and you will see the list of the nine
event types in Alice, as shown earlier in Figure 3-9. Select Let the mouse
orient the camera, the last item in the list. You should see a new event of
this type appear in the Events area, as shown in Figure 3-17.
2 . This event calls a special hidden event handler that will let the user pan
the camera with the mouse when an Alice world is running. You cannot tilt
or zoom the camera with this event; you can only pan left and right.
3. Play the world and try panning left and right by dragging the mouse. After
you are finished experimenting, stop the Alice world.
Alice has an event to allow the user to move the camera by clicking and dragging the mouse
around the window for the playing world.
1. Click the create new event button, and this time click the second-to-last
item in the list, Let the mouse move the camera. As before, you should see
a new event of this type appear in the Events area, as shown in Figure 3-18.
Tutorial 3B—Building Camera Controls with Events 83
(it J m o v e the c a m e r a
2. Note that this event is only slightly different from the Let the mouse orient
the camera event. It allows the user to pan the camera left and right (not
move the camera as the name implies), and move the camera backward and
forward.
3. Play the world and then test the new event by dragging the mouse. Do you
see how this is different from Let the mouse orient the camera? When you
are finished, stop the world before continuing.
A separate event in Alice allows the user to move the camera by using the arrow keys, as
shown in Figure 3-19.
FIGURE 3 - 1 9 : The let the arrow keys move the camera event tile
1. Click the create new event button, and look at the list that appears.
2. Notice that there is no method named Let the arrow keys move the camera.
However, the third item up from the bottom of the list says Let the arrow
keys move <subject>. Select this item, and a new event of this type appears
in the Events area. The last two events you saw had no parameters, but this
one does. The default value for the subject parameter is the camera, so it's
easy to use this event to move the camera with the arrow keys.
3. Like the last event, it only allows you to move the camera forward and back-
ward, and to pan left and right. This was the event used to let the user con-
trol the camera in the amusementPark world in Tutorial 3A. Try it now in
this world, and then you are finished with this tutorial. It is not necessary to
save your work.
84 Chapter 3 • Events
T U T O R I A L 3 C — B U I L D I N G A F L Y I N G M A C H I N E IN A L I C E
In this tutorial, you will create a flying machine—an object that can move around in three-
dimensional space under the control of a user. The purpose of the exercise is to learn to
build user controls for moving objects.
Software Specifications
Let's start with some specifications for the flying machine. The first step in creating soft-
ware is to make sure that you as the programmer know what the program is supposed to do.
Software specifications provide that information. The specifications usually come from the
client—the person requesting that the software be written. The specifications then need to
be refined by the programmer to more specifically reflect the features of a particular pro-
gramming language or development system.
In this part of the tutorial, you will review and refine the specifications but not actually cre-
ate the code. The development of clear specifications is part of the first step in the the pro-
gram development cycle discussed in the last chapter—design, code, test, and debug.
In this case, use the following specification as a starting point for the flying machine world:
Refining Specifications
Let's refine each of these specifications by adding more precise details. First, you need to find
objects in the Alice object galleries that could serve as a flying machine and then select one.
1. Start the Alice software and open a blank world with the grass template.
Next, click the ADD OBJECTS button to look at the Alice galleries. The
Vehicles folder seems like a good place to start, so let's look there. Scroll
through it, and you will see object class tiles for a Biplane, a Blimp, a
Helicopter, a Jet, a Navyjet, and a Seaplane, as shown in Figure 3-20. Don't
add anything to the world, yet; you are just looking through the galleries for
ideas to help refine the specifications.
Tutorial 3C—Building a Flying Machine in Alice 85
FIGURE 3 - 2 0 : Some of the object class tiles from the Vehicles folder in the Local Gallery
2. So far, you have worked with the grass template, so for this world, let's pick
the seaplane, and use the water template. Right now you're just putting
together the specifications, so close the object gallery and note the revision
to the first specification, as follows:
1. Create a water world with a seaplane in it.
3. The specifications call for the world to look somewhat realistic, so let's add
a few items to the water world to make it look better. The Vehicle Gallery
contains a sailboat, and the Environment Gallery contains two different
islands. You can use these. The revised first specification looks like this:
1. Create a water world with a seaplane in it:
a. Select the water template.
b. Add a seaplane to the world.
c. Add a few more items—such as an island or two, and a sailboat.
4. Our second specification says that the object should be able to move in
three-dimensional space. To do this, you will create an event to keep the
seaplane moving while the world is playing. The primitive move method
has parameters for distance and amount. Our refined specifications will call
for the seaplane to move forward one meter. This event will keep happening
while the world is running—as soon as the seaplane finishes moving for-
ward one meter, it will move forward another meter, and so on, for as long
as the world runs. Our revised second specification is:
2. Create an event—while the world is running: do seaplane move forward
one meter.
5. The primitive move method has additional parameters that are not often
used. We can get to them by clicking the word more in the turn method and
then selecting style from the list that appears. Four styles are available, as
seen in Figure 3-21: gently, begin gently, end gently, and abruptly. Gently
means that our movement will begin and end gently. Abruptly means that
the movement will be at a constant speed. If we choose abruptly, then the
motion of our seaplane will look more even.
FIGURE 3 - 2 1 : The m o v e a n d t u r n e v e n t s have f o u r style p a r a m e t e r s
Left and right are easy, but the t u r n method does not have parameters up
and down; it has parameters forward and backward. Is turning up the same
as turning forward or backward? Try this: stand or sit facing straight ahead.
Tilt your head backward. Did your face move up or down? We can see that
turning backward makes an object's orientation turn up, and, conversely,
turning forward makes an object's orientation turn down.
We also need to decide how much the seaplane will turn each time we
press one of the arrow keys. Try one-eighth of a revolution. That's equiv-
alent to 45 degrees. All together, we have the following control event
specifications:
3. Create four turn control events:
a. When the left arrow key is pressed, turn left 1/8 revolution.
b. When the right arrow key is pressed, turn right 1/8 revolution.
c. When the up arrow key is pressed, turn backward 1/8 revolution.
d. When the down arrow key is pressed, turn forward 1/8 revolution.
Tutorial 3C—Building a Flying Machine in Alice 87
7. Finally, the fourth specification says that the user needs to be able to find
the flying machine if it moves off camera, which we can expect to happen
at some point. There are several ways to do this, but one simple way is to
choose a key to let the user point the camera at the seaplane whenever that
key is pressed. Let's use an easy key—the spacebar. The find the seaplane
event specification now looks like this:
4. Create an event: When the spacebar is pressed, point the camera at the
seaplane.
2. Create an event: While the world is running do: seaplane move forward
one meter, style = abruptly.
3. Create four turn control events:
a. When the left arrow key is pressed, turn left 1/8 revolution.
b. When the right arrow key is pressed, turn right 1/8 revolution.
c. When the up arrow key is pressed, turn backward 1/8 revolution.
d. When the down arrow key is pressed, turn forward 1/8 revolution.
4. Create an event: When the spacebar is pressed, point the camera at the
seaplane.
C o d e t h e W o r l d — S p e c i f i c a t i o n 1, C r e a t e a W o r l d w i t h a S e a p l a n e
Now you are ready to create the world. Following the specifications, you need to create a
water world with a seaplane in it, similar to Figure 3-22. Note that this specification is a bit
subjective. What looks somewhat realistic to one person might not look that way to another.
88 Chapter 3 • Events
1. First, start the Alice software. If it is already open, close it and restart Alice.
2. When the Welcome to Alice! dialog box appears, select the water world
from the Templates tab.
3. Once the blank water world opens, click the ADD OBJECTS button, and
add a seaplane to the world from the Vehicles folder in the Local Gallery.
Also add a sailboat from this gallery and position it somewhere on the
water away from the seaplane.
4. Next, add an island or two from the Environment Gallery and position the
island(s) in the world. The world shown in Figure 3-22 also has a light-
house and another boat. You may want to add and position a few addi-
tional objects such as these to make the world more interesting, but don't
make the world appear too crowded. You may also want to reposition the
camera back and up a bit, and then tilt it down toward the seaplane to get a
wider view of the world, similar to what is shown in Figure 3-22.
Tutorial 3C—Building a Flying Machine in Alice
5. When you are finished setting up the world, click the DONE button. You
can also add a few items from other galleries, such as those shown in
Figure 3-22, but don't get carried away.
C o d e t h e W o r l d — S p e c i f i c a t i o n 2, A n i m a t e t h e S e a p l a n e
An event is needed to make the seaplane move continuously. Almost everything is spelled
out in the second revised specification—while the world is running do: seaplane move
forward one meter, style = abruptly.
1. Click the create new event button and choose When the world starts for
the event type.
2. When the new event appears in the Events area, right-click it. From the menu
that appears, select change to, and then select While the world is running.
3. Next, make sure that the seaplane is selected in the Object tree and that the
methods tab is selected. Drag and drop a seaplane move tile into the event in
place of None following the phrase During.
4. Choose the values forward and 1 meter for the direction and amount para-
meters. Also, click the word more, and then select style from the menu that
appears, as was shown in Figure 3-21, and change the style to abruptly so
that the seaplane will move more smoothly. If the seaplane moves too
slowly when the world is tested, remember that you can change the speed
by changing the distance parameter for this event.
C o d e t h e W o r l d — S p e c i f i c a t i o n 3, A d d T u r n C o n t r o l s
Next, events are needed to add controls to turn the seaplane, one for each of the four arrow
keys, as shown in Figure 3-23.
1. Click the create new event button, and select When a key is typed as the
event type. A new event tile of the form When a key is typed will appear in
the Events area.
90 Chapter 3 • Events
The specifications call for us to create a method to point the camera at the seaplane when
the spacebar is pressed.
1. Start by clicking the create new event button, and select When a key is
typed as the event type.
2 . When the new event appears, click the any key parameter and select space
from the menu that appears.
3. Next, make sure that the camera is selected in the Object tree and that the
methods tab is selected in the Details area. Drag and drop a camera point at
method tile into your new event in place of Nothing, and select seaplane,
the entire seaplane when the menu of possible target objects appears.
4. When this step is finished, you should be done coding your seaplane
world. Save the world with the name seaplane before continuing.
Test t h e W o r l d
Once you are finished coding the world, test it to see if it works properly—that is, according
to the specifications. A test plan is often used in professional software development. Such a
plan often includes a series of questions based on the specifications. You need to determine
if this world meets each of the original specifications, so your test plan might include the
following questions:
1. Does the flying machine look like a flying machine in a somewhat realistic
environment? (This is a fairly subjective requirement, with a loose standard
for what looks realistic.)
2 . Is it able to move in three-dimensional space?
Tutorial 3C—Building a Flying Machine in Alice 91
3 . Are there user controls to turn the object up, down, left, and right while the
object is in motion? Do each of these work properly?
4. Can the user find the flying machine if it moves off camera?
To see if the world meets the specifications, play it several times, answering the questions
from the test plan as you go along. It might also be good to let someone else, such as a fel-
low student or your instructor, do so as well. We want to see if it meets the specifications,
and if there are any obvious problems or side effects in the finished world.
D e b u g the World
This might be the hardest part of the entire exercise. If the world does not meet one of the speci-
fications, see if you can isolate the problem and fix it. Usually the problem lies in the code
related to the failed specification, but not always—sometimes it is a side effect of other code.
Remember that software development is a cycle. If you find any errors, you need to repeat
the steps in the cycle to review the design specifications, code any changes, test, and debug.
92 Chapter 3 • Events
Chapter Summary
This chapter consisted of discussions of events and three-dimensional space, followed by hands-on tutorials involving
events, camera controls, and construction of a flying machine in Alice.
• A modern personal computer uses event-driven software for its Graphical User Interface (GUI), which has
icons on the computer screen and a mouse to control a pointer that can be used to operate the computer.
• An event occurs when an event listener detects an event trigger and responds by running an event handler.
• An event listener is a combination of hardware and software that repeatedly checks the computer system
for the event trigger.
• An event trigger can be any activity or condition that causes an event to occur.
• An event handler is a method that is activated when the event trigger occurs. Almost any method can
serve as an event handler.
• When the event listener detects an event trigger, an event handler is called into action.
• A dimension is a way of measuring something. It is an abstract idea invented by people to help us under-
stand something.
• Only one dimension is needed to measure the location of a point on a straight line; on a flat plane, two
dimensions are needed; and in real physical space, three dimensions are needed,
• A three-dimensional space, like the physical world around us, is sometimes referred to as Euclidean
3-space. The 3D worlds of Alice are Euclidean 3-spaces,
• The concepts of distance and direction together make up an object's point of view.
• A direction or position in relation to a scale of measurement is called absolute, and from the point of view
of a specific object, it is called object-relative.
• In Alice's Euclidean 3-space, there are six object-relative directions—forward, backward, left, right, up, and
down. There are also six object-relative positions—in front of, behind, to the left of, to the right of, above,
and below.
In Tutorial 3A, you explored events in Alice and worked with some of Alice's nine different event types that can be used
to provide mouse and keyboard controls. You also saw that some events have a BDE format.
In Tutorial 3B, you experimented with events to create camera controls. You saw that a camera can move, pan, tilt,
and zoom.
In Tutorial 3C, you created a flying machine in Alice. You applied what you had learned about events and the ideas from
Chapter 2 about a program development cycle to design the world before coding and testing it.
Review Questions 93
Review Questions
2. Describe the difference between the terms object-relative position and object-relative direction.
3. Create a drawing of a number line, with three objects at different points on the number line. For each object, list
the following:
4. Describe the function of each of the blue arrows that appears below the world window in the standard Alice
interface.
5. Does the cabin in Alice's lakeSkaterDemoStartworld have a back door? To answer this question, you need to
open the world and manipulate the camera using the camera controls below the world window so that you can
see the back of the cabin.
6. Describe an Alice event of the BDE format that will make a ballerina j u m p up when a key is pressed, spin
around for as long as the key is held d o w n , and return to the ground when the user lets go of the key.
7. Individual keyboard events can be created to control the camera. As such, do the following:
a. Describe a set of two keyboard events to allow the user to pan the camera.
b. Describe a set of two keyboard events to allow the user to tilt the camera.
c. Describe a set of two keyboard events to allow the user to zoom the camera in and out.
8. List and describe each of the four style parameters that can be used for move, turn, and roll methods. Why
is the abruptly style used in the following event?
While the world is running, move seaplane forward 1 meter style = abruptly.
9. Why w a s n ' t Alice's built-in event for moving an object with the arrow keys used in the seaplane world in
Tutorial 3C?
10. Look up the aviation terms pitch, roll, and yaw in a dictionary, or find a Web site on basic aeronautics, and read
about t h e m . How are they related to our seaplane controls?
Chapter 3 • Events
Exercises
1. Create a simple Alice world to let a user drive a vehicle, such as a car, around on the ground. The Vehicles folder
in the Local Gallery has a Zamboni machine, which could be driven around the lakeSkaterDemoStartworld.
2. Create your own set of camera controls to allow the user to pan, tilt, zoom, and move the camera. The built-in
controls do not allow for all of these options. Remember, in Alice w e simulate zooming in and out by moving the
camera closer or farther away.
3. Alice has a Take Picture button to capture the image from the world window while a world is playing. Open the
amusementPark world and, for each element in the following list, use the camera control arrows to frame the
object or group of objects and take the indicated picture:
4. Modify the seaplane world to include a barrel roll control. This would make the plane roll one complete revolu-
tion whenever a chosen key is pressed.
5. Modify the seaplane world to make the seaplane's propeller spin while the world is running. Does the propeller
need to turn or roll to make this work?
6. Modify the seaplane world to make the turn events work more smoothly. To do this, w e can change the form of
each of the turn control events to While the arrow key is pressed instead of When the arrow key is typed, and
change each turn's style to abruptly. You might also want to experiment with the turn at speed primitive
method in place of the turn method.
7. Try to create a speed control for the seaplane w o r l d . This is a little harder than it looks. Here are
some ideas:
8. Create a simple Alice world to fly a pterodactyl instead of a plane. There is a pterodactyl in the Animals folder in
the Local Gallery. You could build a method to flap its wings, and then use this as an event handler for an event
while the world is in motion. Do the wings need to turn or roll? Should they go up and then down, or down and
then up? How far should they move? You should experiment with the pterodactyl and then develop specifica-
tions before coding your world.
Exercises 95
9. The Environment Gallery contains a bedroom. Create an Alice world with a bedroom that contains things like
furniture, a clock, paintings, etc.
Add events to the world to turn the bedroom into a haunted bedroom. For example, you could make a bed disap-
pear into the floor and have a tombstone pop up whenever someone clicks the bed. You can create events that
affect the subparts of an object, to do things like make the clock's hands spin, have dresser drawers open and
close on their own, or make a character's head spin around.
10. The people folder in the local Alice Gallery has hebuilder and shebuilder classes to let you create your own Alice
characters. These characters will have built-in methods to stand, walk, and show different moods, Experiment
with the hebuilder or shebuilder in a simple Alice world to build a character of your own, and then create sev-
eral events to show what the character can do. For example, create a method to make the character walk when
the " W " key is pressed, or show confusion when the " C " key is pressed. You should experiment with the charac-
ter and then develop specifications before coding your world.
Algorithms
List and describe the three major elements of logical structure found in algorithms
Describe how binary bypass and binary choice selection sequences (branching rou-
tines) work, create simple flowchart segments and pseudocode for each, and imple-
ment each in at least one Alice method
Describe how count-controlled and sentinel selections sequences (loops) work, create
simple flowchart segments and pseudocode for each, and implement each in at least one
Alice method
Describe how pretest and posttest loops differ from one another, and why pretest loops
are preferred
Algorithms contain the steps necessary to complete a particular task or solve a particular
problem. A recipe for baking a cake will have a list of all the ingredients needed, as well as
step-by-step instructions on what to do with those ingredients. In other words, the recipe
provides an algorithm for baking a cake.
When young children learn to perform long division, they are learning an algorithm.
Professionals, such as engineers, architects, and doctors, apply many different algorithms in
the course of their daily work. Some algorithms are simple; some can be quite long and
complex. The Holtrop and Mennen Algorithm, which can be used by naval architects to
design the optimum propellers for an oceangoing ship, involves several thousand steps and
must be run on a computer.
Algorithms are sequential in nature, forming a kind of sequential logic. Modern object-oriented
approaches to software development include much more than just algorithm development, yet
programmers need to be able to design and implement sequential algorithms. They need to
understand sequential logic.
Sequential logic forms patterns, which can be understood as the elements of logical struc-
ture. These elements are combined in a myriad of ways to form the complex algorithms
found in modern computer software. A programmer who is familiar with the design pat-
terns of logical structure can more easily create and edit software.
Think about how a programmer's work compares to the work of a plumber or an electrician.
A person who wants to design a plumbing system for a building, such as a house, has a
selection of existing parts from which to choose. We can see these parts in a hardware store
or building supply warehouse—elbows, T-joints, different kinds of valves, and so on.
Despite differences from one house to another, the plumbing systems will be composed of
many of the same parts, which we might think of as the elements of structure for a plumb-
ing system. The architects who design the system need to know how the parts work and
how they fit together. The plumbers who build or repair the system need to know how to
work with each of the parts.
Elements of Logical Structure 99
The same concept is true for an electrical system. The electrical engineers and electricians
who design and build such systems need to be familiar with the parts that are available,
how they work, and how they fit together. Switches, wires, outlets, junction boxes, circuit
breakers, and so on can be thought of as the building blocks of an electrical system.
Now, consider this concept in terms of the elements of the logical structure in an algorithm.
They form the building blocks of the algorithm's sequential logic. However, there are only a
handful of basic elements of logical structure that programmers need to learn, not hundreds
or even thousands of different parts, as in plumbing and electrical systems. In the 1960s,
two Italian mathematicians, Corrado Bohm and Giuseppe Jacopini, showed that algorithms
are composed of three major structures: linear sequences, branching routines, and loops.
These are the building blocks of algorithms that you must understand to be a good com-
puter programmer.
Flowcharts
Bohm and Jacopini used a system they called flow diagrams to describe their work. In
Figure 4 - 1 , you can see part of their manuscript showing some of their flow diagrams,
which soon became known as flowcharts. A flowchart is a diagram that shows the structure
of an algorithm. Bohm and Jacopini weren't the first to use such diagrams; however, they
formalized the concept of flowcharts and used them in their work on algorithms.
Bohm and Jacopini used a simple system of flowcharting with two symbols: rectangles to
show each step in an algorithm, and diamond-shaped boxes to show what they called a
logical predicative. More commonly, the diamond symbol for a logical predicative is called
a decision diamond, a decision box, or a conditional.
Chapter 4 • Algorithms
To say that one thing is "predicated" on another means that one thing is determined by
another. In other words, there is some condition that will determine what happens next. In
an algorithm, these conditions will be either true or false. If the condition is true, one thing
happens; if the condition is false, then something else happens. The path through an algo-
rithm each time it is executed is determined by the state of the true or false conditions in
that algorithm at that time. Flowcharts are designed to show the possible paths through an
algorithm.
Flowcharting Template
Bohm and Jacopini's notion of flow diagrams was relatively simple, but, in practice, flow-
charts quickly became complicated as people continued to add more shapes. Figure 4 - 2
shows a flowcharting template introduced by IBM in 1969. It was accompanied by a 40-page
manual showing the proper way to use all of the symbols.
Flowchart Symbols
In the rest of this chapter, we will use a simple version of flowcharting to help describe the
elements of logical structure found in algorithms. We will use only three symbols: rectan-
gles and diamonds—as Bohm and Jacopini did—and an oval-shaped box, which is used to
mark the beginning and end of an algorithm, as shown in Figure 4-3.
The oval shape is called a terminator. There should be only one terminator at the beginning
of an algorithm and one terminator at the end of an algorithm, because each algorithm
should have one beginning, called an entry point, and one end, called an exit point. Usually
terminators are labeled with the words "start" or "stop," or sometimes "begin" or " e n d . "
Linear Sequences 101
FIGURE 4 - 3 : A f l o w c h a r t d r a w n u s i n g only t h r e e s i m p l e s y m b o l s
STOP
LINEAR S E Q U E N C E S
The simplest element of logical structure in an algorithm is a linear sequence, in which one
instruction follows another as if in a straight line. The most notable characteristic of a linear
sequence is that it has no branching or looping routines. There is only one path of logic
through the sequence, which doesn't divide into separate paths, and nothing is repeated.
On a flowchart, this would appear as a single path of logic, which would always be exe-
cuted one step after another, as shown in Figure 4-4.
Chapter 4 • Algorithms
FIGURE 4 - 4 : A linear s e q u e n c e
Q START ^
\
INPUT
\
PROCESSING
\
OUTPUT
Q STOP ^
Linear sequences are deceptively simple It doesn't seem very complicated to do one thing,
then another, and then another, but it can be. Programmers need to make sure that each lin-
ear sequence meets the following criteria:
In short, linear sequences must have clearly stated entry and exit conditions, and they need
to be complete, correct, and in the proper order.
Selection Sequences—Branching Routines 103
Sometimes an algorithm reaches a point at which the path through the algorithm can go one
way or another. That is, the code can execute a selection sequence. Consider this example
of a student who has chemistry lab at 2:00 p.m. on Fridays only:
Start
IF (Today is Friday)
THEN (Get to chemistry lab by 2:00 p.m.)
Stop
FIGURE 4 - 5 : A s e l e c t i o n s e q u e n c e
START
Get to chemistry
lab by 2:00 p.m.
This is an example of a branching routine. A branching routine occurs whenever the path
or flow of sequential logic in an algorithm splits into two or more paths. Each path is called
a branch. Branching routines are also known as selection sequences or selection structures.
Binary a n d Multiple B r a n c h i n g
If there are two possible paths, then the routine is known as binary branching. If there are
more than two paths, then it is called multiple branching. "Would you like vanilla ice
cream?" is a binary question. It has two possible answers, " y e s " and " n o . " "What flavor ice
cream would you like?" is a question with many possible answers. Binary branching is simi-
lar to the first question; multiple branching is similar to the second.
could be asked, for example: "Would you like vanilla ice cream?" "Would you like choco-
late ice cream?" "Would you like strawberry ice cream?" In a similar manner, every multi-
ple branching routine in an algorithm can be rewritten as a series of binary branching
routines.
The Alice exercises in this chapter focus on binary branching rather than multiple branch-
ing. In fact, Alice does not have an instruction for multiple branching.
Binary Branching
There are two kinds of binary branching: a binary bypass and a binary choice. In a binary
bypass, an instruction is either executed or bypassed, as shown in Figure 4-5. In a binary
choice, one of two instructions is chosen, as shown in Figure 4-6. The difference between a
bypass and a choice is subtle but significant. In a binary bypass, it is possible that nothing
happens, whereas in a binary choice, one of the two instructions (but not both) will occur.
FIGURE 4 - 6 : A binary c h o i c e
START
,„ Go to History
Go to Math class
class
(^ STOP ^
Pseudocode
Sometimes computer programmers use a more formal language, called structured language
or pseudocode, to describe algorithms. The term pseudocode comes from the fact that it
looks something like the code in a computer programming language, but not quite. It's like
code, but it's only a tool to help describe and understand algorithms, just as flowcharts are.
is not true, then the instruction is ignored, and the computer will move on to the next step in
the algorithm. The chemistry lab example prior to Figure 4-5 shows a binary bypass.
A set of instructions, called a block of instructions or a block of code, could take the place
of a single instruction anywhere in an algorithm, including in binary branching routines. In
the preceding example, go to math class could be a whole series of instructions.
One thing is common to all binary branching routines—there must be a condition to deter-
mine what to do. These conditions will be either true or false when the algorithm is exe-
cuted. They are a form of conditional logic known as Boolean logic, which will be
discussed in the next chapter.
REPETITION SEQUENCES—LOOPING
In the branching routines that you saw earlier in the chapter, the algorithms split into differ-
ent paths that all moved forward; nothing was repeated. A repetition sequence occurs when
an algorithm branches backward to a previous instruction, and then repeats part of the algo-
rithm. A repetition sequence forms a loop in an algorithm, which can be seen on a flow-
chart, as shown in Figure 4-7. This figure shows both the pseudocode and a flowchart for
the algorithm for printing numbers from 1 to 10.
In this algorithm, the word WHILE is used for looping instead of the word IF, which was
used for branching. In pseudocode, as in many programming languages, this usage tells the
computer to loop back to the conditional expression when the block of code following the
WHILE instruction is finished. Each time the condition is true, the computer will execute
the block of code, and then come back to the condition again. When the condition is no
longer true, the block of code will be ignored, much like a binary bypass, and the computer
will move on to whatever comes next in the algorithm.
Chapter 4 • Algorithms
Q START ^
BEGIN
LET X = 1
Add 1 to X
WHILE (X < 10)
<
PRINT X
ADD 1 TO X
}
END
Print X
Like all loops, this loop has a control variable in its condition. In programming, a variable
holds a value that can change, much like a variable in algebra, which stands for a number
that could change. A control variable is a variable whose value controls whether or not a
selection sequence will be executed. In this loop, the variable X stands for a number that is
used to keep track of how many times a loop should be executed. In this example, we want
to print the numbers from 1 to 10. X starts at 1 and increases by 1 each time through the
loop. While X is less than 10, the loop is executed and the number is printed. When X
reaches 11, we move on to whatever comes next.
The loop in Figure 4 - 7 is a pretest loop, meaning that the test to determine whether or not
to go though the loop comes before the block of code to be executed. Traditionally, there are
four parts to every pretest loop:
Initialization: an instruction that sets the first value of the control variable
Test: the instruction that looks at the control variable to see if the loop should
be executed
Repetition Sequences—Looping
Figure 4-8 shows the example again, this time using COUNT instead of X and highlighting
the four parts of the loop.
^ START ^
BEGIN
LET COUNT = 1
{
PRINT COUNT
ADD 1 COUNT
}
END
( STOP ^
In a pretest loop, the test to determine whether or not to continue executing the loop comes
before any other instructions that are to be repeated. It is also possible to set up a posttest
loop, with the test to determine whether or not to repeat a loop coming after the instruc-
tions that are to be repeated.
Figure 4 - 1 , near the beginning of this chapter, shows diagrams of four different logical struc-
tures from Bohm and Jacopini's original manuscript. Look closely at both the upper-right
diagram and the lower-right diagram. In both cases, the condition in the diamond-shaped
box is labeled with the Greek letter " a " (alpha), and the rectangular box representing an
instruction to be repeated is labeled with the letter " a . " Notice that the upper structure is a
Chapter 4 • Algorithms
pretest loop with the decision diamond before the instruction to be repeated, and the lower
structure is a posttest loop, with the decision diamond after the instruction to be repeated.
1. Program 1—When the computer is turned on, the program erases the first
hard drive and then asks "Should I do that again for the next hard drive?"
(Of course, this assumes the program will still run after the first hard drive
has been erased.)
2 . Program 2—When the computer is turned on, the program asks "Do you want
me to erase the first hard drive?" If the answer is "yes," it erases the first hard
drive, and then it asks if you want to repeat the process for the next hard drive.
The second program is slightly more complicated than the first, but which do you think is a
safer program to run?
Unfortunately, people often think very differently than the way a computer works. We tend
to do something first, and then ask if it should be repeated, like a posttest loop instead of a
pre-test loop—just the opposite of what computer scientists suggest. Alice has a WHILE
instruction for pretest loops, but it does not contain any commands to set up a posttest loop.
Count-Controlled a n d Sentinel L o o p s
In addition to being a pretest loop, the example in Figure 4-8 is also a count-controlled loop.
Every loop in a computer program is either a count-controlled loop, or a sentinel loop. A count-
controlled loop causes a process to be repeated a specific number of times. A sentinel loop
causes a process to be repeated until a condition or marker, called a sentinel, is encountered.
It's important to make sure that the initial value, the final value, and the increment are coordi-
nated. If a computer were programmed to start the counter at 100, and then increase it by 1
each time through the loop until it reached 0, we would probably get some unexpected results.
Repetition Sequences—Looping
If the increment is positive, then the final value should be higher than the initial value. If the
increment is negative, then the final value should be lower than the initial value.
Alice has a special LOOP instruction for programming count-controlled loops, which auto-
matically handles the counter's increment and final value. Most programming languages
have a similar instruction, such as the FOR instruction in Java. However, Alice's LOOP
instruction does not let us use a negative increment. That is, you could not use the LOOP
instruction to add a negative number to the counter each time through the loop. If you
wanted to start at 100 and count backward until you reached zero, then you would need to
set up your own count-controlled loop using the WHILE instruction instead of the special
LOOP instruction.
A count-controlled loop is a special case of a sentinel loop, in which the sentinel involves
" " * * a counter, but the term "sentinel loop" is generally used to refer only to loops that are not
count-controlled.
As an example of such a loop, imagine a machine that tests a car door. The machine, which
is controlled by a computer program, opens the door, and then closes the door. The
machine could be programmed to repeat this a certain number of times with a count-
controlled loop. However, it could also be programmed to repeat the process until the door
falls off, as shown in the following pseudocode:
BEGIN
LET counter = 0
WHILE (door is still on the car)
{
open the door
close the door
increment counter by 1
}
PRINT "The door fell off after opening and closing this many times:"
PRINT counter
END
The counter in this loop does not control when the loop stops running, so this is not a
count-controlled loop, but rather a sentinel loop. It is the sentinel condition, the door still
being on the car or falling off the car, that controls when the loop will stop.
In summary, when code in a computer program is repeated, the algorithm contains a repeti-
tion structure, which is also called a loop. Algorithms can contain count-controlled loops or
sentinel loops that are not count-controlled. Each loop is also a pretest loop or a posttest
loop. Alice has a WHILE instruction for pretest loops but does not allow posttest loops.
Alice also has a special LOOP instruction for count-controlled loops.
110 Chapter 4 • Algorithms
There are two methods o f programming that are more appropriate than loops in many situ-
ations in which processes are repeated—event-driven programming and recursion. These
methods will be discussed in detail in later chapters.
PARALLEL ALGORITHMS
It is possible for one computer, or several computers working together, to work on several
parts of an algorithm at the same time. Each path of logic that is being executed is called a
thread of sequential logic, and algorithms that run multiple threads at the same time are
called parallel algorithms. The process of running multiple threads is called parallel execu-
tion, concurrent execution, or concurrency.
Parallel algorithms can be quite powerful, but they can be difficult to design and use. Many
problems arise, such as the different threads interfering with each other. It might be easier
to run a restaurant kitchen with four chefs instead of one, but if things aren't carefully coor-
dinated, then chaos could ensue.
Concurrency is mentioned here for two reasons: first, it is becoming more common, even in
simple programs, and second, concurrency is important in Alice. For instance, you need it
when an object should move and turn at the same time, or when two objects should move at
the same time.
You have already seen a simple version of concurrency in Alice. In Chapter 3 , you used the
Do together logical structure, which causes parallel execution of separate instructions. Alice
also has a For all together instruction that can be used with lists, which will be covered in
Chapter 9.
In this exercise, you will modify the triple jump world from Chapter 2 to include user input
and branching. The world contains three objects, each a character from Alice's Adventures
in Wonderland. The existing version of the world contains a method to make all three char-
acters jump, one at a time. The algorithm in w o r l d . m y f i r s t method is simply a linear
sequence. You will modify it to include user input and IF/THEN instructions. The new pro-
gram will ask the user questions about which character should jump, and then have one of
the three characters jump, depending on the answers to those questions.
Alice has a world-level function to ask the user a yes or no question. You are going to add
two questions to w o r l d . m y f i r s t method. First, the method will ask if the user wants
Alice to jump. If the answer is " y e s , " then Alice will jump. If the answer is " n o , " then the
method will ask if the user wants the White Rabbit to jump. If the second answer is " y e s , "
Tutorial 4A—Branching in Alice Methods 111
then the White Rabbit will jump: if the answer is " n o , " then the Cheshire Cat will jump.
The pseudocode and flowchart in Figure 4 - 9 describe this algorithm.
FIGURE 4 - 9 : P s e u d o c o d e a n d a f l o w c h a r t s p e c i f y i n g t h e p r o g r a m to be c r e a t e d in Tutorial 4A
STOP ^
BEGIN
IF("Do you want Alice to jump?" = yes)
Alice jumps
ELSE
IF ("Do you want the White Rabbit to jump? yes)
White Rabbit jumps
ELSE
Cheshire Cat jumps
END
U s e r F u n c t i o n s in Alice
Before you start, you need more information about the user input functions in Alice. There
are three world-level functions in Alice to ask the user a question: ask user for a number,
112 Chapter 4 • Algorithms
ask user for yes or no, and ask user for a string. Figure 4-10 shows the tiles for these three
functions on the functions tab in the Details area for the world.
world's details
random number
3 string
a Joined with b
what as a string
- ask user
ask user for a number
ask user for yes or no
ask user for a string
mouse
mouse distance from left edge
mouse distance from top edge
3 time
time elapsed
<
In the following steps, you will use the function to ask user for yes or no, which returns a
value of true if the user answers " y e s " to the question and false if the user answers " n o . "
This function may be used any place in an Alice method where t r u e or f a l s e can be used,
such as in a condition in an IF/ELSE instruction.
1. Start the Alice software and open the triple jump world created in Chapter 2.
If you cannot find the world, then either load the world from the student
data files for this book, or complete Tutorial 2B to create and save the world
before continuing.
2. Look at the code for world.my f i r s t method, as shown in Figure 4-11.
You can see that there are several instructions that form a linear sequence
in the program. You need to add an IF/ELSE instruction to the method.
Drag a copy of the If/Else tile from the bottom of the Editor area and drop it
into the method just below the three jump instructions.
3 . A short menu will appear asking you if you want to use a true or false con-
dition in the IF/ELSE instruction. Select true, and a light greenish-blue
If/Else tile will appear in your method, as shown in Figure 4-12.
Tutorial 4A—Branching in Alice Methods
9 w o r l d . m y first m e t h o d •
w o r l d . m y first m e t h o d No parameters create new parameter
whiteRabbit.jump
cheshireCat.jump
aliceLiddell.jump
Do in order Do together I f f Ise Loop While For all in order For all together Wait print
FIGURE 4 - 1 2 : T h e t r i p l e j u m p m e t h o d w i t h a n a d d e d If/Else i n s t r u c t i o n t i l e
V w o r l d . m y first m e t h o d |
w o r l d . m y first m e t h o d No parameters create new parameter
whiteRabbit.jump
cheshireCat.jump
aliceLiddell.jump
Blf true
(Do Nothing
Else
(Do Nothing
Do in order Do together If/Else Loop While For all in order For all together Wait print
4. Next, you need to replace true in the If/Else tile with the function to ask user
yes or no. Select the world tile in the Object tree, and then click the functions
tab in the Details area. Scroll through the list of functions and find the function
titled ask user for yes or no. Drag and drop a copy of this function into the
5. A short menu will appear with the options Yes or No? and other.... This
menu is asking you how you want to word the question that the user will
114 Chapter 4 • Algorithms
see. Click other and the Enter a string dialog box will appear. The char-
acter string entered here will form the text of the question the user will see.
Type Do you want Alice to jump? as the string, and then click the OK but-
ton. Your question will now appear in the If/Else tile in place of true as the
condition for the IF/ELSE instruction, as shown in Figure 4 - 1 3 .
(Do Nothing.
Else
(Do Nothing
6. Drag the aliceLiddell.jump tile from its place in the linear sequence above
the If/Else tile, and drop it into the IF/ELSE instruction in place of Do
Nothing immediately below the //clause, and above the word Else. Now if
the user answers " y e s " to the question, Alice will jump.
7. If the user answers " n o " to the first question, he or she should see a second
question. Thus, another IF/ELSE instruction is needed following the word
Else. Drag and drop another IF/Else tile from the bottom of the Editor area
and drop it in place of Do Nothing following the word Else, and then
click True when the short menu appears. Now you have nested IF/ELSE
instructions—one IF/ELSE tile inside another one.
8. You need to put another question in place of true in the second If/Else
instruction. As before, find the function titled ask user for yes or no on the
world's functions tab. Drag and drop a copy of this function into the If/Else
tile in place of true following the word If in the second IF/ELSE instruction.
9. A short menu will appear. Click other and the Enter a string dialog box
will appear. Type Do you want the White Rabbit to jump? as the string, and
click the OK button. Your second question will now appear in the If/Else
tile in place of true as the condition for the IF/ELSE instruction.
10. If the user answers " y e s , " the whiteRabbit should jump. Drag the
whiteRabbit.jump tile and drop it in the instruction in place of Do Nothing
below the //clause and above the word Else.
11. Drag the cheshireCat.jump tile, and drop it in the instruction in place of Do
Nothing below the word Else.
Tutorial 4A—Branching in Alice Methods 115
12. Your method should look like the code shown in Figure 4-14. You are now
ready to test the new program, but first you should save your work. Save
the world with the name jump user choice.
FIGURE 4 - 1 4 : The completed world.my first method in the jump user choice world
• w o r l d . m y first m e t h o d
w o r l d . m y first m e t h o d No parameters create new parameter
No variables
create new variable
0|f ask user for yes or no question - Do you want Alice to jump? more...
aliceLiddell.jump
Else
IT ask user for yes or no question = Do you want the White Rabbit to jump? more..
whiteRabbit.jump
Else
cheshireCat.jump
Do in order Do together If'Else Loop While For all in order For all together Wait print
It's a good idea to test the world under all possible circumstances, which in this case means
trying the world with all possible combinations of user input. This calls for a testing plan.
The specifications in Figure 4-9 show that there are three possible paths for the logic in the
program. The answer to the first question could be " y e s " or " n o . " If it's " y e s , " then Alice
should jump and the program is done. If it's " n o , " then the second question appears. If the
answer to the second question is " y e s , " then the White Rabbit jumps, and the program ends.
If the answer to the second question is " n o , " then the Cheshire Cat jumps, and the program
ends. The testing plan must include three trials, one for each possibility, as follows:
Test your program according to the testing plan, and see if it works as expected. If it does,
you're done; if not, then it's time to debug. Remember to save your world again if you make
any significant changes.
In this exercise, you will experiment with count-controlled loops in Alice. Alice has a
special LOOP instruction to make it easier to set up a count-controlled loop. The LOOP
instruction has two different versions: a simple version and a complicated version. Both
versions of the same loop are shown in Figure 4-15.
Loop us index from 0 upto (but not including) 4 times incrementing by 1 | show simple version.
IceSkater.simpleSpin
In the simple version, the programmer simply tells Alice how many times to repeat the
loop, and Alice will handle the counter, increment, and final value to stop the loop when it
has been executed the specified number of times. In the complicated version, the program-
mer has access to the initial value, the final value, and the increment.
In the next several steps, you will modify the triple jump world created in Chapter 2 using
the simple versions of Alice's LOOP instruction to make the characters jump a specified
number of times.
FIGURE 4 - 1 6 : Parallel e x e c u t i o n of t h e j u m p i n s t r u c t i o n s
HDo together
whiteFlabbit.jump
cheshireCat.jump
aliceLiddell.jump
Do in order Do together HTEIse Loop While For all in order For all together Wait print
4. Save the world first with the name triple jump loop, and then play the
world. If all three characters jump at the same time, then move on to the
next step. If not, then find and fix the error.
5. Next, you will add a simple count-controlled loop to the program to make
the three characters jump a certain number of times. Drag a Loop tile from the
bottom of the Editor area and drop a copy of it into the method just below the
Do together tile. When you do this, a short menu will appear asking you how
many times you want to repeat the loop. Select 5 times.
6. Drag the Do together tile into the Loop tile. Your method is complete and
should now look like Figure 4-17.
118 Chapter 4 • Algorithms
FIGURE 4 - 1 7 : A simple count-controlled loop to make the characters jump five times
% w o r l d . m y first m e t h o d |
w o r l d . m y f i r s t m e t h o d No parameters create new parameter
Do in order Do together If/Else Loop While For all in order For all together Wait print
7. You can now test the world again, to make sure that the characters jump
together five times. Save the world first, and then play it to see if it works.
This world demonstrates the use of the simple version of a loop instruction. All of the
characters should jump together five times. If the program doesn't work properly, review
your work to find the error in your program, and then fix it. Once it works, you are fin-
ished with this exercise.
The LOOP instruction in Alice is really intended to be used only in situations where the
programmer wants to make something happen a certain number of times, such as jumping
five times. Remember that a count-controlled loop is just a special case o f a sentinel loop.
Whenever a more sophisticated loop is called for, such as one that counts backward, it is
best to create your own version o f a count-controlled loop with a W H I L E instruction.
In this tutorial, you are going to use the WHILE instruction to duplicate the effect of the
LOOP instruction used in Tutorial 4B. Remember that a sentinel loop has a value or condi-
tion that tells a loop when to stop executing. A count-controlled loop is just a special case
of a sentinel loop.
You will use the triple jump loop world from Tutorial 4B as your base world, modifying it to
use the WHILE instruction instead of the LOOP instruction, but the new world should func-
tion similarly to the old world. Figure 4-18 shows the algorithm for a simple count-controlled
Tutorial 4C—Using the While Instruction 119
loop alongside the new algorithm for the WHILE loop you will create. Notice that the LOOP
instruction handles the initialization, test, and update automatically, whereas the programmer
must include instructions to deal with these steps in the WHILE loop.
FIGURE 4 - 1 8 : A simple count-controlled loop on the left, and a WHILE loop on the right that functions
as a count-controlled loop
BEGIN
BEGIN
Loop 5 times
{ count = 0 ~) < Initialization
>
Processing'
END
You will need to add a variable to world.my f i r s t method to function as the control vari-
able, add a WHILE loop to the method, and delete the LOOP instruction.
1. Open the triple jump loop world that you saved in Tutorial 4B. If you cannot
find the world, then either load the world from the student data files for this
book or redo Tutorial 4B to create and save the world before continuing.
2 . Select the world tile in the Object tree and the methods tab in the Details
area. Click the edit button next to the my first method tile on the methods
tab; the method world.my f i r s t method should open in the Editor area.
3 . You need to create a new control variable for the WHILE loop that you will
add to the program. Click the create new variable button, and a dialog box
will appear asking you for the name and type of the new variable. Type count
for the name, select Number as the type, and then click the OK button.
4. The variable tile at the top of the method shows that the count is initialized
to 1. Click the 1 and change the value to 0.
120 Chapter 4 • Algorithms
5. Drag a While instruction tile from the bottom of the Editor area and drop it
in the method below the Loop tile. Select true from the short menu that
appears.
6. Next, drag the Do together tile with the three jump instructions from the
Loop tile and drop it in the While tile.
7. Now the Loop tile is no longer needed. Right-click the Loop tile and
click delete.
As discussed earlier in this chapter, there are four parts to every pretest loop: initialization,
test, processing, and update. Each of these parts of the loop needs to be properly in place for
the loop to function as desired. Count is initialized to 0 in the count variable tile at the top of
the method, so this will suffice as the initialization step for the loop. The three jump instruc-
tions are the processing in the middle of the loop. You only need to modify the test and add
the update step.
The condition in the WHILE instruction will be the test to see if the loop needs to be
repeated. The algorithm in Figure 4-18 shows that the loop should continue while the count
is less than 5. It also shows that 1 should be added to c o u n t at the end of the loop. You
need to modify the code in world.my f i r s t method to match this.
1. Drag a copy of the count variable tile and drop it into the While tile in place
of the value true. When the menu appears with different choices for the
conditional expression, choose count < , then other, and set the value to 5.
Now the loop will repeat while count is less than 5.
2 . Drag the count variable tile from the top of the method and drop a copy in
the While tile after the three jump instructions. When you do this, a short
menu will appear asking you how you want to set the value of count.
Choose set value, choose expressions, and then click count.
3. Now the tile says count set value to count. You need to build a math expres-
sion so that the tile will say count set value to count +1. Click the second word
count, and select math from the menu that appears. Then select count + and
then 1. Now world.my f i r s t method should look like Figure 4-19, which
matches the specifications in Figure 4-18.
Tutorial 4C—Using the While Instruction
'"count = 0
Do in order Do together If .Else Loop While For all in order For all together Wait print
4. You need to save and test the world. Save the world with the name triple
jump while loop, and then play the world to make sure that the characters
jump together five times, just as they did with the simple count-controlled
loop in Tutorial 4 B . If the program doesn't work properly, review your work
to find the error in your program, and then fix it. Once it works, you are
finished with this tutorial.
Chapter 4 • Algorithms
Chapter Summary
This chapter consisted of several readings about the logical structure of algorithms—including linear sequences,
selection sequences, repetition sequences, and parallel execution of instructions in an algorithm—followed by three
hands-on tutorials.
• Algorithms are sequential in nature; we can think of the instructions in an algorithm as being executed
one at a time.
• Each element of logical structure is a set of instructions that forms part of an algorithm. Corrado Bohm
and Giuseppe Jacopini showed that algorithms are composed of three major structures: linear
sequences, selection sequences (branching routines), and repetition sequences (loops).
• A flowchart is a diagram showing the structure of an algorithm. Flowcharts are designed to show the
possible paths through an algorithm.
• The simplest element of logical structure in an algorithm is a linear sequence, in which one instruction
follows another as if in a straight line. Linear sequences must have clearly stated entry and exit condi-
tions, and they need to be complete, correct, and in the proper order.
• A selection sequence (branching) occurs whenever the path or flow of sequential logic in an algorithm
splits into two or more paths.
• There are two kinds of binary branching in algorithms: a binary bypass and a binary choice. In a binary
bypass, an instruction is either executed or bypassed. In a binary choice, one of two instructions is chosen,
• A repetition sequence (loop) occurs when an algorithm branches backward to a previous instruction, and
then repeats part of the algorithm.
• A control variable is a variable whose value controls whether or not a repetition sequence will be executed.
• In a pretest loop, the test to determine whether or not to continue executing the loop comes before any
other instructions that are to be repeated. In a posttest loop, it comes afterward. Many computer scien-
tists recommend that only pretest loops be used.
• There are four parts to every pretest loop: initialization, test, processing, and update.
• Every loop in a computer program is either a count-controlled loop or a sentinel loop. A count-controlled
loop causes a process to be repeated a specific number of times. A sentinel loop causes a process to
be repeated until a condition or marker, called a sentinel, is encountered. Actually, a count-controlled
loop is a special case of a sentinel loop.
• It is possible for a computer to execute several instructions from the same algorithm at the same time.
This is called concurrency, and algorithms that include concurrency are called parallel algorithms.
Review Questions 123
In Tutorial 4A, you learned how to use the IF/ELSE instruction to include binary branching in an Alice method, and to
use the ask user a yes or no question function.
In Tutorial 4B, you learned how to include a simple count-controlled loop in Alice with the LOOP instruction, and used
the Do together instruction to perform parallel execution of several methods.
Review Questions
2. Create a set of instructions for a simple everyday process that contains a linear seqeuence of steps, such as
making a cup of coffee or getting from your school to where you live. Exchange directions with another student,
and critique each other's work. In particular, determine if the linear sequences in each algorithm are complete,
correct, and in the proper order.
3. Compare the structures created by using an IF/ELSE instruction and a WHILE instruction in pseudocode and on a
flowchart. How are they the same? How are they different?
4. To add two fractions, such as 1/2 and 1/3, the fractions must have a c o m m o n denominator. Using both
pseudocode and a flowchart, describe a general algorithm for adding two fractions.
5. What is meant by the term "nested" IF/ELSE instructions? Give at least one example of a nested IF/ELSE
instruction using pseudocode and flowcharts to describe your answer.
6. List and describe the four parts of every pretest sentinel loop.
Chapter 4 • Algorithms
7. The following algorithm was intended to result in the numbers from 1 0 to 1 being printed. What will it actually
do? What is wrong with it, and how can it be corrected?
BEGIN
count = 10
While count > 0
{
Print count
Count = count +1
}
Print "The countdown is finished."
END
8. Tutorial 4B shows how to set up a count-controlled loop using the LOOP instruction. Tutorial 4C shows how to do
the same thing using a WHILE instruction. What are the advantages to using the LOOP instruction to set up a
count-controlled loop? What are the advantages in using the WHILE instruction to set up a count-controlled loop?
9. Describe the difference between a pretest loop and a posttest loop. Which is generally safer to use in a c o m -
puter program, and why?
10. A data file for a payroll program consists of a set of records. There is one record for each employee, containing
the employee's ID number, first name, last name, and hours worked. The last record contains " 0 0 0 0 " as the
employee number. Using pseudocode and a flowchart, describe an algorithm that will read in and print each
record no matter how many records are in the file w h e n the algorithm is executed.
Exercises
1. Alice contains a world-level function that will ask the user for a number. Create an Alice world with a character
of your choice that will ask the user for a number, cause the character to j u m p up, use a loop to spin around the
number of times specified, and then come back d o w n . Think about how variables will be used as you design the
algorithm.
2. Modify the triple jump loop world so that Alice j u m p s if the index is equal to 1 , the White Rabbit j u m p s if the
index is equal to 2, the Cheshire Cat j u m p s if the index is equal to 3, and all three characters j u m p if the index
is equal to 4.
3. Add a tree to the triple jump while loop world. Use the tree's height as the sentinel rather than the number 5, so
that the loop will execute when the count is less than or equal to the tree's height, but stop when the count
passes its height. To do this, you can use the character-level function that returns the tree's height.
4. Modify the triple jump while loop world from Tutorial 4C to make the count increase by .5 meters each time
through the loop. How does this affect the number of times the characters j u m p ?
5. Make the count in the triple jump while loop world start at a higher number and decrease each time until it is
less than or equal to a smaller value. For example, the initial value could be 5, the increment could be - 1 , and
the final value could be 1.
Exercises 125
6. Modify the jump user choice world from Tutorial 4A so that it has three questions and three separate IF instruc-
tions, one for each character,
7. Modify the finished triple jump While loop world from Tutorial 4C to use the increment instruction instead of
the instruction that says count set value to count + 1 . To do this, delete the old set value
instruction, drag the count variable tile, drop it into the code for the method, and select increment count by 1
instead of set value.
8. Alice contains Hebuilderan6 Shebuilder class tiles in the People folder of the Local Gallery. You can create your
own character objects in Alice using these tiles. The new character will have a method to walk. Create an Alice
world with a character of your own creation as an object in the world. Using the walk, move, and turn
methods, create an Alice method with a loop to make the character walk around in a complete circle. (You can
approximate a circle with a polygon, such as an octagon.)
9. The Animals object gallery contains a pterodactyl. The student data files for this book have a world named
flapping pterodactylwith a character-level method named flap that will cause the pterodactyl to flap its
wings. Do each of the following:
a. Create a method called pterodactyl fly that will make the pterodactyl move forward while flapping
its wings, and then create a loop in world.my first method to make the pterodactyl fly away.
b. Add controls to your pterodactyl world so that the user can steer the pterodactyl.
c. Add a user control to point the camera at the pterodactyl w h e n the spacebar is pressed.
d. Modify the world to use an event instead of a loop to make the pterodactyl fly while the world is running. You
might need to refer back to Chapter 3, which covers events.
10. In Exercise 9, why is it better to use an event instead of a loop to make the pterodactyl continue flying while the
world is running? In general, w h e n should events be used instead of loops in computer programming?
B o o l e a n Logic in P r o g r a m m i n g
• Describe the function of the Boolean operations AND, OR, and NOT, and show how
they are used in Alice branching and looping instructions
• List and describe the function of the six logical comparison operators, and show how
they are used to form Boolean conditions in Alice
.3 Describe what a Boolean function is and how such functions are used in Alice
Create new methods in Alice that use Boolean conditions, Boolean functions, and
method parameters
127
128 Chapter 5 • Boolean Logic in Programming
BOOLEAN LOGIC
Branching and looping routines contain conditions that are either true or false. In 1854,
George Boole, the first Professor of Mathematics at Queen's College in Cork, Ireland, pub-
lished a book titled An Investigation into the Laws of Thought, on Which are Founded the
Mathematical Theories of Logic and Probabilities. In that book, Boole outlined a system of
logic and a corresponding algebraic language dealing with true and false values. Today that
type of logic is called Boolean logic, and his language is called Boolean algebra. The condi-
tions that exist in branching and looping routines are a form of Boolean logic, which is the
basis for all modern digital electronic technology.
The lwusliiffworks.com Web site has an article about how computers implement
t" W I V Boolean logic at http://computer.howstuffworks.com/hoolean.htm. In 1858, Boole's
original book was republished as An Investigation of the Laws of Thought, which can
still be found in many bookstores and online. The complete text o f an 1848 paper by
Boole titled the "Calculus o f L o g i c " is available at: http://www.maths.tcd.ie/pub/
HisiMath/People/BooIe/CalcLogic. The site is maintained by the University o f Dublin's
Trinity College School o f Mathematics. The school also maintains links to information
about George Boole at http://www.maths.tcd.ie/pub/HistMath/People/Boole.
Boolean logic is a form of mathematics in which the only values used are true and false.
There are three basic operations in Boolean logic—AND, OR, and NOT, as described in
Figure 5-1.
AND OR NOT
true and true = true true or true = true not true = false
true and false = false true or false = true not false = true
false and true = false false or true = true
false and false = false false or false = false
The AND and OR operations are binary operations, meaning that they need two operands.
Basically, when two values are combined in the AND operation, the result is true only if
both values are true. Otherwise, the result is false. In the OR operation, if either value is
true, then the result is true.
Comparing Values 129
The NOT operation is a unary operation, which means that it works on only one operand. It
simply reverses the true or false value of its operand. In other words, NOT true yields false;
NOT false yields true.
The use of AND, OR, and NOT should be common sense. A statement like "today is
Monday AND this is March" can be evaluated for its true or false value; yet people some-
times run into trouble converting the informality of human language into the formality
needed for algorithms. Consider the following conversation:
BOSS: Give me a list of all our offices in Pennsylvania and New Jersey.
PROGRAMMER: Let me get this straight—you want a list of our offices located
in either Pennsylvania or located in New Jersey, right?
BOSS: Yes, isn't that what I just said?
The programmer, who has experience converting the informality of human language into a
formalized computer programming language, knows what would happen if the condition
(state = " P A " AND state = "NJ") were used to create the list. If each office is located in only
one state, then both conditions cannot possibly be true. What should the programmer do,
give the boss a blank sheet of paper? Tell the boss the request is nonsense according to the
rules of Boolean logic? The programmer's response in the dialogue clarified the boss's
request in an appropriate manner.
Boolean expressions can become long and complex with many nested AND, OR, and NOT
clauses layered together. Professional programmers often use Boolean algebra and other for-
mal tools when dealing with the layered complexities of Boolean logic. It won't be necessary
to learn Boolean algebra to complete the exercises in this book; however, most students major-
ing in computer science will need to study it in courses such as "Discrete Mathematics" or
"Computer Math and Logic."
COMPARING VALUES
Often the Boolean conditions in branching and looping routines are based on expressions
that compare values. Consider the following warning message, which might be found in the
documentation for a modern automobile:
The passenger-side air bag may cause injury to children who are under the age of 12 or who
weigh less than 48 pounds. They should not sit in the front passenger seat of this car.
Two items, each with a true or false value, are joined by the OR operation. The two items
are each comparisons of values. The condition "age < 1 2 " is either true or false, as is the
condition "weight < 4 8 . " When the algorithm is executed, the true or false value of each of
these conditions is determined, and then the overall true or false value is determined using
the rules for the OR operation.
The symbol " < " in the above example stands for "is less than." There are six such logical
comparison operators used to compare two values in Boolean logic: equals, is not equal to,
is less than, is greater than, is less than or equal to, and is greater than or equal to. Figure 5-2
shows the symbols most commonly used for these operators.
Notice that several of the computer programming symbols, such as " < > " for "not equals,"
are composed of two characters. This doubling of characters is required because modern
computer keyboards do not include a single symbol for these comparison operators; this is
in contrast to standard algebra, in which the symbol ' V is used for "not equals."
String C o m p a r i s o n s
It's clear that numbers can be compared according to their value, but what about other data
types, such as character strings? Most have their own rules for logical comparisons.
Character strings, for example, are compared according to the place in a collating sequence
for each character of the string. To collate means to put a set of items in order. A collating
sequence is a list that shows the correct order to be used when collating a set of items. The
English language alphabet is a collating sequence. It shows us that when putting things in
alphabetic order, A comes before B, B comes before C, and so on. Modern computers most
often use one of two codes to represent characters in a computer—either the American
Standard Code for Information Interchange (ASCII) or a newer code called Unicode. These
codes can also be used as collating sequences for character string values, just as the English
language alphabet can. Figure 5-3 shows a portion of the ASCII code.
Comparing Values
The ASCII code is based on the English language, and it includes letters, numeric digits,
and some "hidden" characters, such as the Enter key and the E s c key. Each character is
given a numeric value, and the binary equivalents o f those numeric values are used to
store characters in the computer. Unicode is a much larger code, which includes charac-
ters for other alphabets, such as the Greek, Hebrew, Arabic, and Cyrillic alphabets. The
ASCII code is now actually a subset o f the longer Unicode. For more information on the
ASCII code, see www.webopedia.coin/TERM/A/ASCII.html. For more information on
Unicode, see http:/hv\\\Y.wticode.org/standard/WhatIsUnicode.html.
A B C D E F G H I J K L M N 0 P Q R S T U V W X Y Z [ \ ] * _
a b c d e f g h i j k 1 m n o P q r s t u V w x y z { } 1 ~
Comparisons using character strings are often used when searching and sorting data stored
on a computer. While this is very important in data processing and database management,
comparisons using character strings in Alice are rare.
Boolean Functions
The true and false values in computer programming can also come from Boolean functions.
A Boolean function is a function that returns a true or false value instead of a numeric
value. The ask a user a yes or no question function used in the last chapter and shown in
Figure 5-4 is an example of a Boolean function. When a method using the function is
played, a question will appear on the screen. If the user answers " y e s , " then the function
returns the value true. If the user answers " n o , " then the function returns the value false.
ISV ask user for yes or no question = Do you want Alice to Jump? more...
Figure 5-5 shows some spatial relation functions on a seaplane's functions tab in Alice.
Each of these functions is a Boolean function that returns a true or false value.
Chapter 5 • Boolean Logic in Programming
seaplane's details
seaplane is behind
3 point of view
seaplane s point of view
seaplane's position
<
These and other Boolean functions can be used in any place that a true or false value can be
used, such as in an IF instruction or a WHILE instruction, as shown in the s e a p l a n e , f l y
method in Figure 5-6. The seaplane is above water function in the WHILE instruction in
this example will return a value of true, and the loop will be executed as long as the sea-
plane is above the water. Within the loop, there is an IF instruction to cause the seaplane to
wave its wings whenever it is close to the island. This instruction uses a Boolean function
that will return a value of true if the seaplane is within 10 meters of the island.
Comparing Values
No variables
L-rJ Do together
seaplane move forward 5 meters style • abruptly more...
seaplane.propeller spin
seaplane.wave wings
Else
i Do Nothing
seaplane.in water
Do in order Do together Ifffilse Loop While For all in order For all together Wait print
Alice has math comparison functions that can be found on a world's functions tab along
with the AND, OR, and NOT functions; these functions can be used to build more complex
Boolean expressions. Both function types are shown in Figure 5 - 7 .
134 Chapter 5 • Boolean Logic in Programming
world's details
|"properties~|'methods"jfunctions |
boolean logic
not a
both a and b
either a or b , or both
math
a ==b
a !=b
a > b
a >= b
a<b
a <= b
With the functions in Figure 5-7, you can build expressions like these:
If NOT (seaplane is in front of camera) AND ( (time < 10) OR (time > 30) )
The following tutorials will each provide experience with simple uses of Boolean functions
in Alice.
In this exercise, you will modify the jump user choice world from Tutorial 4A to have the com-
puter randomly select who will jump, instead of asking for user input. Alice has a world-level
function that will return a random number in a specified range. The numbers that it returns are
six-digit numbers, greater than or equal to the lowest number specified and less than the high-
est number specified. In this exercise, for example, you will ask Alice to return a number
between 0 and 3. Alice will return numbers such as 1.83475, 0.41257, 2.89175, and so on. All
of the numbers it returns will be greater than or equal to 0, but less than 3.
Tutorial 5A—Branching with Random Numbers 135
In this exercise, if the random number is less than 1, Alice will jump. If it is greater than or
equal to 1 but less than 2 , then the White Rabbit will jump. If it is greater than or equal to 2
but less than 3 , then the Cheshire Cat will jump. Figure 5 - 8 shows the expected results of
the program. The logic is very similar to the user input program in Tutorial 4 A , with nested
IF/ELSE instructions to determine which character will jump.
FIGURE 5 - 8 : The value of the random number will determine who jumps
0 1 2 3
You will add a variable to the program to hold the random number. Figure 5 - 9 shows what
the code for the method will look like after you do this. You can refer to this image to guide
you through the next several steps.
Chapter 5 • Boolean Logic in Programming
variable title
variable set to a
random number
button to create a
new variable
conditions in the
nested IF commands
random number
function
1. Open the jump user choice world saved as part of Tutorial 4A, or load the
world from the student data files for this book.
2 . Click the create new variable button on the right side of w o r l d . my f i r s t
method to add a variable to hold the random number. Name the variable
determinant (because it will determine who jumps), select Number as the
type, and then click OK. You will now see a variable tile for determinant at the
top of the method.
3. Next, you need to tell the computer to set the value of determinant to a ran-
dom number. Drag the determinant variable tile down into
world.my f i r s t method as a new first instruction before the IF/ELSE
instructions. When you do this, a set value dialog box will appear. Set the
value of determinant to 1. The 1 is only a placeholder; you will change it to
a random number in the next step.
4. Now you need to tell the computer to set the value of the variable determinant
to a random number instead of a 1. To do this, select the world tile in the
Object tree, and then click the functions tab in the Details area. Scroll
through the list of functions and find the function titled random number.
Drag and drop a copy of this function into the set value tile in place of the
number 1.
5. You now need to tell the computer what range of values to use when pick-
ing a random number. To do so, click more in the blue random number tile,
and set the minimum value to 0 . Click more again, and this time set the
maximum value to 3. The set value tile should now look like the determi-
nant set value to random number tile near the top of the method shown in
Figure 5-9.
Tutorial 5B—The Nervous Penguin 137
6 . The nested IF/ELSE instructions still contain conditions based on the user
question. You need to replace these conditions following the word If in
each of the nested IF/ELSE instructions with conditions based on the ran-
dom number. To do so, drag the determinant variable tile from the top of
the method down into the first IF/ELSE instruction in place of the blue ask
user yes or no condition tile. When you do this, a short menu will appear.
Select determinant < and 1 as the value. Now the first IF/ELSE instruction
tile should look like it does in Figure 5 - 9 .
7. Do the same thing for the second IF/ELSE instruction, but this time, choose 2
as the value. When you are done, the second IF/ELSE instruction should be
if determinant < 2.
8. The method should now be ready to select a random number and make one
of the three characters jump, based on the value of the random number.
Save the world as triple jump random, and you are ready to test the world.
You need a testing plan for your modified Alice world. If things work correctly, then one of
the three characters should jump each time the world is run. Which character jumps
depends on the value of the random number that the computer picks for the variable you
named determinant.
To test the program properly, you would need to run it several hundred or several thousand
times, and keep track of how many times each character jumps. Over a long period of time,
we would expect each character to jump about one-third of the time the program runs. This
will be left as an exercise at the end of the chapter. For now, test the program to make sure
that the same character does not jump all the time, and that each of the three characters
jumps at least part of the time. Play the world, and then use the restart button several times
to replay the world. Because the numbers are random and not part of a pattern, the same
character might jump several times in a row, but over the course of several replays, each of
the characters can be expected to jump at least once.
In this exercise, you will create a world with two penguins. The first penguin will be con-
trolled by the user and may move around freely in the world. The second penguin, the ner-
vous penguin, will flap its wings and jump up and down whenever the first penguin gets
close to it. A Boolean proximity function returns a value based on the distance from one
object to another. In this tutorial, a proximity function will be used to cause the nervous
penguin to react.
138 Chapter 5 • Boolean Logic in Programming
A proximity function returns a value o f true or false; however, a numeric proximity function
returns the distance between two objects.
6. Now the scene is ready. Click the large green DONE button to exit, and save
the world with the name nervous penguin.
The world will need one method and several events. T h e method will be the nervous pen-
guin's reaction to the other penguin getting too close. Figure 5-11 shows the method you
will need to create.
Tutorial 5B—The Nervous Penguin
Do together
nervousPenguin.jump times « 2
nervousPenguin.wingJIap times = 2
Do in order Do together IfElse Loop While For all in order For all together Wait print u
1. World.my f i r s t method will not be used further, so you can delete it.
Then, select the nervousPenguin tile in the Object tree and the methods tab
in the Details area.
2. Click the create new method button. When the create new method window
appears, type the name react, and then click the OK button.
3. The nervous penguin will need to jump up and down and flap its wings
when the other penguin gets too close. These two actions—jumping and flap-
ping—should happen at the same time. Drag a Do together tile from the bot-
tom of the Editor area and drop it in the new method in place of Do Nothing.
4. Drag a nervousPenguin jump times tile from the methods tab and drop it in
the Do together instruction in place of Do Nothing. When the short menu
appears, select 2 as the number of times.
5. Drag a wing_flap times tile from the methods tab and drop it in the Do
together instruction below the nervousPenguin jump times = 2 instruction.
When the short menu appears, select 2 as the number of times. The new
method is now complete and should resemble Figure 5-11.
Now it's time to create several simple events that will be needed for this world. You will
create methods to provide user controls for the moving penguin, to animate the moving
penguin, to let the user point the camera at the moving penguin in case it moves off camera,
and to cause the nervous penguin to react when the other penguin is near. Figure 5-12
shows these new events.
Chapter 5 • Boolean Logic in Programming
Tj
Let move penguin
A built-in event can be used to provide control of the moving penguin. A second event can
be created to use the penguin walk movejtime method to animate the penguin. The default
event can be modified to serve as this second event.
1. Click the create new event button in the Events area. When the menu
appears, select Let the arrow keys move <subject> as the event type.
2. A new arrow key event will appear in the Events area, as shown in Figure 5-13.
Click camera in the event tile and select penguin, the entire penguin. The
event is now set to let the user move the penguin with the arrow keys.
T
Let . ""-"J move penguin
The first two events are complete. The user can now move the penguin with the arrow keys,
and the penguin will waddle and move its feet while the world is running, even when
standing in place.
Next, you will add an event to allow the user to point the camera at the penguin in case it
moves off camera.
1. Click the create new event button in the Events area. When the menu
appears, select When a key is typed as the event type. A new When any key
is typed do Nothing event tile will appear in the Events area.
2 . Click any key and select Space from the menu that appears. Your actions
will make the spacebar the trigger key for this event.
3 . Select the camera tile in the Object tree and the methods tab in the Details
area. Drag a copy of the camera point at method tile from the methods tab
and drop it in place of Nothing in the new event. Select penguin, the entire
penguin from the menu that appears. The event to allow the user to point the
camera at the moving penguin is now complete, as shown in Figure 5-15.
FIGURE 5 - 1 5 : The event to allow the user to point the camera at the moving penguin
The last event that is needed is the event to cause the nervous penguin to react whenever
the moving penguin gets too close. The event trigger will have a Boolean function that will
return a value of true if the first penguin is within two meters of the nervous penguin. The
event handler will be the n e r v o u s P e n g u i n . r e a c t method. Figure 5-16 shows what the
finished event will look like.
142 Chapter 5 • Boolean Logic in Programming
1. Click the create new event button in the Events area. When the menu
appears, select When something is true as the event type. A new When
None is true event tile will appear in the Events area.
2. Select the penguin tile in the Object tree and the functions tab in the
Details area.
3. Find the penguin is within threshold of object tile, shown in Figure 5-16.
Click and drag the penguin is within threshold of object tile and drop a
copy of it in the new event in place of None following the word When.
Select 2 meters, nervousPenguin, and entire nervousPenguin from the
menus that appear. The trigger for the event is now complete.
4. Select the nervousPenguin tile in the Object tree and the methods tab in the
Details area. Next, drag a copy of the react method and drop it in place of
Nothing following Begin: in the new event.
5. The final event is in place. Save the world again before continuing.
The nervous penguin world is complete and ready for testing. You should be able to move the
penguin around using the arrow keys. Be careful—it moves rather quickly. You should be able
to point the camera at the penguin using the spacebar. The nervous penguin should jump up
and down and flap its wings whenever the first penguin gets within two meters of it.
In this exercise, you will create a world with a sailboat and several objects. When the world
starts, you will be able to click an object, and the sailboat will sail to that object. You will
create a s a i l t o method that uses a sentinel loop to make the sailboat sail toward the
object. The method will use a Boolean condition with a method parameter in the condition.
The loop will have the following logic:
WHILE (NOT (the sailboat is within 5 meters of the [object]))
{
turn to face [object]
move forward 1 meter
}
Tutorial 5C—A Sentinel Sailing Loop 143
The brackets " ( " and " } " are used to mark the beginning and end of the block of code within
the loop. When this code is executed, the sailboat will turn to face a target object, and then
move one meter toward the object. It will continue to do so until it is within five meters of
the object. You will write a s a i l t o method that will work with any object and that will
accept the target object as an input parameter, much like the way the primitive move
method accepts direction and amount as parameters.
You will create your world in two steps. First, you will place an island in the world and
hardcode the island as the target for the s a i l t o method. (To hardcode a value in a pro-
gram means that the programmer puts a specific value in a program instead of a variable or
parameter.) Once this method works, you will add an object parameter called target and put
it in the method in place of island.
T h e Sail t o I s l a n d W o r l d
Let's start by setting the scene for the new Alice world. First, you need to create a water
world with a sailboat in it. Then, you need to adjust the camera.
Next, you need to add an island to the world. You can decide where to put the island, but it
should not be too close to the sailboat, and it should not be directly in front of the sailboat.
FIGURE 5 - 1 8 : An island has been added and positioned in the water world
3 . Now click the large green DONE button to exit Scene Editor mode, and save
the world with the name sail to island.
You are ready to create the new method. In this first version of the world, the sailboat will sail
to the island when the world starts. You will need to create a method that is invoked by an
event with When t h e world s t a r t s as its trigger. The default event does this, but it uses
the method world.my f i r s t method as its event handler. The new method for the default
event will be s a i l b o a t . s a i l t o . Notice that it will be a method for the sailboat object and
not a world-level method as is world.my f i r s t method. You can create the new method,
change the event handler in the default event, and then delete world.my f i r s t method.
Tutorial 5C—A Sentinel Sailing Loop 145
1. Select the sailboat tile in the Object tree and the methods tab in the
Details area.
2. Click the create new method button. When the create new method dialog
box appears, type the name sail to, and click OK. The new method will
appear in the Editor area, and the related method tile will appear in the
Details area.
3. Drag the sail to tile from the Details area and drop it in the default event in
place o f w o r l d . m y f i r s t method.
4. Now world.my f i r s t method is no longer needed. Select the world tile
in the Object tree and the methods tab in the Details area. Click and drag
the my first method tile to the Trash can to delete it.
Now it's time to begin writing the code for the new method. It should contain a WHILE loop
that matches the pseudocode shown at the beginning of this tutorial.
Even though we are learning about the sentinel loop in this tutorial, you might have
noTtooo noticed that the process can also be done with events, and without a
Both techniques are acceptable.
s a i l to method.
1. Select the sailboat tile in the Object tree and the methods tab in the
Details area.
2. Drag a While tile from the bottom of the Editor area and drop it into the
sailboat. sail t o method in the Editor area. Select true from the short
menu that appears.
3. Next, select the functions tab in the Details area and find the sailboat is
within threshold of object tile, as shown in Figure 5-19. This is a Boolean
proximity function. Drag a copy of the tile and drop it in the WHILE
instruction in place of true. Select 5 meters as the distance and island, the
entire island as the object.
4. The While tile now says While sailboat is within 5 meters of island.
However, you want just the opposite. Select the world tile in the Object
tree and find the not tile on the functions tab. Drag a copy of the tile to the
While tile, and drop it in place of the condition sailboat is within 5 meters
of island. Now the condition should be as required, shown in Figure 5-20.
146 Chapter 5 • Boolean Logic in Programming
The s a i l b o a t . s a i l t o method now has the correct loop structure and condition in place.
Two instructions need to be placed in the loop. One will turn the sailboat and one will move
the sailboat. These should be executed together, so they will need to be inside a Do together tile.
1. Drag a Do together tile from the bottom of the Editor area and drop it into
the WHILE instruction in place of Do Nothing.
2 . Select the sailboat tile in the Object tree and the methods tile in the
Details area.
3 . Drag a copy of the sailboat turn to face method tile and drop it in the Do
together tile in place of Do Nothing. Select island, the entire island as the
object, and then click more and change the style to abruptly.
4. Drag a copy of the sailboat move method tile and drop it in the Do together tile
just below the sailboat turn to face tile. Select forward as the direction and
2 meters as the amount, and then click more and change the style to abruptly.
5 . Click File on the menu bar, click Save World As, and then save a copy of
the world with the new name sail to island.
6 . Play the world to see if it works properly. The boat should sail toward the
island and stop before it reaches it. If it does not, then you need to find and
fix any errors in your program. If the boat does not move at all, then it may
be too close to the island when the world starts.
T h e Sail t o A n y O b j e c t W o r l d
Next, you will use the sail to island world as the basis for a new world that will allow the
user to sail the boat to any object in the world. You will add additional objects to the world,
add an event to allow the user to select a target object, and modify the s a i l t o method to
include a target variable instead of the island. First, you will save the world with a new
name so that the sail to island world will be preserved, and then several objects will be
added to the world.
1. Click File on the menu bar, click Save World As, and then save a copy of
the world with the new name sail to object.
2 . Click the green ADD OBJECTS button to enter Scene Editor mode, and using
the blue camera control arrows, pull the camera back a little farther and up a
Tutorial 5C—A Sentinel Sailing Loop 147
bit more so that you can see more open water. As you complete the follow-
ing steps, note that it might be necessary to adjust the camera further.
3. Add several objects to the world. As you place the objects in the world, you
should move them away from each other, positioning them as if they were on
the edge of a large circle. Figure 5-21 shows a world with the following objects:
nifT-^'" I
1 §111
T
4. When you are happy with the collection of objects in your world, click the
large green DONE button to return to Scene Editor mode.
148 Chapter 5 • Boolean Logic in Programming
Now you are ready to modify the s a i l b o a t . s a i l t o method and add a new event. You
will also need to delete the default event, which will actually prevent the world from play-
ing with the changes that you make. Figure 5-22 shows the s a i l t o method with the modi-
fications you will make. The default event should be deleted first.
JQ sailboat.sail to |_
sailboat.sail to jo* target create new parameter
|B Do together
Do in order Do together If Else Loop While For ail in order For all together Wait print
1. Right-click the default event in the Events area and select delete from the
menu that appears. The event will be deleted.
2. Select the sailboat tile in the Object tree and the methods tab in the Details
area, and then click the edit button next to the sail to tile. You should be
able to see the s a i l t o method in the Editor area.
3. Click the create new parameter button to add a target parameter to the
method. When the create new parameter window appears, type the name
target, make sure that Object is selected as the data type, and then click the
OK button. A tile for the target object parameter will appear near the top of
the method.
4. Drag the target object parameter tile and drop it in the WHILE instruction
in place of island.
5. Drag the target object parameter tile again and drop a copy of it into the
sailboat turn to face island instruction in place of island. Select target
from the short menu that appears.
6. Now you can add the new event. Click the create new event button in
the Events area and select When the mouse is clicked on something
from the menu of event types that appears. A new event similar to
Figure 5-23 will appear.
Tutorial 5C—A Sentinel Sailing Loop
7. Click and drag the sail to target tile from the methods tab and drop a copy
of it in the new event in place of the word Nothing. When the target menu
appears, select expressions and then object under mouse cursor. Your new
event should now look like Figure 5-24; the modifications to the world are
now complete.
FIGURE 5 - 2 4 : The new event to cause the sailboat to sail to the selected object
You can now test your new world. The sailboat should sail to whatever object you select
with the mouse. If you click the water, it will sail toward the center point of the world. If
you click the sky background, then the world will stop playing, and Alice will show you an
error message telling you that the target value must not be null. This means that there is no
value for the target parameter because you clicked nothing.
The sailboat moves rather slowly from object to object in the sail to any object world. You
can use the speed slider control in the playing world window to speed things up a bit as
you test your new world.
You might also notice that the sailboat will sail through objects to get to its target. To correct
this, you would need to create methods for collision detection and avoidance in your
world, which is rather time consuming; as such, it is not part of this tutorial.
Chapter 5 • Boolean Logic in Programming
Chapter Summary
This chapter consisted of a discussion of Boolean logic, including the comparison of values and Boolean functions, fol-
lowed by three tutorials. The discussion of Boolean logic included the following:
• Branching and looping routines both contain conditions that are either true or false. These conditions are
a form of Boolean logic.
• Boolean logic is a form of mathematics in which the only values used are true and false.
• There are three basic operations in Boolean logic: AND, OR, and NOT,
• When two values are combined in the AND operation, the result is true only if both values are true.
Otherwise, the result is false. In the OR operation, if either value is true, then the result is true.
• The NOT operation is a unary operation, which means that it works on only one operand, It simply
reverses the true or false value of its operand: NOT true yields false, and NOT false yields true.
• People sometimes run into trouble converting the informality of human language into the formality
needed for algorithms,
• Often the Boolean conditions in branching and looping routines are based on expressions that compare values.
• There are six logical comparison operators used in Boolean logic: equals, is not equal to, is less than, is
greater than, is less than or equal to, and is greater than or equal to.
• Numbers can be compared according to their value, but other data types, such as character strings, have
their own rules for logical comparisons,
• Character strings are compared according to the place in a collating sequence for each character of the
string, To collate means to put a set of items in order. A collating sequence is a list that shows the correct
order to be used when collating a set of items.
• Modern computers most often use one of two codes to represent characters in the computer—either the
American Standard Code for Information Interchange (ASCII), or a newer code called Unicode. These codes
can also be used as collating sequences for character string values, as can the English language alphabet,
• A Boolean function is a function that returns a true or false value instead of a numeric value,
• Boolean functions can be used in any place that a true or false value can be used, such as in an IF
instruction or a WHILE instruction,
• The AND, OR, and NOT functions in Alice can be found on the world's function tab, along with functions
to compare values.
Review Questions 151
In Tutorial 5A, you modified the jump user choice world from Tutorial 4A to have the computer randomly select who will
j u m p , instead of asking for user input. You created Boolean conditions that involve random numbers.
In Tutorial 5B, you created a nervous penguin world with a Boolean function used in an event trigger.
In Tutorial 5C, you created two worlds: one to make a sailboat sail to an Island and one to make a sailboat sail to any
object. Each world contained a sail to method that used a sentinel loop with a Boolean condition in the loop's
WHILE instruction.
Review Questions
2. Truth tables are often used to describe the result of Boolean expressions. Fill in the correct values in each of the
following truth tables. For each cell in the table, apply the operation for the table to the values at the top of the
row and at the beginning of the column for that cell, just as you would fill in values in a multiplication table.
true true
false false
3. The following three Boolean operations are composite operations, which means they are combinations of AND,
OR, and NOT. All three of these are important in designing the logic circuits inside computer chips. Create truth
tables similar to those in Question 2 for each of these operations:
a. X O R - A O R B , but not both.
b. NOR - NOT (A or B)
c. NAND - NOT (A and B)
4. Parentheses can be used in Boolean logic to clarify the order of operations, just as in ordinary arithmetic.
Assuming that the height of a palm tree is 5 meters, the height of a lighthouse is 25 meters, and the height of a
beach house is 10 meters, rewrite the following expression exactly as it is three times, but with parentheses in
different places each time. Determine whether each of the new expressions is true or false.
Height of the beach house is less than the height of the lighthouse and not height of the lighthouse is less
than the height of the tree or height of the beach house equals the height of the tree.
Chapter 5 • Boolean Logic in Programming
5. Boolean conditions are important when using library search engines. Usually a library search engine has fields
such as title, subject, author, year, and publisher. A typical search condition would be something like this:
(author = "Lewis Carrol" AND year < 1865). Write Boolean conditions for searches to find books about each of
the following:
6. Boolean conditions are also important in Internet searches. Write Boolean conditions for searches to find Web
pages about each of the following:
a. John D. Rockefeller and Ida Tarbell
b. Abraham Lincoln and Jefferson Davis, but not schools or parks
c. Cooking a turkey, but not in a microwave or deep-fat fryer
d. George Boole and either Charles Babbage or Herman Hollerith
7. Which of the following does not contain a valid Boolean expression, and why?
a. If (distance to alice < distance to caterpillar OR queen)
b. If (count > 10 AND count < 20)
c. While (count < 5 AND > 1 )
d. While height < count OR height < 12.5
e. If (message = "Hello, World." OR "Hello, World!")
8. Write Boolean conditions to make WHILE loops continue to function until the following occurs:
a. A car door has been opened and closed 1,000 times, or the door falls off the car.
b. A penguin in an Alice world is within 5 meters of an igloo or an Eskimo, or is more than 1 0 0 meters away
from the camera.
c. A sailboat is moving at a speed between 5 and 1 0 meters per second,
10. In most states in the United States, a vehicle must stop at an intersection with a traffic light when the traffic
light is red, except when making a right turn, in which case the driver can pause and then make a right turn on
red if the way is clear, unless otherwise posted. At a particular intersection there is a sign that says, "No right
turn on red, 6 am to 6 p m , except Saturdays and Sundays." Write the set of rules and conditions for this inter-
section as an IF/ELSE instruction with a single Boolean expression.
Exercises
Exercises
1. Assume that we have an Alice world similar to the nervous penguin world, but with a strangePenguin and a
motherPenguin as well as the nervousPenguin. Write code for Boolean conditions that could be used to trigger
events to make the nervousPenguin react in each of the following situations:
a. The strangePenguin is within 2 meters of the nervousPenguin and the motherPenguin is more than
2 meters away.
b. The strangePenguin is within 2 meters of the nervousPenguin or the motherPenguin is more than
2 meters away.
c. The strangePenguin is closer than the motherPenguin.
2. Chicago's Wrigley Field is a baseball field with a vine-covered wall in the outfield, that has a railing above the
wall. A ball that hits the wall and does not leave the playing field is sometimes still in play and sometimes a dou-
ble according to the following rules: A ball striking the railing and rebounding onto the playing field is still in play.
A ball that lodges in the screen that is attached to the bleacher wall is a double. A ball that lodges in vines on the
bleacher wall is a double. A ball entering the vines on the bleacher wall and rebounding onto the playing field is
still in play. Rewrite this as a single Boolean condition of the form:
A ball that hits the wall is ruled a double IF (condition), else the ball is still in play.
3. Years that are evenly divisible by four are leap years, unless they are evenly divisible by 1 0 0 , in which case they
are not leap years, unless they are also evenly divisible by 4 0 0 , in which case they are leap years. Write a sin-
gle Boolean expression that can be used to determine if a year is a leap year.
4. The last paragraph in Tutorial 5A suggests that you would need to run the triple jump random world many times
and keep track of how many times each character j u m p s to properly test the world. Modify the world to include
a loop that will do this, with number variables to keep track of how many times each character j u m p s , and print
statements after the loop to show the values. Test your world to see if one character j u m p s more than the oth-
ers, or if the j u m p s are uniformly distributed. How do the results compare to each other if you run the test sev-
eral times?
For Exercises 5, 6, and 7. create a new Alice world with a grass template and five objects
II v I % a a
° from the people gallery: aliceLiddell, blueBallerina, handsomePrince, maleBalletDancer.
and pinkBallerina. Exercises 5, 6, and 7 will refer to this world as the dancer world.
5. Using the dancermrld, create a method to print the height of each character with the print instruction and the
height function for that character. Using the information shown w h e n the world is played, determine which of
the following is true:
a. aliceLiddell is taller than handsomePrince or shorter than blueBallerina.
b. blueBallerina is taller than pinkBallerina or shorter than pinkBallerina.
c. maleBalletDancer is shorter than handsomePrince and taller than blueBallerina.
d. aliceLiddell is (shorter than pinkBallerina and shorter than maleBalletDancer) or (taller than blueBallerina).
e. aliceLiddell is (shorter than pinkBallerina) and (shorter than maleBalletDancer or taller than blueBallerina).
Chapter 5 • Boolean Logic in Programming
6. Using the dancer world, create a method that will allow the user to select any two of the objects, and that will
then cause the taller of the two objects to spin. If they are the same height, then both should spin. {Hint An
object variable can be used to store the object a user has selected.)
7. Using the d a / x e r w o r l d , create a method that will allow the user to select any three of the objects, and that will
then cause the tallest of the three objects to spin. If more than one is the tallest, then the first of the tallest
objects selected should spin.
8. Sometimes complicated Boolean expressions can be simplified, or rewritten in a different f o r m . One rule that
explains how to do this is DeMorgan's Law. See if you can find information online about DeMorgan's Law and
then use that information to rewrite each of the following using only one NOT operation:
9. The logic in the following code can be implemented with a single event with a compound Boolean condition, or
with t w o events with simple Boolean conditions. What are the advantages and disadvantages of each
approach? When can separate events be combined into one event, and w h e n must separate events be kept as
separate events?
IF (mouse is clicked on island OR mouse is clicked on pier)
THEN sail to pier
10. Create an Alice guessing game world according to the instructions below. The world should have two characters
of your choice. (Hint: Create a flowchart or pseudocode to help design your world.)
a. Pick a random number X, such that 1 < = X < 1 0 0 . In the instruction to pick the random number, click
" m o r e " and select "integer only = true" so that the random number tile looks like something this:
[X set value to random number (minimum = 1 m a x i m u m = 100) integerOnly = true]
b. Ask the user to guess the number. Alice has a world level function to ask the user for a number.
c. Have one of the characters tell the user if the guess is too low. Have the other character tell the user if the
guess is too high.
d. Set up a sentinel loop to repeat the process while the user's guess is not equal to the n u m b e r the
c o m p u t e r picked.
e. Have both characters tell the user w h e n the guess is correct and react, such as with a dance.
T e x t and Sound
Provide a brief definition of the following terms: text, dialog balloon, thought bubble,
personification, typeface, font, breakpoint, billboard, HSB, RGB, and tessellation
List and describe the different ways to add text to an Alice world
• Use the say and think methods to add text messages to an Alice world
Place messages in a special zone below Alice's playing world window with the print
instruction
155
156 Chapter 6 • Text and Sound
The remainder of this chapter includes a brief discussion of each of these items. In addi-
tion, you will learn about sound files, which contain verbal messages that can be added to
an Alice world and then played using an object's p l a y sound method.
The discussions in the chapter are then followed by tutorials showing you how to use the
respective techniques.
Let's start with a discussion of the s a y and t h i n k methods. Figure 6-1 shows a scene from
an Alice world, with text produced by the s a y and t h i n k methods. The text created by these
methods appears in what animators call balloons or bubbles, much like text appears in car-
toons in a newspaper or magazine. A dialog balloon shows words that are supposed to have
been spoken by an object, and a thought bubble shows words that reflect an object's
thoughts. In Figure 6-1, Alice is shown saying "Simon says 'Jump'!" in a dialog balloon pro-
duced by a s a y method, while the Cheshire Cat's thoughts are shown in a thought bubble
produced by a t h i n k method.
The say and t h i n k Methods 157
FIGURE 6 - 1 : The e f f e c t s of t h e s a y a n d t h i n k m e t h o d s
The s a y and t h i n k methods can be used with every object in Alice, including inanimate
objects like rocks, trees, buildings, and vehicles. Figure 6-2 shows a thought balloon associ-
ated with a beach chair. The process of giving human qualities, such as feelings, thoughts,
or human-like movements, to inanimate objects is a form of personification.
158 Chapter 6 • Text and Sound
Personification has a long tradition in literature, often being used by poets and playwrights.
Shakespeare's Romeo and Juliet contains the line "An hour before the worshipped sun
peered forth from the golden window of the East." The sun is portrayed as looking through
a window, like a person would do. Shakespeare, like other writers, often used personifica-
tion when describing things like a smiling moon. In television cartoons, such as Warner
Brothers' Looney Tunes, objects like trees, hammers, and anvils often walk, run, or speak.
The use of the say and t h i n k methods with nonhuman objects in computer animation,
such as Alice worlds, is an extension of this tradition.
The Alice s a y and t h i n k methods work almost identically, with a parameter to allow you
to change the message itself. You can also change the font used for the text, the size of the
text, the color of the text, the color of the bubble in which the text is displayed, and the
amount of time that the message stays on the screen. Tutorial 6A will show you more about
using the s a y and t h i n k methods.
The print Instruction
In typography, a typeface is a full range o f type o f the same design, such as Times New
Roman or Hevetica. A font is a set o f characters o f the same typeface, size, and style.
7lilies New Roman is a typeface; Times New Roman Bold 12 pi. is a font. However, many
people (and a certain large computer software company) use the terms interchangeably.
The print instruction can be used to display messages or the value of variables and parame-
ters in a special text zone at the bottom of a running Alice world. Figure 6 - 3 shows an Alice
world with a text (or print) zone at the bottom of the window for the playing world.
FIGURE 6 - 3 : An Alice world with a print zone below the playing world window
fi/t]World Running... X
Speed: 1x
Resume Restart Stop Take Picture
B I I
The print instruction is often used to show someone the value of a variable while a world is
playing. For example, in a world with a moving vehicle, such as a car, the object's location
in three-dimensional space and its speed could be displayed.
160 Chapter 6 • Text and Sound
A programmer can choose to display the value of a variable using the print instruction
while debugging a world. The print instruction can then be removed once the program is
debugged. For instance, this could be done in the nervous penguin world from Tutorial 5B.
The world contains two penguins, a nervous penguin and a moving penguin. The nervous
penguin is supposed to react whenever the moving penguin comes within 2 meters of the
nervous penguin. The distance from the moving penguin to the nervous penguin could be
displayed using a print instruction. That way, the programmer could note the distance
between the two penguins when the nervous penguin begins to react to the presence of the
other penguin, as shown in Figure 6-4. Tutorial 6B will show you more about the print
instruction.
FIGURE 6 - 4 : The result of using a print instruction in the nervous penguin world from Tutorial 5B
f*.) W o r l d R u n n i n g . . . X
Speed: 1x
Pause Restart Stop Take Picture
: U '
You can also use the print instruction when debugging a program to show that a breakpoint
has been reached. A breakpoint is a spot in a computer program just before or just after
some action occurs. For example, if a printed message shows that a point has been reached
where a bunny should jump, but the bunny does not jump, then that information helps to
isolate the spot in the code where the problem occurred. This is especially useful in the
case where one method calls another method. The person debugging the software can tell if
a problem is in the method doing the calling, or in the method being called. As with many
things about learning Alice, this use of the print instruction is more useful in long, complex
programs than in short, simple programs.
3D Text in Alice
3 D T E X T IN A L I C E
Unlike the text used with the s a y and t h i n k methods or the text in a print instruction, 3D
text is implemented in Alice as its own object. It can be used to communicate with the user
or as an integral element of an Alice world. For example, the 3D text could be an object that
is used as part of a story. However, most often, 3D text is used for titles, such as the opening
title at the beginning of an Alice world, or for the phrase " T h e E n d " at the end of a narrative
Alice world. Figure 6-5 shows an example of 3D text in an Alice world.
FIGURE 6 - 5 : 3D t e x t in an Alice w o r l d
•I W o r l d R u n n i n g . . .
Speed: 1x
3
Pause Restart Stop Take Picture
M
The Alice Local Gallery contains a folder to create 3D text objects. Because 3D text is imple-
mented as an Alice object, methods such as move, t u r n , and r o l l can be used to animate
the text. User-created methods can also be developed to provide special effects for 3D text,
just as they can with any other object. Although 3D text can be resized like any other object,
it does have several special properties which other objects do not have, such as font and
extrusion, which affect the way the text is displayed on the screen. The font property works
like the font property of any other text, while the extrusion property controls the depth of
the text, from front to back.
In Alice, unlike in many other programming languages, you cannot create an instance of an
object in a world while the world is running. This means that 3D text in an Alice world
must be kept off-camera or made invisible until it is needed on-screen. Each object in Alice
Chapter 6 • Text and Sound
has a Boolean isShowing property that can be set to false to make an object invisible. An
object's opacity property, which determines if the object is solid or transparent, also can be
changed to make an object invisible. Tutorial 6C will provide you with more details about
3D text.
A picture file can be added to an Alice world as a billboard. A billboard is a flat two-
dimensional object with length and width, but no depth. Once placed in an Alice world,
the image from the picture file will be seen on both the front and back of the billboard. Like
the 3D text described in the preceding section, billboards are objects that can be manipu-
lated with primitive methods, like move, t u r n , and r o l l , as well as with user-created meth-
ods. Figure 6-6 shows a photograph of the Mona Lisa that has been added to an Alice world
as a billboard.
The current version of Alice (Version 2 . 2 ) easily imports files in several common imaging
formats, including the Graphics Interchange Format (GIF), the Joint Photographic Experts
Group format (JPG), the bitmapped file format (BMP), the Tagged Image File Format (TIF),
Sounds in Alice
and the Portable Network Graphics (PNG) format. Anyone who adds pictures to an Alice
world as billboards should keep in mind that some image files are very large and may add
significantly to the size of the Alice world.
Many graphics-manipulation programs, even simple programs like Microsoft Paint, allow a
user to create and save text as an image file. Titles, credits, and instructions for users can be
presented in an Alice world as a billboard that was created and saved as a picture file.
Figure 6-7 shows instructions for playing a guessing game that have been placed in an Alice
world as a billboard. These instructions were first typed in Microsoft Word and then cut
and pasted into an image in Microsoft Paint; the saved picture file was then imported into
Alice as a billboard. The Snipping Tool in Microsoft Windows 7 also can be used to capture
an image of text from a Word document.
S O U N D S IN A L I C E
Each object in an Alice world has a primitive p l a y sound method that can be used to play
a sound file. Sound files are most often used in Alice worlds to add special effects, such as
the sound of a doorbell, or to play background music as a scene unfolds. A pop-up menu
showing Alice's prerecorded sounds appears when the p l a y sound method is used, as
shown in Figure 6-8.
Chapter 6 • Text and Sound
FIGURE 6 - 8 : A m e n u s h o w i n g t h e p r e r e c o r d e d s o u n d s f o r t h e Alice p l a y s o u n d m e t h o d
doorbell
drip
gong
pop
splash
thudl
thud2
whoosh 1
whoosh2
import sound file...
record new sound...
Notice that the menu also includes options to import a sound file and to record a new
sound. Prerecorded sound files in the WAV or MP3 formats can be imported into Alice, and
new sound files can be recorded directly using the Alice interface. Sound files are stored as
properties of an Alice object, but a sound file stored as part of one object can be played by
any other object in Alice as well.
You can record someone speaking and then use the recording to represent the voice of an
object or to provide audio instructions for the user of an Alice world. For example, an event
could be created to play a recording of someone speaking to provide directions on how to
use the controls for a flight simulator. The directions could be recorded and saved as a prop-
erty of the airplane, with an event in place to play the recording whenever someone presses
the H key for help. The use of the p l a y sound method in Alice is covered in Tutorial 6E.
T U T O R I A L 6 A — U S I N G T H E say A N D think M E T H O D S
In this short tutorial, you will revisit the Hello, World! program from Chapter 1 to learn more
about the s a y and t h i n k methods. World.my f i r s t method in the program from Tutorial l C
already contains two bunny say tiles, as shown in Figure 6-9. In this tutorial, you will learn
how to manipulate the text in these two s a y methods.
The t h i n k method functions almost identically to the s a y method, except that its text is
displayed in a thought bubble instead o f in a dialog balloon.
Tutorial 6A—Using the say and t h i n k Methods
FIGURE 6-9: World. my first method in the Alice world from Chapter 1
No variables
create new variable
Do in order Do together If/Else Loop While For all in order For all together Wait print
Open the hello world Alice world created in Tutorial l C , or open a copy of
the world from the student data files for this book.
If you cannot see the instructions in w o r l d , my f i r s t method, select the
world tile in the Object tree and the methods tab in the Details area, and
then click the edit button next to the name of the method on the methods
tab. You should see the method displayed in the Editor area.
Click the word more following the phrase Hello, Dr. Kernighan! in the sec-
ond say instruction. You should see a short menu, as shown in Figure 6-10,
with several additional parameters for the say method. The t h i n k method
has the same parameters.
FIGURE 6-10: A menu showing the parameters used with both the say and t h i n k methods
4. Select fontSize, and then 30. Note that the choice of 20 is the default size
for all say and t h i n k text in Alice.
5. Save the world again, and then play it to see the effect of your change.
166 Chapter 6 • Text and Sound
The duration parameter determines how long, in seconds, the message will remain on the
screen. It is used just like the duration parameter in many primitive Alice methods, such as
move and t u r n . The bubbleColor parameter affects the background color, and the textColor
parameter affects the font color for the messages displayed by the say and t h i n k methods.
The default value for all durations in Alice is 1 second; the default for say and t h i n k
method bubbles is black text on a white background, and the default font for all text-based
items in Alice is Arial. The number for the fontSize parameter refers to the point size of the
text, but the actual size depends on the size of the window in which the world runs, as well
as the computer's screen resolution. The fontName parameter is the name of the chosen font.
1. Click the word more after Hello, World! in the say Hello, World! instruc-
tion, and then select bubbleColor from the menu that appears.
2 . A color menu will appear with 16 different options, including no color at
the top, a list of 14 colors, and ofher at the bottom, as shown in Figure 6-11.
Select yellow as the new bubbleColor. Notice that the color of the
bubbleColor parameter box in the say tile is now yellow.
FIGURE 6 - 1 1 : A menu showing the colors available for dialog bubbles and thought balloons
• no color
black
red
green
blue
yellow
purple
orange
pink
brown
cyan
magenta
gray
light gray
dark gray
other...
3. Now, click the word more after the bubbleColor parameter and change the
textColor to brown.
4. Play the world to see the effect of the changes you made.
5. Leave the world open for use in the next set of steps.
Tutorial 6A—Using the say and think Methods 167
The other option on the bubbleColor and textColor menus will take you to a custom color
dialog box, which will let you set the color in one of three different ways: by picking a
swatch from a predefined palette of colors, by using HSB color values, or by using RGB
color values. HSB stands for Hue, Saturation, and Brightness. (Brightness is also called
Brilliance.) RGB stands for Red, Green, and Blue. These are two different color models for
describing the color of a pixel on a computer screen, which is determined by blending red,
green, and blue light. The color of a pixel can also be described by setting the hue for the
pixel's color, the color saturation, and its brilliance, as shown in the following steps:
1. Click the bubbleColor parameter in the say Hello, World! instruction tile
and select other from the menu that appears. You should see the Swatches
tab in the Custom Color window, as shown in Figure 6-12.
Recent:
_lI I r
J J J J
J J J J
JJJJ_L J J J J
• • • • • • • • • • • • • J J J _ .
— • • • • • • • • J J
I I
J _
I
Preview
OK Cancel
2. Pick a light green color from those available on the palette, click OK, and
then play the world again to see the effect.
3. Next, click the bubbleColor parameter and select other again. This time,
click the RGB tab. Figure 6-13 shows the RGB tab. You can set the color on
this tab by entering values in the input boxes for red, green, and blue, or by
using the slider controls. The effect of your changes can be seen in the pre-
views at the bottom of the window. Experiment a bit with the colors before
continuing.
Chapter 6 • Text and Sound
Custom Color
Red
170 255
85 170 255
Blue
170 255
OK Cancel
Select the HSB tab, and you will see the HSB color controls, as shown in
Figure 6-14. You can enter numbers in the input boxes for hue, saturation,
and brightness or slide the hue control arrow up and down, and then click
a spot on the rectangle to set saturation and brightness. The equivalent RGB
values will be shown in the information boxes below the HSB input boxes.
Tutorial 6A—Using the s a y and t h i n k Methods
Custom Color
Preview
OK Cancel Reset
5. Click the S (for saturation) radio button, and you will see that the slider
control now affects saturation. Note that clicking the rectangle will affect
hue and brightness.
6. Click the B (for brightness) radio button, and you will see that the slider
control now affects brightness. Note that clicking the rectangle will affect
hue and saturation.
7. The textColor parameter is changed the same way as the bubbleColor
parameter. Experiment with setting the colors and playing the world
before continuing. Be careful—if the textColor and bubbleColor parameters
are the same, the text will be invisible. Select colors that you like or change
them back to black and white before continuing.
You can use the fontName parameter to set the typeface for the s a y and t h i n k methods. The
default typeface is Arial. The available typefaces are determined by the Alice software and
how it interacts with your computer's operating system. Not every typeface that is available
on your computer system in programs such as Microsoft Word or Internet Explorer will work
with the Alice say and t h i n k methods. Figure 6-15 shows a few of the typefaces that work
with the current version of Alice in a variety of environments.
Chapter 6 • Text and Sound
FIGURE 6 - 1 5 : Some of the typefaces that work with the fontName parameter
Arial Haettenschweiler
Book Antigua 'Mo no type Corsiva
Comic Sans M S Palatino L i n o t y p e
C o u r i e r New Times N e w Roman
The only way to be sure which typefaces will work on your system is by trial and error;
however, Arial and Times New Roman will almost always work. The following steps will
show you how to change the typeface by changing the fontName parameter.
1. Click the word more after the text in the bunny say Hello, Dr. Kernighan! tile.
2. Select fontName from the menu that appears, and then select other.
3. You should now see a small window that will allow you to enter a string.
This is one of the weakest parts of Alice. You must type the name of the
typeface you want to use, rather than selecting it from a list as with other
parameters. Type Times New Roman as the new fontName, and then click
OK. Capitalization is not important, but spelling and spacing are.
4. Play the world, and you should see the first message in the Arial typeface
and the second in the Times New Roman typeface.
5. Try experimenting with some of the typefaces shown in Figure 6-15 to see
if they work on your system before continuing.
The s a y and t h i n k methods can be used to display information about the world, although
they are more commonly used as elements of an Alice world's story or simulation. Many
fonts almost have a personality of their own, and particular fonts can be used for particular
characters in a story or for particular situations.
Some special typefaces for characters from languages other than English don't work, but
Arabic, Hebrew, and Cyrillic characters can often be cut from Microsoft Word or from a Web
browser and pasted as the text for the s a y and t h i n k methods. Figure 6-16 shows an exam-
ple of this. The Greek phrase reidcrov Koa/xo^ (translation: Hello World!) has been cut from
Microsoft Word and pasted into a s a y method. The appearance of specific characters, par-
ticularly from languages other than English, may depend on which font you are using.
Tutorial 6 B — T h e print Instruction 171
- *J ^ H j r £ i « 0 o v Kocrjio^! H
1 ) X
i
T U T O R I A L 6 B — T H E PRINT INSTRUCTION
The print instruction can be used to display information in a special print zone below the play-
ing world window, as shown in Figure 6-17. The text displayed here is very simple plain text
and cannot be formatted. You can print any text string as a message in the print zone, or you can
print the names of objects and the values of variables and parameters from a running world.
172 Chapter 6 • Text and Sound
X World Running. x
Speed:1x
Pause Restart Stop Take Picture
In this tutorial, you will print the distance between two penguins in the nervous penguin
world. You will also print a message showing when the point in the program has been
reached where the nervous penguin should jump.
1. Open the nervous penguin world that was created as part of Tutorial 5B, or
open a copy of the world from the student data files for this book.
2 . Select the nervousPenguin tile in the Object tree and the methods tab in the
Details area.
3 . Click the edit button next to the react method tile on the methods tab, and
the method should be displayed in the Editor area. It contains instructions
to make the nervous penguin jump up and to flap its wings.
4 . Drag a print instruction tile from the bottom of the Editor area and drop it
in the method in front of the instructions that are already there.
5. A short menu will appear with two options, text string and object. Select
text string and an Enter Text String window will appear. Type begin reaction
and click the OK button.
Tutorial 6 B — T h e print Instruction 173
6. Now play the world and use the arrow keys to control the moving penguin.
When it gets close to the nervous penguin and the react method is called,
the begin reaction message should be displayed in the world window. In
this case, because the code should work, the nervous penguin will start to
react at the same time, but you can see how this might be useful if the ner-
vous penguin were not reacting.
7. It is not necessary to save the world before continuing, but if you do so, use
the Save World As menu option and give the world a new name to preserve
the original nervous penguin world.
Another useful debugging technique is to display the value of a variable or parameter while a
world is running. Let's add an instruction to the triple jump random world from Tutorial 5A
to display the value of the index variable, which determines which character will jump.
1. Open the triple jump random world from Tutorial 5 A or open a copy of the
world from the student data files for this book.
2. If you cannot see world, my first method in the Editor area, select the
world tile in the Object tree and the methods tab in the Details area, and then
click the edit button next to the name of the method on the methods tab.
3. World.myfirst method contains an instruction to randomly set the value
of the variable determinant, which will determine which character jumps.
Drag the print instruction from the bottom of the Editor area and drop it in
world.my first method just below the tile that sets the value of the
determinant.
4. When the print menu appears, select object, then expressions, and then
determinant. T h e print instruction tile should now say print determinant,
as shown in Figure 6-18.
Chapter 6 • Text and Sound
# w o r l d . m y first m e t h o d
w o r l d . m y f i r s t m e t h o d No parameters create new parameter
print determinant
Else
If determinant <2
Else
worid.jump who= cheshireCat
Do in order Do together If'Else Loop While For all in order For all together Wait print "
5. Try playing the world several times. You should see messages that display
the value of the determinant variable appearing in the print zone. It is not
necessary to save the world, but if you want to do so, save it with a differ-
ent name to preserve the copy of the world without the print instruction.
In this tutorial, you will add opening titles to the triple jump world created in Chapter 2.
Messages and titles can be added to an Alice world as three-dimensional text. Once in the
world, they can be animated and manipulated just like any other Alice object by using
primitive methods or creating new methods of your own.
You can add 3D text to a world through the object gallery or by using the Add 3D Text
option on the File menu. Both ways of starting the process take you to the same place and
produce the same results. In the first part of this exercise, you will add an opening title
using the object gallery.
1. Open the triple jump world created in Tutorial 2B, or open a copy of the
world from the student data files for this book.
Tutorial 6C—Three-Dimensional Text 175
2. Click the ADD OBJECTS button to enter Scene Editor mode and see the
object galleries. Scroll through the Local Gallery until you find the Create 3D
Text tile. It's on the far-right side of the Local Gallery.
3. Click the Create 3D Text tile, and you should see the Add 3D Text window,
as shown in Figure 6-19. It has a place to enter your text, a button with a
pull-down menu to select a font for the text, and buttons for boldface and
italicized text effects. Your window may look different, depending on the
system fonts installed on your computer. If the typeface shown is not Arial,
then click the arrow next to the typeface name and change it to Arial.
FIGURE 6 - 1 9 : The A d d 3D T e x t w i n d o w
4. Click the OK button, and you will see the text appear in the Alice world. In
addition, a tile for the text object will appear in the Object tree. The tile
will have the name 3D Text.
5. Right-click the 3D Text tile in the Object tree and rename the tile
openingTitle.
6. Now that the object has been created, you can change the text to be what
the opening title should say. Click the openingTitle tile in the Object tree
and then click the properties tab in the Details area.
7. Click the words The quick brown fox next to the text property on the prop-
erties tab and change the text to Triple Jump. Press the Enter key after you
have finished changing the text. Notice that the text has changed in the
Alice world window, but the object retains the name openingTitle in the
Object tree.
176 Chapter 6 • Text and Sound
You can get back to a window similar to the Add 3D Text window through the font property
on the properties tab at any time to change the typeface of the 3D text. However, there is no
property for size. Because 3D text is an object in Alice, it is resized like other objects, by
using the primitive r e s i z e method. Let's take a look at the font property.
1. Click the button next to the font tile on the properties tab in the Details
area. The button is labeled with the name of the font. This will open the
Choose a Font window, as shown in Figure 6-20. Notice that it looks very
much like the Add 3D Text window shown in Figure 6-19. You can see the
text in the Choose a Font window, but, unlike the Add 3D Text window,
you cannot change the text. You can only make changes to the text's
appearance by using the buttons near the bottom of the window.
2. Click the typeface button, and a scrolling menu with the names of all the
typefaces currently available will appear. This is much more convenient
than the way in which the fontName parameter is changed for the text for
the say and t h i n k methods, as you saw in Tutorial 6A.
Tutorial 6C—Three-Dimensional Text 177
3. Take a moment to try a few of the typefaces from the list. You will notice
that several of the more uncommon typefaces won't work because Alice has
not been programmed to render 3D text using them. More common fonts,
such as Arial, Times New Roman, and Courier New, should work.
4. Before continuing, select a typeface and color for your title by changing the
font property and the color property on the properties tab.
Next you will position the openingTitle title in the Alice world. This can be done in Scene
Editor mode or by running primitive methods directly. In the next several steps, you will
use the primitive methods approach.
1. Right-click the openingTitle tile in the Object tree, select methods, select
the openingTitle move method, select up, and then select 2 meters. If 2
meters is not an available option, select other and type 2 in the Custom
Number dialog box, and then press Enter.
2. Again right-click openingTitle in the Object tree, select methods, and run
the openingTitle turn to face method to make the text face the camera.
3. If the entire title does not fit in the world window, right-click openingTitle
in the Object tree, select methods, and run the openingTitle move method
to move the title backward a few meters. If you go too far back, or not far
enough, you can use the move method again to move it a little more forward
or backward. Don't forget that you can also use the Undo button. It may
take a few minutes to line it up in a way that looks just right. Position the
text so that you think it looks good in relation to the three characters.
Figure 6-21 shows one possibility. Keep in mind that when you play the
world, the text will disappear before the three characters begin to jump, so
it's okay if the text overlaps the characters.
178 Chapter 6 • Text and Sound
Triple Jump
A 3D text title looks nice, but normally we don't want the text to remain on the screen for the
entire time a world is running. The text can be made to turn, roll, move, etc., including moving
off-camera, by creating methods and events as desired. The text can also be left in place, but
made invisible. In the next few steps, you will add instructions to make the title disappear a
few seconds after the world starts playing. There are two ways to make the title invisible: by
changing the isShowing property or by changing the opacity property. You will try both.
1. Select the world tile in the object tree and the methods tab in the Details area.
Click the edit button next to my first method, and w o r l d , my f i r s t method
should appear in the Editor area.
2. Drag a copy of the Wait instruction tile from the bottom of the Editor area
and drop it into world.my f i r s t method as the first instruction in the
method. When the menu appears, set the duration to 2 seconds.
3. Next, click the openingTitle tile in the object tree, and then click the properties
tab and drag a copy of the isShowing property tile into the method below
the Wait instruction. Select false from the menu that appears. Dragging a
property tile into a method will create an instruction to change that prop-
erty's value. The method should now look something like Figure 6-22.
Tutorial 6C—Three-Dimensional Text 179
Wait 2 seconds
openingTitle set isShowing to false more...
whiteRabbit.jump
cheshireCat.jump
aliceLiddell.jump
Do in order Do together IfJEIse Loop While For all in order For all together Wait print
4. Now play the world and watch what happens. If you have followed the
steps correctly, then the title should disappear after two seconds.
If you played the world again, you would notice that the title disappears very abruptly. In
film and video production, this abrupt change is called a cut. A director may cut from one
scene to another or cut a title from a scene. The term fade applies to a more subtle transition
in which an object or a scene slowly disappears. In Alice, you can cause a fade to occur by
using the opacity property.
This world will not be used further in this book, but you may want to experiment with it a
little on your own. You can experiment with the font and with the bold and italic effects.
You can resize the text in the Scene Editor mode, just as you would any other object. In fact,
you may want to add a second title that says "created by <your name>", and then have the
text fade or move on-screen and then off from the side, from above, or even from below.
180 Chapter 6 • Text and Sound
Picture files containing text and diagrams can be added as billboards in an Alice world. In
this tutorial, you will add a picture file to a new Alice world to see how this is done. To aid
you in this tutorial, the student files for this book contain a file named Mona Lisa.jpg. This
is an image of Leonardo DaVinci's Mona Lisa from the Louvre in Paris. The image is a pho-
tograph of the painting in its frame.
1. You need to put the picture file someplace it can easily be found inside
Alice, such as in the root directory on the primary hard disk drive of the
computer you are using, which will probably be the C: drive. If you are
doing this as part of a course, check with your instructor to see where you
should place the file. The most important thing is to use a directory that
you will be able to find in Step 4.
2. Start a new Alice world with a grass template.
3. Click File on the menu bar, and then click Make Billboard. Your screen
should resemble Figure 6-23.
£ j oa c3 [fj|j 5=
I Antarctica
Ava - concert
Recent II Bronwyn - concert
Christopher - Grand Canyon
Daphne Twins
. Ethan - lacrosse
Desktop |. Philadelphia Museum of Art
Phillies World Series 2008 2009 2010 2011
t Henry OssawaTanner The Banjo Lesson.jpg
i- Kandindky - Yellow Red Blue.jpg
Documents Mona Lisa.jpg
Computer
4. Find the directory where you stored the file Mona Lisa.jpg. Click the name
of the file, and then click the Import button. The picture should appear in
the world, as shown in Figure 6-6 earlier in this chapter.
Tutorial 6D—Picture Files as Alice Billboards 181
The picture file may now be manipulated like any other object, using the tools in the Scene
Editor mode, primitive methods, or any user-created methods that you write for the object.
You may want to experiment with the Scene Editor tools and perhaps use a few methods to
make the picture move around a bit. You can also use the opacity property to make the pic-
ture opaque or invisible, as was shown with 3D text in the previous tutorial. If you rotate
the object, you will notice that it has no depth, that it is flat like a sheet of paper, and that
the original image appears on both sides.
A curious side effect of adding a picture file to an Alice world as a billboard is that the
image is now available as a texture map that can be used for other objects. To see how this
works, you can try the following:
1. Click the ground tile in the Object tree, and then the properties tab in the
Details area.
2. Click ground.GrassTexture next to the skin texture tile.
3. A small menu will appear, and you will notice that Mona Lisa.Mona
Lisa_texture appears as an item on the menu. This is the image from the
original Mona Lisa.jpg picture file. Select this as the skin texture for the
ground, and the Mona Lisa with its frame will now be used as the image
file for the surface of the ground.
4. Save the world as tessellation sample before continuing.
A repeated pattern of an image on a surface is called a tessellation of the surface. The Mona
Lisa is now being used to form a tessellation on the ground. You may want to enter Scene
Editor mode and move farther above the surface to look down to get a better view of the tes-
sellated ground.
You can use any image as the surface for the ground. Figure 6-24 shows an Alice world tes-
sellated with an image of the White Rabbit. In a similar manner, you could use an image file
as the surface for any object, such as the shapes found in the Local Gallery's shapes folder.
The image will be distorted to fit the surface of the shape, but in some cases, it may be
recognizable.
Chapter 6 • Text and Sound
Using image and sound files in Alice raises the issue o f copyrights. You must be careful
when using copyrighted material, such as text, sound, and images, in an Alice world or in
other computer programs that you create. Section 107 of the U.S. copyright law (Title 17.
U.S. code) describes the doctrine o f fair use o f copyrighted material, which covers the
educational use o f such material. The concept o f fair use is explained on the Web at:
http://wmv.co/ivrighl.gov/fls/JlJ02.hlml. The courts have generally agreed that students
and teachers may use copyrighted material for instructional use provided that the material
is used only for "educational purposes in systematic learning activities at nonprofit edu-
cational institutions," and that the material satisfies certain "portion limitations." An edu-
cational presentation may include the following:
• Up to 1 0 % or 1.000 words, whichever is less, o f a copyrighted text work. For example,
an entire poem o f less than 2 5 0 words may be used, but no more than three poems by
one poet, or five poems by different poets from any anthology.
• Up to 10%, but in no event more than 3 0 seconds, o f the music and lyrics from an indi-
vidual musical work.
Up to 10% or three minutes, whichever is less, o f a copyrighted motion media work
(for example, an animation, video, or film image).
• A photograph or illustration may be used in its entirety, but no more than five images by
an artist or photographer may be reproduced. When using photographs and illustrations
from a published collective work, no more than 1 0 % or 15 images, whichever is less.
Tutorial 6E—Sound in Alice Worlds 183
T U T O R I A L 6 E — S O U N D IN A L I C E W O R L D S
In this short tutorial, you will add sound to a very simple Alice world using a sound clip
that comes with Alice. In addition to using the prerecorded sounds that are supplied as part
of the Alice software, you may also import sound clips from an external file or record your
own sound clips.
There are three tiles for three sound clips shown in Figure 6-25: one named Pacino, one
named Sylvester, and one named instructions. Next to each is a green triangular button that
you can use to preview a sound directly before using it in your world.
FIGURE 6 - 2 5 : S o u n d clips
import sound
record sound
+ Texture Maps
You can also rename a sound clip by right-clicking the sound clip tile and then changing
ft II I V j the name, and you can delete a sound by dragging it to the Trash can.
Of course, to play sounds in Alice you need to have a computer with speakers and an active
sound card, and to record sounds, you need to have a properly working microphone con-
nected to your computer. Check with your instructor or the person who maintains the com-
puter you are using to find out about its sound card and microphone. If your computer does
not have sound, you should still read through the tutorial to get a feeling for how sound
works in Alice. In these steps, you will add a chicken to a new Alice world and set up an
event so that the chicken will make a chicken sound whenever the spacebar is pressed.
184 Chapter 6 • Text and Sound
1. S t a r t a n e w A l i c e w o r l d w i t h a grass t e m p l a t e .
2 . C l i c k t h e ADD OBJECTS b u t t o n t o e n t e r S c e n e E d i t o r m o d e a n d a d d a
Chicken t o t h e w o r l d f r o m t h e A n i m a l s f o l d e r i n t h e L o c a l G a l l e r y .
3 . C l i c k t h e DONE b u t t o n a f t e r y o u h a v e a d d e d t h e C h i c k e n t o t h e w o r l d .
N o t i c e t h a t t h e Chicken is o n e o f t h e f e w objects w h o s e instance n a m e
starts w i t h a c a p i t a l letter. T h e r e is n o special reason f o r t h i s o t h e r t h a n that
t h e p r o g r a m m e r w h o c r e a t e d t h e Chicken class o f objects d i d so.
4 . C l i c k t h e create new event b u t t o n i n t h e E v e n t s a r e a a n d s e l e c t When a key
is typed f r o m t h e m e n u t h a t a p p e a r s .
5. C l i c k t h e any key b o x i n t h e t i l e f o r t h e n e w m e t h o d a n d s e l e c t Space f r o m
the m e n u that appears.
6 . N e x t , m a k e s u r e t h a t Chicken i s s e l e c t e d i n t h e O b j e c t t r e e , a n d t h e n c l i c k
t h e methods t a b .
7. D r a g a c o p y o f t h e Chicken play sound t i l e f r o m t h e m e t h o d s t a b a n d d r o p
it i n t h e n e w event i n place o f t h e w o r d Nothing.
8. A m e n u o f a v a i l a b l e s o u n d s w i l l a p p e a r . S e l e c t chicken f r o m t h e l i s t t h a t
appears.
9. P l a y t h e w o r l d , a n d w h e n e v e r y o u p r e s s t h e s p a c e b a r , t h e c h i c k e n s o u n d
will be played.
10. T h e play sound tile has parameters that w i l l let y o u adjust the duration a n d
v o l u m e o f t h e s o u n d , w h i c h c a n b e a c c e s s e d b y c l i c k i n g more o n t h e p l a y
s o u n d tile. Y o u m a y w a n t to experiment w i t h the v o l u m e level, or a d d
some instructions to your w o r l d to animate the Chicken.
Chapter Summary
Chapter Summary
This chapter consisted of a discussion of the various uses of text in an Alice world, followed by a short discussion of
sound in an Alice world and five tutorials.
• There are different ways in which you can show text in an Alice world: by using the say and think
primitive methods, by using the print instruction, by adding 3D text as an Alice object, and by placing a
picture file with an image of text in an Alice world as a billboard,
• In addition to using visual text, sound files containing verbal messages can be added to an Alice world
and then played using an object's play sound method.
• The text created by the say and think methods appears in what animators call balloons or bubbles, much
like text appears in cartoons in a newspaper or magazine. A dialog balloon shows words that are supposed to
have been spoken by an object, and a thought bubble shows words that reflect an object's thoughts.
• The say and think methods can be used with every object in Alice, including inanimate objects like
rocks, trees, buildings, and vehicles. The Alice say and think methods work almost identically, with
parameters to allow you to change the message itself, as well as the font used for the text, the size of the
text, the color of the text, the color of the bubble in which the text is displayed, and the amount of time
that the message stays on the screen.
• The print instruction can be used to display messages or the value of variables and parameters in a spe-
cial text zone at the bottom of a running Alice world. It is most often used to show someone the value of
a variable while a world is playing. Sometimes the value of a variable is displayed using the print instruc-
tion while debugging a world. You can also use the print instruction when debugging a program to show
that a breakpoint has been reached.
o 3D text is implemented in Alice as its own object. It can be used to communicate with the user or as an
element in an Alice world, The Alice Local Gallery contains a folder to create 3D text objects.
• Picture files can be added to an Alice world as a billboard, The current version of Alice can easily import GIF,
JPG, BMP, PNG, and TIF files.
• Each object in an Alice world has a primitive play sound method that can be used to play a sound
file. Sound files are most often used in Alice worlds to add special effects, such as the sound of a door-
bell, or to play background music as a scene unfolds.
• Several sound recordings are included with Alice. Other prerecorded sound files in the WAV or MP3 for-
mats can be imported into Alice, and new sound files can be recorded directly using the Alice interface.
186 Chapter 6 • Text and Sound
In Tutorial 6A, you explored the use of the say and think methods in Alice and how to manipulate the appearance
of the methods' dialog balloons and thought bubbles.
In Tutorial 6B, you saw how the print instruction can be used to display the value of a variable and to show w h e n a
playing Alice world has reached a certain spot. These techniques are often used to debug a program.
In Tutorial 6C, you experimented with the creation and manipulation of 3D text as an object in an Alice world.
In Tutorial 6D, you imported a picture file into an Alice world as a billboard object that can be manipulated with methods
just as other objects are.
Review Questions
2. List and briefly describe the different ways that text can be shown in an Alice world.
3. Describe how to change the typeface for each of the following: text in an Alice dialog balloon or thought bubble,
Alice 3D text, and text displayed by the Alice print instruction.
4. Describe how to change the size of each of the following: text in an Alice dialog balloon or thought bubble, Alice
3D text, and text displayed by the Alice print instruction.
5. Describe how the print instruction can be useful in debugging methods in an Alice world.
6. Which c o m m o n picture file formats work best for importing images into Alice as billboards?
7. How can a picture file that has been imported into Alice for use as a billboard be used to tessellate the ground
in an Alice world?
Exercises 187
8. Describe the notion of "fair use" of copyrighted material for educational purposes. How much of each of the fol-
lowing can probably be used in an Alice world or other student work based on how courts have ruled in the past
on this doctrine?
a. Poems by Langston Hughes
b. A recording of "Use Somebody" by Kings of Leon
c. An early recording of Gershwin's Rhapsody in Blue
d. Beethoven's Symphony No. 5 f r o m the 1 9 9 6 recording by the Vienna Philharmonic
e. Images of artwork from the Guggenheim Museum's Web site
f. Scanned images of pictures from a recent book about art in the Louvre
9. List the recorded sounds that are supplied as part of Alice for use by the play sound method. How can
other sounds be used in Alice?
10. Colors in Alice can be described using the RGB (Red, Green, Blue) color model or the HSB (Hue, Saturation,
Brightness) color model. The term HSL (Hue, Saturation, Luminance) is also used for the HSB color model. Using
the Internet as a research tool, find the meaning of the terms hue, saturation, and brightness (or luminance),
and how these color models are related to the CMYK and Pantone color schemes.
Exercises
1. Add text in dialog balloons or thought bubbles to an existing Alice world. Change the bubbleColor, textColor,
fontSize, and fontName properties to give the text a look and feel that enhances the world. In addition, the text
should match the personality of the character with w h o m it is associated or the tone of the message itself.
2. The ask user for a string function and the ask user for a number function are often used with string and number
variables in a manner similar to the ask user for yes or n o function, discussed in Chapter 4 . Using these func-
tions and the say method discussed in this chapter, create a simple Alice world with a dialog in which a char-
acter asks the user for his or her name, says "hello" to the person by name, asks how old the person is, and
then tells the person approximately how many days old he or she will be on his or her next birthday.
3. Create a title sequence for an existing Alice world of your choice. The titles should be added as 3D text objects,
with animation sequences for the text. The world should have an entry sequence for when the text appears and
an exit sequence for when the text disappears. To get some ideas for entry and exit sequences, you might want
to look at Microsoft PowerPoint. The list of effects on the animations schemes or custom animations on the
Slide Show menu in PowerPoint might give you some ideas for your title sequences in Alice.
4. Foreign language text can sometimes be cut and pasted from Microsoft Word, from other programs, or from a
Web site into Alice say and think method tiles or as Alice 3D text. For example, the Greek language phrase
' A p i c r T O T e \ T | s rn-av aTrov8auTT|s r i X a T w v a " (Aristotle was a student of Plato) can be cut and pasted
from Word into Alice as the text for a 3D text object. The AltaVista Babel Fish Translation Web site
{www.babelfish.altavista.com) is one of many sites you can use to translate text from English into another lan-
guage. Some of the translated text will work in Alice, and some will not, depending on the language and the
typeface used to display the language. Create a simple Alice world with text in one or more languages other
than English. Start by picking a few simple phrases, enter them into the Babel Fish Web site, and translate them
to see how well they work. You can reenter them into Babel Fish and cut and paste the translation from Babel
Fish into Alice as needed while you develop your world,
188 Chapter 6 • Text and Sound
5. Images from most digital cameras can be saved as J P G files, which can be imported into Alice as a billboard.
Create an Alice world in which an image of you or someone you know plays a role.
6. Create an Alice world that is a short tutorial teaching the user about the sound clips built into Alice. Your world
should contain keyboard events to allow the user to trigger each sound, along with either a menu of the built-in
sounds, or a character who tells the user to press a particular key to hear a sound. The world should have a vari-
ety of objects to demonstrate the use of the sounds with matching animations. As always, remember to use good
design techniques as you create the world.
7. You can record a dialog or narration for an Alice world using the record sound feature found on the properties
tab of an Alice object. You can also import sound into Alice from an existing sound file. Select a segment of a
song or other piece of music of your choice, import it into Alice as a sound file, and then create a short music
video sequence in Alice with the sound you added as background. Remember to use proper design techniques
as you create the world.
8. Create a 7 5 - to 30-second animated commercial advertisement for a product or service of your choice as an
Alice world. The world should use some of the features discussed in this chapter. You should begin by selecting
the subject of your advertisement, and then create an outline or storyboard for the advertisement. Once you have
the outline or storyboard, you can write pseudocode as refinement of the specifications for the world, and then
code the world based on the pseudocode. Remember to use good modular design as you develop your world.
9. The Television program Sesame Street often uses the theme of commercial endorsements to teach young chil-
dren about the alphabet, such as segments on the program that are s u p p o s e d l y " . . . brought to you by the let-
ter W ..." Create an Alice world that picks up on this theme to teach children about a letter of the alphabet in a
world with animation and sound.
10. Fairytales, myths, stories from history, and urban legends are all good subjects for Alice worlds with a voiceover
narration. Create an outline or storyboard for such a world, then write pseudocode for the world, and then write
the code itself. Be sure to keep the story short, so that the narration is not too long. You may want to start by
looking through both the Alice Local Gallery and the Alice Web Gallery to find characters for your story. There
are three different approaches you can use to match the timing of the narration to the world:
a. You could record the narration first, and then make the action in the world match the narration.
b. You could animate the story first, and then record a voiceover to match the action.
c. You could record the narration in short sound bytes that are played as required while the action is occurring.
R e c u r s i v e Algorithms
Describe how recursion differs from iteration, including the cost of recursion, and how
to tell when one might be more appropriate to use than the other
W H A T IS R E C U R S I O N ?
FIGURE 7 - 1 : A f e r n w i t h a r e c u r s i v e s t r u c t u r e
Recursion is not a simple concept, so often it takes a while for someone who has never seen
it before to really understand it. This chapter is not intended to make you an expert on
recursion, but only to expose you to the topic. By the time you are done, you should have a
basic understanding of what a recursive algorithm is. Before going on, let's take a look at
another example. Can you see how the following very short story is recursive?
Once upon a time a young princess was sitting with her father, the king. She said to
her father, "My Royal Father, can you read me a story?"
Recursive Algorithms 191
"Yes, my Royal Daughter," said the king, as he opened the Royal Storybook. He began
to read, "Once upon a time a young princess was sitting with her father, the king. She
said to her father, 'My Royal Father, can you read me a story?'"
"Yes, my Royal Daughter," said the king, as he opened the Royal Storybook. He began
to read, "Once upon a time a young princess was sitting with her father, the king. She
said to her father, 'My Royal Father, can you read me a s t o r y ? ' . . . "
RECURSIVE ALGORITHMS
Throughout this book you have seen how one method can call another method. Consider
Figure 7'-2a. The primitive method bunny, move is one of several methods called from
within world.my f i r s t method. In computer programming, an algorithm that calls itself
is said to be recursive. A recursive method is a method that calls itself. Figure 7-2b shows a
simple example of a recursive method, bunny, hop t o c a r r o t , which calls itself. A part of
the algorithm is identical to the overall algorithm because the method being called is the
overall algorithm. In a sense, the method is nested within itself, just as the recursive struc-
ture of the fern is nested within itself in the example above.
(Q w o r l d . m y first m e t h o d ] ^ j Q b u n n y . h o p to carrot
world.my first method No parameters bunny.hop to carrot No parameters
No variables No variables
Let's take a look at another example of a recursive algorithm. Almost everyone knows about
the famous ceiling of the Sistine Chapel in Rome, painted by Michelangelo, but do you
know about its floor? The marble floor of the Sistine Chapel has patterns in the tiles that
look like Figure 7-3. This pattern is an example of a mathematical design called a Sierpinski
gasket.
192 Chapter 7 • Recursive Algorithms
The Sierpinski gasket algorithm splits the triangle into four smaller triangles, and then calls
itself for three of the four smaller triangles. Figure 7-4 shows the result of the algorithm
through five levels of recursion.
AA
Recursion Compared to Iteration 193
In the figure, you can see that the process of dividing the triangle into smaller triangles and
then coloring in (or cutting out) one of them is repeated over and over again, each time at a
smaller level, each time in more detail. The result is a complex structure created by a small,
efficient algorithm.
The Sierpinski gasket algorithm demonstrates the power of recursion in drawing complex
structures, but the power of recursion in computer programming is the way in which com-
puter scientists use recursive algorithms to analyze and solve complex problems. An algo-
rithm is really just a set of instructions describing how to complete a process. Recursion can
describe a very sophisticated process with a simple and efficient set of instructions. Many
of the most important algorithms in computing, such as those used to search large databases
quickly, to perform matrix algebra, and to play games such as chess, depend on the use of
recursion. As a student in an introductory computer programming course, you don't yet
have the skills to write such programs; however, you can spend some time learning about
some basic ideas associated with recursion so that you will be able to use recursion appro-
priately when the time comes to do so.
It's also worth learning about recursion because of its importance in the world around us.
Blood vessels in the human body have a structure that can be best described by recursion;
blood vessels continue to divide into smaller and smaller vessels until they are tiny capil-
laries only a few blood cells wide. The pattern of seeds on the head of a sunflower, the
geometry of a snail's shell, and even DNA gene sequencing all appear to be recursive struc-
tures. The newly emerging fields of Fractal Geometry and Chaos Theory are largely based
on recursion. Seemingly random events, such as the electronic interference in a telephone
circuit, can be described using recursive functions. There is also some evidence that the
human brain is recursive. A basic understanding of recursion will not only help you to
become a better computer programmer, but it may also help you to better understand the
world around you.
R E C U R S I O N C O M P A R E D T O ITERATION
An iterative process is one that uses a loop to repeat a set of instructions, so iteration is just
another name for looping. In many cases, either iteration or recursion can be used to do the
same thing. The bunny.hop t o c a r r o t method shown earlier in this chapter is a good
example of such a case. Figure 7 - 5 shows the recursive bunny, hop t o c a r r o t method on
the left, with an iterative version of the same method using a WHILE loop on the right. Both
methods do the same thing, but one uses recursion, and the other uses iteration.
Chapter 7 • Recursive Algorithms
Else
{Do Nothing
This brings us to an important question—if both iteration and recursion can be used to do
the same thing, then when should iteration be used, and when should recursion be used?
To answer that question, you need to know a little more about some of the characteristics of
recursive methods, including the cost of recursion and the difference between linear and
exponential recursion.
Overhead is the processor time and storage space in a computer's memory needed to man-
age a method as it runs. The computer must set up a section in its memory every time a new
method is called—even if the new method is a copy of an existing method. We don't see
this happening, yet it does consume time and space in the computer's memory. In the
bunny.hop t o c a r r o t example, the computer must set up a new section in its memory
each time the recursive bunny.hop t o c a r r o t method is called. If the bunny hops five
times, then five new sections will be needed in the computer's memory to manage the five
copies of the method. It if hops a thousand times, then a thousand new sections in memory
will be required. The iterative bunny.hop t o c a r r o t method does not have such over-
head, so it is more efficient.
People, such as mathematicians, who deal with theoretical algorithms, almost always think
recursion is a good idea. In the world of computer programming, the overhead associated
with recursion must be considered. Often it is better to use iteration than recursion for
methods that can be written using a simple loop. But before giving up on recursion com-
pletely, let's go back to the Sierpinski gasket algorithm to see the difference between linear
recursion and exponential recursion.
Recursion Compared to Iteration
Linear recursion occurs when a method calls itself only once each time through the
method. Exponential recursion occurs when a method calls itself more than once in each
pass through the method. The graphs in Figure 7 - 6 compare the two types of recursion. The
graph on the left shows the number of copies of the method running for each level of recur-
sion in an algorithm that calls itself once. The graph on the right shows the same thing for
an algorithm that calls itself twice. You can see that the linear recursion graph looks like a
straight line. Only one additional copy of the algorithm is created at each level of recursion.
Look how much more quickly the number of copies of the exponential algorithm grows. At
each level of recursion, the number of copies of the program doubles. If it called itself three
times, then the number of copies would triple at each level, and so on. A method that uses
exponential recursion can very quickly generate many copies of itself to work simultane-
ously on smaller examples of the overall problem.
We now have a rough answer to our question about when to use recursion. For simple tasks
that can be described with linear recursion, iteration seems to be better because of the over-
head of recursion, but for complex problems that can be broken down into smaller parts,
exponential recursion usually works much better.
Chapter 7 • Recursive Algorithms
INFINITE R E C U R S I O N A N D C O N D I T I O N A L R E C U R S I O N
There's one more important concept about recursion that computer programming students
should understand—the difference between infinite recursion and conditional recursion.
Infinite recursion means that an algorithm calls itself repeatedly without stopping. Infinite
recursion occurs when an algorithm does not contain any instructions about when to stop
the recursion. On a computer, infinite recursion continues until all available memory is
used, or until it triggers some time-out mechanism in the operating system. The version of
the Sierpinski gasket algorithm presented earlier is an example of infinite recursion. If you
examine the algorithm carefully, you will see that the Stop instruction is never executed.
Recursion that is not infinite is called conditional recursion because the algorithm must
contain some condition that will stop the recursion. The condition that stops the recursion
is called the base condition or the base case. The algorithm usually contains an IF/ELSE
instruction that causes the algorithm to keep calling itself until the base condition is met. In
the recursive bunny.hop t o c a r r o t method, the algorithm continues to call itself until the
bunny is within 1 meter of the carrot. The base condition is that the distance between the
bunny and the carrot is 1 meter or less. The IF/ELSE command is set up to continue the
recursion while the bunny is more than 1 meter away from the carrot.
In conditional exponentially recursive algorithms, the recursive step breaks the problem
into smaller parts, and then calls the algorithm itself for each of those parts, continuing to
do so until the base case is reached. Sometimes that is enough to solve the original problem;
sometimes another step is needed to combine all of the small solutions into one big solu-
tion. It is such conditional exponentially recursive algorithms that lead to sophisticated and
highly efficient solutions to large programming problems. Unfortunately, they are often
used with complex data structures, such as trees, graphs, and matrices, which are not easily
demonstrated in introductory Alice programming, although the underlying software (in par-
ticular, the operating system) that runs Alice worlds does use them.
In the tutorials in this chapter, you will work with simple linear recursive methods to get a
feeling for recursion and to compare recursive methods to methods that do the same thing
with simple loops.
Tutorial 7A—Creating a Recursive Method 197
In this tutorial, you will create a recursive method to make an airplane taxi from the end of
a runway to a spot near an airplane hangar. Let's start with the specifications for the world.
You must set up a scene with an aircraft that has just landed at an airport. The aircraft must
taxi from the end of the runway to a spot near an airplane hangar. The task is to create a
method that will enable an object to move from wherever it is when the method is called to
a specific spot. In this case, the aircraft should taxi to within 1 meter of the part of the air-
port named garage02.
For a good programmer, a few things will come immediately to mind when presented with
this situation:
After reading the specifications, a good programmer will put together a set of questions for
the person who provided them. Communication like this among the members of a team
working on a software development project is important. In this case, the programmer
198 Chapter 7 • Recursive Algorithms
would ask which airport should be used, which aircraft should be used, and whether any
particular techniques should be used or avoided inside the method. The answers to these
questions are that the airport in the buildings folder in the local Alice object gallery should
be used; the biplane should be used as the aircraft; and the only restriction on the tech-
niques to be used in the method is that recursion should be used.
Now that things are a little clearer, you can begin. In a real situation, a programmer would
probably create an iterative method or simply use the existing primitive move t o method
for this project, but your purpose in this tutorial is to experiment with recursion.
Setting the S c e n e
First you need to build the scene for the new world.
4. Note that a tile for the airport appears in the Object tree, and the view of the
airport in the World window will probably look something like Figure 7-8.
The view is as if you were standing on the ground at the airport.
5. You need to position the camera to get a better view of the airport. Using
the blue camera control arrows, move, tilt, and pan the camera so that the
view of the airport looks more like Figure 7-9, but without the red plane.
The trick is to move the camera and not the airport. This will probably take
a few minutes to do unless you are very familiar with the Scene Editor.
Remember the magic of the Undo button, which can be used if you are
unhappy with one of your moves. Both the right end of the runway and the
hangars on the left should be visible in the window when you are done.
Chapter 7 • Recursive Algorithms
FIGURE 7 - 9 : The World window after positioning the camera, with a red airplane on the runway
6. Next, add a biplane to the world, and position it near the right end of the
runway, similar to the way the red plane is shown in Figure 7-9. Your
biplane won't be red; the one in the picture is red so that you can see it better
in the printed image. The biplane should look as if it just landed and is about
three-fourths of the way down the runway. You will need to move and turn
the biplane.
7. Now that the scene is ready, click the DONE button to exit Scene Editor
mode, and save the world with the name airport setup. This will protect
you from needing to re-create the scene in case something goes wrong.
Now that the scene is ready, you can create a recursive t a x i method to make the biplane
move as desired. Here is the pseudocode modified for the t a x i method:
biplane.taxi (target)
Start
If ( [biplane.distance to target] > 1 meter)
{
biplane.point at target
biplane.move forward 1 meter
Tutorial 7A—Creating a Recursive Method 201
biplane.taxi (target)
}
Stop
It seems fairly straightforward, so let's create the method. You can start by creating the
method and putting the IF/ELSE command in place.
1 . Select the biplane tile in the Object tree and the methods tab in the
Details area.
2 . Click the create new method button, type taxi as the method name, and
then click the OK button. The method b i p l a n e . t a x i should appear in the
Editor area.
3 . The method will need a parameter named target with the data type object.
Click the create new parameter button, type the name target, make sure
that object is selected as the data type, and then click the OK button.
4 . Drag an IF/ELSE tile from the bottom of the Editor area and drop it in the
new t a x i method in place of Do Nothing. Select true as the condition.
Your method should now look like Figure 7 - 1 0 .
If true
(Do Nothing
Else
Do Nothing
Do In order Do together If'Else Loop While For all in order For all together Wait print
6. You need to replace the first 1 with the biplane's distance to function. Select
biplane in the Object tree and drag and drop a copy of the distance to func-
tion in place of the first number 1 in the condition in the IF/ELSE tile.
7. When the menu appears asking for an object, select expressions, and then
target. The instruction should now match the pseudocode on the
previous page.
Now you need to add the instructions that belong inside the IF/ELSE structure. The pseudo-
code shows that there are three of them: biplane.point at (target), biplane.move forward
1 meter, and biplane.taxi (target). You can add them in the order in which they will occur.
1. Select the methods tab in the Details area and drag and drop a copy of the
biplane turn to face instruction tile into the IF/ELSE tile in the Editor area
in place of the words Do Nothing between IF and ELSE. When the menu
appears asking you for the target, select expressions, and then target. Also,
click more and change the style to abruptly.
2. Next, drag a copy of the biplane move tile from the methods tab in the
Details area and drop it into the new method just below the biplane turn to
face instruction. Select forward as the direction and 1 meter as the amount,
and then click more and change the style to abruptly. Note that when you
play the finished world, this value of 1 meter will affect the speed of the
plane as it taxis. You can come back to this instruction and change the
amount to make the plane move more quickly or more slowly.
3. Now drag a copy of the taxi target tile from the methods tab in the Details area
and drop it into the new method just below the biplane move forward instruc-
tion. When the menu appears, select expressions and then target. When you
do this, a Recursion Warning window similar to the one in Figure 7-11 will
appear, warning you that you are about to create a recursive method.
Recursion Warning
A The code you have just dropped in creates a "recur srve method call". W e recommend that you understand
what recursion is before making a call like this. Are you sure you want to do this?
4. Click the Yes, I understand what I am doing, button, and the instruction
tile will pop into place in the method.
Tutorial 7A—Creating a Recursive Method 203
Finally, the method will work more smoothly if the biplane turn to face
and biplane move instructions happen at the same time. Drag a Do
together tile from the bottom of the Editor area and drop it into the method
between the biplane move forward instruction and the biplane.taxi
instruction, and then drag the biplane turn to face and biplane move
instruction tiles into the Do together tile. The method is complete and
should now be similar to Figure 7-12.
FIGURE 7 - 1 2 : T h e c o m p l e t e d r e c u r s i v e b i p l a n e . t a x i m e t h o d
No variables
;E; DO together
Else
(Do Nothing
Do in order Do together IfjElse Loop While For all in order For all together Wait print
To test the method, you need to call it from world .my f i r s t method, so w o r l d , my first
method needs to be modified to call b i p l a n e . t a x i . Also, let's add an instruction to make
the biplane turn to face the camera after it moves. There are two reasons for this: first, it
will help you see if everything is normal after the t a x i method is finished, and second, it
looks a little more interesting. This can only be done outside the t a x i method; otherwise it
would interfere with t a x i meeting its specifications. In a sense, world.my f i r s t method
is being used as a testing shell for b i p l a n e . t a x i .
3. Drag and drop a copy of the biplane.turn to face tile in the methods area on
the Details tab into world.my f i r s t method below the biplane.taxi
instruction. When the menu appears, select camera as the target.
4. Now save the world with the name recursive taxi.
You can now test the world, and see if it works as expected. When you do so you may
notice that the biplane passes through part of the airport terminal. Exercise 3 at the end of
this chapter deals with this. Try the world a few times to see if it works. If it does not work
properly, then track down the error and fix it.
T U T O R I A L 7 B — C O N V E R T I N G A N EXISTING ITERATIVE M E T H O D TO
RECURSION
In addition to creating recursive methods from scratch, it's useful to be able to rewrite an
iterative method as a recursive method, and vice-versa. In this tutorial, you will modify the
s a i l t o method in the sail to object world created as part of Tutorial 5C; you will change
the s a i l t o method from an iterative method into a recursive method.
1. Start Alice and open the sail to object world from Tutorial 5C, or open a
copy of the world that comes with the student data files for this book.
2. Before doing anything else, save the world with the name recursive sail to
so that your changes will not mess up the original world.
3. Select the sailboat in the Object tree and the methods tab in the Details
area, if necessary.
4. Click the edit button next to the s a i l t o method tile; the s a i l b o a t . s a i l
t o method should appear in the Editor area, as shown in Figure 7-13.
JO sailboat.sail to
sailboat.sail to °>>i target create new parameter
HE-Do together
Do in order Do together If/Else Loop While For all in order For all together Wait print
Tutorial 7B—Converting an Existing Iterative Method to Recursion
The pseudocode for the existing iterative method and the pseudocode for a new recursive
method that does the same thing are shown below:
Sailboat.sail to (target)
While( not [sailboat is within 5 meters of target] )
{
Do together
{
sailboat.turn to face target
sailboat.move forward 2 meters
}
}
Stop
Sailboat.sail to (target)
Start
If ( not [sailboat is within 5 meters of target] )
{
Do together
{
sailboat.turn to face target
sailboat.move forward 2 meters
}
sailboat.sail to (target)
}
Stop
Comparing the two versions of the sail to method, you can see that an IF/ELSE instruc-
tion is needed instead of a WHILE loop, and a recursive call needs to be added inside the
method. Let's continue our task with the next set of steps.
1. Drag an IF/ELSE instruction tile from the bottom of the Editor area and
drop it in the method below the WHILE instruction tile. Select true as the
condition from the menu that appears.
2. Drag the Boolean condition tile that starts with the word not from the
WHILE tile and drop it into the IF/ELSE tile in place of true. If you have
done this correctly, then your method should look like Figure 7-14. If it is
not correct, then use the Undo button to back up and try again.
Chapter 7 • Recursive Algorithms
FIGURE 7 - 1 4 : The s a i l t o method after moving the Boolean condition from While to If
O sailboat.sail to
sailboat.sail to '^target create new parameter
While <None>
E Do together
sailboat turntoface target style• abruptly more...
Do Nothing
Else
\ Do Nothing
Do in order Do together If Else Loop While For all in order For all together Wait print
3 . Drag the Do together tile with the sailboat turn to face target and sailboat
move forward 2 meters instructions from the WHILE tile, and drop it into
the IF/ELSE tile in place of Do Nothing between IF and ELSE.
4. Now you are ready to add the recursive call to the method. Drag a copy of the
sail to target method tile from the methods tab in the Details area, and drop
it in the IF/ELSE instruction below the Do together tile but above ELSE.
Select expressions, and then target from the menu that appears. When you
do this, a Recursion Warning window similar to the one in Figure 7-11 in
Tutorial 7 A will appear. The window is warning you that you are about to
create a recursive method and asks you if this is what you intended.
5. Click the Yes, I understand what I am doing button, and the instruction
tile will appear in the method.
6. The last thing you need to do is to get rid of the WHILE tile, which should
now be empty and is no longer needed. Either right-click the While tile and
select delete, or drag the tile to the trash can.
7. The changes to the method are now complete, and it is ready for testing. The
method should look like Figure 7-15. Save the world before continuing.
Tutorial 7B—Converting an Existing Iterative Method to Recursion
Fi Do together
Else
(Oo Nothing
Do in order Do together IfiElse Loop While For all in order For all together Wait print
Play the world and see how your new method works. If all is well, it should appear to func-
tion no differently than the old sail to object world did. T h e changes are all internal and
will not really be seen by the user unless a problem occurs.
Chapter 7 • Recursive Algorithms
Chapter Summary
This chapter consisted of a discussion of recursive algorithms, including a comparison of recursion and iteration, a look
at linear and exponential recursion, and a look at infinite and conditional recursion, followed by two tutorials. The dis-
cussion of recursive algorithms included the following:
• Generally, something is said to be recursive if each of the parts that make up the thing have a structure—
in other words, a design or pattern—that repeats the structure of the whole thing itself.
• An iterative process is one that uses a loop to repeat a set of instructions, so iteration is just another
name for looping, In many cases, either iteration or recursion can be used to do the same thing.
• Overhead is the processor time and storage space in a computer's memory needed to manage a
method as it runs. The computer must set up a section in its memory every time a new method is
called—even if the new method is a copy of an existing method.
• Often it is better to use iteration than recursion for methods that can be written using a simple loop
because of the overhead associated with recursion.
• Linear recursion occurs when a method calls itself only once each time through the method.
• Exponential recursion occurs when a method calls itself more than once in each pass through the
method. Exponentially recursive algorithms are often far more efficient than iterative solutions because
they can repeatedly break a problem into several smaller parts, and then attack those smaller parts in a
way that an iterative algorithm cannot.
• For simple tasks that can be described with linear recursion, iteration seems to be better because of the
overhead of recursion, but for complex problems that can be broken down into smaller parts, exponential
recursion usually works much better.
• Infinite recursion means that an algorithm calls itself repeatedly without stopping. Recursion that is not
infinite is called conditional recursion because the algorithm must contain some condition that will stop
the recursion.
• The condition that stops the recursion is called the base condition or the base case. A properly struc-
tured recursive algorithm should contain a Boolean expression in a selection sequence to test for the
base condition.
In Tutorial 7B, you converted an existing iterative method into a recursive method.
Review Questions
Review Questions
3. Why will a program with infinite recursion eventually crash on a computer system?
4. In a case in which both iterative and recursive solutions to a programming problem exist, how can a program-
mer tell whether to use iteration or recursion?
5. The recursive biplane. taxi method in Tutorial 7A works only with the biplane. How can this be modified
so that it will work with any object?
6. The following joke was all the rage in fourth grade classrooms last year. Explain how this is related to recursion.
"There were three men in a boat, Joe, Pete, and Repeat. Joe and Pete fell out. Who was left?"
7. Write the pseudocode for both an iterative and a recursive method that will multiply any two positive integers
using only addition.
8. It was recently discovered that the famous graphic artist M.C. Escher used the "Droste effect" in at least one of
his drawings. Using the Internet, find out what the Droste effect is, how it is related to recursion, and why it's
called the Droste effect.
9. Assume that a computer student wants to impress his father, w h o is a computer security expert for the CIA, by
writing a program like the one below. The parameter for the program is the network address of a computer
system.
The preceding code is enough to cause some issues between father and son; however, assume that the stu-
dent plays with it some more and then makes a mistake, leaving out the IF/ELSE instruction so that the algo-
rithm looks like this:
10. An important technique in mathematics is proof by induction. We start a proof by induction by proving that if
something is true for one number, then it must be true for the next number also. In other words, if what w e are
trying to prove is true for n, then it must be true for n + 1 . This is called the inductive step in the proof. Next, we
show that it is true for the number 1 . This is called the base step in the proof. Putting the base step and the
inductive step together, we can then see that the item in question must be true for all positive integers because
if it is true for 1 , then it must be true for 1 + 1 , then for 2 + 1 , then 3 + 1 , and so on. How is a proof by induction
similar to conditional linear recursion?
Exercises
1. The Alice people gallery has hebuilder and shebuilder classes of objects that include a w a l k method. Create a
simple Alice world with a few objects of your choice, including a character that you create with hebuilder or
shebuilder, and create both iterative and recursive methods to make the character walk to a target object.
2. In the story Alice's Adventures in Wonderland, there is a part in which Alice grows smaller, and then bigger.
Create an Alice world with aliceLiddell standing between a tall flower and a short flower and with an infinitely
recursive method to keep repeating the following process:
3. Mutual recursion occurs when method A calls method B, and method B calls method A. Together, they function
like a single recursive method. Rewrite the solution to Exercise 2 using mutual recursion.
4. The biplane in the recursive taxi world created in Tutorial 7A moves right though part of the airport to get to its
spot near the hangar, See if you can correct this by adding a cone to the world from the shapes gallery, and posi-
tioning the cone on the tarmac. Then, have the plane move twice, first to the cone, and then from the cone to its
final spot. Once it works, you can then make the cone invisible by changing its opacity property.
5. In Tutorial 7B, you converted an existing iterative method into a recursive method. Starting with the recursive
sail to world from the end of that tutorial (or the copy of that world that comes with the student data files for this
book) convert the recursive s a i l t o method in the world back to an iterative method.
6. A recursive algorithm can be written to draw a spiral, starting in the middle and expanding outward with each
revolution. A similar algorithm can be written to draw a "spirally increasing pseudo-square" like that shown in
Figure 7 - 1 6 . Such an algorithm could be used for a search pattern to search for a lost object, or for a robotic
lawn mower that could be left in the middle of a large field and then programmed to start mowing the field from
the center outward. Create a "recursive Z a m b o n i " Alice world with a snow background and a Zamboni with a
recursive method to make the Zamboni follow the spirally increasing pseudo-square pattern just described. A
Zamboni is the machine that is used to clean an ice-skating rink, such as at a hockey game between periods.
The Alice vehicle gallery has a Zamboni.
FIGURE 7 - 1 6 : A spirally i n c r e a s i n g p s e u d o - s q u a r e
i •
La
7. The Fibonacci sequence is one of the most commonly found patterns in all of nature. The sequence starts with
0 and 1 , and then each term in the sequence is generated by adding the previous two terms. The first few
terms in the sequence are 0 , 1 , 1 , 2, 3, 5, 8 , 1 3 , 2 1 , and 3 4 . Numbers that appear in the sequence are called
Fibonacci numbers.
8. Images generated by certain recursive algorithms are sometimes called fractal images.
9. Here is an example of a very short recursive story (which was already discussed in the main part of the chapter):
Once upon a time a young princess was sitting with her father, the king. She said to
her father, "My Royal Father, can you read me a story?"
"Yes, my Royal Daughter" said the king, as he opened the Royal Storybook. He began
to read, "Once upon a time a young princess was sitting with her father, the king. She
said to her father, 'My Royal Father, can you read me a story?'..."
Create an Alice world that contains a very short recursive story. Start with either an outline or storyboard, and
consider how camera moves can add to the very short story. The Alice Local Gallery's Objects folder contains
Book, Monitor, Picture Frame, and TV classes. One of these may prove helpful in your story.
10. One well-known puzzle that has a recursive solution is the "Towers of Hanoi" puzzle, which can be seen on the
Internet at www.mazeworks.com/hanoi/. See if you can write a simple recursive algorithm in pseudocode as a
solution to the problem. Your solution should work no matter how many discs there are. You should be warned
however, that even though the algorithm is only a few instructions long, it could take a while to figure it out.
Lists a n d A r r a y s in Alice
D A T A S T R U C T U R E S IN A L I C E
A data structure is a scheme for organizing data in the memory of a computer. A set of
names, addresses, and phone numbers stored as a table is an example of a data structure.
Some of the more commonly used data structures include lists, arrays, stacks, queues,
heaps, trees, and graphs. Data structures can be simple, or they can become quite complex.
Computer programmers decide which data structures to use based on the nature of the data.
Programmers also decide the operations that need to be performed on that data because the
way in which the data is organized affects how a program performs different tasks. As an
example of this, let's take a look at two data structures, a queue and a binary tree, and see
how the differences between the two affect how computer programmers use them.
A queue is a set of data items with a beginning and end, called the front and back of the
queue. Data enters the queue at one end and leaves it at the other. Because of this, data exits
the queue in the same order in which it entered the queue, like people in a checkout line at
a supermarket. A queue has many uses in the world of computers. It would, for example, be
a good data structure to use in a program for keeping track of documents waiting to be
printed on a network printer, as shown in Figure 8-1.
• • •
A binary tree is a data structure that looks like an upside-down tree. Each spot on the tree,
called a node, holds an item of data, along with a left pointer and a right pointer, as shown
in Figure 8 - 2 . The pointers are lined up so that the structure forms the upside-down tree,
with a single node at the top, called the root node, and branches increasing on the left and
right as you go down the tree. The nodes at the bottom of each branch, with two empty
pointers, are called the leaf nodes.
Data Structures in Alice 215
DATA: Alice a
LEFT RIGHT
A binary tree is used when it is necessary to keep a set of data items sorted in a particular
order and to be able to quickly find items in the set. The middle item from the set of data is
put in the root node, with anything before the middle item stored in the left branch of the
tree, and anything after it stored in the right branch of the tree, as shown in Figure 8 - 3 . A
binary tree is good for storing information that needs to be searched quickly, such as a dictio-
nary or phone directory.
By comparing the queue with the binary tree, you can see how the structure of the data—in
other words, the way in which the data is organized—affects what can be done efficiently
with the data. The queue works well for keeping track of documents waiting to be printed
Chapter 8 • Lists and Arrays in Alice
on a networked printer because it will keep them in the order in which they were sent to
the printer. The first document sent to the print queue will be the first document to leave
the queue and be printed, the second document will be printed second, and so on.
On the other hand, the queue is not a good data structure to use for a set of objects that needs
to be searched quickly. To find an item in the queue, you need to start at one end of the
queue and go through each item in the queue one at a time until you find the item for which
you are searching. If the object of your search is the first item in a queue of 1,000 items, then
you will only need to look at one item to find it; whereas, if it happens to be the last item,
then you will need to look at all 1,000 items before finding it. On average, you will need to
look at 500 items to find a single object in a queue with 1,000 items.
Now let's look at searching a binary tree. You always start searching the binary tree by look-
ing at the root node. If it does not contain the data item you want, then you follow one of
the pointers to either the node to the left of the root node, or the node to the right of the root
node, depending on how the item for which you are searching compares to the item in the
root node. For example, if you were searching by name for Alice, and the root node had an
object named Cheshire Cat, then you would know to go to the left branch of the tree to find
Alice because it comes before the Cheshire Cat. At the next node you would do the same
thing—if the node does not contain Alice, then you go to that node's left branch or right
branch, and so on until you find Alice. The efficiency of the binary tree comes from the fact
that each time you look at a node, you either find the item you want, or move down one
level in the tree. This cuts the remaining data to be searched in half, because you now only
need to look to the left or to the right of the item you want. With a set of 1,000 objects, you
could always find an object in the tree in 10 tries or fewer.
If it takes l/100th of a second to look at an item, then finding an item in a queue of 1,000 items
could take anywhere from 1/100th of a second if it is the first item, to 10 seconds if it is the last
item. In a binary tree with a thousand items, the longest it would take to find any item is
1/10th of a second. So, you can see that a binary tree is a much better data structure to use in a
situation where objects need to be retrieved quickly.
Thus, if a programmer needs to organize data so that the first item placed in a data structure
will be the first item to leave the data structure, then a queue is a quick and simple way to
do this, but if a programmer wants to organize data so that any item can be retrieved
quickly, then a more complex binary tree would be better. A programmer chooses a data
structure based on how the data will be used. Someone who wants to become an effective
professional programmer must become familiar with many different data structures and
their characteristics.
Data Structures in Alice
It's impossible to learn all about data structures in an introductory course in programming,
although you can start to learn about the simple and commonly used data structures known
as lists and arrays, which are the focus of the remainder of this chapter.
Lists in Alice
One of the simplest of all data structures is a list, which is an ordered set of data. It is often
used to store objects that are to be processed sequentially, meaning one at a time in order. In
fact, lists are often used to set up queues such as the print queue described earlier.
Alice has a number of instructions that can be used to manipulate lists, some of which are
shown on the menu in Figure 8 - 4 . You can see that there are commands to insert or remove
items from the beginning of the list, the end of the list, or at any position in the list, which
in this example is named world.bunnies.
Alice also has two instructions to manipulate lists—For all in order and For all together, as
shown in Figure 8 - 5 . For all in order will perform an operation on each item in a list one at
a time, beginning with the first item in the list and going through the list in order. To iterate
a list means to go through the list in this manner.
Q w o r l d . m y first m e t h o d I
world.my first method No parameters create new parameter
No variables create new variable
Do Nothing
r t
list instructions
Do in order Do together If/Else Loop While For all In order For all together Wait print
Chapter 8 • Lists and Arrays in Alice
For all together will perform an operation on all of the items in a list at the same time.
Notice how For all in order and For all together are different from the Do in order and Do
together instructions that you saw in earlier chapters. Do in order and Do together operate
on a set of instructions. For all in order and For all together operate on a set of objects. Of
course, the Do and For all instructions can be combined to perform sets of instructions on
sets of objects.
Figure 8-6 shows a series of screen shots from an Alice world window capturing the opera-
tion of For all in order on a list of cars. You can see that the cars each turn and begin to
move away one at a time in order. The same instructions are being executed one at a time
on each object in the list; the first car turns and moves, then the second car turns and
moves, and so on.
«-5
Figure 8-7 shows a similar series of screen shots capturing the operation of For all together
on the same list of cars. You can see that the cars each turn and begin to drive away all at
the same time. In Tutorial 8B, you will create a list containing a group of toy soldiers, and
use For all in order and For all together to make the soldiers perform a drill routine.
Data Structures in Alice
11
•
A r r a y s in Alice
An array is a set of indexed variables, each containing objects of the same data type. For
example, if we wanted to store a list of five phone numbers for use by a computer program,
we might call them p h o n e y , p h o n e y , p h o n e y , p h o n e y , and p h o n e y . The value in brack-
ets after each occurrence of phone is the index value for that item. There is not one phone
variable, but several phone variables, each identified by its unique index value. Notice that
the index values start with 0 rather than 1. This is true in almost all programming languages.
In mathematics, especially matrix algebra, index values for elements in an array are usu-
HUIIi Q a a
ally subscripted—which means they are placed half a line below the other characters in
the name o f the variable, much like the 2 in H 0 , the chemical formula for water. In many
2
programming languages, however, they are simply placed in brackets. An array o f the
names o f four cities might be referred to as c i t y , city,, c i t y , and city , or as city[0],
0 2 3
city[ 1 ] , c i t y [ 2 ] , and city[3]. Sometimes both brackets and subscripting are used. In any
ease, such variables are often referred to as subscripted variables, even when brackets are
used without true subscripting.
At first glance, it might seem that there is little difference between an array and a list; how-
ever, a list is a set of objects, while an array is a set of variables that hold objects. It is as if a
list were a collection of things, and an array were a collection of boxes that hold things. If
we remove an item from the middle of a list, then the list simply gets smaller by one object;
whereas, if we remove an item from a " b o x " in an array, then that " b o x " is simply empty.
Figure 8 - 8 shows this. If we remove the second item in a list, then the old third item
becomes the new second item, and so on for all of the rest of the items in the list. If we
remove the second object from an array, then the second " b o x " in the array is simply empty.
The third item will remain in the third " b o x , " and so on throughout the array.
Chapter 8 • Lists and Arrays in Alice
list
array
There is one other crucial difference between an array and a list: a list is linear, while an
array may be multidimensional. To say that a list is linear means that we can think of it as a
straight line. It has one item, then a second, then a third, and so on, as if in one continuous
straight line. To say that an array has more than one dimension means that each object in an
array could have more than one subscript, referring to its location in the array in different
dimensions. Recall from Chapter 2 that a dimension is simply a way of measuring some-
thing, such as the length, width, and height of three-dimensional objects. A two-dimen-
sional array, for example, could be thought of as having rows and columns, with one
subscript for the row and one for the column. Such a two dimensional array is sometimes
called a table or a two-dimensional matrix. A simple one-dimensional array is sometimes
called a vector.
You won't be working with any two-dimensional arrays in Alice, but in Tutorial 8D, you
will look at a world that sorts the objects in a simple linear array. The world uses a special
object in Alice called an Array Visualization Object, which is used to show us an array in
an Alice world, rather than just creating it in the memory of the computer.
In this tutorial, you will create a list with eight ballerinas in the list, and then write a
method to make the ballerinas perform movements individually and all at once. The pur-
pose of the exercise is to learn how to create lists in Alice as well as how to use the For all
in order and For all together instructions tiles.
Tutorial 8A—Eight Ballerinas 221
You will begin by opening a world that already has eight ballerinas in it, with methods to
enable the ballerinas to perform some individual movements. You will explore the methods
this world contains before creating and working with a list of the ballerinas.
1. Start the Alice software and open the eight ballerinas world from the stu-
dent data files for this book.
2 . Notice that the world contains eight ballerinas, whose names can be seen in
the object tree: Bronwyn, Ava, Addie, Mardi, Evelyn, Daphne, Kristen, and
Meagan. The opening scene from the world is shown in Figure 8 - 9 . Click
the world tile in the Object tree and the methods tab in the Details area,
and you will see that in addition to my f i r s t method, there are generic
instructions to make any ballerina jump, put its arms up or down, spin,
jump and move at the same time, and bow. Before creating a list of the bal-
lerinas, you will try each of these methods with different ballerinas.
3 . Click the edit button next to the my first method tile, and you will see
world.my f i r s t method appear in the Editor area.
4. First, drag a copy of the jump who tile from the methods tab into world.my
f i r s t method in the Editor area. When the menus appear, select Bronwyn,
the entire Bronwyn.
Chapter 8 • Lists and Arrays in Alice
5. Next, drag a copy of the armsUp who tile into world.my f i r s t method
and drop it below the world.jump who = Bronwyn instruction tile. When
the menus appear, select Ava, the entire Ava.
6. Now, drag a copy of the armsDown who tile and drop it below the
world. armsUp who = Ava instruction tile in world.my f i r s t method.
When the menus appear again, select Ava, the entire Ava.
7. Drag a copy of the spin who tile into world.my f i r s t method and drop it
below the world.armsDown who = Ava instruction tile. When the menus
appear, select Addie, the entire Addie.
8 . Drag a copy of the jumpMove who direction tile into world.my first
method and drop it below the world.spin who = Addie instruction tile.
When the menus appear, select Daphne, the entire Daphne, and left as the
direction.
9. Drag another copy of the jumpMove who direction tile into world.my
f i r s t method and drop it below the first world.jumpMove instruction tile.
When the menus appear again, select Daphne, the entire Daphne, but this
time choose right as the direction.
10. Finally, drag a copy of the bow who tile into world.my f i r s t method
and drop it below all of the other instruction tiles. When the menus appear,
select Mardi, the entire Mardi.
11. Now world.my f i r s t method contains an example of each of the instruc-
tions for the individual movements for a ballerina. Save the world with the
name ballerina movements, and then play it to see what each of the move-
ments looks like. You may want to try it a few times or to experiment with
the various instructions for the ballerinas before continuing.
C r e a t i n g a List o f t h e B a l l e r i n a s
Your next task is to create a list containing the eight ballerinas so that you can try the For
all in order and For all together instructions. You won't need the sample instructions you
just tried, so they can be discarded. It's actually easier to restart the eight ballerinas world
than to delete each of the instructions in world.my f i r s t method. You will begin by
reopening the eight ballerinas world and creating a list of the ballerinas.
1. Close and reopen the Alice software. This will ensure that memory is clear
before creating the new world. If the system warns you that the world has
been modified and asks you if you want to save it, select no.
2 . Reopen the original eight ballerinas world from the student data files for
this book.
Tutorial 8A—Eight Ballerinas
S a v e t h e w o r l d w i t h t h e n a m e ballerina company s o t h a t y o u r c h a n g e s w i l l
n o t a f f e c t t h e o r i g i n a l eight ballerinas world.
S e l e c t t h e world t i l e i n t h e O b j e c t t r e e a n d t h e properties t a b i n t h e
Details area.
C l i c k t h e create new v a r i a b l e b u t t o n o n t h e p r o p e r t i e s t a b ; t h e c r e a t e n e w
v a r i a b l e d i a l o g b o x s h o u l d a p p e a r . T y p e c o m p a n y as t h e n a m e , s e l e c t
Object a s t h e t y p e , a n d m a k e s u r e t h a t t h e make a o p t i o n i s c h e c k e d a n d
t h a t list i s s e l e c t e d i n t h e V a l u e s s e c t i o n o f t h e w i n d o w . D o n o t c l i c k t h e
O K b u t t o n at this t i m e .
N e x t , y o u w i l l a d d t h e b a l l e r i n a s t o t h e n e w l i s t . C l i c k t h e new item b u t t o n
i n t h e c r e a t e n e w v a r i a b l e d i a l o g b o x , a n d a l i n e f o r item 0 s h o u l d a p p e a r
j u s t a b o v e t h e b u t t o n , as s h o w n i n F i g u r e 8 - 1 0 .
Name: company
T
W e :
Number
Boolean
® Object
O Other...
item 0 = <None>
new item
OK Cancel
10. When you are finished, click the OK button in the create new variable dia-
log box. A new tile for the company list should appear in the properties
tab. You now have a list containing the eight ballerinas.
11. Save the world before continuing.
Now that you have a list with the eight ballerinas in the list, you can place some instruc-
tions in world.my f i r s t method to create a routine for the ballerina company. The rou-
tine will be a fairly simple one, just enough for you to learn how to use the For all in order
and For all together instructions.
One at a time, each of the ballerinas will spin while saying her name, and then the ballerinas
will perform a few movements together. When they are finished, each will bow, and then the
entire company will bow together.
1. Click the methods tab in the Details area, and the blank world.my first
method should appear in the Editor area. If it does not appear, click the edit
button next to the my first method tile in the Details area. If it is not blank,
then delete any instructions it contains.
2 . First, each of the ballerinas will do something one at time, so drag a copy of
the For all in order tile from the bottom of the Editor area and drop it into
world.my f i r s t method in place of Do Nothing. When the menus appear,
select expressions and then world.company. An instruction tile will
appear in world.my f i r s t method that says For all world.company, one
item_from_company at a time.
3 . Each ballerina will do two things together—say her name and spin—so
drag a copy of the Do together tile from the bottom of the Editor area and
drop it in the For all instruction tile in place of Do Nothing.
4. Now an instruction needs to be added to make the ballerina say her name.
Figure 8-11 shows what this instruction will look like when it is complete.
Drag the item_from_company object tile from the For all world.company,
[obj] one item__from_company at a time tile, and drop it into the Do
together tile in place of Do Nothing.
5. A menu will appear allowing you to select which of the primitive methods you
want to have the item_jrom_company perform. Select item_from_company say,
and then hello.
6 . However, item_from_company should say its own name, not hello. You
must use a function to do this. Select the functions tab in the Details area,
find what as a string, and then drag and drop a copy of it in the
item_from_company say hello instruction in place of the word hello.
7. When the menu appears, select expressions, and then item_from_company.
Now the instruction looks as it should.
8 . Save the world again and test it before continuing. Each ballerina should
say her own name in turn.
If everything works okay so far, then you can continue. If not, then you need to find and fix
any errors before continuing. Once everything is okay, you can proceed with creating the
dance routine. To do this, you need to add the spin instruction to the Do together tile; then
you can start adding the dance routine.
1. Click the methods tab in the Details area so that you can again see the list
of generic methods in the world.
2. Drag a copy of the spin who tile from the methods tab and drop it below
the item_from_company say instruction in the Do together tile in
world.my f i r s t method. When the menu appears, select expressions,
and then item_from_company.
3. A spin takes two seconds to complete, so, to synchronize the spin and say
instructions, click the word more in the item_from_company say instruc-
tion tile and set the duration to 2 seconds.
4. Test the world again, and this time each ballerina should say her name
while spinning. If it looks correct, then save the world again.
Next you will add instructions to world.my f i r s t method to create the dance routine. All
of the ballerinas will perform the routine together, so the instructions will be contained in a
For all together tile. The ballerinas will jump, spin, jump left, jump right, and then spin
again. After they are finished, they will each bow while saying their names, and then the
company will bow together.
1. Drag a copy of the For all together tile from the bottom of the Editor area and
drop it into world.my f i r s t method below the For all world.company,
one item_from_company at a time tile. When the menus appear, select
expressions, and then world.company. An instruction tile will appear in
226 Chapter 8 • Lists and Arrays in Alice
Now you can add the instructions to make the ballerinas each say their names and bow at
the end of the routine. They will drop their arms after bowing, and then all bow together.
1. Drag a For all in order tile from the bottom of the Editor area and drop it
into the bottom of world.my f i r s t method after all of the other instruc-
tion tiles in the method. When the menu appears, select expressions and
world.company.
2. Drag the second object tile that says one item_from_company from the top
of the new For all world.company, one item_from_company at a time tile,
and drop it into the tile in place of Do Nothing.
3 . Select item_from_company say, and then hello from the menus that
appear.
4 . Select the functions tab in the Details area, and then scroll through the func-
tions until you find the what as a string function. Drag a copy of it from the
functions tab and drop it in the item_from_company say hello instruction in
place of the word hello. When the menu appears, select expressions, and
then item_from_company. The say instruction is now complete.
5. Select the methods tab in the Details area, and drag a copy of the bow who
instruction from the methods tab and drop it just below the
item_from_company say instruction tile. When the menu appears, select
expressions, and then item_from_company.
6. Drag a copy of the armsDown who instruction from the methods tab and
drop it below the world.bow who item_from_company instruction tile.
When the menu appears, select expressions, and then item_from company.
Tutorial 8B—Marching Toy Soldiers
Finally, the last movement that needs to be added to the routine is the company bowing
together.
1. Drag a copy of the For all together tile from the bottom of the Editor area and
drop it into world.my f i r s t method below all of the other instructions.
When the menus appear, select expressions, and then world.company.
2. Drag a copy of the bow who instruction from the methods tab and drop it in
the new For all world.company tile in place of Do Nothing. When the menu
appears, select expressions, and then item_from_company.
3. That's it! Save the method, and then play the world to see what happens. If
everything is correct, the ballerinas should each say their name while spin-
ning, complete several moves together, bow individually while saying their
names, and then bow together. If they do not, then find and fix the error
before continuing.
You now know how to create a list and how to use the For all in order and For all together
instructions to perform operations on lists.
In this tutorial, you will work with a list of toy soldiers to make them complete a marching
drill routine. You will use the For all in order and For all together instructions to make the
soldiers complete marching maneuvers sequentially and concurrently in the routine.
T h e Toy S o l d i e r s W o r l d
In the student data files for this book, there is a toy soldier world containing a list of four
toy soldiers with methods to make each of them march. You probably could create such a
world on your own, but in the interest of time, you will start with a world in which this has
already been done. You will start by exploring the existing world to become familiar with
its features.
1. Start the Alice software and open the toy soldiers world from the student
data files for this book. When the world loads, you should see a squad of
four toy soldiers on the screen, as in Figure 8-12. The first toy soldier has
black pants, and the rest have blue pants. You should also notice that there
are tiles for four toy soldiers in the Object tree, named toySoldierl through
toySoldier4.
Chapter 8 • Lists and Arrays in Alice
•C f § ff
2 . Before doing anything else, save the world with the name toy soldiers
marching so that your changes do not affect the original foy soldiers world.
3. Click the properties tab in the Details area, and you will see that there are
two variables: a list of objects named squad, and a Boolean variable named
marching, which is initialized to true, as in Figure 8-13.
FIGURE 8 - 1 3 : A list variable and a Boolean variable for the toy soldiers world
world's details
squad = | toySoldiert,toySoldier2,toySoldier3,toySolriierl
| \Vr\marching - true
4. Click the button after the equals sign following the squad tile on the prop-
erties tab, and you will see the Collection Editor window open, as shown in
Figure 8-14. The Collection Editor window shows that the list contains the
four toy soldiers, with toy soldierl as the first element, and so on up to toy
soldier4 as the last element in the list. Click the OK button to close the
Collection Editor window.
Tutorial 8B—Marching Toy Soldiers
I Collection Editor
Values:
itemO = toySoldiert
item 1 = toySoldier2
item 2 - toySoldier3
item 3 - toySoldier4
5. Look in the Events area and you will see that there is an event to run the
method w o r l d . squadMarch while the world is running.
6. Click the methods tab in the Editor area and then the edit button next to
squadMarch to see what this method does. If you look at the method in the
Editor area, you will see that if the Boolean variable world.marching is true,
then each of the four toy soldiers will march, and if it is not true, then nothing
happens—in other words, they will not march. The world.marching variable
is a state control variable, which controls the status of the toy soldiers. When
it is true, they will be marching; when it is false, they will not be marching.
7. Because the Boolean variable marching is initialized to true, the squad
should march if the world is played. Play the world and you should see the
soldiers march off the screen. Once they have marched away, you can stop
the world.
8. From now on, you do not want the soldiers to march away when the world
starts, so click the true button next to the marching tile on the world's
properties tab in the Details area, and change it to false.
You are now ready to create a method to make all of the soldiers complete a marching drill
routine. They will start marching, then after two seconds they will turn right one at a time,
and then after another two seconds, they will turn right all at once. This process will be
repeated four times, which should create an interesting marching routine using only a few
simple instructions. Figure 8-15 shows what this method will look like when it is finished.
230 Chapter 8 • Lists and Arrays in Alice
^ 0 j my first Q world.routine L
world.routine No parameters create new parameter
Wait 2 seconds
Wait 2 seconds
Do in order Do together If Else Loop While For all in order For all together Wait print
Click the world tile in the Object tree, and then the methods tab in the
Details area.
Click the create new method button on the methods tab, type the name
routine in the new method dialog window that appears, and then click the
OK button.
Click the properties tab and drag a copy of the marching Boolean variable
tile from the properties tab and drop it into the w o r l d . r o u t i n e method in
place of Do Nothing. Select true from the menu that appears. Setting the
marching variable to true will have the affect of a "Forward, march!" com-
mand and will start the soldiers marching when the routine is run.
The routine will contain a process to be repeated four times, so drag a copy
of the loop instruction from the bottom of the Editor area and drop it in the
w o r l d . r o u t i n e method below the world.marching set value to true instruc-
tion. Select other from the menu that appears, enter the value 4 using the
calculator style keypad that appears, and then click the Okay button.
Drag a copy of the Wait instruction from the bottom of the Editor area and
drop it into the loop instruction in place of Do Nothing. Set the duration for
the wait to 2 seconds.
Tutorial 8B—Marching Toy Soldiers 231
6 . Drag a copy of the For all in order tile from the bottom of the Editor area
and drop it into the loop instruction below the wait instruction. When the
menus appear, select expressions, and then world.squad.
7. The new instruction now says For all world.squad one [obj] item_from_squad
at a time. Drag a copy of the item_from_squad parameter in this instruction
and drop it in the same instruction in place of Do Nothing.
8 . When the menus appear, select item_from_squad turn, then right, and then
Vt revolution.
9. Next, right-click the wait tile in the w o r l d . r o u t i n e method and select
make copy. Move the copy of the wait instruction to the end of the loop
instruction, inside the Loop tile but below the For all tile.
10. Drag a copy of the For all together tile from the bottom of the Editor area
and drop it into the loop instruction below the second wait instruction.
When the menus appear, select expressions, and then world.squad.
11. The new instruction now says For all world.squad every [obj] item_from_squad
together. Drag a copy of the itemJfrom_squad parameter in this instruction and
drop it in the same instruction in place of Do Nothing.
12. When the menus appear, select item_from_squad turn, then right, and then
% revolution.
13. Finally, drag a copy of the marching Boolean variable tile from the properties
tab and drop it into the w o r l d . r o u t i n e method at the very bottom, below the
loop instruction tile. Select false from the menu that appears. This will have
the effect of a "Halt" command and will stop the soldiers from marching.
14. Your new method is now complete. Save the world again before continuing.
Finally, to make the soldiers carry out the routine when the world starts, you need to put a
routine instruction in world.my f i r s t method.
1. Click the world.my first method tab in the Editor area and the method
should become visible. It should be blank except for Do Nothing.
2. Drag a copy of the routine tile from the methods tab in the Details area and
drop it into world.my f i r s t method in place of Do Nothing.
3. Save the world again before continuing.
4. Play the world and watch what happens. The soldiers should complete two cir-
cuits of their routine before stopping. Each iteration through the loop in the
r o u t i n e method is only one-half of the routine's circuit, which is why they will
complete two circuits when the loop is set to repeat four times. If the method
does not perform as expected, then find and fix any errors before continuing.
Chapter 8 • Lists and Arrays in Alice
In this tutorial, you will create a method to make the toy soldiers from the previous tutorial
salute, which will provide you with practice in manipulating the parts of objects that are
contained in a list. Manipulating the parts of an object can be the most tedious part of pro-
gramming objects in three-dimensional virtual worlds like Alice, but the result is that the
objects function more like similar items in the real world.
You will actually create two methods. First, you will create a generic salute method to make
any soldier salute; then you will the use the For all together instruction to create a method
to make the entire squad salute. It is necessary to use several move and turn instructions to
manipulate the right arms of the toy soldiers to make them salute.
To salute, a soldier needs to raise its arm into a saluting position, and then drop the arm
back to its original position. You will first create a generic method with a who parameter to
enable any soldier to salute.
1. If necessary, start the Alice software and open the toy soldiers marching
world that you saved in the previous tutorial, or open the world from the
student data files for this book. When the world loads, you should see a
squad of four toy soldiers on the screen, as shown in Figure 8-12.
2. Save the world with the name toy soldiers salute before continuing so that
you do not change the existing toy soldiers marching world.
3. Click the create new method button on the methods tab in the world's
Details area, type the name salute in the New Method dialog window that
opens, and then click the OK button. A new method named w o r l d . s a l u t e
will appear in the Editor area.
4. Click the create new parameter button at the top of the new method in the
Editor area, and the Create New Parameter window will open. Type the
name who, make sure that Object is selected as the parameter type, and
then click the OK button.
Figure 8-16 shows what the first part of the s a l u t e method will look like. This is the part
that will cause the soldier to raise his arm into a saluting position.
Tutorial 8C—Saluting Toy Soldiers
Do together
1who "s part named riglrtArm.forearm roll right 0.2 revolutions more...
: Who 's part named nghtAim turn backward 0.2 revolutions more...
You can see that three things need to happen to make the soldier salute:
The numeric values for the amounts of these movements were determined through calcula-
tion combined with trial and error. All three of these instructions need to be carried out at
the same time, so they will be placed inside a Do together tile. Because the method will be a
generic method to make any soldier salute, you will also need to use an object parameter in
the method to indicate which soldier should salute.
There is one complication that you will encounter in creating the s a l u t e method. To
manipulate parts of an object in a generic method, such as a soldier's arm or forearm, it is
often necessary to use a function that points to the object's part by name. The two parts you
need to manipulate are the rightArm and the rightArm.forearm. When the time comes
below to use these, you will need to type in their names, so be careful: the capitalization
and spelling are important.
1. Drag a Do together tile from the bottom of the Editor area and drop it into
the w o r l d , s a l u t e method in place of Do nothing.
2 . Drag a copy of the who parameter tile from the top line of the
w o r l d , s a l u t e method and drop it in the Do together tile in place of Do
Nothing.
3. When the menus appear, select world.salute who roll, then right, and then
other. Use the calculator style keypad to enter .2, and then click the
Okay button.
4. The last instruction in the method now reads who roll right .2 revolutions.
This needs to be modified, because you do not actually want who to roll,
but who's forearm to roll.
Chapter 8 • Lists and Arrays in Alice
You will now need to use the function that points to an object's part. To get
to this function, you will need to look at the functions tab for one of the toy
soldiers.
1. Click the toySoldierl tile in the Object tree and then the functions tab in
the Editor area.
2 . Scroll through the functions until you find the toySoldierl's part named
key function tile. It is near the bottom of the functions tab. Drag the tile
into the Editor area and drop it in the who roll right .2 revolutions instruc-
tion in place of who.
3. Now click the toy soldierl parameter just before the words part named,
and select expressions, and then who from the menu that appears.
4. Finally, click the empty white box just after part named in the same
instruction, select other from the menu that appears, and the Enter a string
dialog window will appear. Carefully type rightArm.forearm in the box,
and then click the OK button. The instruction should now look like the roll
instruction in Figure 8-17.
who "s part named rightArm.forearm roll right 0.2 revolutions more...
Now you will add the instruction to make the forearm turn backward .3 revolutions.
1. Drag a copy of the who parameter tile from the top of the w o r l d . s a l u t e
method, and drop it in the Do together tile just below the roll instruction.
2 . When the menus appear, select world.salute who turn, then backward, and
then other. Use the calculator style keypad to enter .3, and then click the
Okay button.
3. You need to again use the part name function, but this time you can copy it
from the previous instruction. Drag a copy of the purple box that says who's
part named rightArm.forearm from the roll instruction and drop it on the
Clipboard; then drag it from the Clipboard and drop it into the who turn
instruction at the bottom of the Do together tile in place of who. Your turn
instruction should now look like the turn instruction in Figure 8-18.
Tutorial 8C—Saluting Toy Soldiers
who "s part named rightArm.forearm turn backward 0.3 revolutions more...
Next, you will add the instruction to make the entire arm turn backward 0.2 revolutions.
You will do this by copying and modifying the instruction that you just completed.
Do together
who 's part named iightArm.fnrearm roll right 0.2 revolutions more...
t who
's part named riglrtArm.forearm
The s a l u t e method is not finished yet, but you can unit test it to see what it does so far. It
should cause a soldier to raise its arm into a saluting position. To test the method, you will
need to modify world.my first method, and then play the world. World.my first
method currently contains the routine instruction, which the soldiers carry out in their
marching routine. You will temporarily disable the routine instruction to unit test the
s a l u t e method.
1. Click the world tile in the object tree and then the methods tab in the
details area.
2. Click the world.my first method tab in the Editor area, and the method
should become visible.
3. Right-click the world.routine instruction tile and select disable from the
menu that appears.
236 Chapter 8 • Lists and Arrays in Alice
4. Drag a copy of the salute who method tile from the methods tab and drop it
into world.my f i r s t method in the Editor area above the routine instruc-
tion so that it becomes the first instruction in the method.
5. Select toySoldierl, the entire toySoldierl, from the menus that appear.
6. Now play the world. The first soldier should raise his arm into a saluting
position. If it does not, then check your work and fix the problem in the
s a l u t e method. If the method runs but the salute looks funny, then you
should check the direction and amount of the parameters in the turn and
roll instructions in the s a l u t e method. If you get a "subject must not be
null" error message, then the name of one of the parts you typed as the part
named parameters in the rum and roll instructions may be wrong.
7. Save the world again before continuing.
The method makes the toy soldier raise its arm into a saluting position, but it also needs to
make it drop its arm. To add this to the method, you will simply make a copy of the Do together
tile in the s a l u t e method, and then reverse the direction of each of the arm movements.
Do together
jij who "s part named rightArm.forearm roll left 0.2 revolutions more...
who 's part named rightArm.forearm turn forward 0.3 revolutions more...
who 's part named rightArm turn forward 0.2 revolutions more...
4. Now the soldier should raise its salute, and then drop its salute. Play the
world again to see if it works, fix any errors you encounter, and then save
the world again before proceeding.
Tutorial 8C—Saluting Toy Soldiers
M a k i n g All o f t h e S o l d i e r s S a l u t e
Now that you have a generic method to make any soldier salute, you need to create a
method to make the entire squad of soldiers salute together. To do this, you will create a
s q u a d S a l u t e method that contains the generic s a l u t e method inside a For all together
instruction for the squad of soldiers. Your finished method should look like Figure 8-21.
f O world.squadSalute | ^
w o r l d . s q u a d S a l u t e No parameters create new parameter
Do in order Do together IfiElse Loop While For all in order For all together Wait print
1. Click the create new method button on the methods tab in the world's
Details area.
2. Type the name squadSalute in the New Method dialog window that opens,
and then click the OK button. A new method named w o r l d . s q u a d S a l u t e
will open in the Editor area.
3 . You will use a For all together instruction to have the soldiers all salute
at the same time. Drag a copy of the For all together tile from the bottom
of the Editor area and drop it in the s q u a d S a l u t e method in place of
Do Nothing.
4. When the menus appear, select expressions, and then world.squad.
5. Drag a copy of the salute who tile from the methods tab and drop it into the
For all tile in place of Do Nothing.
6. When the menus appear, select expressions, and then item_from_squad.
7. The s q u a d S a l u t e method is finished and should resemble Figure 8-21.
Save your world before continuing.
1. Click the world.my first method tab in the Editor area to see the method.
The method still contains the instruction world.salute who = toySoldierl
and the disabled routine instruction.
Chapter 8 • Lists and Arrays in Alice
2. Drag a copy of the squadSalute method from the Editor area and drop it
into world.my f i r s t method between the two instructions.
3. Now play the world to see if it works as expected. If it does, then the first
soldier should salute, followed by all of the soldiers saluting together.
Do in order Do together IfElse Loop While For all in order For all together Wait print
i
2. Save the world again, and then play the world to see if it performs as
expected. The first soldier salutes, all soldiers salute, and then they complete
their routine. If the world does not perform as expected, then find and fix any
errors before continuing.
If you like, you can copy and paste from the existing instructions in world.my first
method to make the soldiers turn and salute again when they are finished with their marching
routine.
This tutorial is a little different from the others because you will not create any new worlds
but simply examine a world from the student data files for this book. The world, named six-
teen ballerinas, has an array that contains sixteen ballerinas. The array exists as an Array
Visualization Object, which will let you see the array as a set of adjacent boxes in the Alice
world, much like the way an array would be stored as a set of consecutive locations in a
computer's memory.
Tutorial 8D—Sorting an Array of Sixteen Ballerinas
The array has room for sixteen elements, with one ballerina stored in each spot in the array.
The ballerinas are different sizes, and the world contains a method to sort the ballerinas in the
array according to their height. The sorting method uses the bubble sort technique, which is
not the most efficient sort, but it is fairly easy to understand.
1. Start the Alice software and open the world named sixteen ballerinas that
is in the student data files for this book.
2. You will see that the world has a set of sixteen ballerinas, all lined up in
separate " b o x e s " in an array. The ballerinas are all different heights, as seen
in Figure 8-23.
3. Play the world, and you will see that the ballerinas are sorted in order
according to their heights.
4. Click the array tile in the Object tree and the methods tab in the Details
area. You will see that there are two different user-created methods for the
array—swap and bubbleSort.
5. Click the edit button next to the swap method; the method becomes visible in
the Editor area. There are two spots in the method where the duration is set
to .1 seconds. Changing these to a larger number will slow down the sort.
6. Click the edit button next to the bubbleSort method; the method becomes
visible in the Editor area.
Notice that there are two loops in the bubbleSort method, a WHILE loop and a count-
controlled loop. T h e count-controlled loop goes through the array once, comparing each ele-
ment in the array to the next element. This is done by using the index variable from the
loop to refer to the element in the array. The elements array[index] and arraylindex +1] are
Chapter 8 • Lists and Arrays in Alice
adjacent elements in the array. If index is 2, for example, then index +1 will be 3, and the
two elements being compared will be array[2] and array[3]. If the two elements are out of
order, then they are swapped. Each time through the loop, comparing each item to its adja-
cent item, is called a pass though the loop.
The method continues to make passes through the loop until no more swaps occur. The
Boolean variable called changed is used to keep track of when a swap occurs. It is set to
false at the beginning of the WHILE loop, and is only reset to true if a swap occurs when
going through the inner count-controlled loop. This will cause the program to keep repeat-
ing passes through the list until no swap occurs; then the program stops.
In other words, in a bubble sort, the computer goes through the array, comparing each value
to the one that follows it. If they are out of order, then they are swapped; otherwise, they are
left in place. The computer continues to make passes through the array until it makes one
pass in which no swaps occur. Once it can do this, the list is in the correct order, and the
sorting stops. As stated earlier, this is not the most efficient way to sort an array, but it is a
reasonably easy-to-understand technique that correctly sorts an array.
If you look through the various parts of this world, you will see that it contains both an
array and a list. The world is really just included for demonstration purposes so that you
can see a program that operates on an array.
Close the Alice software when you are finished examining the sixteen ballerinas world.
Chapter Summary
Chapter Summary
This chapter consisted of a discussion of data structures, followed by four tutorials. The discussion of data structures
included the following:
• A data structure is a scheme for organizing data in the memory of a computer. Some of the more com-
monly used data structures include lists, arrays, stacks, queues, heaps, trees, and graphs.
• Alice has instructions that will allow you to manipulate two of the most basic data structures—lists
and arrays.
• Computer programmers decide which data structures to use based on the nature of the data and the
processes that need to be performed on that data because the way in which the data is organized
affects the performance of a program for different tasks.
• A queue is a set of data items with a beginning and end, called the front and back of the queue. Data
enters the queue at one end and leaves it at the other, Because of this, data exits the queue in the same
order in which it entered the queue, like people in a checkout line at a supermarket,
• A binary tree is a data structure that looks like an upside-down tree. Each spot on the tree, called a
node, holds an item of data along with a left pointer and a right pointer. The pointers are lined up so that
the structure forms the upside-down tree, with a single node at the top, called the root node, and
branches increasing on the left and right as you go down the tree.
• By comparing the queue with the binary tree, you can see how the structure of the data affects what can
be done efficiently with the data,
• One of the simplest of all data structures is a list, which is an ordered set of data. It is often used to store
objects that are to be processed sequentially,
• Alice has a number of instructions that can be used to manipulate lists, including For all in order and For
all together.
• For all in order will perform an instruction on each item in a list one at a time, beginning with the first item
in the list and going through the list in order. This is known as iterating the list,
• For all together will perform an operation on all of the items in a list at the same time,
• An array is a set of indexed variables, each containing objects of the same data type.
• A list is a set of objects, while an array is a set of variables that hold objects, It is as if a list were a collec-
tion of things, and an array were a collection of boxes that hold things.
Chapter 8 • Lists and Arrays in Alice
• A list is linear, while an array may be multidimensional. A two-dimensional array, for example, could be
thought of as having rows and columns, with one subscript for the row and one for the column. A two-
dimensional array is sometimes called a table, or a two-dimensional matrix. A simple one-dimensional
array is sometimes called a vector
• Alice has a special object called an Array Visualization Object, which is used to show us an array in an
Alice world, rather than just creating it in the memory of the computer.
In Tutorial 8A, you created a list of ballerinas and used the For all in order and For all together instructions to perform
operations on the list.
In Tutorial 8B, you again used the For all in order and For all together instructions to perform operations on a list of toy
soldiers so they would complete a marching routine.
In Tutorial 8C, you created a generic method that performs operations on the parts of objects contained in a list to
make the toy soldiers salute.
Tutorial 8D demonstrated the use of an Array Visualization Object in a method that uses the bubble sort technique to
sort a set of objects stored as an array.
Review Questions
2. How do programmers decide what data structures to use for different programs?
3. Why is a queue a good data structure to use for keeping track of documents to be printed on a network printer?
4. Why would a binary tree be a good data structure to use for storing a dictionary on a computer?
8. What is the difference between using the Do together and the For all together instructions in an Alice world?
9. The swap method in Tutorial 8D contains an object variable called temp. Why is it needed in this method?
Exercises
10. An encapsulated data structure is one that includes functions, such as adding an element to the data structure,
but the details of those methods are hidden from the user. In other words, they can use the methods, but they
cannot see inside t h e m . List several encapsulated methods that would be useful for all of the following data
structures: a queue, a binary tree, a list, and an array. List several methods that would each be useful for one of
the data structures but not necessarily the others.
Exercises
1. Create an Alice world with four helicopters and a list containing the helicopters. Program the world to make the
helicopters each lift off from the ground one at a time, and then all turn and fly away together.
2. The Animals folder in the Alice Local Gallery contains several different kinds of fish, including a goldfish and a
shark. The Ocean folder contains an ocean floor background. Using these items, create an Alice world with a
school of goldfish that swim around together, and then scatter w h e n a shark appears. You may be tempted to
use the Lilfish in the Ocean folder instead of the goldfish, but be c a r e f u l — e a c h instance of the Lilfish requires
more than 2 megabytes of memory, while each Goldfish requires only 3 0 kilobytes.
3. Create a drill routine of your own for the toy soldiers world from Tutorial 8B that demonstrates the use of the For
all in order and For all together instructions, along with good modular programming techniques.
4. Create an Alice world with several objects from the People gallery. Place some of the objects in one list and
some of the objects in another list. Create a method to make each object in the first list say hello to each object
in the second list, and vice versa.
5. Create several new generic movement methods for the eight ballerinas world, and then demonstrate their use
in methods that use the For all in order anti For all together instructions.
6. Create a series of keyboard and mouse events for either the eight ballerinas world that will allow the user to
control a ballet routine, or for the toy soldiers world that will allow the user to control a marching drill routine
while the world is running.
7. Open the generic triple j u m p world from the student data files for this book and add a set of five different
heights to the world as a list of numbers. Create a method to iterate through the list and have the three charac-
ters j u m p each of the heights contained in the list.
8. Create a search method for the sixteen ballerinas world that will do all of the following:
If the list does not contain a ballerina with the name that the user entered, then one of the ballerinas should tell
the user that this is the case.
Chapter 8 • Lists and Arrays in Alice
9. The Bugs folder inside the Animals folder in the Alice Local Gallery contains a Butterfly class of objects.
Complete the following:
10. The National Institute for Standards and Technology has a Dictionary of Algorithms and Data Structures on the
Web at http://www.nist.gov/dads/. Look up the definitions for the data structures stack and queue, and then
describe the differences between a stack and a queue.
M a k i n g Animated M o v i e s with Alice
Describe each of the three phases in the moviemaking process: preproduction, pro-
duction, and postproduction
Describe some of the more common camera shots used in moviemaking, including: wide
shot, long shot, close-up, medium shot, extreme close-up, two-shot, head and shoulders
shot, point-of-view (POV) shot, low-angle shot, high-angle shot, aerial shot, three-quarter
shot, over-the-shoulder shot, profile shot, moving shot, and following shot
• Outline the plot and visual flow of a movie using storyboards and shot lists
Position the camera in an Alice world to match shots described in a storyboard and
shot list
• Use dummy objects to simulate the use of multiple cameras in an Alice world
INTRODUCTION
In this chapter, you will use Alice to make short animated movies. The chapter includes
some background information on the nature of movies, a look at the process of moviemak-
ing, and several tutorials that show you how to plan and set up camera shots for recording
an Alice world as a movie.
This chapter focuses on the visual aspects of moviemaking. The sound techniques dis-
cussed in Chapter 6 can be used in conjunction with the techniques in this chapter.
Animated moviemaking is both processor and memory intensive. Recording movies from
Alice worlds works best on computers with more memory, a good processor, and a good
video card. See Appendix A for more specific information on hardware requirements.
A movie is a flat two-dimensional picture that moves. Actually, when we view a movie, we
are watching a rapidly changing series of still images, each slightly different from the previ-
ous image. Instead of seeing many still images, we experience them as a moving picture.
See Figure 9-1.
FIGURE 9 - 1 : V i d e o - e d i t i n g s o f t w a r e s h o w i n g several f r a m e s f r o m a m o v i e
Each still image in a movie is called a frame, and the number of frames per second (fps) in a
movie is called the frame rate. The frame rate for films in a movie theatre is 2 4 fps, while
the frame for broadcast television is roughly 30 fps. Anything slower than around 16 fps
might look a bit choppy.
Most computer monitors refresh their displays 60 or 72 times per second, so when you are
viewing an Alice world, you are seeing images that are changing faster than the frame rates
for television or film. The moviemaking option in Alice captures a series of still pictures
The Moviemaking Process
many times a second while an Alice world is playing, and then combines the still images
into a movie.
In the late 1800s, pioneering inventors like Thomas Edison in the United States and the
Lumiere brothers in France developed cameras and projectors that could record and project
movies using photographic film, giving rise to the motion picture film industry. The devel-
opment of electronics in the 20th century, including television and computer technology,
has taken us to the 21st century age of digital video, in which video cameras and display
screens are everywhere, and film-based recording is mostly a thing of the past.
Yet, despite the movie industry's change to digital technology, the fundamental principles
of moviemaking remain the same. For example, movies don't need to be long to be interest-
ing. The Lumiere brothers' first films, which were each less than a minute long, were a big
hit because of the novelty of moving pictures, and because of the human aspect of filmmak-
ing: people are captivated by movies that tell a story. Their most popular films were those
that told a story.
Your experience making movies with Alice will, in some ways, be like that of the Lumiere
brothers. You won't start by making feature-length films; you will create short m o v i e s —
most less than a minute in length. And, like the Lumiere brothers, you should keep in mind
that the most interesting movies tell a story.
The moviemaking process has three phases: preproduction, production, and postproduc-
tion, as shown in Figure 9 - 2 .
FIGURE 9 - 2 : The m o v i e m a k i n g p r o c e s s
Production is the heart of the moviemaking process, the actual recording of the movie. In
traditional filmmaking, it is when the cameras are rolling and action is captured on film.
The production phase for an animated movie includes creating the animations and record-
ing them. Today most animations are computer generated imagery (CGI). In fact, many
Chapter 9 • Making Animated Movies with Alice
traditional movies often include some CGI, and, of course, Alice movies are produced
entirely with CGI.
Yet, as important as it is, production takes up only a small part of the time needed to make
a movie. Preproduction, the planning and preparation required before production can
begin, usually takes much longer than production. Preproduction includes developing ideas
for the movie, writing the script, casting, scheduling production, and gathering all of the
resources for production—including people, equipment, and facilities.
Postproduction includes all of the tasks that take place after a movie is recorded, such as
editing, adding titles, and packaging the final product.
If you are going to make movies, then you need to allow enough time to do so—good
moviemaking takes time. Creating short animated movies using Alice is a lot like producing
a single scene from a feature-length movie, yet the development of an Alice movie still
includes preproduction, production, and postproduction. The rest of this chapter will take
you through the process, but first, let's review the mechanism for recording movies in Alice.
Tutorial I E showed you how to record your first Alice world, Hello World!, as a movie file
that was about four seconds long. For review, we'll go through the recording process
again, but this time you will record Alice's lakeSkater example world, which is about
55 seconds long.
You may recall from Chapter 1 that Alice allows you to export a world as a video file using
the QuickTime .mov format. You can then view the world, post it to a Web page as an
embedded or streaming video, or you can use Adobe Premiere, Windows Live Movie Maker,
Apple's iMovie, or other software to edit the movie or save it in another format.
1. Start Alice, and open the lakeSkater Alice world from the examples tab.
2 . Click File on the menu bar, and then click the Export Video option. The
Save World As dialog window appears. You must save the world as a part
of the recording process, and you may save it in a new location with a new
name if you would like to do so. Save the world before continuing. Alice's
Export video window will appear next. See Figure 9 - 3 .
Tutorial 9A—Recording a Movie from Alice 249
3. Type the name of your movie file in the File name text box before recording
the video. The name of the movie file does not need to be the same as the
name of the Alice world.
4. Click the Record button to start recording your movie. The world will start
playing and recording at the same time. As the world plays, Alice is ren-
dering and capturing about 30 frames a second. The world takes about
55 seconds to play all the way through. At the end, the skater winks, then
blinks, and then the camera pulls back. When this happens, the world is
finished playing.
Chapter 9 • Making Animated Movies with Alice
5. Press the Stop Recording button to finish recording. The recording does not
stop automatically so you will you need to pay attention and watch for the
end of the action. You may want to play the world first without recording
so that you will recognize when the action is complete.
If you stop during recording and wish to restart recording, press the C l e a r button first to
clear the frames that have already been recorded. Also, note that you do not need to record
your Alice world from the beginning. You could play the world, pause it, and then record
from that point forward only.
6. Click the Export Video button to save the recording as a movie file. The file
will be saved in the same folder that you used to save the Alice world file
(*.a2w) in Step 2. Alice will first encode the video and then the audio; then
Alice merges the video and audio together. Alice records the movie file
frame by frame. This process takes longer on computers that have less
memory or a less sophisticated video card, so be patient. When the infor-
mation boxes stop appearing, the video has been saved.
PREPRODUCTION
It works best to have a design for something before building it. This is just as true for
movies as it is for computer programs. So, the first part of preproduction is designing your
movie. The primary design document for a movie is a script, which is a scene-by-scene
description of the movie, with dialog and descriptions of the critical action. See Figure 9 - 4
for an example. You need to decide the type and topic of your movie, outline the plot, pick
the setting and characters, and then write the script.
Preproduction
FIGURE 9 - 4 : S a m p l e s c r i p t
CLASSROOM-AFTERNOON
There is a desk or table and blackboard in the front
of the room. A door is to the right of the desk, MARIE
stands to the left of the desk, looking toward the
back of the room.
Yet, even in carefully scripted movies things change during the actual production process,
so no script is really carved in stone. In some cases, experimental moviemakers start a pro-
duction without any script—making things up as they go along. However, it is probably best
to spend some time developing a script before attempting to produce a movie, even a very
short one.
Once the script is written, the next step is to gather the necessary resources to make it into a
movie. This includes things like casting (selecting the actors), finding locations for scenes
in the movie, creating any additional scenery, gathering costumes and props, putting
together a crew, making sure you have the right equipment, preparing any special effects,
dealing with any legal issues, budgeting the project, and scheduling production. Often, the
script is shaped to fit the available resources. For example, students making a two-minute
movie as a project for a drama class would likely use easily accessible locations, rather than
spending hundreds of thousands of dollars on a travel budget or for extensive scenery.
Making animated films is a little different from making live-action movies, mainly because
artists create the characters, costumes, props, and scenery. However, there is still a lot of
work to do before the movie can be recorded. As an Alice moviemaker, you will pick your
characters (complete with costumes), props, and scenery from a gallery. You can shape your
script to fit the characters in the gallery and the programming techniques that you know
how to use to animate those characters.
Chapter 9 • Making Animated Movies with Alice
A full discussion of planning a movie would be a whole book in itself, so here we will just
take a brief look at some of the more important elements of making a movie.
Movie Types
Most movies fit into one of several types, and the type a moviemaker chooses will deter-
mine a lot about the structure of the movie. The most important thing about the type of a
movie is whether the work is a screenplay or a documentary.
At the end of the first act or near the beginning of the second act a problem is introduced, in
the form of an obstacle or a villain, called the antagonist. As the second act progresses, the
hero moves toward solving the problem and reaching his or her objective, but usually by
the end of the second act something has gone wrong and the hero is in trouble.
The third act is the conclusion in which the trouble is resolved. As a moviemaker, you need
to decide if you want your story to have a happy ending. Many stories, whether three-act
screenplays or five-act theatrical dramas, do have happy endings, but some very good sto-
ries, such as Shakespeare's Hamlet or Eric Segal's Love Story, do not. In any case, the final
act brings the story to a close.
Figure 9 - 5 shows the structure of a three-act screenplay and the structure of an essay-like
documentary side-by-side. For our purposes, this is a simplification of the complex struc-
tures of many movies, but even most complex movies fit one of these two general patterns
fairly well.
Preproduction
Some shorter movies are simply a slice-of-life vignette, showing an everyday event, such as
a boy riding by on a bicycle, or a flock of geese flying overhead. Slice-of-life vignettes might
tell a story, but they also may just be intended to show the subject in action. The purpose of
a vignette might be to show the viewer something about the subject, or to demonstrate that
the moviemaker has mastered some new moviemaking techniques or technology, as Edison
and the Lumiere brothers did.
Shorter movies may also be a comedy sketch—the visual equivalent of telling a joke—like a
skit that Boy Scouts or Girl Scouts might act out around a campfire. A short movie could
also be a commercial advertisement, which attempts to convince someone about the merits
of a particular product or service, or to expose them to something in a positive way that
they will remember.
Movie Topics
At first glance, the idea of a topic seems pretty simple: what is your movie about? Is it a
screenplay about a particular person or an incident in a person's life? Is it a documentary
about how to do something? Is it an essay telling you why the moviemaker thinks you
should do something, such as voting for a particular candidate?
Movie topics can be simple elements of everyday life, or they can be complex ideas deeply
rooted in the cultural traditions of a society. It's really up to you as a moviemaker to decide
what your movie will be about, but one thing is certain, before you start making a movie,
you should have a topic and know your topic well. Many novice writers are told to write
what you know. The same is good advice for novice moviemakers: make movies about
things that you understand.
Chapter 9 • Making Animated Movies with Alice
O u t l i n i n g t h e Plot: S c e n e s , S h o t s , a n d S t o r y b o a r d i n g
Once you determine the type and topic for your movie, then you can develop an overall
structure for the plot. The plot is the storyline or plan for the dramatic flow of the movie. It
is tied to the visual flow of the movie—how the movie progresses from scene to scene.
Before actually writing a complete script you can start by outlining the main ideas for your
plot. How does the movie open? What action comes first? What comes after that, and so on,
and finally, how are things wrapped up?
A scene is part of a movie that takes place in a single location at a particular time. A movie
is a sequence of scenes, and the scene outline for a movie should describe the location,
characters, and action for each scene. The 1939 film Gone with the Wind, for example, has
67 scenes that take place in about 20 different locations. (Links to a description of the plot
and an outline of the scenes in Gone with the Wind are at the History in Film Web site,
online at: www.historyinfilm.com/gwtw/index.htm.)
Each scene is a collection of shots. A shot is a particular view of the action from a specific
camera, set up in a specific way. A shot list is a list of the shots needed for each scene,
describing the kind of shot, the characters involved, roughly what happens in the shot, and
the length of time the shot stays on the screen. See Figure 9-6. Other details, such as light-
ing and special effects, could also be included.
FIGURE 9 - 6 : An act is composed of scenes; scenes are composed of shots; a shot is a series of frames
Act I
There are many characteristics of shots, such as the distance from the camera to the subject
of the shot, the angle of the camera, how the subject is lit, what colors predominate, and so
on. Many different kinds of shots are used to make movies, but here are some of the most
common, described in terms of the subject's apparent distance from the camera, and the
camera angle:
Wide shot: a shot that shows a broad view of a scene from a distance
Long shot: a shot of a person, object, or action from a long way away,
focusing on the subject in an overall context
Preproduction
Lighting can be an important aspect o f a camera shot, but it is not covered in this chapter
because it is a more advanced skill that takes time to learn. Beginning filmmakers should
simply make sure that their subjects are well lit so they can be seen clearly, which should
not be a problem in Alice virtual worlds. If necessary, additional lights can be added to an
Alice world from the Lights folder in the Alice local object gallery. Exercise 9 - 6 deals
with lighting.
Storyboards can help describe the shots in a movie as well as its plot. A storyboard is a col-
lection of rough sketches of particular shots showing both the visual flow of the movie from
scene to scene and the progression of the movie's plot. They are called storyboards because
the sketches for the shots in a single scene are usually pasted on a single large board so they
can be viewed together. Many people find storyboards very helpful in preproduction and
production. Storyboards can be an important tool in developing a movie. See Figure 9 - 7 .
FIGURE 9 - 7 : A storyboard for the scene described by the script in Figure 9-4
1A opening
1B Marie reacts
Even in today's modern world of technology, storyboards are still often drawn by hand. Yet,
you do not need to be a great artist to draw a storyboard; each image in a storyboard is just a
rough sketch of what a particular shot should look like.
The tools for describing a movie—plot and scene outlines, storyboards, scripts, and shot
lists—are often developed together in preproduction. More visually oriented people may
prefer to start with a storyboard, while more verbally oriented people might start by writing
Tutorial 9B—Storyboarding 257
a script, but eventually all of these tools together will serve as the documentation to define
the movie for the production staff.
TUTORIAL 9B—STORYBOARDING
In this tutorial, you will develop a storyboard and shot list for an existing video before you
try to plan a new video with these techniques. In this case, you will develop a storyboard
and shot list for Alice's lakeSkater example world.
You can do this by yourself, or by working with others. Most video projects are developed
by a team, and this exercise works quite well with a group of two to four people.
1. Prepare for the exercise by getting lined paper for note taking, blank paper
for sketching, and pens or pencils for writing and sketching. Pencils usu-
ally work best for sketching.
2. If you are working in a team, decide who will take which roles for this
exercise—you will need someone to create the shot list, someone to sketch
the shots, someone to work the buttons, and someone to direct the exercise.
The director will decide when to stop, pause, and restart the action, and he
or she will coordinate everyone else's work. You don't need to say "cut"
and "action," but the director should call the shots and should be clearly
understood by the person pushing the buttons. It is important in a team for
the director to listen to the team members, and for the team members to
respect the director's decisions so that things run smoothly. Of course, if
you are working by yourself you will fill all the roles.
3. Find and play the lakeSkater movie file lakeSkater.mov that you saved in
Tutorial 9A, or copy it from the student data files for this book. The movie
file works better for this exercise than the Alice world because you can
stop, start, and rewind the movie file more easily.
4. Play the movie, and then practice pausing, rewinding, and starting the
movie to freeze the screen when a shot changes. For our purposes here, a
shot changes when the camera position changes, not when the skater
moves into a different position. You are trying to document the different
shots in the movie, not the details of the skater's routine.
5. When you are ready, play the world, pausing when the shot changes. Each
time you pause, you should make a rough sketch of the shot, and make an
Chapter 9 • Making Animated Movies with Alice
entry in the shot list describing the kind of shot, the characters, roughly what
happens in the shot, and the length of time the shot stays on the screen.
6 . Compare your sketches and shot list to those in the file lakeSkaterShots.docx
that comes with the student data files for this book. It is a Word document
that integrates a storyboard and shot list for the movie.
Camera placement in Alice is different from the real world for two reasons: first, in Alice,
the moviemaker programs the camera to move, and second, Alice only has one camera.
However, as you will discover while completing the next tutorial, it's not that hard to
manipulate the camera to simulate multiple cameras capturing a scene.
Alice uses dummy objects to mark spots in an Alice world. A dummy object is an invisible
object that occupies a single point in an Alice world. Alice has commands to drop a dummy
where a camera is, and to drop a dummy where an object is. An Alice moviemaker can play
around with camera angles and placement within a scene using dummy objects to mark key
spots, and then program the camera to move to those spots as a scene progresses. You will
do so in the following tutorials.
Dummy objects can also be used to set marks for where objects should be in a scene, similar
to the way movie directors set marks for actors and props in a scene. Exercise 9 - 8 at the end
of this chapter deals with this process, called blocking.
You can use many different effects when transitioning from shot to shot. In the upcoming
tutorials you will use simple jump cuts for shot transitions. A jump cut, sometimes called
simply a cut, is a sudden transition from one shot to another. The last frame of one shot is
followed immediately by the first frame of the following shot, without any transition effects.
A jump cut is the most sudden and most commonly used transition from one shot to another.
A video fade occurs when the viewer's image lightens or darkens to or from a solid color.
For example, a script may contain the direction slow fade to black at the end of a scene,
meaning that the image the viewer sees would slowly fade to black, as if someone were
turning down the lights on a scene. Fades can be to or from any color, but black is the most
common, followed by white. A transition from one shot to another could also fade through
black, with one scene fading to black and the next then fading from black.
Tutorial 9C—Simulating Multiple Cameras
A w i p e occurs when a still image or another shot moves to cover the current shot like a
curtain coming down. Wipes can occur from any direction. A curtain coming down would
be a wipe from above, for example. Exercise 9 - 9 at the end of this chapter deals with fades
and wipes.
In this tutorial, you will take the role of a director who must place cameras for recording a
scene that has already been prepared. You will start with a script, a storyboard, and an
Alice world that follows that script, but which is seen by a single fixed camera. Your task
will be to simulate multiple cameras to record the scene as shown in the storyboards. In
this tutorial, you will complete a short exercise to simulate multiple cameras.
The secret to simulating multiple cameras in Alice is to move the camera using a duration
of zero seconds for the move. This will look like a jump cut in a movie. However, you can't
just move the camera—you need to move and aim the camera. Each Alice object has a point
of v i e w — a property marking the object's location and orientation. Setting a camera's point
of view to that of another object will move and reorient the camera. So, you can best simu-
late multiple cameras by setting the camera's point of view to that of another object with a
duration of 0 seconds for the instruction. In this part of the tutorial, you will move pre-
placed dummy objects to change the camera's point of view, simulating a director switching
from one camera to another.
1. Open the Alice world wonderland that comes with the student data files
for this book.
2 . Play the world and watch what happens. Notice that the entire world is a
single shot from a high angle. The scene is complete when Alice says
"Oh dear!"
3. Click the plus sign next to Dummy Objects in the Object tree, and you will
see that there are three dummy objects: first position, second position, and
opening position, as shown in Figure 9 - 8 . If necessary, scroll down in the
Object tree window to see them. The three dummy objects have been
arranged to mark positions and points of view for the camera so you can
turn this single-shot scene into a three-shot scene.
Chapter 9 • Making Animated Movies with Alice
+ u j : water rail
Efi ^cheshireCat
I I Dummy Objects
Gf^ first position
second position
(^opening position
4. Select the camera tile in the Object tree, and then the methods tab in the
Details area. Drag a camera set point of view to method tile from the meth-
ods tab and drop it in World.my first method as the first instruction,
above the Wait 2 seconds tile.
5. From the menu that appears, select Dummy Objects, and then opening
position as the target object.
6 . Select more... in the newly placed camera set point of view instruction tile,
and set the duration to 0 seconds.
7. Drag the new camera set point of view to instruction tile and drop it on the
Clipboard to make a copy of it; then drag the tile from the Clipboard and drop
it in World.my first method after the Wait 2 seconds instruction tile.
8 . Change the target parameter for this copy of the instruction to first position.
9 . Drag another copy of the camera set point of view to instruction tile from
the Clipboard, and drop it in World.my first method after cheshireCat
say Touch the yellow flower.
10. Change the target parameter for this copy of the instruction to second
position. World.my first method should now look like Figure 9 - 9 , which
indicates where the three camera set point of view instruction tiles should be.
Tutorial 9D—Recording Camera Positions for a Multi-Shot Scene
world.myfirstmethod ()
No variables
camera set point of view to opening position duration = 0 seconds
instructions Wait 2 seconds
added to position -
camera set point of view to first position duration = 0 seconds
the camera
cheshireCat.head point at Alice.neck.head
cheshireCat say Touch the purpleflower,duration = 2 seconds
Alice.touchPurpleFlower
cheshireCat.head point at Alice.neck.head
Alice say Oh my! duration = 2 seconds
cheshireCat sav Touch the yellowflower,duration = 2 seconds
• camera set point of view to second position duration = 0 seconds
Alice. touchYellow Flower
cheshireCat.head point at Alice.neck.head
.Alice say Oh dear! duration = 2 seconds
11. Save the world with the name Wonderland revised, and then play the
world to see the difference the new instructions make. You should notice
that there are now two jump cuts, and that the scene now is composed of
three shots instead of one—the high-angle opening shot, a two shot of the
Cheshire Cat and Alice, followed by a high-angle medium shot. It looks as
if the scene is being recorded by more than one camera.
12. Save the world as a movie file with the name Magic Flowers by using the
Export Video option on the File menu.
The script in Figure 9 - 4 describes a scene to be recorded as a part of a movie. The scene is
an interaction between two characters, Marie and Joe Cool. The storyboard in Figure 9 - 7
describes the shots that will be used for the scene. The scene has been prepared as the Alice
world Shut the Door, but you must line up the camera locations to match the shots
described in the storyboard.
Chapter 9 • Making Animated Movies with Alice
1. After reviewing the script and storyboard, open the Alice world Shut the
Door that comes with the student data files for this book. Play the world,
and notice that the entire world is a single shot.
2 . Save the world with the name Shut the Door complete.
The storyboard shows that the camera's initial point of view will be used in three of the
shots—1A, 1C, and I E . You need to save the camera's initial point of view before manipulating
the camera to set up the other shots. This can be done by dropping a dummy at the camera
location, and then setting the dummy object's point of view to match that of the camera.
1. Click the green ADD OBJECTS button to enter Alice's Scene Editor mode.
2 . Click the more controls button to the right of the World window. Advanced
controls will appear as shown in Figure 9-10.
~ affect subparts
aspect ratio: H/ 3
I ^1
tens angle: e^CP—
fewer controls «
Notice in Figure 9 - 1 0 that the aspect ratio o f the Alice world window can be changed
using the advanced controls in Alice's Scene Editor mode. The aspect ratio is the ratio of
an image's width to its height. Ratios in Alice include 4/3 ( 1 . 3 3 ) , 1.85, and 2 . 3 5 . The 4/3
ratio is the standard television ratio, while the other two are wider cinema formats. An
Alice world is recorded as video using the aspect ratio set for the World window at the
time o f recording.
3. Click the drop dummy at camera button. A Dummy Objects tile will appear
in the Object tree.
Tutorial 9D—Recording Camera Positions for a Multi-Shot Scene
4. Click the plus sign next to the Dummy Objects tile and a tile for the dummy
object named dummy will appear, as shown in Figure 9-11.
3|}WWrlTl
>£f camera
Qi light
Qground
s uj) school
^BigTable
a SJloeCool
EB marie
a I I Dummy Objects
(?) dummy
The opening point of view of the camera is now recorded. Next, you will line up and record
the camera's point of view for the second shot, which according to the storyboard is a three-
quarter shot of Marie reacting to Joe Cool's greeting.
1. Using the blue camera control arrows below the World window, manipu-
late the camera until a shot is lined up similar to the one shown in shot I B
in the storyboard in Figure 9-7. Notice that when you line up the shot,
Marie will be in position, but will still be facing the back of the room, not
Joe Cool.
2. Click the drop dummy at camera button. A new dummy object will appear
in the Object tree.
3 . Right-click the dummy tile and rename the object marieThreeQuarters.
4. Right-click the marieThreeQuarters tile again, and then select methods,
marieThreeQuarters set point of view to, and camera from the menus that
appear.
5. Save the world again before continuing.
Chapter 9 • Making Animated Movies with Alice
The second point of view of the camera is now recorded. The point of view for the third
shot will be the same as for the opening, but the fourth shot will be an over-the-shoulder
shot showing Marie from behind Joe Cool. Joe Cool is currently out of the room, behind the
door. An examination of the code for the Shut the Door world would show that Joe Cool
will move three meters forward when he enters, so you will move Joe Cool three meters for-
ward, line up the shot, and then move him backward three meters to his original position.
To line up and record the point of view for the fourth shot:
1. Right-click the joeCool tile in the Object tree, and then select methods.
JoeCool move, and forward from the menus that appear. Set the distance
for the move to 3 meters.
2 . Using the blue camera control arrows below the World window, manipu-
late the camera until a shot is lined up with the camera behind Joe Cool,
similar to that shown in shot I D in the storyboard in Figure 9 - 7 .
3. Click the drop dummy at camera button. A new dummy object will appear
in the Object tree.
4 . Right-click the dummy tile and rename the object behindjoe.
5. Right-click the behindjoe tile again, and then select methods, behindjoe set
point of view to, and camera from the menus that appear.
6. Right-click the joeCool tile in the Object tree, and then select methods,
JoeCool move, and backward from the menus that appear. Set the distance
for the move to 3 meters.
7. Save the world again before continuing.
Now all three camera points of view are saved, so you can add instructions to World.my
first method to position the camera for each of the five shots. The transitions between
shots will be simple jump cuts, similar to those in the previous tutorial.
5. Drag the c a m e r a set point of view to instruction tile and drop it on the
Clipboard; then drag the tile from the Clipboard and drop it in World.my
first method above the marie.no instruction tile. Change the instruction
tile's target to marieThreeQuarters.
6. Drag another c a m e r a set point of view instruction tile from the Clipboard
and drop it in World.my first method above the joeCool say Je t'dore
instruction tile; leave its target as opening.
7. In a similar manner, insert a fourth camera set point of view tile immedi-
ately below the joeCool say Je t'dore instruction tile with behind.Joe as the
target, and then a fifth camera set point of view tile immediately below the
Marie Shut the Door? instruction tile with opening as the target. Figure 9-12
shows these last three camera set point of view instruction tiles in place.
FIGURE 9 - 1 2 : Code showing the last three camera set point of view instruction tiles in place
Wait 1 second
The world is now ready. It is not necessary to realign the camera before beginning because
the first instruction in World.my first method will do so. Play the worlds, and you
should see the five shots as in the storyboard.
Chapter 9 • Making Animated Movies with Alice
POSTPRODUCTION
The postproduction process includes editing recorded scenes to form a complete movie,
adding titles to the movie, refining the movie's soundtrack, making a master copy of the
movie, and preparing it for distribution. This chapter will not cover most of the postproduc-
tion process; however, the following is a list of postproduction tips you should keep in
mind when creating a movie in Alice:
Alice movies can either stand on their own as complete movies, or they
can be edited using video-editing or moviemaking software. Alice movie
files can be imported into most common video-editing software, such as
Adobe Premiere, Windows Live Movie Maker, or Apple's iMovie, for post-
production work. You can download Windows Live Movie Maker for free
from Microsoft at http://windowslive.com/desktop/rnoviemaker.
Titles and sound can be added to your movie using video-editing software,
or from within Alice, using some of the techniques described in Chapter 6 .
The movie files that Alice outputs are QuickTime movie files. Sometimes
Windows Media Player has trouble playing QuickTime files. You can view
the movies using the QuickTime viewer, which can be downloaded for
free from Apple at www.appIe.com/quicktime/download.
Uploading your movie files to social networking and media sharing sites,
such as YouTube, might be easier if you first convert them to Adobe's
Flash movie format (.flv). This can be done with Flash, or with many
other free movie file conversion programs available on the Web. Simply
use a search engine, such as Google, to look for "free .mov to .flv" soft-
ware. Most conversion programs are easy to use. The directions for
uploading movies to social networking and media sharing sites vary from
one site to another, but are generally easy to follow.
• The file size for an Alice movie depends on the length of the movie and
the size of the World window when the movie is recorded as video. If
your file is too large, try shrinking the World window by clicking and
dragging its perimeter and then recording it again.
Chapter Summary
Chapter Summary
This chapter consisted of a discussion of the technical nature and history of movies, the moviemaking process, camera
placement and shot transitions during production, and a brief look at postproduction, followed by four hands-on tutori-
als involving making movies with Alice.
• A movie is a flat two-dimensional picture that moves. When we view a movie we are watching a rapidly
changing series of still pictures that creates the illusion that something is moving,
• Each of the still images in a movie is called a frame, and the number of frames per second (fps) in a
movie is called the frame rate. The frame rate for films is 2 4 fps, while the frame for broadcast television
is roughly 3 0 fps, Alice renders and saves each frame when it exports a movie into the QuickTime movie
file format.
• The motion picture film industry began with pioneers like the Lumiere Brothers in France and Thomas
Edison in the United States in the late nineteenth century. Film-based movie recording is largely a thing
of the past, due to the rise of digital moviemaking.
• The moviemaking process has three phases: preproduction, production, and postproduction. Production
is the heart of the moviemaking process, the actual recording of the movie when cameras are set up and
rolling and action is recorded. Preproduction encompasses all of the planning and preparation that is
necessary before production can begin. Postproduction includes all of the tasks required after a movie is
recorded, such as editing, adding titles, and packaging the final product.
• The production phase for an animated movie includes creating the animations and recording them.
Today most animations are computer generated imagery (CGI). Many traditional movies often include
some CGI. Alice movies are produced entirely in CGI.
• Common movie types include screenplays, documentaries, slice-of-life vignettes, comedy sketches, and
commercial advertisements. Many screenplays follow a three-act format. A documentary is an expository
movie that teaches a lesson or presents an opinion, much like an essay, with a thesis, points of evidence,
and a conclusion. Documentaries can also be used as teaching tools.
• The primary design document for a movie is called a script, which is a scene-by-scene description of the
movie with dialog and descriptions of the critical action.
• A shot is a particular view of the action in a movie from a specific camera set up in a specific way. A shot
list is a list of the shots needed for each scene, describing the kind of shot, the characters involved,
roughly what happens in the shot, and the length of time the shot stays on the screen, Other details,
such as lighting and special effects, could also be included.
Chapter 9 • Making Animated Movies with Alice
• A storyboard is a collection of rough sketches of particular shots showing both the visual flow of the
movie from scene to scene and the progression of the movie's plot.
• Many different kinds of shots are used to make movies. The most common were described in terms of
the subject's apparent distance from the camera and the camera angle.
In Tutorial 9A, you reviewed the process of recording a movie from an Alice world.
In Tutorial 9C, you learned to simulate multiple cameras in an Alice world, using d u m m y objects and j u m p cuts.
In Tutorial 9 D , you learned to line up and record camera positions using d u m m y objects, and then program the c a m -
era's point of view using the d u m m y objects as the camera is recording.
A brief discussion at the end of the chapter summarized some tips for postproduction.
Review Questions
3. How are preproduction and production processes different for animated movies compared to live-action movies?
6. How are the terms act, scene, shot, and frame related to one another?
7. The chapter contains a list of camera shots described in terms of the subject's apparent distance from the
camera and the camera angle. Explain which types of shot would be appropriate for each of the following, and
why (more than one type of shot may be appropriate for each situation):
a. Establishing where a character is in relation to the surrounding environment, such as at a football game, or
walking through a park
b. Showing the relative position of two characters as they talk with one another
Exercises
8. What is meant by the term point of view? How can points of view be recorded and used for camera positions in
an Alice world?
9. How can j u m p cuts from one camera to another be simulated in Alice with a single camera?
10. What movie file format does Alice use to record movies, and what software is best used to view movies of this
type? Which format works better for posting movies to social networking and media sharing sites, and how can
Alice movie files be converted to this format?
Exercises
1. Create a plot outline, shot list, and storyboard for a scene for an animated version of a short nursery rhyme or
children's story, such as The Three Little Pigs. Keep in mind the scope of your project and try to keep your
scene relatively short, with fewer than a dozen camera shots.
2. Videos of the first short films by Thomas Edison and the Lumiere Brothers are widely available on the Internet.
View some of these films and describe how they are different from modern movies. In particular, how does
camera placement and shot selection seem to be different from that used in making modern movies?
3. The student data files for this book contain the Alice world The Letter P. The world is similar to a scene from the
children's television show Sesame Street, in which a letter of the alphabet sponsors part of the show. View the
world as it is, and then do the following:
a. Develop a shot list for the world that includes multiple camera points of view for multiple shots in the scene
instead of a single shot.
b. Modify The Letter P world to include the shots you described. Save the finished world as a movie file.
The student data files for this book include a ballerinas dancing Alice world, a Japanese fan dancer Alice world, and a
toy soldiers marching Alice world. You will use these worlds for Exercises 4, 5, and 6.
4. Open each of the three worlds mentioned above, view the world, and then create a shot list or storyboard
describing how the world could be recorded using three different camera points of view. Explain why you chose
the three points of view that you did for each world.
5. Modify one of the three worlds from Exercise 4, using the three camera points of view that you described. Save
the finished world as an Alice world and as a movie file.
6. Adjusting the lighting in a scene can create different dramatic effects in a movie. Alice has several different lights in
the lights folder in the Local Alice Object Gallery. You can darken a scene by adjusting the ambient light brightness
and fog properties of an Alice world. Open one of the three Alice worlds mentioned above, or a version of the world
that you modified in Exercise 5. Darken the scene, and then add lights, using them to illuminate different characters
as the world plays. Save the file as an Alice world and as a movie file when you are done.
Chapter 9 • Making Animated Movies with Alice
7. The aspect ratio and lens angle tor an Alice world can be changed using the advanced Scene Editor controls.
Pick an Alice world that you have created or modified and view it with different settings for the aspect ratio and
lens angle.
8. Dummy objects in Alice can be used for blocking a s c e n e — m a r k i n g the positions for object placement and
movement, similar to the way d u m m y objects were used in this chapter for camera positioning. The move to,
turn to face, and point at instructions can be used to make objects move in relation to the d u m m y objects.
Create a simple Alice world with two characters who engage in a dialog. Have the characters enter the scene,
greet each other, and then have one character tell the other character a joke. Use d u m m y objects for blocking
the scene and for camera placement.
9. Billboard objects, which were discussed in Chapter 6, can be used in Alice to create curtains for fade effects
and wipes. An image of a black rectangle, for example, could be used to fade to black, or fade from black. The
opacity property of a billboard can be changed to achieve a fade effect, or a billboard can be moved in front of
the camera to achieve a wipe effect. Using a drawing or painting program, create a black rectangle and then
use the saved rectangle to do the following:
a. Add opening and closing fade from black and fade to black effects to a copy of Alice's lakeSkater example
world. Save the finished world as a movie file.
b. Add a wipe effect between two shots in the Shut the Door complete Nice world that resulted from Tutorial 9D.
(Hint: This is harder than it appears.)
A copy of the world is included with the student data files for this book.
You will need to move the rectangle in front of the camera before changing the camera point of view, and may
need a second copy of the rectangle to finish the wipe after the change.
10. Two advanced camera techniques are the Hitchcock Zoom and the Ken Burns Effect. Using the Internet, find out
who Alfred Hitchcock and Ken Burns are, and what these two effects are. Try to create each of these two effects
in Alice. (Hint: Alfred Hitchcock was a master at manipulating camera properties.)
Video G a m e P r o g r a m m i n g
Describe at least five different roles, other than programming, in the video game industry
Describe four different roles for computer programmers in the creation of video games
Use a physics engine to make an object fly through the air in a simple video game
Chapter 1 0 • Video Game Programming
In this chapter, you will explore video game programming, starting with a look at what
video games are, then moving on to a discussion of careers in the video game industry. The
chapter describes the roles that programmers play in video game development, including
some of the features of video games that programmers need to build. The chapter includes
hands-on tutorials in Alice that will introduce you to video game programming.
A video game is a game played on a video screen, controlled electronically using computer
software. It is an interactive combination of hardware and software that allows the user to
play a game against another person or against a computer. A few electrical engineers and com-
puter pioneers experimented with games on cathode ray tubes in the 1950s and 1960s, but the
first commercial video games from Magnavox and Atari appeared in the 1970s. They were
instant hits, and as the personal computer industry grew, so did the video game industry.
Today, millions of copies of the most popular video games sell each year for systems like
Nintendo's W i i and Microsoft Xbox. Many more games are available for personal computers,
from simple games like minesweeper and solitaire, which come with the Microsoft Windows
operating system, to Massive Multiplayer Online Role-Playing Games. A Massive Multiplayer
Online Role-Playing Game (MMORPG) is played online with hundreds or thousands of peo-
ple, each playing the role of a character in a virtual environment at the same time. One of the
most popular MMORPGs, World ofWarcraft, has more than 10 million subscribers.
The great variety of video games fit into several different genres. The most popular include:
Casino games: Traditional casino games like blackjack, poker, and roulette are
popular as computer games, especially the Texas Hold 'Em variation of poker.
Platform games and maze games: Platform games like Donkey Kong and
the Mario Brothers games require the user to move through a virtual world
by climbing and jumping from one platform to another while avoiding
obstacles. Maze games are similar but require the player to move through
a maze while avoiding obstacles. Pacman and its variations are the most
popular maze games.
Role-playing games: In a role-playing game, the player plays the role of a
particular character, usually the hero of an adventure. Role-playing games
often combine features of many other games.
Driving and racing games: There are a variety of games in which the
player drives a race car, skis down a hill, or is involved in some other
form of racing, either against the computer or another player.
• Sports games: Many video games are based on sports, such as baseball,
football, and basketball. Some require the player to develop keyboard and
mouse skills to play the game, while others are strategy games in which
the player plays the role of a coach making decisions.
Puzzles: Puzzle games require the player to complete a puzzle by either
manipulating objects on the screen, or solving a word puzzle. Puzzle
games, such as Tetris, can be more fast-paced and more sophisticated than
actual physical puzzles.
Simulations: Real-world environments can be simulated on a computer as
the basis of a game. Some, such as Flight Simulator, require the player to
carry out tasks, such as flying a plane, while others are strategy games.
Military strategy and management strategy games, like the Tycoon series
of games and SimCity, are very popular and can take many hours to play.
Some simulations are purely for entertainment, while others are intended
to teach players real-world skills.
Music and dance games: Games based on music and dancing, such as
Dance Dance Revolution and Guitar Hero, are among the most popular
games for game consoles, such as Wii and PlayStation. In most of these
games, the players must perform, either against or with other players.
Many of the most popular games are not limited to a similar genre, but are a combination of
two or more, such as an adventure game that is also a shooter game. The characteristics of a
good game vary depending on the type of game, but most of the more popular games are fast
Chapter 10 • Video Game Programming
paced, have different levels of play, and include sophisticated graphics. They are easy to
learn to play, but are challenging to the user and, in general, have some sort of intellectual
component that occupies the player's mind.
Many people are attracted to careers in video game development because they like video
games and think it would be fun to build games as a career, but what is it really like to work
in the video game industry? In some ways it is similar to the rest of the creative entertainment
industries, which include the music and motion picture industries, while in other ways it is
more like traditional book publishing—with a software development component. Most com-
mercially successful video games are developed by teams of professionals with specialized
skills working on large development projects. Many work for large software and entertain-
ment companies like Electronic Arts, Microsoft, and Nintendo, but some work for small
startup companies that might have only one or two very successful games. Industry experts
estimate that less than five percent of all professional video game development projects actu-
ally make money, largely because of the enormous investment needed to build a commercial
quality video game. Employment in the video game industry can be volatile, as many smaller
video game companies come and go.
There are always opportunities for talented newcomers who can build video games, but most
of the people who make a living in the industry have spent years developing and perfecting
their skills. Primary jobs in the video game industry include game design, game develop-
ment project management, script writing, graphics arts, music and sound engineering, pro-
gramming, and quality assurance. Secondary support is provided by business managers,
office staff, and technical professionals, including computer and network support personnel.
G a m e Development Project M a n a g e m e n t
In the video game industry, a producer is in charge of a game development project; this role
is similar to the role of a movie producer or a general contractor for a construction project.
A video game producer should have a solid business background and excellent manage-
ment skills, especially the ability to manage a large team of diverse people. Of course, it
helps if the person is familiar with video games, but often video game producers are people
with similar experience in related industries, such as the film or television industry.
The producer has overall responsibility for the development team and reports to a com-
pany's senior management, who may be the owner or representatives of the entity financing
the game development project. On a larger project, assistant producers may be in charge of
specific areas, such as the sound team or project finances.
Video Game Careers
Game Design
A game designer is a person who takes a concept or idea for a game and develops it into a
plan for the overall play of a game, including the game's general theme, setting or environ-
ment, objectives, rules of play, structure, and so on. Game designers are to the video game
industry what architects are to the construction industry.
Often a team of designers works together, with one senior person serving as the lead designer
who coordinates the work of other designers and associated skilled professionals, such as
graphic artists. Many game designers focus on specific aspects of a game. For example, a level
designer may develop the levels of play within a game while the interface designer works
with graphic artists and human-computer interaction (HCI) programmers to build the game's
user interface.
Game designers, especially lead designers, work closely with producers to manage the game
development project. Game designers must be aware of constraints imposed by the budget,
the technology available, and the skills of the team, and should have an awareness of avail-
able resources. Many game designers are programmers or other skilled professionals who
developed their design skills while working on previous projects. Others earned specialized
college degrees with the specific intent of becoming a game designer.
The job market for game designers is very volatile, with many designers working on a
project-by-project basis for different companies.
Script Writing
In many modern video game genres, writers are responsible for developing a script for a
game, much like a script for a movie, describing the action or flow of a game, along with
dialog for characters in the game. The characters themselves may be developed by game
designers and graphic artists working together with a writer.
Writers are also responsible for developing and editing any text that appears in a game,
including instructions and help screen text. Some writers specialize in translating game text
from one language to another. All writers need to have a cultural awareness of the game's
target audience.
Graphics Arts
Graphic artists with special skills, often called game artists, create the artwork for a video
game. Some fill traditional roles, such as package design, or text layout, while others have
special skills for creating three-dimensional objects and characters using tools such as
3D Studio Max and Maya. Many artists specialize in specific game elements, such as
characters, vehicles, or natural terrain.
Chapter 10 • Video Game Programming
Often one graphic artist with exceptional artistic and management skill serves as a project's
art director, coordinating other artists and making sure their work fits the overall artistic
vision for the project.
Composers, musicians, voice-over artists, and sound engineers all play a role in the develop-
ment of modern video games, just as they do in the movie industry. The amount of music,
and thus the need for people with musical talent, depends on the type of video game.
Often a game company hires outside musical talent to create original music for a video
game, but sometimes they use in-house personnel. Sound engineers who are responsible for
the recording process and for integrating the recorded sounds into a video game are most
likely to be in-house personnel, as are sound engineers who specialize in creating and
recording special effects, which are most often computer generated. Often the same person
is in charge of sound engineering and special sound effects.
Programming
At its heart, a video game development project is a software development project requiring
people with software engineering and programming skills. Often, a lead programmer with
good management skills will supervise many people with specialized programming skills
working on different aspects of game programming. Many game programmers will use exist-
ing software as the basis for their work, including game engines. A game engine is a software
tool that allows developers to assemble video games from existing objects and methods,
much like the way a person can build an Alice world from existing objects and methods.
Larger and older companies have their own in-house game engines, but some firms use com-
mercially available general purpose games engines. Game Maker, for example, is an easy-to-
use game engine from Yoyo Games, which will host games created with Game Maker on
their Web site, www.yoyogames.com.
Sophisticated games still require specialized custom programming, and someone needs to
build the game engines and other software tools used by game developers. Here is a look at
some of the programming specialists who work on video game development:
programmers develop software for Nintendo's Wii game system that takes
advantage of things like the Wii Wheel, The Wii Balance Board, or the Wii
MotionPlus Controller. (See www.nintendo.com/wii/console/accessories.)
Artificial Intelligence programmers develop the logic in a game, especially
for strategy games in which a user may play against the computer.
Artificial Intelligence (AI) is a branch of computer science devoted to
developing software that can mimic human intelligence in a computer,
especially human perception and decision making.
Graphics programmers work with graphic artists to create new graphical
elements for games and to implement the graphics created by the artists.
Physics programmers implement software that simulates the movement of
objects in the real world, which are affected by things like gravity and the
collision of one object with another. Physics programmers generally need
to have an understanding of physics as well as advanced math skills.
Data Communications programmers create and maintain the software
used for networked versions of video games, particularly for MMORPGs
played over the Internet.
Whatever their specialty, game programmers need to have good general software develop-
ment skills and a firm knowledge of more advanced programming topics, such as data
structures and the mathematics of computer programming. Game programmers often also
need specialized knowledge and experience in their particular programming area.
Quality A s s u r a n c e
Quality assurance specialists in the video game industry are responsible for the overall
quality of video games and the correctness of the underlying software. Software quality
assurance specialists test video game software under all possible circumstances to make
sure that it works properly, testing the overall software and components of the software as
they are developed. Software testing typically requires special training—usually a degree in
computer science, with courses in software testing and validation.
Video game testers are also employed to examine games for both correctness and payabil-
ity. They are not only concerned with whether or not a game works properly, but also with
how well it works. Is it interesting and fun to play? Will it be a marketable commercial
product? What can be done to make the game better?
Most video game testers are people with advanced game playing skills, the ability to recog-
nize which features of a game could be problematic, and the ability to identify and commu-
nicate things that could improve the game. Video game testers should have in-depth
knowledge of video games and a good understanding of how the potential audience for a
video game will react to various aspects of game play.
Chapter 1 0 * Video Game Programming
There are several features of video games that must be built by programmers or imported
into a video game from somewhere else, including a user interface, scorekeeping, artificial
intelligence, graphics, and a physics engine. Entire semesters, or even a series of courses,
can be spent examining each of these. We will look at each briefly and see how some are
implemented in Alice.
A User Interface
A user interface provides controls for a game so that the user can play the game. The most
common user interfaces are a command-driven interface and a Graphical User Interface
(GUI). With a command-driven interface, users communicate with the computer by giving it
individual commands, usually by typing them on a keyboard, similar to the Windows com-
mand prompt. Very few video games use a command-driven interface.
Event-driven programming, which was covered in Chapter 3, is essential for building a GUI.
The nature of the interface depends on the type of game being played. In first-person
shooter games the user moves a camera or pointer with the mouse or keyboard controls,
while in other games, such as a chess game, the keyboard or mouse control game objects
that move while the camera stays fixed.
j j
Let , , , move object
Scorekeeping
Scorekeeping is an important part of most video games, and can be accomplished through
the use of simple numeric variables. Someone with basic programming skills should be able
to build scorekeeping methods for a game.
In negative scorekeeping, players start with a certain number of points and lose points as
they make errors, or as time goes by. Sometimes both are used together, with positive score-
keeping for things a player accomplishes and negative scorekeeping—usually in the form of
penalty points subtracted from the total score—for things a player does wrong.
In Alice, there are two primary ways to keep track of scores—through method variables and
through properties of objects. Both can be manipulated by Alice methods and events.
Figure 10-2 shows examples of both in an Alice world. Method variables are best used to
keep track of the time or points for a person playing a game. Such points are not attached to
any object in the game.
Video Game Programming Features
T|
Let , | . m o v e object
M J W J ^ H I ........ ._ _ _ . . .
Scorekeeping
Scorekeeping is an important part of most video games, and can be accomplished through
the use of simple numeric variables. Someone with basic programming skills should be able
to build scorekeeping methods for a game.
In negative scorekeeping, players start with a certain number of points and lose points as
they make errors, or as time goes by. Sometimes both are used together, with positive score-
keeping for things a player accomplishes and negative scorekeeping—usually in the form of
penalty points subtracted from the total score—for things a player does wrong.
In Alice, there are two primary ways to keep track of scores—through method variables and
through properties of objects. Both can be manipulated by Alice methods and events.
Figure 10-2 shows examples of both in an Alice world. Method variables are best used to
keep track of the time or points for a person playing a game. Such points are not attached to
any object in the game.
Chapter 10 • Video Game Programming
FIGURE 1 0 - 2 : M e t h o d v a r i a b l e s a n d p r o p e r t i e s of o b j e c t s in Alice
create new variable velocity set value to ask user for a number question = laur
Properties of objects can be used to keep track of scores associated with objects, such as
characters, in a game. They can also be used to keep track of characteristics of an object that
could change as a game is played. One technique used in some video games is aging—in
which properties of an object are reduced over time, affecting the ability of an object. For
example, in a game with a frog who hops, the distance the frog is able to hop could be
decreased as the game progresses, simulating the frog growing more tired.
Graphics
Graphics are the visual images that people see when they play a video game. They are the
video part of video gaming. The graphics for video games vary widely, from the simple two-
dimensional block graphics of Nolan Bushnell's Pong or the first versions of Tetris, to modern
role-playing games with three-dimensional graphics that mimic the look of the real world.
Ultimately, the graphics for video games need to be developed using rather sophisticated
mathematics, which will be beyond the reach of most people and are the domain of a few
highly trained professionals. Many three-dimensional virtual world environments, liko
Alice or the Sims, for example, use quaternions, which can be described as four-dimensional
imaginary numbers that are used to keep track of rigid bodies in three-dimensional space as
they move and rotate. Matrix algebra, Euler angles, hyperbolic geometry, fractals, and other
advanced math are also used to program graphics for video games and simulations that look
like the real physical world in which we live.
Fortunately, experts in these areas have developed graphics engines and APIs, which can be
used by people with more ordinary math skills to create video games and simulations. A
graphics engine is a set of encapsulated software components that perform the necessary
math and render objects for video games, simulations, and other software. Graphics engines
Video Game Programming Features 281
often provide a software toolkit which includes objects and functions that game developers
can use to work with graphics in two-dimensional or three-dimensional environments,
without doing all the math.
Graphics APIs allow programmers to include instructions for graphics programming in their
software. Two of the most common graphics APIs are OpenGL and DirectX, which interface
with the operating system and software built into a computer's graphics hardware to pro-
vide a library of graphics commands in various computer programming languages. Java
OpenGL or JOGL, for example, is a cross-platform API that provides graphics commands for
the Java programming language. It was used in the development of Alice. DirectX is a
graphics API from Microsoft for use with the Windows operating system. It includes
Microsoft Direct3D, which is the base for all graphics programming on the Microsoft Xbox
series of video game consoles.
Users of graphics APIs need to be programmers who have some facility with mathematics,
such as a grasp of standard high school level algebra and geometry. However, many video
game engines include a graphics engine that provides even more simplified graphics com-
mands than a graphics API, allowing people with very little knowledge of mathematics to
create and move objects.
The three-dimensional graphics needed for Alice have all been incorporated into the sys-
tem, so Alice will handle the graphics when you use commands, such as move or turn, to
manipulate objects.
Physics Engines
Rendering objects so that they look like objects in the real world is only part of what is
needed for video games and simulations that mimic the real world. The physics of moving
objects, including the effects of gravity, friction, objects bumping into one another, wind
resistance and fluid dynamics, need to be addressed so that objects will act like objects in
the real world. Fortunately, just as graphics programmers have created graphics engines for
others to use, physics programmers have created physics engines which have objects and
methods to address these issues. Physics APIs also exist.
Yet, even when using a physics engine or a gaming engine with a built-in physics engine,
keeping track of moving objects and the interactions between them can be rather complicated,
especially in 3D virtual worlds. In fact, it can become so complicated that it can take up most
of the processing power of a good modern computer. Fortunately, video game programmers
don't have to account for every interaction between objects in virtual worlds, just enough to
make the game somewhat realistic and believable, especially in video games, which don't
need to be as realistic as simulations. Games only need to be entertaining so that people will
want to play them, while at least some elements of simulations may need to be very realistic.
Chapter 10 • Video Game Programming
Often gaming software only attempts to implement the minimum amount of physics needed
for a particular game. Large game development companies have their own libraries of
physics routines with just enough physics software for certain games or families of games.
Physics engines and APIs for certain types of physics programming are available to the pub-
lic. For example, Box2d is a popular physics engine for two-dimensional games, while the
Nvidia PhysX Software Development Kit, Newton Game Dynamics, and Bullet are all 3D
physics engines used by game developers to make their games behave more realistically.
Bullet is an open source physics engine used for many gaming platforms including Xbox,
Wii, Windows, the iPhone, and others. It has been used for many popular games, including
some of the Grand Theft Auto games, and to create virtual worlds for Hollywood movies,
including several by Disney and Sony.
Alice does not have a built-in physics engine, so you must build your own software for real-
istic object interaction or get the software from someone else. Two of the simpler things that
can be done with physics engines are collision detection (detecting when objects in a vir-
tual world collide with one another) and ballistics (determining the paths of objects, such
as baseballs, as they fly through the air).
The following tutorials explore game programming. In Tutorial 10A, you will learn how to
add a scorekeeping mechanism to a video game. Tutorial 10B will show you how to include
simple collision detection in a video game. Tutorial IOC allows you to examine ballistics
software for throwing a ball though the air.
In this tutorial, you will add a scorekeeping mechanism to a video game. Both the score-
keeping mechanism and the game are simple—the game is a guessing game. The scorekeep-
ing mechanism will keep track of the number of guesses.
The game, called Where's Alice?, is shown in Figure 10-3. Alice is hiding behind one of
three doors. The user must guess which door. However, things are a bit complicated
because if the user picks the wrong door, then Alice can move to a different door.
Tutorial 10A—Where's Alice?
Scorekeeping usually involves using a variable to keep track of the user's score and instruc-
tions in methods or events to add or subtract points, depending on what happens in the
game. Scorekeeping points are related to the object of the game. The object of Where's
Alice? is to find Alice in as few guesses as possible, so one point will be added each time
the user picks a door. At the end of the game, the program will display the number of
guesses it took to find Alice.
Some games have more complicated scorekeeping mechanisms, some of which use more
than one variable. Some role-playing games and adventure games, for example, have vari-
ables for an overall score and additional variables for things such as the strength of a char-
acter. As the game progresses, the character's power strengthens or weakens, with the game
ending if the character's power drops too low. Points, in this case strength points, are added
to or subtracted from the strength variable depending on what happens in the game. In this
example, the character would be an object, and strength would be a property of the object,
possibly along with other similar properties, such as hunger and health.
In this tutorial, the scorekeeping mechanism is simple, and only one action, picking a door,
will add a point to the user's score. You will start by playing the game without a scorekeeping
mechanism. Then, you will add scorekeeping, and you can try the game again.
Chapter 10 • Video Game Programming
1. Open the Alice world where's Alice.a2w that is included in the student
data files for this chapter. Notice that the world contains a billboard with
directions for the game, shown in Figure 10-4. Also, notice that this world
has a wider window—the window's aspect ratio is 2.35 to 1, which was set
using the advanced controls in scene editor mode.
Where's Alice?
Alice is hiding behind door 1, door 2, or door 3.
See if you can find her.
2. Play the game a few times to become familiar with how it works.
You may examine the code for the game, if you would like to see how it works. The main
method in the game is world.game, shown in Figure 10-5.
Tutorial 1 OA—Where's Alice?
# world.game
world.game Noparameters
selected set value to round random number integerOnly = true minimum = -\ maximum = 4 duration =0 seconds more...
Do in order Do together It/Else Loop While For all in order For all together Wait print
The method first moves the directions for the game off-screen, and then it plays a loop in
which the computer picks an integer between 1 and 3 , places Alice behind the correspond-
ing door, and then asks the user to guess which door. The loop will repeat as long as the
guess and the door that Alice is behind are not the same. When the guess is the same as the
correct door, the loop ends and Alice says "You found m e ! "
After you play the game a few times, you can add scorekeeping to the game. You will add a
scorekeeping variable, an instruction to increment the score each time the user guesses, and
instructions to build and display a message showing the score at the end of the game.
1. Click the create new variable button on the world.game tab in the Editor area.
2. Name the new variable score, make sure that Number is selected as the
variable type, that its initial Value is zero, as shown in Figure 10-6, and
then click the OK button.
Chapter 10 • Video Game Programming
0 •makea [list •]
3. Drag a copy of the score variable tile from the top of the method and drop it
just below the userChoice... instruction inside the While loop. A menu will
appear, as shown in Figure 1 0 - 7 .
FIGURE 1 0 - 7 : The menu that appears when you drop the score variable in the method; the green line
shows where the new instruction will be placed
Now you need to add instructions to build a message to display the score and to show this
message. An unused string variable called message is already in the method, as you can see
in Figure 1 0 - 7 . You will add an instruction to build the message by concatenating three
parts of the message—"It took you " + score + " guesses." To concatenate strings means to
put strings together to build a larger string. Alice has a string function [ [A] joined with [B] j
that does this.
Tutorial 10A—Where's Alice?
1. Drag a copy of the message variable tile from the top of the method and
drop it in the method as the last instruction in the method, after the Alice
say "You found me!" instruction. A set value menu will appear.
2 . Select set value, then other, and enter It took you, with a blank space after
you, as the string.
3 . Next, drag a copy of the [ [A] joined with [B] ] function tile from the world's
details tab in the Details area and drop it in the new instruction in place of
[It took you ]. A b menu will appear, asking you for the next part of the
string.
4. Select default string from the menu that appears.
5. Now you will replace the default string with the variable score. Drag a copy
of the [ [what] as a string] function tile from the world's details tab and
drop it in the new instruction in place of default string. A what menu will
appear, as shown in Figure 10-8.
FIGURE 1 0 - 8 : The menu that appears when you use the [[what] as a string]function to put a numeric
value in a string
•
•
what
the entire world
placeAlice
camera
light
riessai >
, Q score =• 0
ground
leftDoor
rightDoor
jmber miridleDoor • minimum =1 max}}
aliceUddell •
Dummy Objects •
open door •
1
conds nore...
2
rth del 3 selected
instructions userChoice
event
r all in message nrinf
expressions score
I
6. Select expressions and then score from the menus, as shown in Figure 10-8.
Chapter 10 • Video Game Programming
7. Drag another copy of the [ [A] joined with [B] ] function tile from the
world's details tab and drop this copy in the new instruction in place of the
word joined in [ [It took you ] joined with [score] ]. A b menu will appear,
asking you for the last part of the string.
8. Select other from the menu, then enter guesses! as the string. Be sure to
include a blank space before the " g " in guesses as well as an exclamation
point at the end of the word. The new instruction is complete and should
look like the one shown in Figure 10-9.
Finally, you will add an instruction to display the score, and then save the new copy of the
game. Alice will say the scorekeeping message.
1. Select the aliceLiddell tile in the object tree and the methods tab in the
Details area.
2. Drag a copy of the aliceLiddell say tile from the methods tab and drop it in
the method as the last instruction in the method, after the message set
value ... instruction. A what menu will appear.
3 . Select expressions, and then message from the menus that appear.
4. Click more... in the new Alice say [message] instruction and change the
duration to 2 seconds.
5. The world.game method should match Figure 10-10. Save the world as
where's Alice, but in a different location from the data files for this chapter
so that you won't wipe out the original where's Alice world.
Tutorial 10B—Don't Splash the Penguin!
FIGURE 1 0 - 1 0 : The complete world, game method for the Where's Alice? Game
0 world.game |
world.game Noparameters create n e wparameter j
Wait 5 seconds
world.close doors
selected s e t value t o round random number integer Only = Hue minimum - 1 maximum =4 duration • 0 s e c o n d s more...
w o r l d . p l a c e A l i c e door • s e l e c t e d
userChoice set value t o a s k user for a n u m b e r question = P i c k a door, any door: title = W h e r e ' s Alice? duration = 0 s e c o n d s more...
message set value t o It t o o k y o u joined with score a s a string joined with guesses! more...
Your new world is now complete. Try the new version of the game a few times and see how
scorekeeping makes it more interesting.
In this tutorial, you will create an exciting new video game called Don't Splash the Penguin!
The game contains an ice skating rink with a penguin at one end and a flag at the other.
There are holes in the ice, and the player's goal is to get the penguin to the flag as quickly as
possible without falling through the holes in the ice. Figure 10-11 shows the penguin in the
starting position, an overhead view of the skating rink full of holes, and the flag the penguin
must reach.
Chapter 10 • Video Game Programming
It can take a long time to build a complete video game, even a simple game like this one, so
an Alice world with the objects needed for the game has been created and saved with the
data files for this chapter as Splash setup.a2w. The objects in the world include the frozen
lake from the lakeSkater demo world, a snowbank around the skating rink on the lake, the
penguin, the flagpole, and, of course, the holes in the ice. There are also some hidden
objects, including the camera, a directional light attached to the camera to help make the
scene more visible, and dummy objects to keep track of camera and object positions. All of
these are in the world in their correct starting positions.
The world also contains two Alice billboards—one with a victory message to be displayed
when the penguin reaches the flagpole and one with a game over message to be displayed if
the penguin falls through one of the holes in the ice. These are off camera.
Your main tasks will be to add simple user controls for the penguin and to add collision
detection to the world. Both will be implemented using events. The penguin controls are
very easy, but the collision detection is a bit more complicated. You will also add code to
show the victory or game over billboards at the appropriate times and to display the time it
took to reach the flagpole from the start of the game.
You will start by opening the world and exploring it, then you will add user controls for the
penguin.
1. Open the Alice world Splash setup.a2w that is included in the student data
files for this chapter.
2. Save the world as penguin splash.a2w.
3 . Notice that the world contains an event to keep the camera pointed at the
penguin. This is the only code in the setup world. Play the world and you
will see the camera turn to point at the penguin. Later, as you play the
game, the camera will stay pointed at the penguin because of this event.
Tutorial 10B—Don't Splash the Penguin!
I
the entire World
Camera
A Play Light
lake
happysky
v"v* Camera hole2
hole3
ffl i i $ l a Camera move
hole4
Camera turn
holes
delete Camera roll
hole6
save object Camera resire
17, hoiez hole7
Camera say
G5hole3
Camera think hole9
( ? ) hole4
Camera play sound holet
I7j holes
Camera get a good look at hole 10
[ ? ; holee
Camera move to hole 11
i ? •hole/
Camera move toward hole 12
Camera move away from snowbank
Camera's details Camera orient to hole 13
["properties [methods [fundi Camera turn to face hole 14
Camera point at hole 15
create new method
Camera set point of view to hole 16
Camera set pose penguin
Camera move
Camera stand up flagpole
Camera turn
Camera set color to directionalLight
Camera roll starting position
Camera set opacity to
Camera resize Camera set vehicle to splash
Camera set skin texture to victory
Camera say Camera set fillingStyle to onscreen
X I
Chapter 10 • Video Game Programming
Next, you will add collision detection to the world. Collision detection works by checking
to see if one object overlaps another in a virtual space, like the world of Alice. This can be
very complicated, as you must check each part of each object that is moving to see if it over-
laps with any part of any other object. The shapes of objects in a virtual world can be
approximated by a collection of geometric shapes, such as circles, rectangles, and triangles
on a two-dimensional flat plane, or with spheres, rectangular solids, and cylinders in a
three-dimensional world. The mathematics for this are complicated, and collision detection
software can be time consuming to create. Often physics engines with built-in collision
detection are included in gaming engines. In this case, you will create your own simple col-
lision detection software, checking to see if the penguin hits a hole, hits the snowbank that
surrounds the skating rink, or reaches the flagpole.
The holes in the ice are each flat circles, with a radius of 1 meter, on the surface of the ice.
Every object in Alice has a point of reference marking its location on the world. For 3D
objects that are characters, like the penguin, the point of reference is usually at the center of
the base of the object, which, for the penguin, would be on the ground halfway between the
penguin's feet. For the circles that form the holes, the point of reference is at the center of
the circle. This makes collision detection much easier—you simply need to see if the pen-
guin is within 1 meter (the radius) of the center of each hole.
The holes are stored in a list, which will make it easier to check all of the holes at once using
Alice's for all together instruction. This is similar to the technique used in sophisticated col-
lision detection engines. Objects are placed in an array or a list, and the collision detection
software checks the shapes of the objects stored in the lists to see if they are overlapping.
You are going to build an event that will continuously run while the world is playing, with
an event handler method that will react whenever the penguin is within 1 meter of the cen-
ter of a hole. There it is—collision detection made simple. First you will build the event
handler method, and then you will add the event.
1. Click the create new method button on the world's methods tab.
2. Name the new method collisionCheck, and click the OK button.
Tutorial 10B—Don't Splash the Penguin!
Drag a For all together tile from the bottom of the Editor area and drop it
into the c o l l i s i o n C h e c k method in place of Do Nothing. Select expres-
sions, World.holes from the menus that appear.
Drag an IF/ELSE tile from the bottom of the Editor area and drop it into the
For all together tile in place of Do Nothing. Select true as the condition.
Select the penguin tile in the Object tree and the functions tab in the pen-
guin's Details area. Drag a copy of the penguin is within [threshold] of [object]
tile from the functions tab and drop it in the IF/ELSE tile in place of the true
parameter. Select 1 meter, expressions, item_from_holes, from the menus that
appear, as shown in Figure 10-13.
FIGURE 1 0 - 1 3 : Menus for building the condition to see if the penguin is within 1 meter of a hole
p a2w- [Modified]
Let
HBJ aaaj wml
World. collisionChed
W o r l d . c o l l i s i o n C h e c k Not. h 0 | e 1 5
hole 16
No variables
penguin
H F o r a l l World.holes flagpole i_holes together
directionalLight
If
is within starting position
a
1 meter • splash
Els victory
2 meters »
C onscreen
S meters •
6. Select the methods tab in the penguin's Details area. Drag a copy of the
penguin move tile and drop it in the IF/ELSE tile in place of Do Nothing.
Select down and 5 meters as the parameters for the move instruction.
7. Select [more...] on the move instruction tile, and set the duration to
.25 seconds.
8. Your method should now look like Figure 10-14. Save the world before
continuing.
FIGURE 1 0 - 1 4 : The collisionCheck method with instructions to make the penguin fall
through the holes
9 World.collisionCheck
W o r l d . c o l l i s i o n C h e c k Mo parameters
No variables
Do in order Do together If .Else Loop While For all in order For all together Wait print
Next, you will create the event to go with this event handler.
2 . Select When the world starts from the menu that appears.
3 . Right-click the new W h e n the world starts event tile and change it to a
While the world is running event.
4. Drag the collisionCheck method tile from the methods tab in the world's
Details area and drop it in the new event in place of the None parameter
following During.
Now the penguin will fall through the holes. Play the world and try it. The arrow keys should
control the penguin's movements. Whenever the penguin gets within 1 meter of the center of
a hole, it should fall through the ice. However, something is still missing. You need to show
the splash billboard with the game over message when the penguin falls through a hole.
A dummy object named onScreen has been set up in front of the camera. To show the bill-
board, you simply need to set the billboard's point of view to that of the onScreen object
with a duration of zero for the instruction. This will be similar to a jump cut in a movie, as
discussed in Chapter 9.
1. Select the splash tile in the Object tree and the methods tab in splash's
Details area.
2 . Drag a splash set point of view to tile from the methods tab and drop it into
the IF/ELSE tile in the collisionCheck method just below the penguin
move down tile. Select onScreen from the menu that appears.
3 . Click [more...] on the splash set point of view to onScreen instruction tile
and set the duration to 0 seconds.
4. You will also add a Wait instruction to include a delay between the pen-
guin falling through the ice and the end of game message appearing. Drag a
Wait instruction from the bottom of the editor area and drop it between the
penguin move down tile and the [splash] set point of view to [onScreen] tile
in the IF/ELSE tile in the World.collisionCheck method. Set the duration
to 1 second.
5. Your method should now look like Figure 10-15. Save the world before
continuing.
Chapter 10 • Video Game Programming
FIGURE 1 0 - 1 5 : T h e c o l l i s i o n C h e c k m e t h o d w i t h c o d e for e n d i n g t h e g a m e
O World.collisionCheck |
W o r l d . c o l l i s i o n C h e c k No parameters create new parameter
Wait 1 second
Else
(Do Nothing
Do in order Do together If'Else Loop While For all in order For all together Wait print
Play the world a few times and see what happens when the penguin hits a hole. T h e
collision detection for the holes is now complete, but the penguin can still go through
the snowbank around the skating rink, so next you will add collision detection for the
snowbank. T h e perimeter snowbank is actually a doughnut-shaped object called a torus.
The point of reference for the snowbank object is in the center of the circle formed by
the torus, much like the reference point for a circle is in the center of the circle. T h e
snowbank has an inner radius—the distance from the center point to the inside edge of
the snowbank, and an outer radius—the distance from the center point to the outside
edge of the snowbank. T h e inner radius is 10.5 meters. This means that if the penguin
reaches any point 10.5 meters from the center of the torus-shaped snowbank, it hits the
snowbank. You will add code to the c o l l i s i o n C h e c k method to detect this collision
with the snowbank.
Physics engines have software that will react to a collision when it occurs. Objects could
bounce off of other objects, break into pieces, and so on. In the case of the penguin hitting a
hole in the ice, the penguin falls though the hole. In the case of the penguin hitting the
snowbank, you will simply make the penguin move back a quarter meter toward the center
of the torus, as if it is bouncing off of the snowbank.
1. Drag an IF/ELSE tile from the bottom of the Editor area and drop it into the
c o l l i s i o n C h e c k method just below the For all together tile. Select true as
the condition.
Tutorial 10B—Don't Splash the Penguin!
2. Select the penguin tile in the Object tree and the functions tab in the pen-
guin's Details area. Drag a copy of the penguin is at least [threshold] away
from [object] tile from the functions tab and drop it in the new IF/ELSE tile
in place of the true parameter. Select 1 meter, expressions, snowBank, from
the menus that appear.
3. Select the 1 meter parameter in the penguin is at least [1 meter ] away from
[snowBank] tile and change it to 10.5 meters.
4. Drag a copy of the penguin move toward tile from the methods tab in the
penguin's Details area and drop it in the new IF/ELSE tile in place of Do
Nothing. Select 1 meter and snowBank as the parameters for the move
toward instruction. This instruction will make the penguin move back
toward the center point of the torus.
5. Change the amount = 1 meter parameter in the new penguin move toward
instruction tile to .25 meters.
6. Select [more...] on the penguin move toward instruction tile and set the
duration to 0 seconds. Save the world before continuing.
FIGURE 1 0 - 1 6 : T h e c o l l i s i o n C h e c k m e t h o d w i t h c o d e for e n d i n g t h e g a m e
penguin move amount = 1 meter toward target = snowBank duration '0 seconds style - abruptly more...
Else
(Do Nothing
Next, you will add instructions to the c o l l i s i o n C h e c k method to detect and react when
the penguin reaches the flagpole. When this happens, the victory message should appear.
1. Drag an IF/Else tile from the bottom of the Editor area and drop it into the
bottom of the collisionCheck method tile. Select true as the condition.
2. Select the penguin tile in the Object tree and the functions tab in the pen-
guin's Details area. Drag a copy of the penguin distance to tile from the func-
tions tab and drop it in the IF/ELSE tile in place of the true parameter. Select 1
meter, expressions, flagpole from the menus that appear.
Tutorial 10B—Don't Splash the Penguin!
4. Find the time elapsed tile on the functions tab in the world's Details area.
Drag and drop a copy of it into the [World.startTime] set value to [1] tile in
place of the value 1, so that the instruction looks as shown in Figure 10-18.
1. Drag the Time tile from the properties tab in the world's Details area and
drop it in the c o l l i s i o n C h e c k method in the If [penguin] distance to
flagpole < 0.5 tile above the victory set opacity to 1(100%) instruction tile.
Select 1 as the value from the menu that appears.
2. Drag the time elapsed tile on the functions tab in the world's Details area.
Drag and drop a copy of it into the World.time set value to [1] tile in place
of the value 1.
3 . Click the down arrow next to the time elapsed parameter in the
World.time set value to [elapsed time] instruction tile and select math,
[time elapsed - ], expressions, and World.startTime from the menus that
appear, as shown in Figure 10-19.
Else
[Do Nothing
b
•if penguin distance to flagpole < 0.5
0.25
World.time set value to time elapsed more... 0.5
4. Drag a print tile from the bottom of the Editor area and drop it in the If
[penguin] distance to flagpole < 0.5 tile as the last instruction in the tile,
just above Else. Select object, expressions, and World.time from the menus
that appear.
5. Congratulations, Don't Splash the Penguin! is now complete. Save the
world, and then see how quickly you can get the penguin to the flagpole.
In this tutorial, you will examine a ballistics routine from a physics engine for Alice, simi-
lar to that found in other physics engines. Ballistics is the science of projectiles, which are
objects flying through the air after they have been thrown or launched by some force.
Projectiles include balls in a sporting event, such as baseballs, basketballs, or footballs, bul-
lets, arrows, darts, horseshoes, or any object that is flying through the air without some
power of its own. A rocket becomes a projectile once its engine runs out of fuel. Projectiles
are an important part of many video games. A person jumping freely through the air is, in
terms of physics, a projectile.
You will examine an Alice world in which an athlete (the jock character from the Alice gal-
leries) throws a ball at a target object, shown in Figure 10-20.
Tutorial 10C—Video Game Ballistics
The path that the ball takes is a curve called a parabola. The shape of the parabola is affected
by the force of gravity, air resistance, the angle at which the ball is thrown, and the ball's ini-
tial velocity. Simulations need to match the real world as closely as possible, but video
games don't need to match the real world exactly, as long as they are real enough for game
play. In this case, we will ignore the air resistance because it complicates the math for the
problem and because a game can still appear realistic without it. Figure 10-21 shows what
the path of the ball would look like if the athlete threw the ball at an angle of 45 degrees with
an initial velocity of 8 meters per second.
Chapter 1 0 * Video Game Programming
E •
bo
•5
10 1i 1: 2 5 3I 35 4C
Distance (meters)
Once the ball leaves the athlete's hand, it moves forward and up, with the forward velocity
and upward velocity determined by how hard the ball was thrown and at what angle. The
ball's forward velocity doesn't change if we leave out air resistance, but its upward veloc-
ity is slowed down by gravity, until finally the force of gravity pulls it downward and it
hits the ground. For every second the ball is in the air, the force of gravity will first slow
down the ball's upward velocity by 9.8 meters per second, and then after it starts coming
down will increase its downward velocity by 9.8 meters per second. The equations shown
in Figure 10-22 show how to use this information to figure out the position of the ball at
any time after it was thrown.
X= V t 0x
1 -
y= V t--gt 0y
2
t is t h e t i m e s i n c e t h e ball w a s thrown
In the Alice ballistics routine, a loop is set up to figure out the position at each 1/100 of a
second after the ball is thrown, and then, using that data, to move the ball from its old loca-
tion to the new location. The Alice method to do all of this is shown in Figure 10-23.
w o r l d myfirst m e t h o d ^pTkihrowBa^JS^h^CsTlght 1
l u * V x - 0 , [lMJvy-0 , @ X - 0 , [I«|Y«0
Do t o g e t h e r
Obviously, to write the method you would need to know the math and physics for all of
this, which most people don't. That's why we need physics engines created by people with
advanced math and physics skills. When the ball hits the ground, it might bounce, it might
break open, or it might just stick in the soft earth. What actually happens depends on many
factors that are, like air resistance, too complicated for us to consider in this example, so we
will assume that the ball stops where it lands. In fact, the math for a complete and accurate
physics engine requires knowledge of matrix algebra, trigonometry, calculus, and differen-
tial equations. You've heard the expression, "It isn't rocket science"? Well, without a
physics engine, the knowledge of math and physics needed to create a realistic video game,
even for simple things like a person throwing a ball, is, literally, rocket science.
In the remainder of this tutorial, you will load and play the Alice world with the ballistics
routine discussed above, and then you will change the world so that user can input the
angle and velocity with which the ball was thrown.
1. Open the Alice world Ball.a2w that is included in the student data files for
this chapter. Notice that world.my f i r s t method contains two events
which are disabled. You will work with these later.
Chapter 10 • Video Game Programming
4. Click the Physics tile in the Object tree and then the edit button next to the
flight method. This is the ballistics method discussed earlier in this chapter.
Notice that it has three input parameters—object, which is the object being
thrown, angle, and velocity. The angle and velocity are the initial angle and
velocity with which the object is thrown.
You are going to modify the j o c k . t h r o w b a l l method to make the initial velocity and
angle input parameters for the method. You will then activate the input instructions in
world.my f i r s t method to let the user input the initial velocity and angle.
To make the initial velocity and angle input parameters for the method:
1. Save the world as throw ball with user input before continuing.
2. Click the tab for the j o c k , throw b a l l method in the Editor area.
3. Click the create new parameter button in the method to create a new
parameter. Name the parameter throwAngle and make sure it is a
Number parameter, and then click OK. T h e new parameter will appear at
the top of the method.
Tutorial 10C—Video Game Ballistics
4. Click the create new parameter button again. Name this parameter
throwVelocity, make sure it is a Number parameter, and then click OK. This
parameter will also appear at the top of the method, as shown in Figure 10-25.
5. Scroll down in the method and find the physics.flight instruction. Click the
angle = 35 parameter in the instruction tile, and, using the menus that
appear, change it by selecting expressions and throwAngle.
6. In a similar manner, click the velocity = 8.1 parameter and change it by
selecting expressions and throwVelocity from the menus that appear.
7. Save the world before continuing.
Now you will activate the input instructions in World.my f i r s t method and use their val-
ues for method parameters.
The new world is now complete. When you play the world, it will ask for the angle and
velocity of the throw. T h e values that the user inputs are saved as angle and velocity,
and are then passed to the j o c k . t h r o w b a l l method, which in turn passes them on to
the p h y s i c s . f l i g h t method. Try it a few times and see what happens with different
Chapter 10 • Video Game Programming
values. The pin will fall if the ball hits it. There are many different combinations of
angles and velocities that will work, but one of them is an angle of 35 degrees and a
velocity of 8.1 meters per second.
We have not examined all of the math in the p h y s i c s . f l i g h t method. If you are familiar
with the physics it uses, then you should be able to see what's happening in the method. If
you are not familiar with the physics, then there is no need to examine the method.
There are two kinds of game programmers who deal with physics engines like this ballistics
routine—those who use physics engines and those who program them. Someone needs to
create physics engines, but, just as with graphics and other aspects of programming, most
people use software created by specialists. However, all good programmers need to under-
stand some math to be able to use physics engines and similar software. So, if you want to
program video games, you should study some math, computer graphics, and software engi-
neering, no matter what area of video game programming you choose as your specialty.
Chapter Summary
Chapter Summary
This chapter included brief discussions of different genres of video games, video game development careers, and
some c o m m o n video game programming features. It included two tutorials—one about collision detection and another
about ballistics.
• A video game is a game that is played on a video screen controlled electronically using computer soft-
ware, It is an interactive combination of hardware and software that allows the user to play a game
against another person or against a computer.
• The great variety of video games fit into several different genres, The most popular include adventure
games, casino games, board games, shooter games, platform games, maze games, role-playing games,
driving and racing games, sports games, puzzles, simulations, and music and dance games.
• Many of the most popular games are not limited to a similar genre, but are a combination of two or more.
• A Massive Multiplayer Online Role-Playing Game (MMORPG) is played online with hundreds or thousands of
people, each playing the role of a character at the same time over the Internet in a virtual environment.
• Most commercially successful video games are developed by teams of professionals with specialized
skills working in large development projects.
• Primary jobs in the video game industry include game design, game development project management,
script writing, graphics arts, music and sound engineering, programming, and quality assurance.
Secondary support is provided by business managers, office staff, and technical professionals, including
computer and network support personnel.
• A game designer is a person who takes a concept or idea for a game and develops it into a plan for the
overall play of a game, including the game's general theme, setting or environment, objectives, rules of
play, structure, and so on. Often a team of designers works together, with one senior person serving as
the lead designer who coordinates the work of other designers and associated skilled professionals, such
as graphic artists.
• The person in charge of a game development project is not a designer, but a game's producer, whose
role is similar to that of a movie producer or a general contractor for a construction project.
• Writers are responsible for developing a script for a game, much like a script for a movie, and work with
game designers and graphic artists to create storylines and characters for a game.
• Graphic artists with special skills, often called game artists, create the artwork for a video game. Many
artists specialize in specific game elements. A graphic artist with exceptional artistic and management
skill will often serve as a game development project's art director.
• Composers, musicians, voice-over artists, and sound engineers all play a role in the development of the
sound for modern video games,
Chapter 10 • Video Game Programming
• A video game development project is a software development project requiring people with software
engineering and programming skills A lead programmer with good management skills will supervise
many people with specialized programming skills working on different aspects of game programming.
• Artificial Intelligence (Al) programmers develop the logic in a game, especially for strategy games in
which a user may play against the computer
• Graphics programmers work with graphic artists to create new graphical elements for games and to
implement the graphics created by the artists.
• Physics programmers implement software that simulates the movement of objects in the real world,
which are affected by things like gravity and the collision of one object with another.
• Data communications programmers create and maintain the software used for networked versions of
video games.
• Video game software includes features that must be built by programmers or imported into a video
game from somewhere else, including a user interface, scorekeeping, artificial intelligence, graphics,
sound, and a physics engine.
• An Application Programmer Interface (API) is software that provides expanded capabilities for computer
programmers.
• A graphics engine is a set of encapsulated software components that perform the necessary math and
render objects for video games, simulations, and other software.
• Physics engines have objects and methods to address the physics of moving objects, including the
effects of gravity, friction, objects bumping into one another, wind resistance, and fluid dynamics, so that
objects in a video game will act like objects in the real world.
In Tutorial 10B, you created the Don't Splash the Penguin! video game with collision detection.
In Tutorial 10C, you examined an Alice world that uses a ballistics routine from a physics engine to make an athlete
throw a ball like he would in the real world.
Review Questions
3. List five different jobs in the video game industry other than programming, and describe some of the responsi-
bilities of each of the jobs. Using the Internet as a research tool, include in your answer the typical salaries and
the type of education or training needed for each job.
4. Describe four specialized kinds of programming needed in the video game industry.
5. Create a table that has rows for eight different genres of video games and columns for five c o m m o n video
game programming features. Fill in the table with the value—high, medium, and tow—indicating how
important specific programming features are for each type of game.
7. Why is a physics engine or equivalent software needed to develop many video games?
8. Imagine that you are building an action-adventure video game with a character who could grow weaker or
stronger. Describe how scorekeeping works in video games and how this is similar to scorekeeping.
9. Describe what is meant by collision detection and how it generally works in a modern video game.
10. What areas of mathematics does someone need to study to create the software for a physics engine?
Exercises
1. Working alone or with other students, design a video g a m e that has shopping in a supermarket as its major
theme, This should be a general design for a game not necessarily based on Alice. You will design the game,
but you will not build it. What genre will your g a m e be? What are its objectives, rules of play, structure, and so
on? What does the user interface look like? How will scorekeeping work? What other programming features are
needed for the game?
2. Create a development plan for the game you described in Exercise 1 . What specialists are needed to create
your game? What work will each of t h e m need to do? How will your development team be organized?
The Alice world penguin splash included with the student data files for this chapter has the result of Tutorial 10A. It will
be used for Exercises 3 through 6.
3. Add sound to the penguin splash world. You could use events to initiate sound when the penguin hits the snow-
bank, falls into a hole, or reaches the flag.
4. Using Don't Splash the Penguin! as the title, add an opening title in 3D to the penguin splash world, or create
an opening billboard and add it to the world. The billboard could also include simple instructions for playing
Don't Splash the Penguin!
5. Add another character, perhaps a second penguin, to penguin splash, positioned near the flagpole. When the
penguin reaches the flagpole, have this character tell the user how long it has been since the game started.
Chapter 1 0 * Video Game Programming
6. The Alice world throw ball with user input included with the student data files for this chapter has the result of
Tutorial 10B. Add two characters. The data files coach.a2wand cheerleader.a2w, also included with the student
data files for this chapter, have characters with methods for different behaviors that can be imported into an
Alice world. Add the coach and the cheerleader to the throw ball with user inputworld. Position the coach a few
feet behind the pin, in line with the pin and the athlete. Have the coach and cheerleader react when the ball hits
the pin. Have the coach react if he is hit by the ball.
7. Using the techniques for collision detection found in the Don't Splash the Penguin! tutorial, create a Don't
Splash the Bunny! world. Your world should start with a water template, using green circles as islands. The cir-
cles can be found in the Shapes folder in the Alice object gallery. Create a game that allows the user to move
the bunny around on an island and then j u m p from one island to another. You will need to create a j u m p method
and a triggering event. Pick an object to be the bunny's target, and create a game that requires the user to get
the bunny to the target as quickly as possible.
8. The game 23 matches is a simple game that could be turned into a video game. The game starts with 2 3 matches
laid down on the ground or on a table. Players take turns picking 1 , 2 , or 3 matches. The player who picks up the
last match wins the game. Create a version of this game using Alice. The user can play against the computer, or
one person can play against another. Remember the six Ps of programming—Proper Prior Planning Prevents Poor
Programming. Take the time to design your world before you build it.
9. Tic-tac-toe is a simple game that almost everyone knows how to play. An artificial intelligence engine for tic-
tac-toe played against the computer would have to have the logic for the game in a series of IF/ELSE instruc-
tions telling the computer what moves to make. See if you can figure out or find a set of rules for how to win
the game, and then write them as a series of IF/ELSE instructions. First, however, you will need to decide on a
numbering scheme for the squares on the board,
10. An object can be saved in one Alice world and used in another. Save the physics object with the ballistics
flight method from Tutorial 10B and then develop another simple Alice world that uses it. You don't need to
know anything about the internal math of the method to use it, but you do need to know that it takes an initial
angle and initial velocity as its parameters. You should keep your world simple; do not try to make a character
look like it is throwing something, like the athlete in Tutorial 10B does, because that could take a lot of time to
implement. The Alice local object gallery has a cannon that you could use. You might create a loop or event to
keep something moving, and try to hit it with an object fired from the cannon.
Appendix A
Acquiring and Installing the Alice Software
In this appendix, you will learn the basics of acquiring and installing Alice.
At the time this book was published, versions of Alice 2.2 were available for I B M PC com-
patible computers running the Windows operating system and Apple Macintosh computers
running OSX.
A V G A graphics card capable of high (16-bit) color and 1024 X 768 reso-
lution (A 3D video card is recommended.)
311
Appendix A
When the Alice program icon is clicked, the standard version of Alice will load and run on
your computer. This is a hardware accelerated version of Alice that will use the circuitry in
your computer's video card to render Alice on your computer screen.
The SlowAndSteadyAlice icon is for a special software rendering version of Alice that will
run code through your machine's CPU to render Alice on the screen rather than trying to
take advantage of the machine's video card. As the name implies, it is slower than the hard-
ware accelerated version of Alice, but it is more reliable, especially on machines with older
video cards. The developers of Alice recommend that you try the standard version of Alice
first, and if it does not run well, then try the slow and steady version. The standard version
of Alice should run well on almost any personal computer that is less than two years old.
The Alice software has been carefully designed so that it will not interfere with your sys-
tem's registry, DLL files, or any other parts of your system software. However, to accomplish
this, the Windows feature that allows you to run a program simply by clicking the icon for a
saved file will not work for Alice worlds. You must run Alice first and then load saved
worlds from inside Alice. You must also connect any storage devices that you want Alice to
see, such as flash ROM drives, to your system before running Alice.
The Alice software was written with the assumption that it would be stored on a computer's
C: disk drive. Instructions for changing this, such as for using Alice in a networked environ-
ment, can be found on the Alice download page at www.Alice.org.
One final tip: To make Alice easier to use, you can create a shortcut to either version of the
Alice software and place the shortcut on your desktop. To do this, copy and paste the icon
in the same Alice folder where the original resides, and then drag the new shortcut icon to
your desktop. This is an easy way to keep the original Alice program in its folder so that it
will run properly, while still being acessible from your desktop. The shortcut can also be
placed on the taskbar at the bottom of your computer screen.
Appendix B
T h e Alice M e n u s
Although Alice does not contain a menu-driven set of commands like Microsoft Word, it is
useful to be familiar with the features on the four Alice menus: File, Edit, Tools, and Help.
The menus also show shortcut keys for various functions in Alice. This appendix contains a
short summary of the options on the menus for Alice Version 2.2.
T h e File M e n u
New World: Starts a new Alice world. It will take you to the Templates tab
of the Welcome to Alice! window, as described in Chapter 1.
Open World: Opens an existing Alice world. It will take you to the Open a
world tab of the Welcome to Alice! window, allowing you to navigate the
system's directories, as described in Chapter 1.
Save World: Saves the current Alice world. If used with a world that has
not yet been saved, it will function like Save As; otherwise, it resaves the
current world without further user interaction, as described in Chapter 1.
• Save World As: Saves the current Alice world with a new name or loca-
tion. The Save World As window will appear, allowing you to select the
location and enter the name of the file in which the world will be saved,
as described in Chapter 1.
Export As a Web Page: Exports the current Alice world as a folder with an
HTML file, an a2w file, and an applet.jar file. A Save World for the Web
window will open with options for the title of the Web page, the author's
name, the size of the viewing window on the Web page, the location of the
saved files, and whether or not to include code from the world on the page.
• Export Video: This option is discussed in Chapters 1 and 9.
Export Code for Printing: Exports code from Alice methods and events to
an HTML Web page for viewing or printing. A dialog box will appear
allowing you to select which items to export and where to save the result-
ing HTML file, as described in Chapter 1.
• Import: Used to import external files into an Alice world. Most com-
monly, it is used to import objects saved from other worlds as a2c files.
Right-clicking an object's tile in the Object tree will let you save an object,
which can be imported into another world by using this option. Other
files, including sound files and graphic image files, can also be imported,
and they will show up as options on the appropriate menus.
313
314 Appendix B
Rendering: Has options for forcing software rendering that will cause
Alice to run in the slow and steady mode, show the number of frames per
second being rendered as an Alice world plays, numerically change the
World window position and size, lock the window's aspect ratio, make
sure the window is always visible, and select the rendering order for Alice
so that it will try to render a world using either DirectX or Java3D render-
ing first.
Screen Grab: Has options that affect the function of the Take Picture but-
ton on the playing world window, including which directory to use when
saving an image, the base filename for the image file, how many digits to
append to the base filename, whether to use the JPG or PNG image file for-
mat, and whether or not to show a dialog box when the Take Picture but-
ton is pressed while an Alice world is playing.
Seldom Used: Has nine check boxes that affect different aspects of Alice
and options to change the number of Clipboards available on the Alice
interface, the number of minutes to wait before reminding a user that the
current world has not been saved, and the number of backup copies of
each world to maintain. The nine radio boxes allow you to turn features of
Alice on or off, including showing the startup dialog box when Alice
launches, showing warnings when browsing the Web Gallery, opening
tabs that were previously open when a world loads, picking up tiles while
dropping and dragging, using alpha blending in picked-up tiles, saving
thumbnails with saved world files, showing world statistics on the bottom
of the Alice interface, clearing text output each time a world is played,
and enabling a special high-contrast video mode for use with projectors.
The Help Menu 315
The Tools M e n u
Text Output: Shows a copy of the text log file for this world, including
information about the version of Alice and the operating system in use, a
record indicating each time the world was started or stopped, any mes-
sages that appeared in the print zone, and any error messages that were
generated. The text in the window can be copied to the system's Clipboard
and then pasted in Microsoft Word or other programs with an option to
paste text from the Clipboard.
Error Console: Functions the same as the Text Output option.
The Help M e n u
Example Worlds: Opens the Examples tab on the Welcome to Alice! window.
The set of binary digits, or bits, that the CPU understands as an instruction set is called the
computer's machine code. Eventually, everything that a computer does must be translated into
its machine code. Each CPU, or each family of CPUs, such as the Intel Pentium family, has its
own machine code. There are as many machine codes as there are families of processing units.
When a new processor is invented and manufactured, it only understands its machine code.
Systems programmers work with these binary codes to create a new language called assem-
bly language. They do this by using machine code to build an assembler, which is a pro-
gram that translates assembly language into machine code. Assembly languages are made
up of very primitive instructions, just like machine code, but they can be written using the
following: numbers other than base two; mnemonics, or short words that sound like the
instructions they represent, such as ADD for addition or SUB for subtraction; and symbolic
names instead of numbers to refer to memory locations.
Writing sophisticated software, such as word processors and video games, is still rather dif-
ficult and very time-consuming in assembly language, so computer scientists and software
engineers build translators that can handle high-level languages, which are closer to human
languages. They are easier for people to understand, but harder to translate into a computer's
machine code. Java, JavaScript, VB.net, C, C , and Python are all examples of modern high-
+ +
level computer programming languages. COBOL, FORTAN, BASIC, and Pascal are all examples
of once-popular high-level languages that are now seldom used.
The translators that convert high-level languages into machine code fall into two categories:
compilers and interpreters. Using a compiler, a programmer ends up with two stored copies of
the program. The first, in the original high-level programming language, is called the source
code. The second stored copy of the program, which is the same program after translation into
a particular machine code, is called the object code. Even after translation into machine code,
a program may still need to be processed so that it will run on a particular computer with a
particular operating system. A program that has been translated into machine code and pre-
pared to run on a particular system is called executable code or an executable file.
317
Appendix C
A n interpreter is much simpler than a compiler. Rather than translating an entire source
code program into object code all at once, the compiler translates each instruction one at a
time and then immediately feeds it to the CPU to be processed before translating the next
instruction. The only stored copy of the program is the original source code program.
Scripting languages, such as JavaScript or Visual BASIC for Applications (VBA), often work
this way. Scripting languages are simplified high-level programming languages that allow
someone to program in a particular environment. JavaScript can be added to the H T M L
code for Web pages to provide them with some primitive data-processing capability. VBA
allows someone to program features in Microsoft Office products, such as Microsoft Word
or PowerPoint.
Interpreters are often used for teaching languages. Serious computer programming lan-
guages, such as Java and C + +
, that are used by professional programmers, are sometimes
referred to as production languages. Teaching languages are languages that are not generally
used in production environments but are instead used to teach someone the logic of com-
puter programming or the processes used in creating computer software before attempting
to teach them to use production languages. Alice is an example of a teaching language. Its
primary purpose is to be used as a tool to introduce people to computer programming.
One of the first high-level languages in existence was the F O R T R A N language, created in
the 1950s by the U.S. Government in cooperation with IBM, which, at the time, was by far
the world's largest computer company. F O R T R A N was intended to be used by scientists
and engineers working on large, primitive mainframe computers of the day—about 20 years
before the first personal computers appeared—to program mathematical formulas and
processes. In fact, the name F O R T R A N comes from the two words "formula translator."
Before FORTRAN, all software had to be created using assembly language and machine code.
Once FORTRAN appeared, people began to use it for much more than science and engineering.
The increasing use of FORTRAN in the business world led to the development of the COBOL
language in 1960. Like the name FORTRAN, COBOL is an acronym that comes from the words
"common business-oriented language." It was based on work by Grace Hopper, who rose to
become an admiral in the United States Navy before she retired more than 30 years later. It is
estimated that as of the year 2000 there were more lines of code written in COBOL than in any
other computer programming language. However, during the last five years, the use of COBOL
has declined rapidly as other programming languages and applications software, such as elec-
tronic spreadsheets, have become more common.
Computer Programming Languages
Over the years, many high-level programming languages have evolved, each with different
features that have changed the way people create and use computer software. Algol, BASIC
(Beginner's All-purpose Instruction Code), Pascal, Smalltalk, ML, LISP, Prolog, and C are
some of the most well known of these. Today, Java, C++, and VB.NET are probably the
most important languages for professional programmers to know. New languages
continue to emerge, such as the Python and Haskel languages that first appeared in the
1 9 9 0 s . The Association for Computing Machinery's Hello World! page, on the Web at
www2.latech.edu/~acm/HeIIoWorld.htin], has sample Hello World! programs in almost
2 0 0 different programming languages.
Glossary
absolute direction—A direction in relation to a scale of billboard—A picture file placed into an Alice world as a flat two-
measurement. dimensional object with length and width, but no depth. Once
act—A dramatic component of a story. The most common placed in an Alice world, the image from the picture file will be
arrangement for a screenplay is a three-act structure. Acts are seen on both the front and back of the billboard. Billboards are
a collection of smaller units called scenes. In movies, scenes objects that can be manipulated with primitive methods, like
are composed of individual shots. move, turn, and roll, as well as with user-created methods.
algorithm—A step-by-step process. binary branching—A branching routine in an algorithm in which
American Standard Code for Information Interchange the path or flow of the algorithm's sequential logic splits into
(ASCII)—An 8-bit code used to represent characters in a exactly two possible paths.
computer. It includes letters, numeric digits, and some "hidden"binary bypass—A binary branching routine in which an instruction
control characters, such as the enter key and the escape key. or set of instructions is either executed or bypassed.
Each character is given a numeric value, and the binary equiva- binary choice—A binary branching routine in which one of two
lents of those numeric values are used to store characters in instructions (or one of two sets of instructions), but not both, is
the computer. executed.
AND—A binary Boolean operation. Boolean means that it uses onl binary
y tree—A data structure in which each node on the tree
true and false values, and binary means that it needs two holds an item of data along with a left pointer and a right
operands. When two values are combined using the AND oper- pointer. The pointers are lined up so that the structure forms an
ation, the result is true only if both values are true. Otherwise, upside down tree, with a single node at the top, called the root
the result is false. node, and branches increasing on the left and right as you go
Application Program Interface (API)—Software that provides down the tree.
expanded capabilities for computer programmers. In Java, for Boolean algebra—A formal language for a system of Boolean
example, the Abstract Windowing Toolkit (AWT) and Swing are logic dealing with true and false values.
two APIs that provide programmers with the ability to create Boolean function—A function that returns a true or false value
their own GUIs for Java programs. instead of a numeric value.
array—A set of indexed variables, each containing objects of the Boolean logic—A system of logic dealing with true and false val-
same data type. An array can be thought of as a set of num- ues. It was first described by George Boole in 1854. The condi-
bered boxes each containing a value of a particular data type. tions that exist in branching and looping routines are aformof
Array Visualization Object—A special object in Alice used to Boolean logic, which is the basis for all modern digital elec-
show an array in an Alice world, rather than just creating it in tronic technology.
the memory of the computer. The name of the object in Alice isbranch—A path or flow of sequential logic in an algorithm.
ArrayVisualization. branching routine—A set of instructions in an algorithm in which
Artificial Intelligence (Al)—A branch of computer science devoted the path or flow of sequential logic splits into two or more
to developing software that can mimic human intelligence in a paths. Branching routines are also known as selection
computer, especially human perception and decision making. sequences or selection structures.
aspect ratio—The ratio of an image's width to its height. Aspectbreakpoint—A spot in a computer program just before or just
ratios in Alice include 4/3 (1.33), 1.85, and 2.35. The 4/3 ratio after some action occurs. Breakpoints are often used in
is the standard television ratio, while the other two are wider debugging.
cinema formats. Newer HD televisions have a 16/9 ratio. CamelCase—The practice of writing compound names without
ballistics—The science of determining the paths of projectiles, using blank spaces, but capitalizing the first letter of each
which are objects flying through the air after they have been name that forms the compound name, like the name
thrown or launched by some force. Projectiles include balls in a CamelCase itself. The very first letter in a CamelCase name
sporting event, bullets, arrows, darts, horseshoes, or any object may or may not be capitalized, such as CheshireCat or
that is flying through the air without some power of its own. cheshireCat. CamelCase is used with most programming lan-
base case—The condition that stops a recursive algorithm from guages and is recommended by many software developers,
continuing, also called the base condition. such as Microsoft.
base condition—The condition that stops a recursive algorithm Cartesian coordinates—A system of quantification for two dimen-
from continuing, also called the base case. sions developed by the French mathematician Rene Descartes.
BDE event format—An event format in which the event's tile has Cartesian coordinates have an X-axis, and a Y-axis. The location
places for three different event handlers. BDE stands for of each point is referred to by an ordered pair of the form (x, y),
"Begins, During, and End." You can tell the world what methods in which x represents the point's location along the X-axis and y
to run when the event begins, during the time that the event is represents its location along the Y-axis.
occurring, and when the event ends.
321
Glossary
CGI—Computer generated imagery, which includes both still dialog balloon—A box with rounded corners that shows words
images and movie frames generated by a computer. Alice is that are supposed to have been spoken by an object, much like
completely CGI. text appears in cartoons in a newspaper or magazine. Text cre-
class—A group of objects with the same properties and the same ated by the say method appears in a dialog balloon.
methods. dimension—A value on a continuous scale applied to some prop-
collate—To put a set of items in order according to a particular erty in a process called quantification. A dimension is a way of
criteria. measuring something.
collating sequence—A list that shows the correct order to be documentary—An expository movie that teaches a lesson or pres-
used when collating a set of items, The English language ents an opinion, much like an essay, with a thesis, points of
alphabet is commonly used as a collating sequence. The ASCII evidence, and a conclusion.
code and Unicode are often used as collating sequences in dummy object—An invisible object, also called a dummy, that
computers. occupies a single point in an Alice world. Alice has commands
collision detection—The act of detecting when objects in a virtual to drop a dummy where a camera is, and to drop a dummy
world collide with one another. Often this is done by detecting where an object is. Dummy objects have both a location and a
when the parts that make up an object overlap or occupy the point of view and can be used to mark key spots and program
same space or are about to do so. the camera or other objects to move to those spots as needed.
comedy sketch—The visual equivalent of telling or acting out a encapsulation—The concealment of the details of a method (or
joke, like a skit that Boy Scouts or Girl Scouts might act out an object) from the user. Programmers may use an encapsu-
around a campfire. lated method, but cannot see its inner workings. Alice primitive
methods, such as move and turn, are examples of encapsu-
command driven interface—A user interface through which peo-
lated methods.
ple control a computer by typing in commands. Most modern
software, such as word processing, electronic spreadsheets, Euclidean 3-space—A space measured in three dimensions by
Internet browsers, and computer games, use graphical user an X-axis, a Y-axis and a Z-axis that are each straight lines per-
interfaces (GUIs), but older computers had only command- pendicular to one another. The physical world around us can be
driven interfaces, in which it was often necessary to write or thought of as a Euclidean 3-space.
run a computer program in order to complete tasks that event—An event trigger, and the name of a method, called an
involved more than a few steps. event handler. Whenever the event trigger occurs, the event
commercial advertisement—Any message that attempts to con- handler is called into action.
vince someone about the merits of a particular product or serv- event handler—A method that is activated when an event trigger
ice, or to expose them to something in a positive and occurs.
memorable way. event listener—A combination of hardware and software that
computer program—A step-by-step set of instructions telling a repeatedly checks the computer system for the event trigger.
computer how to perform a specific task. Every computer pro- event trigger—Any activity or condition selected by the program-
gram is an algorithm. mer to initiate an event, such as someone pressing the enter
computer programming language—A particular set of instruc- key, or a bank account balance going below zero. When an
tions for programming a computer, along with the grammar and event listener detects an event trigger, an event handler is
syntax for using those instructions. called into action.
concurrency—The process of running multiple threads of an algo- event-driven programming—The development of software that
rithm at the same time. A thread is part of an algorithm that uses events to provide controls in computer systems. The use
may be executed at the same time as other parts of an algo- of a GUI on a modern personal computer requires event-driven
rithm, or at the same time as another copy of itself. Algorithms programming.
that allow concurrency are known as parallel algorithms. exponential recursion—Recursion in which a method calls itself
conditional recursion—Recursion that is not infinite. more than once in each pass through the recursive method. As
control variable—A variable whose value controls whether or not a result, the number of copies of the world that are running
a particular path in a selection sequence or in a repetition grows exponentially.
sequence will be executed. fade—A transition that occurs when the viewer's image lightens or
counter—The control variable for a count-controlled loop. A darkens to or from a solid color. For example, a script may con-
counter needs to have an initial value, a final value, and an tain the direction slow fade to black at the end of a scene,
increment. meaning that the image the viewer sees would slowly fade to
black, as if someone were slowly turning down the lights on a
count-controlled loop—An element of logical structure in an
scene. Fades can be to or from any color, but black is the most
algorithm in which a process is repeated a specific number
common, followed by white.
of times.
data structure—A scheme for organizing data in the memory of a final value—The last value processed by a loop.
computer. flowchart—A diagram showing the structure of an algorithm.
Flowcharts are designed to show the possible paths through an
algorithm.
Glossary
font—A specification for a set of characters that includes typeface,Integrated Development Environment (IDE)—A computer pro-
size, style, and weight of the characters. Although the terms gram that is used to write other computer programs.
typeface and font are not synonymous, they are often used integration test—A test of a software method that checks to see
interchangeably. For example, Times New Roman is a typeface, if the method works when it is placed into a larger program in
whereas Times New Roman, 10 point, italics, bold is a com- combination with other methods.
plete specification for a font.
iterate a list—To go through the set of items in the list one at
frame (n.)—Each still image in a movie. a time.
frame (v.)—To position the camera so that a particular item fills iteration—Each instance or occurrence of the body of instructions
the screen. in a loop. The term iteration is also used to refer generally to
frame rate—The number of frames per second (fps) in a movie. looping as opposed to recursion.
The frame rate for films in a movie theatre is 24 fps, while thiterative
e process—A process that uses a loop to repeat a set of
frame for broadcast television is roughly 30 fps. Anything instructions.
slower than around 16 fps may look a bit choppy. jump cut—A sudden transition from one shot to another. The last
function—A method that returns a value, such as the distance frame of one shot is followed immediately by the first frame of
between two objects. the following shot, without any transition effects. A jump cut,
game engine—A software tool that allows developers to assemble sometimes called simply a cut, is the most sudden and most
video games from existing objects and methods, much like the commonly used transition from one shot to another.
way a person can build an Alice world from existing objects alinearnd recursion—Recursion in which a method calls itself only
methods. once each time through the method. Consequently, the number
Graphical User Interface (GUI)—A user interface that has icons of copies of the method running grows linearly.
on the computer screen and a mouse to confrol a pointer thatlinear sequence—The simplest element of logical structure in an
can be used to operate the computer by manipulating the algorithm, in which one instruction follows another as if in a
icons. Most modern software, such as word processing, elec- straight line. Linear sequences must have clearly stated entry
tronic spreadsheets, Internet browsers, and computer games, and exit conditions, and they need to be complete, correct, and
depends on the use of a GUI. in the proper order.
graphics engine—A set of encapsulated software components list—An ordered set of data. In Alice, a list may be implemented as
that perform the necessary math and render objects for video an object or as a variable.
games, simulations, and other software. Graphics engines often
logical comparison operators—Operators that compare two val-
provide a software tool kit which includes objects and functions
ues according to either their numeric value or their value
that software developers can use to work with graphics in two-
according to a collating sequence, depending on the data type
dimensional or three-dimensional environments, without doing
of the values. They return a value of true or false.
all the math.
loop—An element of logical structure in an algorithm in which the
hardcode—To put a specific value in a program instead of a vari- path of logic branches backward to a previous instruction,
able or parameter. repeating part of the algorithm. A loop is also called a repetition
HSB—A color model for computer graphics in which the color of a sequence.
pixel is expressed in terms of its hue, saturation, and brilliance.
Massive Multiplayer Online Role-Playing Game (MMORPG)—A
Human Computer Interaction (HCI)—A specialized area of com- game played online with hundreds or thousands of people,
puting dealing with the development of user interface hardware each playing the role of a character in a virtual environment at
and software. the same time.
IDE—See Integrated Development Environnment matrix—A matrix is an array, most commonly a two-dimensional
increment—The amount by which something is increased, such array of numeric values.
as the amount by which a counter in a loop in increased eacmethod—A
h program that manipulates the properties of an object.
time through the loop. method header—The lines of text at the top of the method that
index value—A value, usually an integer, used to identify either an provide information about how the method works, such as the
element in an array, or an iteration of a loop. full name of the method and the name and type of any param-
infinite recursion—Recursion that continues without ending on its eters or variables used in the method.
own. It must be stopped by some external source, such as method parameter—A piece of information that you must give to
interrupting a program or turning off a computer. a method whenever you run the method.
initial value—The starting value for a counter in a loop. module—A unit of software organization that is logically independ-
instance—A copy of an object from a particular class. ent, performs a well-defined single task, and is compatible with
instantiation—The act of adding an instance of an object class to other modules.
an Alice world.
Glossary
modular development—The process by which the parts, or mod- orientation—The direction an object is facing. Location and orien-
ules, that make up a complete solution to a problem are devel- tation together are known as the point of view of an object.
oped individually and then combined to form that complete overhead—The extra CPU time and space in a computer's mem-
solution. Modular development is often used together with top- ory needed to manage a method as it runs.
down design in which one concept or big idea, is broken down
pan—To turn a camera left or right without moving the position of
into several parts, and then those parts are further broken
the camera, although it is possible that you could pan and
down. The end result is a collection of small solutions, called
move at the same time.
modules, which collectively contain the overall solution to the
original problem. parallel algorithm—An algorithm in which multiple threads of
sequential logic may be executed at the same time.
movie—A flat two-dimensional picture that moves. When we view
a movie we are watching a rapidly changing series of still parameter—A variable whose value is passed from one method to
images, each slightly different from the previous image. Instead another. Parameters have data types and they are stored in the
of seeing many still images, we experience them as a moving memory of the computer, just like properties.
picture. personification—The process of giving human qualities such as
multiple branching—The occurrence of a branching routine in an feelings, thoughts, speech, or human-like movements to inani-
algorithm where the path or flow of the algorithm's sequential mate objects.
physics engine—A set of software components addressing the
logic splits into more than two possible paths from a single point.
node—An organizational unit in a data structure, such as a graph physics of moving objects, including the effects of gravity, fric-
or a tree, with a data element and one or more pointers to tion, objects bumping into one another, wind resistance and
other nodes. In object-oriented programming, each node in a fluid dynamics that need to be addressed so that game and
data structure is an object, and the data element is an object orsimulation objects will act like objects in the real world.
a primitive data type. plot—A storyline or plan for the dramatic flow of the movie. It is
NOT—A unary Boolean operation, Boolean means that it uses only tied to the visual flow of the movie—how the movie progresses
true and false values, and unary means that it works on only from scene to scene.
one operand. It simply reverses the true or false value of its point of view—A property marking an object's location and orien-
operand. In other words, NOT true yields false; NOT false tation. Each Alice object has a point of view property.
yields true. postproduction—The final phase of the moviemaking process.
object—Something that can be represented by data in the com- Postproduction includes all of the tasks that take place after a
puter's memory and manipulated by computer programs; a col- movie is recorded, such as editing, adding titles, and packaging
lection of properties and the methods used to manipulate those the final product
properties. posttest loop—A loop in which the test to determine whether or
object-relative direction—A direction from the point of view of a not to continue executing the loop comes after the body of
particular object. It is determined by the object's position and instructions that are to be repeated. The body of instructions in
orientation. In Alice's Euclidean 3-space, there are six major a posttest loop must be executed at least once, since the test
object-relative directions—forward, backward, left, right, up, occurs after they are executed.
and down. preproduction—The first phase of the moviemaking process.
object-relative position—The position of one object in relation to Preproduction is the planning and preparation that is necessary
the position and orientation of another object. In Alice's before production can begin. It includes developing ideas for
Euclidean 3-space, there are six major object-relative posi- the movie, writing the script, casting, scheduling production,
tions—in front of, behind, to the left of, to the right of, above, and gathering all of the resources for production—including
and below. people, equipment, and facilities. It usually takes much longer
than production.
off-camera—A term used to describe the location of an object in
an Alice world that cannot be seen on the screen with the cam- pretest loop—A loop in which the test to determine whether or
era in its current position. not to continue executing the loop comes before the body of
object-oriented programming (OOP)—A modern approach to instructions that are to be repeated. It is possible that the body
computer programming focusing on objects as collections of of instructions in a pretest loop may not be executed, since the
properties and the methods that are used to manipulate those test occurs before they are to be executed.
properties. primitive method—A built-in, predefined method that is part of
OR—A binary Boolean operation. Boolean means that it uses only each Alice object. Primitive methods provide simple basic
true and false values, and binary means that it needs two behaviors, such as move, turn, and roll, and cannot be edited
operands. When two values are combined using the OR opera- like user-defined methods can be.
tion, if either value is true, then the result is true. Otherwise, thproduction—The
e second phase of the moviemaking process.
result is false. Production is the heart of the moviemaking process, the actual
ordered pair—Any pair of values of the form (x, y) in which one recording of the movie. In traditional filmmaking, it is when the
dimension is always listed first, and another dimension is cameras are rolling and action is captured on film. The produc-
always listed second. tion phase for an animated movie includes creating the anima-
tions and recording them.
Glossary
property—Data that describes an object in some way. shot—A particular view of something from a specific camera,
proximity function—A function that returns a value based on the set up in a specific way. Each scene in a movie is a collection
distance between two objects. A Boolean proximity function of shots.
returns a true or false value. A numeric proximity function shot list—A list of the shots needed for each scene in a movie,
returns a numeric value. describing the kind of shot, the characters involved, roughly
pseudocode—A structured language used to describe algorithms. what happens in the shot, and the length of time the shot stays
The term pseudocode comes from the fact that it looks some- on the screen. Other details, such as lighting and special
thing like the code in a computer programming language, but effects, could also be included.
not quite. side effect—An unintended result produced by running a method.
quantification—The process of creating a dimension by assigning Typically, side effects are caused by two events or methods that
a value on a continuous scale to some property. overlap each other.
queue—A simple linear data structure with a beginning and end, slice-of-life vignette—A short movie showing an everyday event,
called the front and back of the queue, in which data items such as a boy riding by on a bicycle, or a flock of geese flying
enter the back of the queue and leave from the front of the overhead. Slice-of-life vignettes might tell a story, but they also
queue in the same order in which they entered the queue. The might just be intended to show the subject in action, without
front and back of the queue are also referred to as the queue's really telling a story. They are often used to demonstrate that
head and tail. A queue is a first in first out, or FIFO, data the moviemaker has mastered some new moviemaking tech-
structure. niques or technology.
recursion—A design or pattern for part of something that repeats software development cycle—An engineering process in which
the structure of the whole thing itself. In computer program- software developers (programmers and software engineers)
ming, recursion occurs when an algorithm calls itself. design, code, test, and debug new software.
recursive method—A method that calls itself. state of an object—The values stored in the properties of the
object at any one time.
repetition sequence—An element of logical structure in an algo-
rithm in which the path of logic branches backward to a previ- storyboard—A collection of rough sketches of particular shots
ous instruction, repeating part of the algorithm. A repetition showing both the visual flow of a movie from scene to scene
sequence is also called a loop. and the progression of the movie's plot. They are called story-
boards because the sketches for the shots in a single scene
reusable code—Software modules that are solutions to smaller
are usually pasted on a single large board so they can be
problems and which can be applied elsewhere. Most of the
viewed together. Storyboards can be an important tool in devel-
software on a computer system is filled with layers of reusable
oping a movie.
code because computer programs contain many small tasks
that need to be repeated, such as getting a user's name and structured language—Another term for pseudocode; structured
password. Object-oriented programming and modular develop- programming languages are programming languages with
ment encourage the use of reusable code. built-in language for logical structures, like the WHILE com-
mand in Alice).
RGB—A color model for computer graphics in which the color of a
pixel is expressed in terms of its red, green, and blue light tessellation—A repeated pattern of an image on the surface of
components. an object.
root node—A node at the top of a tree, to which no pointers in ttest he for correctness—A test to determine whether or not a pro-
tree are directed. gram performs correctly according to its original specifications.
It is not concerned with the program's time or space efficiency,
scene—A part of a movie that takes place in a single location at a
but simply its correctness.
particular time. It is a collection of individual shots. A movie is a
sequence of scenes, grouped into acts. testing shell—A short method created to simulate the environ-
ment in which a newly developed method will be run. This is
screenplay—The video equivalent of a play in a theatre. A screen-
especially important if the method being tested will be receiving
play unfolds over a series of scenes, and the plot determines
values from other methods, or passing values on to other meth-
the structure of the story. It could be fictional, or it could tell a
ods. The testing shell can be written to pass known values into
true story. The word screenplay is also used to refer to the
the method being tested, and then the output can be captured
script for a screenplay.
and examined for correctness. A testing shell is also known as
script—A scene-by-scene description of a movie, with dialog and a testing hull.
descriptions of the critical action. It is the primary design docu-
text—The visual use of words (that is, the written language) in
ment for a movie.
computer software,
selection sequence—An element of logical structure in an algo-
rithm in which the path or flow of sequential logic splits into thought bubble—A cloud-like box appearing in an Alice world
two or more paths. showing words that are supposed to represent the thoughts of
sentinel loop—An element of logical structure in an algorithm in an object. Text created by the thought method appears in a
which a process is repeated until a condition or marker, called thought bubble.
a sentinel, is encountered.
Index
Please note that bolded numbers indicate where a key term is defined in the text.
pseudocode, 1 0 4 - 1 0 5
recursive, 1 9 0 , 1 9 1 - 1 9 3
About Alice submenu, 10, 3 1 5
sequential, 98
abruptly parameter, 85, 86, 89
simple count-controlled loop, 1 1 8 - 1 1 9
absolute direction, 66
steps in, 9 8 - 9 9
Abstract Windowing Toolkit. See AWT (Abstract Windowing
stopping, 196
Toolkit)
terminators, 100
actions, undoing and redoing, 9 , 4 5
true or false conditions, 100
acts, 2 5 2
Alice
actual parameters, 5 7
acquiring, 311
Add 3D Text submenu, 1 7 4 - 1 7 5 , 314
exiting, 12
Addie, the entire Addie instruction, 222
general information about, 10
Add instance to world button, 16, 40, 46
IDE (Integrated Development Environment), 4
ADD OBJECTS button, 14, 46, 84, 8 8 , 1 3 8 , 1 4 3 , 1 4 6 , 1 7 5 ,
installing, 4, 3 1 1 - 3 1 2
184, 198, 262
menus, 3 1 3 - 3 1 5
Adobe Premiere, 248, 266
most recent versions, 6
adventure games, 272
objects, 3
aerial shot, 255
rapid feedback, 4
aging, 280
rendering on-screen, 312
Al (Artificial Intelligence), 2 7 7
settings, 10
aircraft, defining, 197
standard version, 312
Airport class information window, 198
syntax, 4
airport object, 1 9 8 - 1 9 9 , 203
tutorials, 5
airport setup Alice world, 1 9 8 - 2 0 0
virtual worlds, 3
Airport tile, 198
visualization, 4
[[A] joined with [FJ]] string function, 2 8 6 - 2 8 8
Alice billboards, 290
Algol, 319
Alice error message box, 10
algorithms, 2, 98
Alice icon, 311
base case, 1 9 6
Alice interface, 4 - 1 0 , 1 3 , 1 9
base condition, 196
Alice world open, 7
branching routines, 99
buttons, 9 , 1 1
concurrency, 116
Details area, 8
conditional recursion, 1 9 6
drag-and-drop, 37
drawing Sierpinski gasket, 1 9 2 - 1 9 3
Editor area, 8
elements of logical structure, 99
Events area, 8 - 9
entry and exit points, 100
icons, 9
exponentially recursive, 195
lake Skater Alice world, 7
flowcharts, 9 9 - 1 0 0
main work areas, 7 - 9
IF/ELSE instruction, 196
menus, 9 - 1 0
infinite recursion, 196
Object tree, 8
linear sequences, 9 9 , 1 0 1 - 1 0 2
resizing, 71
logical structures, 8
returning to, 12
looping, 9 9 , 1 0 5
World window, 7
printing numbers 1 to 1 0 , 1 0 5
327
Index 329
c cheshireCat tile, 4 6 - 4 8 , 5 2 - 5 3
cheshireCat turn to face method, 4 8
C, 20, 317, 319 Chicken object, 184
C + + , 3, 3 7 , 3 1 7 - 3 1 9 Chicken play sound tile, 184
CamelCase, 4 6 chicken sound, 184
camera, 7 , 1 9 , 9 0 , 2 6 3 - 2 6 4 chicken tile, 16
arrow keys moving, 83 Choose a Font window, 176
building controls with events, 8 0 - 8 3 Class Bunny icon, 16
initial point of view, 2 6 2 - 2 9 3 classes, 1 5 - 1 7
instructions to move while world is playing, 2 6 4 Class Penguin tile, 39
mouse moving, 8 2 - 8 3 Clipboard icon, 9
moving, 8 3 , 1 4 3 close-up, 255
panning, 8 1 - 8 3 closing Alice worlds, 22
placement, 2 5 8 - 2 5 9 COBOL, 317, 318
positioning, 199 code
recording positions for multi-shot scene, 2 6 1 - 2 6 6 author, 23
simulating multiple, 2 5 9 - 2 6 1 printing from Alice world, 2 2 - 2 3
starting position, 291 reusing, 197
text facing, 177 coding
tilt control, 81 jump methods, 5 0 - 5 2
zooming, 81 methods, 37
camera command, 4 3 recursion, 2 0 0 - 2 0 4
camera get a good look at method, 44 collate, 130
camera parameter, 292 collating sequence, 1 3 0
camera point at method, 43 Collection Editor window, 228
camera point at method tile, 9 0 , 1 4 1 collisionCheck method, 292, 2 9 4 - 2 9 6 , 2 9 8 - 2 9 9
camera set point of view to instruction tile, 2 6 4 - 2 6 5 collision detection, 2 8 2 , 2 9 2 - 2 9 5
Index 331
collision detection event handler, 2 9 2 - 2 9 4 create new variable button, 136, 223, 285
color create new variable dialog box, 2 2 3 - 2 2 4
background, 1 6 6 - 1 6 7 Custom Color window, 1 6 8 - 1 6 9
brightness, 169 Custom Number dialog box, 177
saturation, 169 cut, 179
text, 1 6 6 - 1 6 7 , 1 7 7
color menu, 166 D
color property, 177 Dance Dance Revolution, 273
Colossal Cave, 272 dance routine for ballerinas, 2 2 4 - 2 2 7
comedy sketch, 2 5 3 Daphne, the entire Daphne option, 222
command-driven interface, 64, 278 data
commercial advertisement, 2 5 3 organizing, 216
comparing values, 129 queue, 214
Boolean function, 1 3 1 - 1 3 4 sorting and binary trees, 215
OR operation, 130 data communications programmers, 277
string comparisons, 1 3 0 - 1 3 1 data structures, 2 1 4
compilers, 317 arrays, 2 1 9 - 2 2 0
composers, 276 binary tree, 2 1 4 - 2 1 5
computer generated imagery. See CGI (computer generated lists, 2 1 7 - 2 1 8
imagery) need for different, 2 1 4 - 2 1 7
computer programming languages, 3 organizing data, 216
computer programs, 2 queue, 214, 2 1 5 - 2 1 6
computers, 317 data types, 5 4 - 5 5
computer software, modular development of, 34 DaVinci, Leonardo, 180
concurrent execution, 110 debugging
conditional, 99 breakpoint, 1 6 0
conditional recursion, 1 9 6 displaying value of variable, 160
control tiles, 19, 37 methods, 3 7 - 3 9
control variable, 1 0 6 , 1 1 9 software, 53
copyrighted material, 1 8 2 - 1 8 3 decision diamond, 99
count command, 120 default events, 1 4 , 1 8 , 23
count + command, 120 default methods, 1 4 , 1 8 , 23
count-controlled loops, 1 0 8 - 1 0 9 , 1 1 6 - 1 1 8 , 239 default string command, 287
count control variable, 1 1 9 delete command, 9 , 1 7 , 1 2 0 , 1 4 8 , 206
counter, 1 0 8 - 1 0 9 Descartes, Rene, 67
count set value to count tile, 120 designing methods, 4 9 - 5 0
COUNT variable, 107 Details area, 8 , 1 4 6
count variable tile, 120 functions tab, 1 1 2 , 1 1 3 , 1 3 6 , 1 4 2 , 1 4 5 , 2 0 1 , 2 2 5 - 2 2 6 ,
CPU (central processing unit), 317 293, 297, 299
Create 3D Text tile, 175 methods tab, 1 8 - 1 9 , 40, 50, 5 2 - 5 3 , 55, 7 2 - 7 3 , 7 7 , 1 1 9 ,
create new event button, 7 5 - 7 6 , 8 2 - 8 3 , 8 9 - 9 0 , 1 4 0 , 139-142,145, 148,165,172,178, 201-204, 221,
148, 292 2 2 4 - 2 2 6 , 230, 232, 235, 237, 239, 260, 264, 288,
create new method button, 4 1 , 5 0 , 1 3 9 , 1 4 5 , 292 2 9 4 - 2 9 5 , 297, 304
create new method dialog box, 1 3 9 , 1 4 5 properties tab, 1 7 5 - 1 7 6 , 1 7 8 - 1 7 9 , 1 8 1 , 2 2 3 , 2 2 8 ,
create new parameter button, 148, 3 0 4 - 3 0 5 230, 298
Create New Parameter dialog box, 55, 232 determinant set value to random number tile, 136
Index
GIF (Graphics Interchange Format) files, 162 howstuffworks.com Web site, 128
Gone with the Wind, 254 HSB (Hue, Saturation, and Brightness) color values, 167,
go to math class, 105 168-169
Grand Theft Auto games, 282 HTML files, 23
Graphical User Interface. See GUI (Graphical User Interface) human-computer interaction. See HCI (human-computer
graphic artists, 2 7 5 - 2 7 6 interaction)
graphics, 2 8 0 - 2 8 1 human-computer interaction programmers. See HCI
graphics APIs, 281 (human-computer interaction) programmers
graphics engines, 2 8 0 - 2 8 1
graphics-manipulation programs, 163
I
graphics programmers, 277 IBM flowcharting template, 100
grass background, 198 IceSkater object, 8
grass template, 46, 7 1 , 8 4 , 1 8 0 , 1 8 4 icons, 9
grass thumbnail, 13 IDE (Integrated Development Environment), 4
ground tile, 1 3 , 1 8 1 IF (condition) THEN (instruction A) ELSE (instruction B), 105
guesses! string, 288 IF/ELSE instruction, 112, 2 0 1 , 2 0 5 - 2 0 6 , 2 9 6 - 2 9 7
GUI events, 278 algorithms, 196
GUI (Graphical User Interface), 64, 278 aliceLiddell.jump tile, 114
Guitar Hero, 273 condition, 112
nested, 137
H IF/ELSE structure, instructions inside, 2 0 2 - 2 0 3
Halo, 273 If/Else tile, 1 1 2 - 1 1 4
Hamlet (Shakespeare), 252 IF instruction and Boolean functions, 132
hardcode, 143 IF/THEN instruction, 1 0 4 - 1 0 5 , 1 1 0
Haskel, 319 importing
HCI (human-computer interaction), 2 7 6 sound clips, 183
HCI (human-computer interaction) programmers, 275, sound files, 164
276-277 Import submenu, 3 1 3
head and shoulders shot, 255 increment, 1 0 8 - 1 0 9
height parameter, 5 4 - 5 7 increment world.game.score by 1 instruction, 2 8 6
"Hello, Dr. Kernighan!" string, 20 index, 108
Hello, World! program, 1 2 - 2 0 , 1 5 6 index values, 219
programming languages, 319 infinite recursion, 1 9 6
saving code as HTML files, 2 2 - 2 3 information
Hello, World! string, 20 displaying, 1 7 1 - 1 7 4
hello method, 225 searching quickly, 215
hello world Alice world, 165 Information window, 40
playing, 2 4 initialization, 1 0 6 , 1 2 0
recording as movie file, 2 3 - 2 5 initial value, 1 0 8
hello world world, 2 2 installing Alice, 3 1 1 - 3 1 2
Help menu, 10 instances, 16
submenus, 315 instantiation, 16
high-level programming languages, 317 instructions and manipulating lists, 217
History in Film Web site, 254 instruction tiles, 9 , 1 8 3
Holtrop and Mennen Algorithm, 98 instruction zone, 72
Hopper, Grace, 318
Index 335
location, 65 matrix, 2 2 0
logical comparison operators, 1 3 0 matrix algebra, 2 1 9
logical predicative, 99 Maya, 275
logical structure, 9 8 - 1 0 0 maze games, 273
logic tiles, 19, 37 menus, 9 - 1 0 , 3 1 3 - 3 1 5
long shot, 254 message command, 288
Looney Tunes cartoons, 158 messages, displaying, 1 5 9 - 1
looping, 8 message string variable, 286
looping routines, 128 message variable tile, 2 8 7
comparing values, 1 2 9 - 1 3 4 method header, 51
LOOP instruction, 1 0 9 , 1 1 6 , 1 1 8 , 230 method parameter, 19
loops, 9 9 , 1 0 5 methods, 2, 8, 98
bubbleSort method, 239 assembling, 8
control variable, 1 0 6 branching, 1 1 0 - 1 1 6
count-controlled loops, 1 0 8 - 1 0 9 coding, 37
index, 1 0 8 copying, 9
marching routine, 230 creation, 4 5 - 5 4
posttest loops, 1 0 7 - 1 0 9 debugging, 3 7 - 3 9
pretest loops, 1 0 6 - 1 0 9 default, 1 4 , 1 8 , 23
sentinel loops, 1 0 8 - 1 0 9 designing, 36, 4 9 - 5 0
sentinel sailing, 1 4 2 - 1 5 0 editing, 8
Loop tile, 117 efficiency, 38
deleting, 120 encapsulation, 3 9
Love Story (Segal), 252 errors and, 54
low-angle shot, 255 exponential recursion, 195
Lumiere brothers, 247 instruction zone, 5 1 - 5 2
IWl integration tests, 38
•VI linear recursion, 195
machine code, 317, 318 name of, 18
Macintosh, 311 overhead, 194
Mac version of Alice system requirements, 311 parameters, 5 4 - 5 7
Magic Flowers file, 261 performing simple tasks, 35
Make Billboard submenu, 314 predefined, 39
make copy command, 9, 231 primitive, 3 9 - 4 5
marching Boolean variable, 228, 2 3 0 - 2 3 1 recursive, 191
marching routine creation, 2 2 9 - 2 3 1 reusing, 35
Mardi, the entire Mardi option, 222 specifications, 4 9 , 1 9 7
marieThreeQuarters tile, 263, 265 specific task for, 197
Mario Brothers, 273 target parameter, 197
Massive Multiplayer Online Role-Playing Game. See testing, 3 7 - 3 9
MMORPG (Massive Multiplayer Online Role-Playing Game) tiles, 37
math command, 120 true or false used, 112
mathematics undesirable side effects, 38
Boolean logic, 128 unit tests, 38
comparison functions, 1 3 3 - 1 3 4 user-created, 4 5 - 5 4
index values for array elements, 219
Index 337
encapsulation, 3 9
finding lost object, 4 3 - 4 5
listing, 4 1 - 4 2 random number function, 136
print determinant, 173 random numbers, 1 3 4 - 1 3 7
printing rapid feedback, 4
code from Alice world, 2 2 - 2 3 react method, 1 4 2 , 1 7 2 - 1 7 3
numbers 1 to 1 0 , 1 0 5 recording
programs infinite, 1 9 6
Key F e a t u r e s
Charles W. Herbert has been teaching Computer Science and Computer Information
Systems at Community College of Philadelphia since 1984, where he has served
as the Chair of the CIS Department, Director of Computer Science, and Director of
Technical Education. He has worked extensively as a professional programmer. Using
his background in curriculum development, he is currently a Principal Investigator for
an NSF funded team exploring the use of virtual reality programming in community
college computing courses. He is also the co-author of Alice 2.0: Introductory
Concepts and Techniques.
ISBN-13: 17fi-0-S3a-474kb-3
ISBN-ID: Q-S3fl-M7flbb-7
; 4 COURSE T E C H N O L O G Y
t% CENGAGE Learning-
To learn m o r e a b o u t C o u r s e Technology, v i s i t w w w . c e n g a g e . c o m / c o u r s e t e c h n o l o g y
To learn m o r e a b o u t C e n g a g e Learning, visit w w w . c e n g a g e . c o m
Purchase any o f o u r p r o d u c t s at y o u r local c o l l e g e s t o r e or at o u r
9 '780538"478663'
preferred online store www.cengagebrain.com