24
CHAPTER 1 Objects Objects 1 CHAPTER OBJECTIVES In this chapter you will: Be introduced to Alice and Java and how they’re used in this book. Create virtual worlds in Alice. Call methods on objects to make them behave in particular ways (such as moving and turning). Explore the set of methods that are available to all Alice objects. Set and modify the properties of an object. Create new objects from predefined classes. Cause multiple animation actions to occur at the same time. Explore composite objects (which are made up of other objects) and interact with a composite’s individual parts. W elcome to Programming with Alice and Java. If you’re concerned at all about venturing into the world of computer programming, don’t be. This book is designed to teach programming with intuitive and engaging techniques. And we use two of today’s most exciting technologies: Alice, in which you build your own virtual worlds, and Java, the most popular programming language in use today. Jump on in—the water’s warm! 6184_LEWI_CH01_p001-024.qxd 1/17/08 6:40 PM Page 1

Objects - Pearson...Not only will we examine the code that makes the objects in ThunkIt do what they do, but you’ll create game objects of your own and then design levels of the

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Objects - Pearson...Not only will we examine the code that makes the objects in ThunkIt do what they do, but you’ll create game objects of your own and then design levels of the

C H A P T E R

1

ObjectsObjects

1

C H A P T E R O B J E C T I V E S

In this chapter you will:

Be introduced to Alice and Java and how they’re used in this book.

Create virtual worlds in Alice.

Call methods on objects to make them behave in particular ways (such asmoving and turning).

Explore the set of methods that are available to all Alice objects.

Set and modify the properties of an object.

Create new objects from predefined classes.

Cause multiple animation actions to occur at the same time.

Explore composite objects (which are made up of other objects) andinteract with a composite’s individual parts.

Welcome to Programming with Alice and Java. If you’re

concerned at all about venturing into the world of computer

programming, don’t be. This book is designed to teach

programming with intuitive and engaging techniques. And we use

two of today’s most exciting technologies: Alice, in which you build

your own virtual worlds, and Java, the most popular programming

language in use today. Jump on in—the water’s warm!

6184_LEWI_CH01_p001-024.qxd 1/17/08 6:40 PM Page 1

Page 2: Objects - Pearson...Not only will we examine the code that makes the objects in ThunkIt do what they do, but you’ll create game objects of your own and then design levels of the

There was a time when the people who knew how to program a computer lived ina world of their own—a complex world full of arcane symbols and mathematicalterms. It was the world of the geek and the nerd. Not anymore.

Computers are technical devices, certainly, but that doesn’t meanthat we have to be overwhelmed by their complexity. Almost every-one can use a computer these days because most programs aredesigned to be truly usable—much of the inherent complexity ismanaged for us. In a similar way, the techniques for programming acomputer have become more accessible as well.

For you, this may be a one-time exploration into computing. Or you may haveyour sights set on continuing in this field. Either way, you’re in the right place.Computing is one of the world’s fastest growing disciplines, and the demand forgood programmers is rising. But even if you’re not looking for a career, the con-cepts we’ll explore here are helpful in many other ways.

In this book we focus on object-oriented programming (OOP), which is the mostpopular approach to computer programming today. It has gained dominance be-cause it is a natural, intuitive way to think about problems and their solutions.

OOP is largely responsible for taking the world of programmingaway from the geeks and making it more accessible.

As the name implies, object-oriented programming is all about man-aging objects. An object can be anything—a character in an anima-tion, a scoreboard in a game, a list of friends, whatever. In OOP,we create the objects we need and then we tell those objects to dothings for us.

Two technologies that make use of an object-oriented approach are Alice andJava, the cornerstones of this book.

Alice and JavaIn the first five chapters of this book, we focus on Alice, an environment designedto introduce programming concepts in an engaging manner. In the remainingchapters we focus on Java, a popular programming language in use by profession-als today. Alice will help us lay the foundation, and Java will give us the freedomto explore many other possibilities.

Alice is a computer environment in which you create virtual worlds containingthree-dimensional characters and objects that move and interact. Figure 1.1 shows

2 CHAPTER 1 Objects

1.1 Introduction

Programming a computer nolonger has to be a complex,arcane experience.

In object-orientedprogramming, we create theobjects we need and tell them toperform services for us.

