You are on page 1of 88

Greenfoot

AnIntroductiontoOOP
Presentedby
AdrienneDecker
StephanieHoeppner
FranTrees

SomematerialsbasedonGreenroomResources.Freetouse,modifyand
distributeunderCreativeCommonsAttributionShareAlike3.0License.

Greenfoot
aacombinationbetweenaframeworkfor
combination between a framework for
creatingtwodimensionalgridassignmentsin
JavaandanIDE.
atoolforteachingprogrammingwiththeJava
language.
Intendedforages14andolder.
Downloadfrom:http://www.greenfoot.org/
Ithasinterfacetranslationsintolanguages
includingFrench,GermanandItalian.
2

Session Description
SessionDescription
Inthispresentation,wewillintroduce
G
Greenfoot.
f
Thispresentationisaimedatteachersof
introductoryJavaprogrammingcourses(high
schoolsanduniversities)whohavenever
workedwiththeGreenfoot environment
before.

Presentation Description
PresentationDescription
Thispresentationisintendedtogiveeducators
an introduction to the Greenfoot environment,a
anintroductiontotheGreenfoot
environment a
demonstrationofhowitcanbeusedtointroduce
objectorientedprogrammingtostudents,anda
j
p g
g
,
guidedapproachtodevelopingGreenfoot
experiencesthatcanbeintegratedintoexisting
curricula.
i l
Th
Thesessionispracticallyorientedandallows
i i
i ll
i
d d ll
participantstouseGreenfoot intheirclassroom
immediately.
immediately
4

SessionGoals
TointroducetheGreenfoot environment
Asourcecodeeditor
Aclassbrowser
Compilationcontrol
Executioncontrol
Execution control

Whilediscussingtheteachingof
Javathroughexamples
Java through examples

Agenda
Building
BuildingaGreenfoot
a Greenfoot program(tolearnabout
program (to learn about
Greenfoot)CRABS,WORMS,andLOBSTERS
Startwithanexistingscenario
Start with an existing scenario
Introduceobjectsandclasses
Workwithinteractingclasses
Work with interacting classes
Lookatmovementintheworld
Includerandombehaviorandsound
I l d
d
b h i
d
d

Agenda
Moving
Movingbeyondthefirstscenario:
beyond the first scenario:
Demonstrationofsomeadvancedfeaturesof
Greenfoot:
Imagecontrol
Animation
CollisionDetection

Agenda
SSomeexamplesusingGreenfoot
l
i G
f t toteachor
t t h
reviewCStopics
Greenfoot.org
PublishingScenarios
AvailableResources

Questions?????
Q

Greenfoot (LittleCrabScenario)
(Little Crab Scenario)
Like
LikeBlueJ,Greenfoot
BlueJ Greenfoot teachesobject
teaches objectoriented
oriented
programminginavisualmanner.Eachactoris
an object that moves around in a world (also
anobjectthatmovesaroundinaworld(also
anobject).
Thisallowsteachingofobjectoriented
principles(methodinvocation,objectstate)
i i l (
h di
i
bj
)
beforeevenbeginningtolookatorwrite
code.
d
9

Greenfoot Environment
ClassDiagram

World

10

Greenfoot classes
(HelpOption)

Actor

GreenfootSound

Greenfoot

MouseInfo

GreenfootImage

World

Objects and Classes


ObjectsandClasses

Instance
ofthe
Crabclass

Class
Crab

constructor

12

Defining state (attributes)


Definingstate(attributes)

Object
Inspector

13

Defining behavior (methods)


Definingbehavior(methods)

Crab
methods

14

Defining behavior (methods)


Definingbehavior(methods)

Methods
Methods
inheritedfrom
Animal

15

Definingbehavior(methods)

Methods
Methods
inheritedfrom
Actor

16

Actors
'Actors'
Actors havepredefinedstate:
have predefined state:
image
location(intheworld)
location (in the world)
rotation

CreateanewCrabandpress">Act"
Click"Run"tocallactcontinuously

Nothing
h
happens!
!

18

LetsinvestigatetheJavacodeforact!
import greenfoot.; // (World, Actor,
G
GreenfootImage,
f tI
and
d Greenfoot)
G
f t)
/
This class defines a crab. Crabs live on the
beach.
/
public
bli class
l
Crab
C b extends
t d Animal
A i l
{
Thecrabdoes
public void act()
{
nothingwhenit
}
acts!
}
19

Defining the Crabsbehaviorforact


DefiningtheCrab
s behavior for act
public class Crab extends Animal
{
public void act()
{
move();
}
}

