Greenfoot AnIntroductiontoOOP
Presentedby AdrienneDecker StephanieHoeppner FranTrees
SomematerialsbasedonGreenroomResources.Freetouse,modifyand distributeunderCreativeCommonsAttributionͲShareAlike3.0License. 1 Greenfoot
acombinationbetweenaframeworkfor creatingtwoͲdimensionalgridassignmentsin JavaandanIDE. atoolforteachingprogrammingwiththeJava language. Intendedforages14andolder. Downloadfrom:http://www.greenfoot.org/ Ithasinterfacetranslationsintolanguages includingFrench,GermanandItalian.
2 SessionDescription Inthispresentation,wewillintroduce GfGreenfoot. Thispresentationisaimedatteachersof introductoryJavaprogrammingcourses(high schoolsanduniversities)whohavenever workedwiththeGreenfoot environment before.
3 PresentationDescription Thispresentationisintendedtogiveeducators anintroductiontotheGreenfoot environment,a demonstrationofhowitcanbeusedtointroduce objectͲorientedppgrogramming tostudents,anda guidedapproachtodevelopingGreenfoot experiencesthatcanbeintegratedintoexisting currilicula.
Thesessionispractillicallyoridientedandallows participantstouseGreenfoot intheirclassroom immediately.
4 SessionGoals
TointroducetheGreenfoot environment Asourcecodeeditor Aclassbrowser Compilationcontrol Executioncontrol Whilediscussingtheteachingof Javathroughexamples
5 Agenda
BuildingaGreenfoot program(tolearnabout Greenfoot)CRABS,WORMS,andLOBSTERS Startwithanexistingscenario Introduceobjectsandclasses Workwithinteractingclasses Lookatmovementintheworld IldIncluderandombbhehav iorandsound
6 Agenda
Movingbeyondthefirstscenario: Demonstrationofsomeadvancedfeaturesof Greenfoot: Imagecontrol Animation CollisionDetection
7 Agenda
SomeexamplesusingGftGreenfoot tottheachor reviewCStopics Greenfoot.org PublishingScenarios AvailableResources Questions?????
8 Greenfoot (LittleCrabScenario)
LikeBlueJ,Greenfoot teachesobjectͲoriented programminginavisualmanner.Eachactoris anobjectthatmovesaroundinaworld(also anobject).
ThisallowsteachingofobjectͲoriented priilinciples(hd(methodiiinvocation,objectstate) beforeevenbeginningtolookatorwrite code.
9 Greenfoot Environment
ClassDiagram
World
10 Greenfoot classes (HelpOption)
Actor GreenfootSound
Greenfoot MouseInfo
GreenfootImage World ObjectsandClasses Class Crab
Instance ofthe constructor Crabclass
12 Definingstate(attributes)
Object Inspector
13 Definingbehavior(methods)
Crab methods
14 Definingbehavior(methods)
Methods inheritedfrom Animal
15 Definingbehavior(methods)
Methods inheritedfrom Actor
16 Actors
'Actors'havepredefinedstate:
image location(intheworld) rotation CreateanewCrabandpress">Act" Click"ŹRun"tocallactcontinuously
Nothing h!happens!
18 LetsinvestigatetheJavacodeforact! import greenfoot.; // (World, Actor, GftIGreenfootImage, and GftGreenfoot)
/ This class defines a crab. Crabs live on the beach. / public cl ass C rab ext end s A n ima l { public void act() Thecrabdoes { nothingwhenit } } acts!
19 DefiningtheCrab sbehaviorforact
public class Crab extends Animal { public void act() { move(); } }
Compile
ŹRun Whathappens?
20 MovementͲKeyPoint
Youcanchoosethelllevelofabtbstrac tion /comp lex ity toexposetoyourstudentsbypreparingthe scenario.
move(); setLocation( getX()+1, getY() ); DefiningtheCrab sbehaviorfor act
Ifcrabisattheedge,turnaroundand gotheotherway. public class Crab extends Animal { public void act() { move(); // more code here
} }
22 Ifcrabisattheedge,turnaroundand gotheotherway.
23 Ifcrabisattheedge,turnsmoothlyand gotheotherway! public void act() { move(); if( atWorldEdge() ) { turn(15); } }
24 ObjectsandClasses Populateyourworldwithcrabs
Eachinstanceofa CbCrab hasitsown attributes(state).
25 ObjectsandClasses
Thedescriptionofwhatcomprisesanobject ofaparticular typeisaclass Aclass definesthebehavior andattributes(characteristics) ofobjects(whatanobjectknowsaboutitself). Objects areinstances ofaclass.
objects Crab Crab class:blueprint forcrabs 26 Whatacrabknowsaboutitself:
Crabscannot directlyaccess: x y Rotation World image
Needaccessors andmutators providedby Actor todothat.
27 Crab inheritsfromActor Crabscannot directlyaccess: x y Rotation World image
Needaccessors and mutators provided byActortodothat.
28 Crab inheritsfromActor Crabscannot directlyaccess: x y Rotation World image
Needaccessors and mutators provided byActor todothat.
29 Crab inheritsfromActor Crabscannot directlyaccess: x y Rotation World image
Needaccessors and mutators provided byActor todothat.
30 Crab inheritsfromActor
Crabscannot directlyaccess: x y Rotation World image
Needaccessors and mutators provided byActor todothat.
31 ObjectsandClasses
Populateyourworldwithafewinstancesofthe Crab class. Cantherebemorethanoneobjectinaposition? CanaCrab movetoapositionthatanother Crab occupies? CanaCrab moveoutsidetheboundariesofthe world? Howisinvokingtheact methodofaCrab differentfromclickingtheact executioncontrol button.
32 Populatingtheworld (Usi ngtheGftGreenfoot API) http://www.greenfoot.org/doc/javadoc/ public CrabWorld() { super(560, 560, 1);
addObject(new Crab(), 100, 200); addObject(new Crab(), 150,290); addObject(new Crab(), 300,400); addObject(new Crab(), 500,50);
}
33 SavetheWorld!
34 Interactingclasses Thecrabsarehungry! CCabsrabseatwoos.rms. 1. RightclickAnimal;choose"New Subclass..." 2. Nameit"Worm". 3. Chooseanimage.
Addwormstoyourworld. ŹRun Whathappens?
35 ModifytheCrabclasstoteachthecrab toeatworms. Ifthecrabseesaworm Worm.class Eattheworm
36 ModifytheCrabclasstoteachthecrab toeatworms Ifthecrabseesaworm 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); GftlSdGreenfoot.playSound("sl urp.wav "); } Youcanchoosethelllevelof abstraction/complexitytoexposetoyour studentsbypreparingthescenario. Animal definescanSeeandeat... ...butitdoesnothaveto. 38 Summary:sofar ..
Thedifferencebetweenobjectsandclasses Methodsignatureanddefinition Parameters Booleanexpressions int,boolean,andvoid returns private vs public if;if-else
39 Moreinterestingbehavior
RandomNumbers InGreenfoot: int r = Greenfoot.getRandomNumber(();100); Returnsarandomint between0(inclusive)and100(exclusive)
int r = Greenfoot. getRandomNumber(100)- 50; Returnsarandomint betweenͲ50(inclusive)and50(exclusive)
40 AmoreinterestingCrab public class Crab extends Animal { public void act() { if ( atWorldEdge( ) ) { turn(15 ); } 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 TheimprovedCrab public class Crab extends Animal { public void act() { turnAtEdge() randomTurn(); move(); lookForWorm();
} }
42 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! Whoseresponsibilityisittokeeptrackofthe worms? WorldMethods? Howdowe"stop"theGREENFOOTGame?
44 Boring
NothingEXCITINGhappens! Introduce
TheLobster
45 Interactiveprograms TheLLbobstermeetsthecrab
Crabseatworms. Lobsterseatcrabs! Yougettocontrolthesinglecrab!
46 TheLobster
TheLobster beha v esliketteheccabrabdddidbuteats crabsinsteadofworms. public void act() { turnAtEdge(); randomTurn(); move(); lookForCrab(); }
Thecrab's behaviorwillchange.
47 TheinteractiveCrab
Thecrabiscontrolledbythekeyboard. LeftarrowturnthecrabͲ4degrees Rightarrowturnsthecrab4 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! Theimagefilesusedforyouranimation shouldliveintheimagesfolderforthe project. crab.png crab2.png
50 Animatethecrab!
private GreenfootImage image1; private GreenfootImage image2;
public Crab() { image1 = new GreenfootImage("crab.png"); image2 = new GreenfootImage("crab2.png"); setImage(image1); }
51 Animatethecrab! public void act() { checkKeypress(); move(); lookForWorm(); switchImage(); }
52 OurnewWorld
53 Gameisoverwhenthereareno wormsORwhenalobstereatsthe crab
DistinguishbetweenWINandLOSS
54 (Some)AdvancedFeatures
CollisionDetection&Animations
55 KeyPoint(Reiterated)
Youcancontrolthelevelofabstractionforthe studentswithregardstomovementand animation.
56 MovingActors
public void move(double distance) { double angle = Math.toRadians( getRotation() );
int xx(=(int)Math.round(getX()+Math.cos(angle) distance); int y=(int)Math.round(getY()+Math.sin(angle) distance);
setLocation(x, y); }
57 MotionUsingVectors
SmoothMover classusesaVector tohold directionandspeedofmotion. CancreatesubclassesofSmoothMover to usethisstyleofmotion. Canillustratetheseparationofmodldeland view.
58 CollisionDetection
Evenifyoudon thavethestudentscontrol motion/turning/etc.youcanstillhavethem writemoresophisticatedcollisiondetection behaviorsusingthebuiltinmethodsin Actor.
59 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) jilijava.util.List getObjectsInRange(int radius,jlCljava.lang.Class cls)
ActorgetOneIntersectingObject(java.lang.Class cls)
ActorgetOneObjectAtOffset(int dx,int dy,java.lang.Class cls)
60 gggjetOneIntersectingObject(jjgava.lang.Class cls)
Passintheclassoftheobjecttolookforaparticular typeofcollision Passinnull tolookforanyintersectingobject
ReturnsoneActor objectthatmatchesthecriteria. null isreturnedifnointersectionsaredetected
61 getOneObjectAtOffset (itint dx, itint dy, jlCljava.lang.Class clls)
LkLookelhlsewhereforanobjec t(passinadxanddy) TheClassparameterworksthesameasprevious.
Returnssameasprevious:anActor objectthatis null ifnoitintersec tionsaredtdetec tdted.
62 gggjetIntersectingObjects(jjgava.lang.Class cls)
Returnsalist(java.util.List)ofall intersectingobjectsofaparticularclasstypecls. Passinginnull returnsintersectionsofalltypes.
Canbeusedtodiscusscollections,generics,forͲeach loop.
63 getObjectsAtOffset (int dx, int dy, java.lang.Class cls)
AnalogoustogetObjectAtOffset exceptthatit returnsalloftheobjectsthatareintersecting.
64 ggjetObjectsInRan ge
List getObjectsInRange(int r, java. lang.Class cls) Return all objects within range 'r' around this object. cell:10pixels
An object is "in range" if its center point is inside the circle.
r=6(cells) 65 gggetNeighbours
Mostusefulinaworldwhereactorsare containedinacell(likeGridWorld casestudy forAPCSExam). Returnsthelistofneighborsinthefour cardinaldirectionsdistance cellsaway fromtheactorscurrentlocation. PiPassingtrue totheblboolean parameter includesthediagonals.
66 GreenfootImage
Thisistheclassthatrepresentstheimagesof theactorsandtheworldinthescenarios. Youcanprogrammaticallymanipulatethese imagesordrawyourownimages programmatically.
67 DrawingMethods clear() drawImage(GreenfootImage image,int x,int y) drawLine(int x1,int y1,int x2,int y2) drawOval(int x,int y,int width,int height) Outline Shapes drawPolygon(int[] xPoints,int[] yPoints,int nPoints) drawRect(int x,int y,int width,int height) drawShape(java.awt.Shape shape) Setsthecurrent drawingcolor. fill() Needstobedone beforedrawingor FilledͲin fillOval(int x,int y,int width,int height) filling. Shapes fillPolygon(int[] xPoints,int[] yPoints,int nPoints) fillRect(int x,int y,int width,int height) 68 fillShape(java.awt.Shape shape) Sidenote:DrawingText
drawString(java.lang.String string,int x,int y) Drawthetextgivenbythespecifiedstring,using thecurrentfontandcolor. java.awt.Font getFont() Getthecurrentfont. setColor(java.awt.Color color) Setthecurrentdrawingcolor. setFont(java.awt.Font f) Setthecurrentfont.
69 Growing,Shrinking,Transparency
int getHeight() Returntheheightoftheimage. Growing int getWidth() & Returnthewidthoftheimage. Shrinking scale(int width,int height) Scalesthisimagetoanewsize.
int getTransparency() Returnthecurrenttransparencyoftheimage. setTransparency(int t) Setthetransparencyoftheimage.
mirrorHorizontally() Mirrorstheimagehorizontally(fliparoundthexͲaxis). Other mirrorVertically() animated Mirrorstheimagevertically(fliparoundtheyͲaxis). effects rotate(int degrees) Rotatesthisimagearoundthecenter. 70 FunwithImages
Usefulifinterestedinusingsomeofthemedia computationstuff SeegetColorAt(x,y)andsetColorAt(x,y) methods Grayscale animage Filtersonimages Createnegative Chromakey Canbeusedtoreinforceloops
71 Greenfoot
SimpleAssignments withDiceandCards
72 BooleanExpressions:Craps Thegameconsistsofrolling26Ͳsideddice.Theshootermakesa"comeͲ outroll"withtheintentionofestablishingapoint. Iftheshooter' scomeͲoutrollisa2,3or12,itiscalled"craps"(the shooterissaidto"crapout")andtheroundendswithplayerslosing.
AcomeͲoutrollof7or11iscalleda"natural,"resultinginawin.
Iftheshooter' scomeͲoutrollisa4,5,6,8,9,or10,thisnumberbecomes the"point".Oncethe"point"isestablished,theshooterwillnow continuerollingforeitherthepointnumberoraseven. Iftheshhtooterissuccessfflulinrollingthepoiitntnumber,theresultisawin. Iftheshooterrollsaseven(calleda"sevenͲout"),theresultisaloss.
73 BooleanExpressions:Craps
74 ArraysandArrayLists:Poker(part1)
75 Interfaces:Poker(Part2)
76 Interfaces:Poker(Part2) publicinterfaceIHandPropertyTester { /** *Returnstrueifandonlyifhandsatisfiesthisproperty *@param handisthehandtested *@returntrueifhandsatisfiespropertybeingtested */ boolean hasProperty(Handhand);
/** *Returnsthevalueofthishandifhandsatisfiestheproperty *@param handisthehandtested *@returnvalueofthehandtested. */ int getHighValue(Handhand); }
77 Arraysand2ͲDarrays
78 StudentLottery (h(Whogetsthisquestionorprize?)
79 BeyondAdvanced (andontoreally,reallycool)
GamePads,Kinect
80 GamePads
PS2andXBox likegamepads Supportclassesneededandavailable(along withdocumentationandexamples) http://www.greenfoot.org/doc/gamepad/
81 Kinect
http://www. greenfoot. org/doc/kinect/ Kinect video
82 Crabs,andLobsters,andBears ohmy!?!
Help,Resources,&Community
83
GreenfootGallery
Share! Greenroom
Meet! Moreinformation www.greenfoot.org discussiongroup scenarioreppyository tutorials(textandvideo) Greenfoot Gallery Greenroom Adrienne:newyorkͲhub@greenfoot. org Fran:newjerseyͲ[email protected] Questions?
DiscussionTime
88