Professional Documents
Culture Documents
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
Instance
ofthe
Crabclass
Class
Crab
constructor
12
Object
Inspector
13
Crab
methods
14
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
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() );
Ifcrabisattheedge,turnaroundand
gotheotherway.
h
h
22
Ifcrabisattheedge,turnaroundand
go the other way
gotheotherway.
23
Ifcrabisattheedge,turnsmoothlyand
go the other way!
gotheotherway!
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
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
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
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
40
41
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
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
51
52
OurnewWorld
53
Gameisoverwhenthereareno
wormsORwhenalobstereatsthe
crab
DistinguishbetweenWINandLOSS
54
55
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
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
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)
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
Filledin
Shapes
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
java.awt.Font getFont()
Getthecurrentfont.
setColor(java.awt.Color color)
g
Setthecurrentdrawingcolor.
setFont(java.awt.Font f)
Set the current font.
Setthecurrentfont.
69
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
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
75
76
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