Compile
Run
Whathappens?
20

MovementKey
Movement
KeyPoint
Point
YYoucanchoosethelevelofabstraction/complexity
h
th l l f b t ti /
l it
toexposetoyourstudentsbypreparingthe
scenario.
scenario
move();
setLocation( getX()+1, getY() );

Defining the Crabsbehaviorfor


DefiningtheCrab
s behavior for act

Ifcrabisattheedge,turnaroundand
gotheotherway.
h
h

public class Crab extends Animal


{
public void act()
{
move();
// more code here
}
}

22

Ifcrabisattheedge,turnaroundand
go the other way
gotheotherway.

23

Ifcrabisattheedge,turnsmoothlyand
go the other way!
gotheotherway!

public void act()


{
move();
()
if( atWorldEdge() )
{
turn(15);
}
}

24

ObjectsandClasses
Populateyourworldwithcrabs
l
ld
h b
Eachinstanceofa
C b hasitsown
Crab
has its own
attributes(state).

25

ObjectsandClasses
Thedescriptionofwhatcomprisesanobject ofaparticular
typeisaclass
yp
Aclass definesthebehavior andattributes(characteristics)
ofobjects(whatanobjectknowsaboutitself).
Objects areinstances ofaclass.

Crab objects

Crab class:blueprint
: blueprint
forcrabs
26

What a crab knows about itself:


Whatacrabknowsaboutitself:
Crabscannot
directlyaccess:
x
y
Rotation
World
image
Needaccessors
andmutators
providedby
Actor todothat.
to do that
27

Crab inheritsfromActor
inherits from Actor
Crabscannot
directly access
directlyaccess:

x
y
Rotation
World
i
image

Need
Needaccessors
accessors and
and
mutators provided
byActortodothat.
28

Crab inheritsfromActor
inherits from Actor
Crabscannot
directly access
directlyaccess:

x
y
Rotation
World
i
image

Need
Needaccessors
accessors and
and
mutators provided
byActor todothat.
29

Crab inheritsfromActor
inherits from Actor
Crabscannot
directly access
directlyaccess:

x
y
Rotation
World
i
image

Need
Needaccessors
accessors and
and
mutators provided
byActor todothat.
30

Crab inheritsfromActor
inherits from Actor
Crabs
Crabscannot
can not
directlyaccess:

x
y
Rotation
World
image

Needaccessors and
mutators provided
by Actor todothat.
by
to do that
31

Objects and Classes


ObjectsandClasses
Populateyourworldwithafewinstancesofthe
p
y
Crab class.
Cantherebemorethanoneobjectinaposition?
CanaCrab movetoapositionthatanother
Crab occupies?
CanaCrab
Can a Crab moveoutsidetheboundariesofthe
move outside the boundaries of the
world?
Howisinvokingtheact
g
methodofaCrab
differentfromclickingtheact executioncontrol
button.
32

Populatingtheworld
(U i th G
(UsingtheGreenfoot
f t API)
http://www.greenfoot.org/doc/javadoc/

public CrabWorld()
{
super(560, 560, 1);
addObject(new
addObject(new
addObject(new
addObject(new

Crab()
Crab(),
Crab(),
Crab(),
Crab(),

100
100,200);
200);
150,290);
300,400);
500,50);

}
33

SavetheWorld!

34

Interactingclasses
Thecrabsarehungry!
h
b
h
Crabseatworms.
C abs eat o s.
1. RightclickAnimal;choose"New Subclass..."
2 Nameit"Worm".
2.
Name it "Worm"
3. Chooseanimage.
Addwormstoyourworld.
Run
pp
Whathappens?
35

ModifytheCrabclasstoteachthecrab
toeatworms.
Ifthecrabseesaworm
If the crab sees a worm

Worm.class

Eattheworm

36

ModifytheCrabclasstoteachthecrab
toeatworms
Ifthecrabseesaworm
If the crab sees a worm
Eattheworm

public void act()


{
move();
if(canSee(Worm.class))
{
eat(Worm.class);
}
else if( atWorldEdge() )
{
turn(15);
}
}
37