6184_LEWI_CH01_p001-024.qxd 1/17/08 6:40 PM Page 2

Page 3: Objects - Pearson...Not only will we examine the code that makes the objects in ThunkIt do what they do, but you’ll create game objects of your own and then design levels of the

You can use Alice to create animations in which characters play out a scene or tocreate games and other interactive worlds in which objects respond to mouseclicks and keyboard input. When you create an Alice world, you are the boss. Youdecide which objects to include in your world and how they will behave. With Alice, you’re part movie director and part choreographer. You provide the instruc-tions, like move forward and turn right, and the objects in your world carry outthose instructions.

Though it won’t feel like it, when you build a virtual world in Aliceand dictate the way it behaves, you are programming. After all,that’s what object-oriented programming is all about—tellingobjects what to do.

Once Alice paves the way, we’ll transition into developing programs in Java,which is a general-purpose programming language. Java can be used to create ani-mations and games, as we can in Alice, but it is far more versatile. You wouldn’tuse Alice to create a social network or help manage a student organization, butyou could with Java.

Java was created by James Gosling at Sun Microsystems. It’s become one of themost popular programming languages in use today.

One of the ways we’ll explore the capabilities of Java is by examining a programcalled ThunkIt, a game in which the user helps stranded students get back to theirschool by solving a variety of puzzles. In each level of the game a student movesobstacles and uses various gadgets to outwit the detention robots and get one stepcloser to school. A screen shot of ThunkIt is shown in Figure 1.2.

1.1 Introduction 3

An Alice virtual world

Figure 1.1

Both Alice and Java use an object-oriented approach.

a screen shot from an Alice virtual world. Alice was developed at Carnegie MellonUniversity and is named in honor of Lewis Carroll and his wonderful books Alicein Wonderland and Through the Looking Glass.

6184_LEWI_CH01_p001-024.qxd 1/17/08 6:40 PM Page 3

Page 4: Objects - Pearson...Not only will we examine the code that makes the objects in ThunkIt do what they do, but you’ll create game objects of your own and then design levels of the

Not only will we examine the code that makes the objects in ThunkIt do whatthey do, but you’ll create game objects of your own and then design levels of thegame that use them. More on that later.

Our goal in this book is not to teach Alice or Java per se, but rather to use them toteach fundamental programming concepts. These concepts apply not only to Aliceand Java, but also to many other popular programming languages.

No matter which programming language you use, you need a development envi-ronment in which to create and execute your programs. Let’s take a look at theAlice development environment.

4 CHAPTER 1 Objects

ThunkIt, a Java program

Figure 1.2

1.2 The Alice EnvironmentAlice animations are made and executed within the Alice integrated developmentenvironment (IDE). Versions of Alice are available for both Windows and Mac

OS, and can be downloaded for free from the Alice website (www.alice.org). Appendix A contains information about installing theAlice environment.

As shown in Figure 1.3, when you start the Alice environment, itpresents a window that allows you to specify what you want to doinitially. Depending on which tab you pick, you can choose to:

A development environmentis a program used to create andrun another program.

6184_LEWI_CH01_p001-024.qxd 1/17/08 6:40 PM Page 4

Page 5: Objects - Pearson...Not only will we examine the code that makes the objects in ThunkIt do what they do, but you’ll create game objects of your own and then design levels of the

The tutorials are a good place to start, and we encourage you to usethem to get acquainted with the Alice environment and its capabili-ties. Likewise, feel free to open and explore the various exampleworlds provided. Play around with them. Have fun. Don’t worry ifyou don’t understand everything you see in the tutorials and exam-ples—we cover the key topics carefully in this book. Just don’t beafraid to explore and experiment.

The primary Alice window contains several distinct areas, as shown in Figure 1.4.The toolbar includes a button to play the current animation, which brings up aseparate window in which the animation is displayed and controlled. The worldview shows the virtual world as it initially appears to the camera, and has controlsfor adjusting the camera’s initial point of view. The object tree lists all objects inthe world, allowing you to select a particular object as you develop an animation.

1.2 The Alice Environment 5

The Alice welcomescreen

Figure 1.3

Programming is aparticipation sport! The moreyou play, the better you’ll get.Explore and experiment!

