trees greenfoot

88
Greenfoot An Introduction to OOP Presented by Adrienne Decker Stephanie Hoeppner Fran Trees 1 Some materials based on Greenroom Resources. Free to use, modify and distribute under Creative Commons AttributionͲShare Alike 3.0 License.

Upload: eriani-wulandari

Post on 03-Oct-2015

31 views

Category:

Documents


9 download

DESCRIPTION

biologi

TRANSCRIPT

  • GreenfootAnIntroductiontoOOP

    PresentedbyAdrienneDecker

    StephanieHoeppnerFranTrees

    1

    SomematerialsbasedonGreenroomResources.Freetouse,modifyanddistributeunderCreativeCommonsAttributionShareAlike3.0License.

  • GreenfootGreenfoot

    a combination between a framework foracombinationbetweenaframeworkforcreatingtwodimensionalgridassignmentsinJavaandanIDE.

    atoolforteachingprogrammingwiththeJavalanguage. Intendedforages14andolder. Downloadfrom:http://www.greenfoot.org/ IthasinterfacetranslationsintolanguagesincludingFrench,GermanandItalian.

    2

  • Session DescriptionSessionDescription Inthispresentation,wewillintroduceG fGreenfoot.

    ThispresentationisaimedatteachersofintroductoryJavaprogrammingcourses(highschoolsanduniversities)whohaveneverworkedwiththeGreenfoot environmentbefore.

    3

  • Presentation DescriptionPresentationDescription Thispresentationisintendedtogiveeducatorsan introduction to the Greenfoot environment aanintroductiontotheGreenfoot environment,ademonstrationofhowitcanbeusedtointroduceobjectorientedprogrammingtostudents,andaj p g g ,guidedapproachtodevelopingGreenfootexperiencesthatcanbeintegratedintoexisting

    i lcurricula.

    Th i i i ll i d d ll ThesessionispracticallyorientedandallowsparticipantstouseGreenfoot intheirclassroomimmediatelyimmediately.

    4

  • SessionGoals

    TointroducetheGreenfoot environment Asourcecodeeditor Aclassbrowser Compilationcontrol Execution controlExecutioncontrol

    WhilediscussingtheteachingofJava through examples Javathroughexamples

    5

  • AgendaAgenda

    Building a Greenfoot program (to learn aboutBuildingaGreenfoot program(tolearnaboutGreenfoot)CRABS,WORMS,andLOBSTERS Start with an existing scenario Startwithanexistingscenario IntroduceobjectsandclassesWork with interacting classes Workwithinteractingclasses

    LookatmovementintheworldI l d d b h i d d Includerandombehaviorandsound

    6

  • AgendaAgenda

    Moving beyond the first scenario:Movingbeyondthefirstscenario:DemonstrationofsomeadvancedfeaturesofGreenfoot:Greenfoot: ImagecontrolAnimation Animation

    CollisionDetection

    7

  • AgendaAgenda

    S l i G f t t t h SomeexamplesusingGreenfoot toteachorreviewCStopics

    Greenfoot.org PublishingScenarios AvailableResources

    Questions?????Q

    8

  • Greenfoot (Little Crab Scenario)Greenfoot (LittleCrabScenario)

    Like BlueJ Greenfoot teaches objectorientedLikeBlueJ,Greenfoot teachesobject orientedprogramminginavisualmanner.Eachactorisan object that moves around in a world (alsoanobjectthatmovesaroundinaworld(alsoanobject).

    Thisallowsteachingofobjectorientedi i l ( h d i i bj )principles(methodinvocation,objectstate)

    beforeevenbeginningtolookatorwritedcode.

    9

  • Greenfoot EnvironmentGreenfoot Environment

    ClassDiagram

    World

    10

  • Greenfoot classes(HelpOption)

    ActorActor GreenfootSoundGreenfootSound

    GreenfootGreenfoot MouseInfoMouseInfo

    GreenfootImageGreenfootImage WorldWorld

  • Objects and Classes ClassObjectsandClasses Class Crab

    Instance

    constructoroftheCrabclass

    12

  • Defining state (attributes)Definingstate(attributes)

    ObjectInspector

    13

  • Defining behavior (methods)Definingbehavior(methods)

    Crabmethods

    14

  • Defining behavior (methods)Definingbehavior(methods)

    MethodsMethodsinheritedfromAnimal

    15

  • Definingbehavior(methods)

    MethodsMethodsinheritedfromActor

    16

  • ActorsActors

    'Actors' have predefined state:Actors havepredefinedstate:

    image location (in the world)location(intheworld) rotation

  • CreateanewCrabandpress">Act"Click"Run"tocallactcontinuously

    Nothingh !happens!

    18

  • LetsinvestigatetheJavacodeforact!

    import greenfoot.; // (World, Actor, G f tI d G f t)GreenfootImage, and Greenfoot)

    /This class defines a crab. Crabs live on the beach.

    /bli l C b t d A i lpublic class Crab extends Animal

    {public void act(){

    Thecrabdoes{}

    }nothingwhenitacts!

    19

  • Defining the Crabs behavior for actDefiningtheCrab sbehaviorforactpublic class Crab extends Animal{

    public void act(){{

    move();}}

    } Compile Compile Run Whathappens?

    20

  • MovementKey PointMovement KeyPoint

    Y h th l l f b t ti / l it Youcanchoosethelevelofabstraction/complexitytoexposetoyourstudentsbypreparingthescenarioscenario.

    move();move(); setLocation( getX()+1, getY() );

  • Defining the Crabs behavior for actDefiningtheCrab sbehaviorfor act Ifcrabisattheedge,turnaroundand

    h h

    public class Crab extends Animal

    gotheotherway.

    public class Crab extends Animal{

    public void act(){{

    move();// more code here

    }}

    22

  • Ifcrabisattheedge,turnaroundandgo the other waygotheotherway.

    23

  • Ifcrabisattheedge,turnsmoothlyandgo the other way!gotheotherway!

    public void act(){

    ()move();if( atWorldEdge() ){{

    turn(15);}

    }

    24

  • ObjectsandClassesl ld h bPopulateyourworldwithcrabs

    EachinstanceofaC b has its ownCrab hasitsownattributes(state).

    25

  • ObjectsandClasses

    Thedescriptionofwhatcomprisesanobject ofaparticulartypeisaclassyp

    Aclass definesthebehavior andattributes(characteristics)ofobjects(whatanobjectknowsaboutitself).

    Objects areinstances ofaclass.

    Crab class: blueprintCrab objects Crab class:blueprintforcrabs

    26

  • What a crab knows about itself:Whatacrabknowsaboutitself:

    Crabscannotdirectlyaccess:

    xyyRotationWorldimage

    NeedaccessorsandmutatorsprovidedbyActor to do thatActor todothat.

    27

  • Crab inherits from ActorCrab inheritsfromActor Crabscannotdirectly accessdirectlyaccess: x yy Rotation Worldi image

    Need accessors andNeedaccessors andmutators providedbyActortodothat.

    28

  • Crab inherits from ActorCrab inheritsfromActor Crabscannotdirectly accessdirectlyaccess: x yy Rotation Worldi image

    Need accessors andNeedaccessors andmutators providedbyActor todothat.

    29

  • Crab inherits from ActorCrab inheritsfromActor Crabscannotdirectly accessdirectlyaccess: x yy Rotation Worldi image

    Need accessors andNeedaccessors andmutators providedbyActor todothat.

    30

  • Crab inherits from ActorCrab inheritsfromActor Crabs can notCrabscannotdirectlyaccess: x y Rotation WorldWorld image

    Needaccessors andmutators providedby Actor to do thatbyActor todothat.

    31

  • Objects and ClassesObjectsandClasses Populateyourworldwithafewinstancesofthep yCrab class.

    Cantherebemorethanoneobjectinaposition? CanaCrabmovetoapositionthatanotherCrab occupies?

    Can a Crabmove outside the boundaries of the CanaCrabmoveoutsidetheboundariesoftheworld?

    HowisinvokingtheactmethodofaCrab gdifferentfromclickingtheact executioncontrolbutton.

    32

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

    public CrabWorld() {

    super(560, 560, 1);

    addObject(new Crab() 100 200);addObject(new Crab(), 100,200);addObject(new Crab(), 150,290);addObject(new Crab(), 300,400);addObject(new Crab(), 500,50);

    }}

    33

  • SavetheWorld!

    34

  • Interactingclassesh b hThecrabsarehungry!

    Crabseatworms.C abs eat o s.1. RightclickAnimal;choose"New Subclass..."2 Name it "Worm"2. Nameit"Worm".

    3. Chooseanimage.

    Addwormstoyourworld.

    RunWhathappens?pp

    35

  • ModifytheCrabclasstoteachthecrabtoeatworms.

    If the crab sees a worm Worm.classIfthecrabseesaworm Eattheworm

    Worm.class

    36

  • ModifytheCrabclasstoteachthecrabtoeatworms

    If the crab sees a wormIfthecrabseesaworm Eattheworm public void act()

    {{move();if(canSee(Worm.class)){{

    eat(Worm.class);}else if( atWorldEdge() )else if( atWorldEdge() ){

    turn(15);}

    }37

  • Greenfoot soundsGreenfoot soundsif(canSee(Worm.class)){{

    eat(Worm.class);G f t l S d(" l ")Greenfoot.playSound("slurp.wav");

    }Y h h l l f Youcanchoosethelevelofabstraction/complexitytoexposetoyour

    d b i h istudentsbypreparingthescenario. Animal definescanSeeandeat...

    38

    ...butitdoesnothaveto.

  • Summary: so far..Summary:sofar..

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

    39

  • More interesting behaviorMoreinterestingbehavior

    Random NumbersRandomNumbers InGreenfoot:

    int r = Greenfoot.getRandomNumber(100);g ( ); Returnsarandomint between0(inclusive)and100(exclusive)

    int r Greenfoot getRandomNumber(100) 50; int r = Greenfoot.getRandomNumber(100)- 50; Returnsarandomint between50(inclusive)and50(exclusive)

    40

  • A more interesting CrabAmoreinterestingCrabpublic class Crab extends Animal{{

    public void act(){

    if ( atWorldEdge( ) ){

    (1 )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

  • The improved CrabTheimprovedCrabpublic class Crab extends Animal{

    public void act(){{

    turnAtEdge()randomTurn();move();lookForWorm();

    }}}

    42

  • An alternate CrabWorldAnalternateCrabWorldpublic 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

  • Gameisoverwhentherearenoworms!

    Whose responsibility is it to keep track of theWhoseresponsibilityisittokeeptrackoftheworms?

    World Methods? WorldMethods? Howdowe"stop"theGREENFOOTGame?

    44

  • BoringBoring

    NothingEXCITINGhappens! Introduce

    TheLobster

    45

  • InteractiveprogramsTh L b h bTheLobstermeetsthecrab

    Crabseatworms. Lobsterseatcrabs! Yougettocontrolthesinglecrab!

    46

  • The LobsterTheLobster

    TheLobster behaveslikethecrabdidbuteatse obste be a es e t e c ab d d but eatscrabsinsteadofworms.

    public void act(){

    turnAtEdge();randomTurn();move();lookForCrab();

    }}

    The crab's behavior will changeThecrab sbehaviorwillchange.

    47

  • The interactive CrabTheinteractiveCrab

    The crab is controlled by the keyboardThecrabiscontrolledbythekeyboard. Leftarrowturnthecrab4degreesRight arrow turns the crab 4 degrees Rightarrowturnsthecrab4 degrees

    public void act()public void act(){

    checkKeypress();move();lookForWorm();

    }

    48

  • KeypressKeypress

    public void checkKeypress()public void checkKeypress(){

    if (Greenfoot.isKeyDown("left")) {

    turn(-4);}}if (Greenfoot.isKeyDown("right")) {

    turn(4);turn(4);}

    }

    49

  • Animatedcreaturesh bAnimatethecrab!

    The image files used for your animationTheimagefilesusedforyouranimationshouldliveintheimagesfolderfortheprojectproject. crab.pngcrab2 png crab2.png

    50

  • Animate the crab!Animatethecrab!private GreenfootImage image1;p g gprivate GreenfootImage image2;

    public Crab(){

    iimage1 = new GreenfootImage("crab.png");image2 = new GreenfootImage("crab2.png");setImage(image1);setImage(image1);

    }

    51

  • Animate the crab!Animatethecrab!

    public void act()public void act(){

    checkKeypress();checkKeypress();move();lookForWorm();lookForWorm();switchImage();

    }}

    52

  • OurnewWorld

    53

  • GameisoverwhentherearenowormsORwhenalobstereatsthe

    crab

    DistinguishbetweenWINandLOSS

    54

  • (Some) Advanced Features(Some)AdvancedFeatures

    CollisionDetection&Animations

    55

  • Key Point (Reiterated)KeyPoint(Reiterated)

    You can control the level of abstraction for theYoucancontrolthelevelofabstractionforthestudentswithregardstomovementandanimationanimation.

    56

  • Moving ActorsMovingActorspublic void move(double distance) {double angle = Math.toRadians( getRotation() );

    int x=(int)Math.round(getX()+Math.cos(angle) distance);int x (int)Math.round(getX()+Math.cos(angle) distance);int y=(int)Math.round(getY()+Math.sin(angle) distance);

    i ( )setLocation(x, y);}

    57

  • Motion Using VectorsMotionUsingVectors

    SmoothMover class uses a Vector to holdSmoothMover classusesaVector toholddirectionandspeedofmotion.

    Can create subclasses of SmoothMover to CancreatesubclassesofSmoothMover tousethisstyleofmotion.C ill h i f d l d Canillustratetheseparationofmodelandview.

    58

  • Collision DetectionCollisionDetection

    Even if you dont have the students controlEvenifyoudon thavethestudentscontrolmotion/turning/etc.youcanstillhavethemwrite more sophisticated collision detectionwritemoresophisticatedcollisiondetectionbehaviorsusingthebuiltinmethodsinActorActor.

    59

  • Collision Detection MethodsCollisionDetectionMethodsjava.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 il i Obj (i di j l Cl l )java.util.List getObjectsInRange(int radius,java.lang.Class cls)

    ActorgetOneIntersectingObject(java.lang.Class cls)

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

    60

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

    Pass in the class of the object to look for a particularPassintheclassoftheobjecttolookforaparticulartypeofcollision

    Passinnull tolookforanyintersectingobjecty g j

    Returns one Actor object that matches the criteria.ReturnsoneActor objectthatmatchesthecriteria. null isreturnedifnointersectionsaredetected

    61

  • getOneObjectAtOffset(i t d i t d j l Cl l )(int dx, int dy, java.lang.Class cls)

    L k l h f bj t ( i d d d ) Lookelsewhereforanobject(passinadxanddy) TheClassparameterworksthesameasprevious.

    Returnssameasprevious:anActor objectthatisll if i t ti d t t dnull ifnointersectionsaredetected.

    62

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

    Returns a list (java.util.List) of allReturnsalist(java.util.List)ofallintersectingobjectsofaparticularclasstypecls. Passinginnull returnsintersectionsofalltypes.g yp

    Can be used to discuss collections, generics, foreachCanbeusedtodiscusscollections,generics,for eachloop.

    63

  • getObjectsAtOffset(int dx int dy(int dx, int dy,

    java.lang.Class cls)

    Analogous to getObjectAtOffset except that it AnalogoustogetObjectAtOffset exceptthatitreturnsalloftheobjectsthatareintersecting.

    64

  • getObjectsInRangeg j g

    List getObjectsInRange(int r, java lang Class cls)

    ll l

    List getObjectsInRange(int r, java.lang.Class cls)Return all objects within range 'r' around this object.

    cell:10pixels

    An object is "in jrange" if its center point is inside theinside the circle.

    65

    r=6(cells)

  • getNeighboursg g

    Most useful in a world where actors areMostusefulinaworldwhereactorsarecontainedinacell(likeGridWorld casestudyfor AP CS Exam)forAPCSExam).

    Returnsthelistofneighborsinthefourcardinal directions distance cells awaycardinaldirectionsdistance cellsawayfromtheactorscurrentlocation.P i h b l Passingtrue totheboolean parameterincludesthediagonals.

    66

  • GreenfootImageGreenfootImage

    This is the class that represents the images ofThisistheclassthatrepresentstheimagesoftheactorsandtheworldinthescenarios.

    You can programmatically manipulate these Youcanprogrammaticallymanipulatetheseimagesordrawyourownimagesprogrammaticallyprogrammatically.

    67

  • Drawing MethodsDrawingMethodsclear()

    drawImage(GreenfootImage image int x int y)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)drawOval(int x,int y,int width,int height)

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

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

    OutlineShapes

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

    drawShape(java.awt.Shape shape)

    fill()

    Setsthecurrentdrawingcolor.

    Needs to be done()

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

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

    FilledinShapes

    Needstobedonebeforedrawingor

    filling.yg y

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

    fillShape(java.awt.Shape shape)68

  • Sidenote: Drawing TextSidenote:DrawingText

    drawString(java.lang.String string, int x, int y)drawString(java.lang.String string,int x,int y) Drawthetextgivenbythespecifiedstring,usingthecurrentfontandcolor.

    java.awt.Font getFont() Getthecurrentfont.

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

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

    69

  • Growing, Shrinking, TransparencyGrowing,Shrinking,Transparencyint getHeight()

    Return the height of the imageReturntheheightoftheimage.int getWidth()

    Returnthewidthoftheimage.scale(int width,int height)

    Growing&

    Shrinking

    Scalesthisimagetoanewsize.

    int getTransparency()Return the current transparency of the image.Returnthecurrenttransparencyoftheimage.

    setTransparency(int t)Setthetransparencyoftheimage.

    mirrorHorizontally()mirrorHorizontally()Mirrorstheimagehorizontally(fliparoundthexaxis).

    mirrorVertically()Mirrorstheimagevertically(fliparoundtheyaxis).

    Otheranimated

    rotate(int degrees)Rotatesthisimagearoundthecenter. 70

    effects

  • Fun with ImagesFunwithImages

    Useful if interested in using some of the mediaUsefulifinterestedinusingsomeofthemediacomputationstuff

    See getColorAt(x,y) and setColorAt(x,y)SeegetColorAt(x,y)andsetColorAt(x,y)methods Grayscale animagey g Filtersonimages Createnegative Chromakey

    Canbeusedtoreinforceloopsp

    71

  • GreenfootGreenfoot

    SimpleAssignmentswith Dice and CardswithDiceandCards

    72

  • BooleanExpressions:CrapsThegameconsistsofrolling26sideddice.Theshootermakesa"comeoutroll"withtheintentionofestablishingapoint.If the shooter's comeout roll is a 2 3 or 12 it is called "craps" (theIftheshooter scomeoutrollisa2,3or12,itiscalled craps (theshooterissaidto"crapout")andtheroundendswithplayerslosing.

    Acomeoutrollof7or11iscalleda"natural,"resultinginawin.

    If the shooter's comeout roll is a 4 5 6 8 9 or 10 this number becomesIftheshooter scomeoutrollisa4,5,6,8,9,or10,thisnumberbecomesthe"point".Oncethe"point"isestablished,theshooterwillnowcontinuerollingforeitherthepointnumberoraseven.

    If th h t i f l i lli th i t b th lt i iIftheshooterissuccessfulinrollingthepointnumber,theresultisawin.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 handisthehandtestedp*@returntrueifhandsatisfiespropertybeingtested*/boolean hasProperty(Handhand);

    /***Returnsthevalueofthishandifhandsatisfiestheproperty*@param handisthehandtested*@returnvalueofthehandtested.*/int getHighValue(Handhand);

    }}

    77

  • Arrays and 2D arraysArraysand2 Darrays

    78

  • StudentLottery( h h )(Whogetsthisquestionorprize?)

    79

  • BeyondAdvanced(andontoreally,reallycool)

    GamePads,Kinect

    80

  • Game PadsGamePads

    PS2 and XBox like game padsPS2andXBox likegamepads Supportclassesneededandavailable(alongwith documentation and examples)withdocumentationandexamples)

    http://www.greenfoot.org/doc/gamepad/

    81

  • KinectKinect

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

    82

  • Crabs,andLobsters,andBearsohmy!?!

    Help,Resources,&Community

    83

  • Greenfoot GalleryGreenfootGallery

    Share!Share!

  • Greenroom

    Meet!

  • More informationMoreinformation www.greenfoot.org

    discussiongroup

    scenariorepositoryp y

    tutorials(textandvideo)

    Greenfoot GalleryGreenfoot Gallery

    Greenroom

    Adrienne: newyork hub@greenfoot org Adrienne:[email protected]

    Fran:[email protected]

  • Questions?Questions?

    DiscussionTime

    88