Greenfoot sounds
if(canSee(Worm.class))
{
eat(Worm.class);
G
Greenfoot.playSound("slurp.wav");
f t l S
d(" l
")
}

YYoucanchoosethelevelof
h
h l l f
abstraction/complexitytoexposetoyour
studentsbypreparingthescenario.
d
b
i
h
i
Animal definescanSeeandeat...
...butitdoesnothaveto.
38

Summary: so far..
Summary:sofar..

Thedifferencebetweenobjectsandclasses
The
difference between objects and classes
Methodsignatureanddefinition
Parameters
Booleanexpressions
int,boolean,andvoid returns
private vs public
if;if-else
39

More interesting behavior


Moreinterestingbehavior
RandomNumbers
Random Numbers
InGreenfoot:
int r = Greenfoot.getRandomNumber(100);
g
(
);
Returnsarandomint between0(inclusive)and100(exclusive)
int r = Greenfoot.getRandomNumber(100)Greenfoot getRandomNumber(100) 50;
Returnsarandomint between50(inclusive)and50(exclusive)

40

A more interesting Crab


AmoreinterestingCrab
public class Crab extends Animal
{
public void act()
{
if ( atWorldEdge( ) )
{
turn(15);
(1 )
}
move();
if (canSee(Worm.class))
{
eat(Worm.class);
}
// Generate a random int between 0 and 100
// If the number is less than 10, turn a random number of degrees
// between 0 and 45 (right or left).
}
}

41

The improved Crab


TheimprovedCrab
public class Crab extends Animal
{
public void act()
{
turnAtEdge()
randomTurn();
move();
lookForWorm();
}
}
42

An alternate CrabWorld
AnalternateCrabWorld
public CrabWorld()
{
super(560, 560, 1);
populateWithCrabs();
populateWithWorms();
}
public void populateWithCrabs()
{
final int NUM_CRABS =
//add NUM_CRABS crabs in random locations
}
public void populateWithWorms()
{
final int NUM_WORMS =
//add NUM_WORMS worms in random locations
}
43

Gameisoverwhenthereareno
worms!
Whose
Whoseresponsibilityisittokeeptrackofthe
responsibility is it to keep track of the
worms?
WorldMethods?
World Methods?
Howdowe"stop"theGREENFOOTGame?

44

Boring
NothingEXCITINGhappens!
Introduce

TheLobster

45

Interactiveprograms
Th L b
TheLobstermeetsthecrab
h
b
Crabseatworms.
Lobsterseatcrabs!
Yougettocontrolthesinglecrab!

46

The Lobster
TheLobster
TheLobster
e obste be
behaveslikethecrabdidbuteats
a es e t e c ab d d but eats
crabsinsteadofworms.
public void act()
{
turnAtEdge();
randomTurn();
move();
lookForCrab();
}

Thecrab
The crab'ssbehaviorwillchange.
behavior will change
47

The interactive Crab


TheinteractiveCrab
Thecrabiscontrolledbythekeyboard.
The crab is controlled by the keyboard
Leftarrowturnthecrab4degrees
Rightarrowturnsthecrab4
Right arrow turns the crab 4 degrees
public void act()
{
checkKeypress();
move();
lookForWorm();
}
48

Keypress
public void checkKeypress()
{
if (Greenfoot.isKeyDown("left"))
{
turn(-4);
}
if (Greenfoot.isKeyDown("right"))
{
turn(4);
}
}
49

Animatedcreatures
Animatethecrab!
h
b
The
Theimagefilesusedforyouranimation
image files used for your animation
shouldliveintheimagesfolderforthe
project.
project
crab.png
crab2.png
crab2 png

50

Animate the crab!


Animatethecrab!
p
private
GreenfootImage
g image1;
g
private GreenfootImage image2;
public Crab()
{
image1 = new GreenfootImage("crab.png");
image2 = new GreenfootImage("crab2.png");
setImage(image1);
}

51

Animate the crab!


Animatethecrab!
public void act()
{
checkKeypress();
move();
lookForWorm();
switchImage();
}

52

OurnewWorld

53

Gameisoverwhenthereareno
wormsORwhenalobstereatsthe
crab
DistinguishbetweenWINandLOSS

54

(Some) Advanced Features


(Some)AdvancedFeatures
CollisionDetection&Animations

55

Key Point (Reiterated)


KeyPoint(Reiterated)
You
Youcancontrolthelevelofabstractionforthe
can control the level of abstraction for the
studentswithregardstomovementand
animation.
animation

56

Moving Actors
MovingActors
public void move(double distance) {
double angle = Math.toRadians( getRotation() );
int x
x=(int)Math.round(getX()+Math.cos(angle)
(int)Math.round(getX()+Math.cos(angle) distance);
int y=(int)Math.round(getY()+Math.sin(angle) distance);
setLocation(x,
i (
y);
)
}

57

Motion Using Vectors


MotionUsingVectors
SmoothMover classusesa
class uses a Vector tohold
to hold

directionandspeedofmotion.
Cancreatesubclassesof
Can create subclasses of SmoothMover to
to
usethisstyleofmotion.
Canillustratetheseparationofmodeland
C ill
h
i
f
d l d
view.

58

Collision Detection
CollisionDetection
Even
Evenifyoudon
if you dontthavethestudentscontrol
have the students control
motion/turning/etc.youcanstillhavethem
write more sophisticated collision detection
writemoresophisticatedcollisiondetection
behaviorsusingthebuiltinmethodsin
Actor.

59

Collision Detection Methods


CollisionDetectionMethods
java.util.List getIntersectingObjects(java.lang.Class cls)
java.util.List getNeighbours(int distance,boolean diagonal,java.lang.Class cls)
java.util.List getObjectsAtOffset(int dx,int dy,java.lang.Class cls)
j
java.util.List
il i getObjectsInRange(int
Obj
(i radius,java.lang.Class
di j
l
Cl cls)
l)
ActorgetOneIntersectingObject(java.lang.Class cls)
ActorgetOneObjectAtOffset(int dx,int dy,java.lang.Class cls)

60

getOneIntersectingObject(java.lang.Class
g
g j
(j
g
cls)
)

Pass
Passintheclassoftheobjecttolookforaparticular
in the class of the object to look for a particular
typeofcollision
Passinnull tolookforanyintersectingobject
y
g j
Returnsone
Returns one Actor objectthatmatchesthecriteria.
object that matches the criteria.
null isreturnedifnointersectionsaredetected

61

getOneObjectAtOffset
(int
(i
t dx,
d
i t dy,
int
d
j
java.lang.Class
l
Cl
cls)
l )
Lookelsewhereforanobject(passinadxanddy)
L k l
h
f
bj t (
i d
dd )
TheClassparameterworksthesameasprevious.
Returnssameasprevious:anActor objectthatis
null
ll ifnointersectionsaredetected.
if
i t
ti
d t t d

62

getIntersectingObjects(java.lang.Class
g
g j
(j
g
cls)
)

Returns
Returnsalist(java.util.List)ofall
a list (java.util.List) of all
intersectingobjectsofaparticularclasstypecls.
Passingin
g null returnsintersectionsofalltypes.
yp
Can
Canbeusedtodiscusscollections,generics,for
be used to discuss collections, generics, foreach
each
loop.

63

getObjectsAtOffset
(int dx,
dx int dy,
dy
java.lang.Class cls)

Analogous
Analogousto
to getObjectAtOffset exceptthatit
except that it
returnsalloftheobjectsthatareintersecting.

64

g
getObjectsInRange
j
g
List getObjectsInRange(int r, java.lang.Class
java lang Class cls)

Return all objects within range 'r' around this object.

cell:10pixels
ll
l

An object
j
is "in
range" if its
center point is
inside the
circle.
r=6(cells)
65

g
getNeighbours
g
Most
Mostusefulinaworldwhereactorsare
useful in a world where actors are
containedinacell(likeGridWorld casestudy
for AP CS Exam)
forAPCSExam).
Returnsthelistofneighborsinthefour
cardinal directions distance cellsaway
cardinaldirectionsdistance
cells away
fromtheactorscurrentlocation.
Passing
P i true totheboolean
h b l
parameter
includesthediagonals.
66

GreenfootImage
This
Thisistheclassthatrepresentstheimagesof
is the class that represents the images of
theactorsandtheworldinthescenarios.
Youcanprogrammaticallymanipulatethese
You can programmatically manipulate these
imagesordrawyourownimages
programmatically.
programmatically

67

Drawing Methods
DrawingMethods
clear()
drawImage(GreenfootImage image,int
image int x,int
x int y)
y)
drawLine(int x1,int y1,int x2,int y2)
drawOval(int x,int
x int y,int
y int width,int
width int height)
height)
Outline
Shapes