• run a tutorial,

• open a world you’ve had open recently (if any),

• start a new world using an existing template,

• explore one of several example worlds, or

• open an Alice world that was previously stored on your computer.

6184_LEWI_CH01_p001-024.qxd 1/17/08 6:40 PM Page 5

Page 6: Objects - Pearson...Not only will we examine the code that makes the objects in ThunkIt do what they do, but you’ll create game objects of your own and then design levels of the

Let’s start by exploring a simple Alice world called SpinningCubes (stored in thefile SpinningCubes.a2w). This world contains two cubes, one red and one blue, asshown in Figure 1.5. When you play the animation, first the blue cube spins in onedirection, then the red cube spins in the opposite direction. Try it! We encourageyou to keep the Alice environment open while you’re reading this book, experi-menting with our sample worlds as you go along.

6 CHAPTER 1 Objects

The Alice developmentenvironment

Figure 1.4

1.3 Objects in Alice

We’ll explore all of these aspects of the Alice environment over time as appropri-ate. For now, just begin to get a feel for the layout of the environment.

Appendix A contains the details of using the Alice environment to accomplishparticular tasks. Use it as needed as you progress through the chapters.

The details panel provides information about the particular object currently se-lected in the object tree. The method editor is where you make changes to the codethat dictates what your animation does. Finally, the events editor is where youspecify what will happen when particular events occur.

6184_LEWI_CH01_p001-024.qxd 2/18/08 3:45 PM Page 6

Page 7: Objects - Pearson...Not only will we examine the code that makes the objects in ThunkIt do what they do, but you’ll create game objects of your own and then design levels of the

The two cubes in this animation are objects, as is everything in an Alice world.The objects contained in an Alice world are listed in the object tree, as shown inFigure 1.6. The SpinningCubes world contains objects that represent the camera,the light source, the ground, and the two cubes.

1.3 Objects in Alice 7

The SpinningCubesworld

Figure 1.5

The object tree for theSpinningCubes world

Figure 1.6

All Alice worlds have a camera and a light source. The camera represents the pointof view of the person watching the animation. Most worlds also have some kindof ground surface as well. The templates in the Alice welcome screen provide sev-eral basic ground surfaces from which to choose. The SpinningCubes worldmakes use of a ground surface covered in grass.

The camera’s initial point of view of the world can be set using the camera controls,shown in Figure 1.7 and located under the world view window in the Alice envi-ronment. The camera controls may take some getting used to. The first controlshifts the camera up, down, right, or left. The second control moves the camera for-ward or backward in the world, or rotates the camera right or left. The third con-trol pivots the camera’s view up or down. Experiment with the controls to get a feelfor how they can be used to get a particular point of view on the world.

6184_LEWI_CH01_p001-024.qxd 1/17/08 6:40 PM Page 7

Page 8: Objects - Pearson...Not only will we examine the code that makes the objects in ThunkIt do what they do, but you’ll create game objects of your own and then design levels of the

Calling MethodsA method is a set of statements that can be called (or invoked) whenever we wantthose statements to be executed. Every object has methods that define that object’s

potential behavior. For example, most Alice objects have a methodcalled turn that, when called, will rotate the object. Similarly, themove method will move an object in a particular direction when it iscalled.

The world object in every Alice animation has a method calledmy first method that is executed whenever the animation is played.

This method often calls methods in other objects. The my first method methodfor SpinningCubes is shown in Figure 1.8.

8 CHAPTER 1 Objects

We get an object to dosomething by calling one of itsmethods.

