
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 IldIncluderandombhbehav iorandsound 6 Agenda Movingbeyondthefirstscenario: Demonstrationofsomeadvancedfeaturesof Greenfoot: Imagecontrol Animation CollisionDetection 7 Agenda SomeexamplesusingGftGreenfoot tothteachor 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("s lurp.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 TheLbLobstermeetsthecrab 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
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages88 Page
-
File Size-