drawPolygon(int[] xPoints,int[] yPoints,int nPoints)


drawRect(int x,int
x, int y,int
y, int width,int
width, int height)
height)
drawShape(java.awt.Shape shape)
()
fill()

Filledin
Shapes

fillOval(int x,int y,int width,int height)

Setsthecurrent
drawingcolor.
Needs to be done
Needstobedone
beforedrawingor
filling.

yg
xPoints,int[] yyPoints,int nPoints)
fillPolygon(int[]
fillRect(int x,int y,int width,int height)
fillShape(java.awt.Shape shape)

68

Sidenote: Drawing Text


Sidenote:DrawingText
string, int x,int
x, int y)
drawString(java.lang.String string,int
Drawthetextgivenbythespecifiedstring,using
thecurrentfontandcolor.

java.awt.Font getFont()
Getthecurrentfont.

setColor(java.awt.Color color)
g
Setthecurrentdrawingcolor.

setFont(java.awt.Font f)
Set the current font.
Setthecurrentfont.
69

Growing, Shrinking, Transparency


Growing,Shrinking,Transparency
Growing
&
Shrinking

int getHeight()
Return the height of the image
Returntheheightoftheimage.
int getWidth()
Returnthewidthoftheimage.
scale(int width,int height)
Scalesthisimagetoanewsize.
int getTransparency()
Return the current transparency of the image.
Returnthecurrenttransparencyoftheimage.
setTransparency(int t)
Setthetransparencyoftheimage.

Other
animated
effects

mirrorHorizontally()
mirrorHorizontally()
Mirrorstheimagehorizontally(fliparoundthexaxis).
mirrorVertically()
Mirrorstheimagevertically(fliparoundtheyaxis).
rotate(int degrees)
Rotatesthisimagearoundthecenter.

70

Fun with Images


FunwithImages
Useful
Usefulifinterestedinusingsomeofthemedia
if interested in using some of the media
computationstuff
SeegetColorAt(x,y)andsetColorAt(x,y)
See getColorAt(x,y) and setColorAt(x,y)
methods
Grayscale
y
animage
g
Filtersonimages
Createnegative
Chromakey

Canbeusedtoreinforceloops
p
71

Greenfoot
SimpleAssignments
with Dice and Cards
withDiceandCards

72

BooleanExpressions:Craps
Thegameconsistsofrolling26sideddice.Theshootermakesa"come
outroll"withtheintentionofestablishingapoint.
If the shooter'sscomeoutrollisa2,3or12,itiscalled
Iftheshooter
comeout roll is a 2 3 or 12 it is called "craps"
craps (the
(the
shooterissaidto"crapout")andtheroundendswithplayerslosing.
Acomeoutrollof7or11iscalleda"natural,"resultinginawin.
Iftheshooter
If
the shooter'sscomeoutrollisa4,5,6,8,9,or10,thisnumberbecomes
comeout roll is a 4 5 6 8 9 or 10 this number becomes
the"point".Oncethe"point"isestablished,theshooterwillnow
continuerollingforeitherthepointnumberoraseven.
If th h t i
Iftheshooterissuccessfulinrollingthepointnumber,theresultisawin.
f li
lli th
i t
b th
lt i
i
Iftheshooterrollsaseven(calleda"sevenout"),theresultisaloss.

73

BooleanExpressions:Craps

74

Arrays and ArrayLists: Poker (part 1)


ArraysandArrayLists:Poker(part1)

75

Interfaces: Poker (Part2)


Interfaces:Poker(Part2)

76

Interfaces: Poker (Part2)


Interfaces:Poker(Part2)
publicinterfaceIHandPropertyTester
{
/**
*Returnstrueifandonlyifhandsatisfiesthisproperty
*@param
p
handisthehandtested
*@returntrueifhandsatisfiespropertybeingtested
*/
boolean hasProperty(Handhand);
/**
*Returnsthevalueofthishandifhandsatisfiestheproperty
*@param handisthehandtested
*@returnvalueofthehandtested.
*/
int getHighValue(Handhand);
}
77

Arrays and 2D
Arraysand2
Darrays
arrays

78

StudentLottery
( h
(Whogetsthisquestionorprize?)
h
)

79

BeyondAdvanced
(andontoreally,reallycool)
GamePads,Kinect

80

Game Pads
GamePads
PS2
PS2andXBox
and XBox likegamepads
like game pads
Supportclassesneededandavailable(along
with documentation and examples)
withdocumentationandexamples)
http://www.greenfoot.org/doc/gamepad/

81

Kinect
http://www.greenfoot.org/doc/kinect/
http://www greenfoot org/doc/kinect/
Kinect video

82

Crabs,andLobsters,andBears
ohmy!?!
Help,Resources,&Community

83

Greenfoot Gallery
GreenfootGallery
Share!

Greenroom

Meet!

More information
Moreinformation
www.greenfoot.org
discussiongroup
scenariorepository
p
y
tutorials(textandvideo)
Greenfoot Gallery
Greenroom
Adrienne:newyorkhub@greenfoot.org
Adrienne: newyork hub@greenfoot org

Fran:newjerseyhub@greenfoot.org

Questions?
DiscussionTime

88

You might also like