In this example, the first line in my first method is a comment, in green type andbeginning with two slash marks (//). Comments are included for the humanreader and do not have any effect on the animation. We typically include a com-ment at the beginning of my first method to indicate the file name of the world.

The my firstmethod method for theSpinningCubes world

Figure 1.8

Once you use the camera controls to set the initial point of view, the camera willkeep that orientation throughout the animation unless you dictate otherwise. Aswe’ll see in later examples, we can set it up so that the camera’s orientationchanges as the animation unfolds.

The camera controls

Figure 1.7

1. Using the camera controls, change the camera viewpoint in SpinningCubesso that the blue cube is in the foreground and the red cube is behind it in thebackground.

2. Change the camera viewpoint in SpinningCubes so that it looks down onthe cubes from above.

6184_LEWI_CH01_p001-024.qxd 2/18/08 3:45 PM Page 8

Page 9: Objects - Pearson...Not only will we examine the code that makes the objects in ThunkIt do what they do, but you’ll create game objects of your own and then design levels of the
Page 10: Objects - Pearson...Not only will we examine the code that makes the objects in ThunkIt do what they do, but you’ll create game objects of your own and then design levels of the

To add a control statement (such as Wait) to a method, simply drag it up from the listinto the method editor. Comments can also be added in this way. As you drag, a greenline appears to indicate where you are adding the new statement. Depending on thestatement, it may prompt you to set certain parameter values when you add it to themethod. Consult Appendix A if needed for help with these environment operations.

The available methods for an object are listed in the details panel when that objectis selected in the object tree. Figure 1.11 shows part of the methods tab of thedetails panel for one of the cube objects. To add a new call to a method, drag themethod name from the details panel to the method editor.

10 CHAPTER 1 Objects

6. Make additional calls to the turn method in SpinningCubes so that eachcube spins in both directions, first right then left.

7. Modify SpinningCubes so that the cubes float up into the air 1 meter afterthey spin.

8. Modify SpinningCubes so that cube makes a “pop” sound after it spinsand cube2 makes a “thud” sound after it spins.

T

h

e

b

u

i

l

t

-

i

n

m

e

t

h

o

d

s

f

o

r

a

c

u

b

e

o

b

j

e

c

t

w

i

l

l

b

e

f

o

u

n

d

i

n

a

l

m

o

s

t

a

l

l

o

t

h

e

r

A

l

i

c

e

o

b

j

e

c

t

s

a

s

w

e

l

l

.

T

h

e

y

p

r

o

v

i

d

e

s

e

v

e

r

a

l

b

a

s

i

c

m

o

v

e

m

e

n

t

o

p

-

e

r

a

t

i

o

n

s

,

i

n

c

l

u

d

i

n

g

s

o

m

e

t

h

a

t

m

o

v

e

r

e

l

a

t

i

v

e

t

o

o

t

h

e

r

o

b

j

e

c

t

s

o

r

a

t

a

p

a

r

t

i

c

u

l

a

r

s

p

e

e

d

.

T

h

e

b

u

i

l

t

-

i

n

m

e

t

h

o

d

s

a

l

s

o

i

n

c

l

u

d

e

sa

y

an

d

th

in

k

,w

hi

ch

p

ro

du

ce

s

pe

ec

h

bu

bb

le

s

ab

ov

e

th

e

ob

je

ct

,

as

i

n

a

co

mi

c

st

ri

p.

An

ot

he

r

me

th

od

,

pl

ay

s

ou

nd

,

al

lo

ws

a

n

ob

je

ct

t

o

pl

ay

a

s

ou

nd

f

il

e.

A

fe

w

so

un

d

ef

fe

ct

s

ar

e

bu

il

t

in

to

t

he

A

li

ce

e

nv

ir

on

me

nt

,

bu

t

yo

u

ca

n

im

po

rt

a

ny

.w

av

o

r

.m

p3

s

ou

nd

f

il

e

to

u

se

i

n

yo

ur

a

ni

ma

ti

on

.

Th

e

fu

ll

l

is

t

of

b

ui

lt

-i

n

me

th

od

s

ar

e

de

sc

ri

be

d

in

A

pp

en

di

x

B.

F

ee

l

fr

ee

t

o

ex

pe

ri

-

me

nt

w

it

h

th

es

e

me

th

od

s—

we

’l

l

se

e

ma

ny

o

f

th

em

i

n

us

e

in

u

pc

om

in

g

ex

am

pl

es

.

Yo

u’

ll

l

ea

rn

h

ow

t

o

ad

d

yo

ur

o

wn

m

et

ho

ds

t

o

an

o

bj

ec

t

in

C

ha

pt

er

2

.

So

me

o

f

th

e

me

th

od

s

av

ai

la

bl

e

fo

r

cu

be

Fi

gu

re

1

.1

1

Al

l

Al

ic

e

ob

je

ct

s

ha

ve

a

s

et

o

fb

ui

lt

-i

n

me

th

od

s

th

at