Presentation is loading. Please wait.

Presentation is loading. Please wait.

Getting your Feet Green

Similar presentations

Presentation on theme: "Getting your Feet Green"— Presentation transcript:

1 Getting your Feet Green
Teaching Java and Object Oriented Programming Techniques With Greenfoot

2 Introduction: Basic Housekeeping
Hello and Welcome to TCEA 2015. Please set all phones to vibrate. If you have an important call, please take it in the hall. During breaks, Please feel free to share our experience on Social Media. Tweets and likes are appreciated. #TCEA2015 #Greenfoot

3 Background: Java and Greenfoot
Java is one of the most widely used programming languages on Earth. Refrigerators, thermostats, cars: many devices in the Internet of Things speak java. Greenfoot is one of the easiest ways to learn Java syntax and Object Oriented Programming techniques while not being buried in the minutia of the language. Greenfoot is an introductory and education IDE that is also capable of some professional results. Greenfoot makes coding fun by allowing the new developer to concentrate on creating. Greenfoot keeps the complicated stuff “under the hood”.

4 How to Teach Code: Practice
In a word, the best way to teach coding is “practice”. The instructor leads and the students follow along. It may seem boring at times to copy line after line of code from a book or screen into a text editor but as you type through the lines you begin to see how they fit together. You can not learn by copy and paste or by lecturing about code others have written. You need to type it for yourself. The goal of this instructional period is to teach you how to teach others to code, even if you are not an expert. I will give you resources and some techniques to use with your students but the main thing to remember is to have them type out the code. Having said that…Let’s get started.

5 The Greenfoot IDE: Wombats Everywhere
You should find a flash drive at your work station. Go ahead and insert it into a USB port. Once it is recognized, navigate from “Computer” to the flash drive and let’s see what’s there. You should see an application called Greenfoot as well as one called BlueJ. This is a bonus I have tossed in. BlueJ is also a java IDE that is a bit more advanced that Greenfoot. It is a logical progression from one to the other as the student becomes more skilled. You will also see a folder labeled SDK. This is a version of the Java Development Kit that is required for both Greenfoot and BlueJ to run. These flash drives are completely self contained and should work on any Windows system without running an install file of any kind. Just plug and go.

6 Object Oriented Programming: Class In Session
Object Oriented Programming is a way of developing software using small units of code to model real world objects. It is a step away from the old procedural monolithic style of coding that depended on the program following a set script. OOP as we will call it, uses smaller sections of code, each designed to do a single task. They are put together like building blocks to accomplish whatever task to program is required to do. It is a good idea to begin each lesson by giving your students the fundamental concepts that they should master by the end of the lesson. In this case, our first concepts are Classes and Objects. These are the fundamental building blocks of OOP

7 Object Oriented Programming: The Object of the Game
Start Greenfoot from your flash drive and navigate to the folder entitled examples. Open the folder called “Wombats and Leaves” and then open the Project file called “Project”. The Greenfoot IDE or “Integrated Development Environment” is very simple and easy to navigate. The large central section is called the “world”. It is where the action takes place. There is a longer narrow section along the right side of the screen called the Class Navigation Windows. You can see the different classes within your project here and follow their hierarchy of inheritance. Finally, the section along the bottom contains the Run, Pause, Speed, and Reset buttons. We will investigate each of these controls as we move through the program.

8 Greenfoot programs or “scenarios” require two basic classes: the World and the Actor class. The world class is the container while the actor does whatever action is required. The cross-hatched lines mean that the class has yet to be compiled. A compiler is a program that takes code and makes it into something a computer can act on; in this case, Java byte code. What we are writing are essentially text files with a “.java” prefix. The compiler turns them into Java classes. Click the “Compile” button and let’s see what happens…

9 The cross-hatching goes away and we can see exactly what “Wombat World” looks like. It is supposed to be sand but any image may be used. We have two actor classes in our list but neither appear in the program yet. In order to place one, RIGHT CLICK on the “Wombat” class, place your cursor on the sand colored area and LEFT CLICK. You just built your first Object using a Class as a pattern.

10 Classes: Inheritance We need to pause and look at an important concept in OOP, Inheritance. Just as we receive features and tendencies from our parents, classes can access methods and other constructs from their parent classes. The arrow leading from “Wombat” up to “Actor” shows an inheritance relationship. “Wombat” is a type of “Actor” It can do anything an actor can do in addition to all the things unique to wombats. Now lets see what these actors can do.

11 If we RIGHT CLICK on the Wombat image we can see a list of the METHODS available in the Wombat class as well as the methods that the Wombat inherits from the actor class. LEFT CLICK on the void act() method and see the results.

12 The wombat moves to the right by one square
The wombat moves to the right by one square. We have just called a METHOD and the object responded. Now look at the buttons below the World image. You will notice and “Act” button there as well. LEFT CLICK the “Act” button and see the results. The wombat has moved another square. The “Act” button allows us to call the Act method for any actor. All actors in Greenfoot have an act() method. Now click the “Run” button. The wombat continues to move. The “Run” button calls the act() method continuously as it was meant to be called. The act() method is a loop.

13 Source Code: Lets Look at the Instructions
Now lets look at the source code. In the navigation column, LEFT CLICK on the Wombat entry and select “Open Editor” from the menu.

14 The lines that begin with “import” allow us to use libraries of code that have been written for the Java language or for Greenfoot itself. The line public class Wombat extends Actor is the class declaration. It tells us what class we have and what it inherits from. One method we need to look at has the same name as the class itself. We call this method the CONSTRUCTOR and it is where we put code to initialize our class.

15 Break Time: Everyone take 10 minutes
Please be back on time so that we can make the most of your time today. Don’t forget to promote the class on social media. #Greenfoot #Java #TCEA15 #TechnologyNEducation Facebook: Blog:

16 New Scenario: The Little Crab Game
In Greenfoot, LEFT CLICK File and select “Open”. Browse to the “Examples” folder and open the “Little Crab” directory. Select the “Project” file and Greenfoot will open the Little Crab scenario. Our goal here is to build, as much as possible in the time we have, a playable game. This is how I would teach a classroom of students, with some minor modifications on the presentation.

17 Our goal here is to build, as much as possible in the time we have, a playable game. This is how I would teach a classroom of students, with some minor modifications on the presentation. You’ll notice that the class icons are cross-hatched. Go ahead and click the compile button to build them into usable classes. Once you have the classes compiled, put a crab into the world.

18 RIGHT CLICK on the Crab class in the navigation panel
RIGHT CLICK on the Crab class in the navigation panel. Select “Open Editor” from the context menu. Lets start adding code to our crab class.

19 Currently we have a single import statement that allows us to use the libraries specific to Greenfoot. We have a multi-line comment, and we have a class definition. Finally we have a public method called act() that exists in all Greenfoot actors. If we were to close the code editor and click on the “Run” button in the Greenfoot interface, absolutely NOTHING would happen because the act() method is empty. Obviously the first thing we want our crab to do is move. We need to find or build a method to tell our crab how to move. Fortunately for us, crab is a sub-class of actor, which has a method we can use. If we type in move(); between the opening and closing curly brackets in the act() method recompile our class, and then click the “Run” button, we find that things have changed.

20 Having our crab stuck at the edge of the world is not very useful
Having our crab stuck at the edge of the world is not very useful. Fortunately there is another method from the actor. If we RIGHT CLICK on the “Actor” class in our Greenfoot interface we see that instead of source code, we find documentation. This is a list of all the methods available to the Actor class. As we look through the list we find a “turn()” method that allows our actor to turn a number of degrees. Lets add that method call after the move() call in our crab code. Notice the number “5” contained within the parenthesis. This is called a parameter and it tells our method “how much” or “what” to do. Move() does not have a parameter and if we look at the move code, we see it is not needed as the actor continues to move until it is unable. The Turn() method, however, requires a number of degrees to know how far to turn. Hence the parameter. Now, run the code and see the changes.

21 Explanations: What is Going On Here??
I’m not sure that is better. Now we are going in circles. As you know, the act() method is a loop. It continues to fire until the program terminates, or as long as the actor exists. The crab is moving and then turning 5 degrees and then moving in succession and so it goes in circles. Take a moment and modify the parameter to see what effect making the number larger or smaller has. Try adding a non-numeric character and see what happens. (This is what I am constantly telling my kids…Try to break it and you’ll see how it works.)

22 Logical Flow: Making Decisions
The crab still gets hung up at the edge of the world. It does not know how to react. We have to teach it. Open the code editor for the “Animal” class. It opens in the documentation mode. Look through the methods and see if you can find one we could use. atWorldEdge() is described as a Boolean data type. This means that the method returns a value of True or False based on conditions within the program. We need a way to check those conditions using this method. We are going to use and IF statement as our logic tester.

23 //action code goes here; }
Modify the crab act() method as follows: The correct format for an “IF” statement in java is… if (condition) { //action code goes here; } If our condition (atWorldEdge()) returns true then we need to turn away from the edge. Once we are no long trapped we can keep moving. Recompile the code, add a new crab, and test out the results. It appears that our crab turns a lot more than 17 degrees. However, remember that the crab is turning 17 degrees, rechecking its position, and if it is still trapped, turning again. All this happens VERY rapidly. Once the crab is COMPLETELY clear of the edge, it continues in a straight line until it encounters the edge again. You can experiment with the amount of turning necessary to get away from the wall an still look natural within the game.

24 Recap: Let’s Take a Moment to Reflect
It is important to bring out programming concepts and practices to your students as you walk through the code. It is a good idea to assign vocabulary words as you enter new sections (Whether or not you use Michael Kölling’s book Introduction to Programming with Greenfoot (available from Prentice Hall), you need to make sure that your kids understand not only what they are doing, but WHY. Key Terms So Far… Class: A software model or pattern of a real world object. Things created from classes are called objects or instances interchangeably. Object: A software construct created when a class is instantiated to mimic some behavior of a real world object. Constructor: A method in a class, with the same name as the class, called when a class is instantiated. It basically creates the class. Parameter: A condition required for a method to work; usually contained in parenthesis after the class name. Method: A section of code that tells an object to do something. It may or may not return a value or response. Return Value: A response or message returned by a method upon completion of it’s task.

25 Back to Business: Random is Good
Much of what makes a good simulation comes of being unpredictable. If the antagonist behaves the same way every time, then a pattern develops and the game is easily beaten. We need to introduce some random behavior to make our characters seem more life-like. To accomplish this, we use a method from Greenfoot itself that allows us to create “Random” numbers. (These numbers aren’t really random as they are the results of a VERY lengthy and involved mathematical operation but for our purposes, they are close enough.)

26 Add the following code in another IF statement:
if (Greenfoot.getRandomNumber(100) < 10) { turn(5); } The method is a part of the Greenfoot environment itself. We call it using what is known as DOT NOTATION. The method expects a parameter that is an Integer (whole number). This number acts as the upper limit for our random number generator. The method will return an integer between zero and the upper limit. In this case we want a random number between 0 and If we determine that our numbers is less than 10 (ergo. 10% of the time) then our statement returns correct and the IF code fires. 90% of the time the number will be greater than 10 and the IF statement will be passed over.

27 Adding a New Character: Worms
Lets add a new character to the mix. In doing so, realize that far and away the hardest part of game development is character creation and design. Code is easy compared to drawing, coloring, and designing a good character. Greenfoot takes care of much of this by providing an extensive library or ready made sprites or images for your use. You may also create images in Photoshop or GIMP as long as they are PNG or JPG format. To create a new class, RIGHT CLICK on ANIMAL (make sure it is ANIMAL that you are right clicking on) and select Make a New Subclass from the menu.

28 To create a new class, simply fill in the appropriate box with a name, in this case, Worm as all class names should be capitalized. Select an image – scroll down until you see the worm image, just below sand.jpg and click to highlight it. Now click OK and you will see a new class Now, see if you can add some worms to your world. Don’t forget to recompile. Worm

29 OK we have worms. What do we DO with them?
We need to tell our crab how to eat them as this will be the primary scoring activity of our game. The crab eats as many worms as possible before something else eats him. To eat a worm, the crab must be able to find them. There are two methods from the Animal class that will help us; boolean canSee(java.class) and void eat(java.class). Both expect a parameter of the java class of some type; in this case, a worm class. The canSee() method returns a Boolean (true/false) value, while the eat() method just does it’s job and does not return a value as evidenced by its VOID description. We will need another IF statement and we will be putting this in the CRAB code editor, not worm. (WHY?)

30 If (canSee(Worm.class)) { eat(Worm.class); }
Add the following code to the act() method of the Crab class If (canSee(Worm.class)) { eat(Worm.class); } The logic is simple here. If the crab is within one block of a worm then he can see the worm. (Crabs don’t have great eye sight). If the conditions are met then the canSee method returns a Boolean value of True. If this is the case then the crab can and will eat the worm, completely destroying that one instance of the worm class. It will only destroy the worm object it eats. That worm will disappear from the world. This is why we put the code in the crab and not the worm. Now, recompile, place some worms and a crab into the world and click the “Run” button

31 More Random Behavior: Our Crab is Unnatural
Can anyone tell me what is wrong with our crab? It incorporates random motion in the frequency of its turns but something is not right. If you can’t guess, I’ll tell you. The crab only turns one way. Our intrepid hero is channeling the spirit of Dale Earnhart. He only turns left. We need to create another randomizer to mix up his turns a bit. In our already random IF statement, add the following: turn(Greenfoot.getRandomNumber(90) – 45);

32 What could this code possibly mean?
We are still using the turn() method but now for some reason we are getting a random number between 0 and 90 and subtracting 45 from it. Notice that 45 is half of % of the time the answer we get will be positive and the other half of the time the number will be negative. Therefore, 50% of the time our turn will be right and 50% of the time, our turn will go left. Recompile, add some worms and a crab, and run the code.

33 Creating Our Own Methods
We can create methods in Greenfoot as easily as we can use methods already created for us. We create these methods to ENCAPSULATE the code and make our program more modular. The goal of Object Oriented Programming is easily supportable code because it is built in fundamental units like blocks which are then put together to do the job. Lets move our looking and eating code into its own method. First we need to declare the method.

34 Well I Declare: Making Methods
Method definition involves declaring the method to be public or private, deciding on a return value, if any, and finally naming the method according to the conventions you have been given by whoever you are working for. We want our method to be public so that we can call it from anywhere. We don’t need a return value, and we can call it “lookForWorm()” It is a standard practice in Java to capitalize the class names and leave methods and variables lower case. It is also common practice to use camel notation to make the spaceless variable names easier to read.

35 We create the skeleton of our method below the last closing curly bracket of the “act()” method.
We declare the method public, we do not want a return value so we use the “void” keyword, and finally, we call it “lookForWorm()” according to common practice. We include the open and closing curly brackets to place the code

36 Now we go back in to the act method and replace all that code with a simple function call. We use the name of the function followed by parenthesis and a semi colon. We don’t need anything in the parenthesis because our method does not have a parameter. When our program reaches this point in the code it will automatically skip down to the method we call and perform that operation. It will then return to the same place in the “act()” method and continue on from there.

37 Now It’s Your Turn: Create a Method
Create a method on the Act() method of the crab class to encapsulate the random behavior of our crab. Take that code that generates random movement and place it in a public method with no parameters and no return. Create a method to encapsulate the edge of the world detection functionality. It needs no parameters and does not have a return. Be sure to include calls for both these methods in the “act()” method.

38 You should have three new methods, each public and each with no return or parameters.
You should also have three new method calls in the act() method after move() Now is a good time to mention COMMENTING your code. A comment is a note to yourself or another developer about what a method is supposed to be or do. The computer compiler will ignore comments but they are nice to have when you reopen a program a year later to do maintenance work on it and can’t remember what you were trying to do.

39 There are two types of comments; in-line and multiple line.
In-line comments are used to document a single line of code. They are designated with a pair of forward slashes as shown here. Multiline comments are usually found in the header of the class or prior to a method and may be used to give a more in-depth explanation of the purpose of the code. They are designated by a forward slash followed by an asterisk and then ended by an asterisk followed by a forward slash.

40 Behavior: Our Program has a Problem
So far so good but our game has a couple of problems. We need an enemy. In this case, the EVIL LOBSTER (a known crab eater.) will play the part of the villain of this picture. Our crab moves on his own. We need to control his movement. If this is supposed to be a game then we need to be able to PLAY. In point of fact, our crab behaves exactly as our lobster ought to. It moves randomly around and eats things. We are going to create a new class for lobsters and transfer the code from crab into lobster. We will then put new code into the crab to allow us to control his actions.

41 Let’s See What You’ve Learned
Go ahead and create a new class for lobster. We want to make it a subclass of Animal so that we can take advantage of the Animal methods. RIGHT CLICK on Animal and select New Subclass; In the dialog box, name the class Lobster and select the lobster image. Click OK.

42 RIGHT CLICK on Animal, Select New subclass from the menu
Name the class “Lobster” and select an appropriate image. Finally, click OK to add the class to our program.

43 Swapping Code We now open the crab editor, select ALL the code in the class, ctl + C to copy the code. We open the Lobster editor, select ALL the code already there, and then ctl + V to paste the new code in and get rid of the old. We will need to modify the new code slightly. First, we change the name of the class to Lobster.

44 We will need to modify the new code slightly
We will need to modify the new code slightly. First, we change the name of the class to Lobster. Our crab already behaves perfectly as a villain but we want him to eat crabs and not worms so we will modify the lookForWorm into lookforCrab() and change the target class. And finally, we change the method name and method call to reflect the new target.

45 Lets get the Player Involved
We are going to use a Greenfoot method called static boolean isKeyDown(“string”); to control the movement of our crab. The static keyword tells us that this is a class method. The boolean tells us that it returns a TRUE or FALSE value, and the “string” inside the parenthesis tells us we need to send it a string or text parameter; in this case, the name of the key we want to check on. We still want our crab to look for worms and we still want him to move so we will just remove the random motion code and replace it with our new code. We leave the lookForWorm() and move() methods alone.

46 We replaced the randomTurn() method with a checkKeyPress() method to see what key is being pressed.
If the left arrow key is pressed we want our crab to to turn left, if the right arrow key is used we want the crab to turn right. We also added a call to this method in place of the randomTurn() method call in act() And finally, we got rid of the turnAtWorldEdge() method. I mean…you are driving this thing right? Recompile and make sure everything works and then it will be time to try it out.

47 This is the End: Stopping the Game
We need to find a place to stop this game, hopefully when all the worms are eaten and not when our crab is eaten. We are going to search the “Greenfoot Documentation” to find a method to help us accomplish this. In the Greenfoot editor, click on the “Help” menu and select “Greenfoot Class Documentation” from the menu. A web page will open that lists the various classes available in Greenfoot. Click on the Greenfoot entry and the page will navigate to a document that lists the methods for the Greenfoot class itself. See if you can find a method to stop a game.

48 Stop() I think the stop() fits the bill nicely. It requires no parameters and simply brings an ongoing scenario to a halt when called. Where should we put it? One place we can use it now is when the lobster catches the crab. Look at the lobster code and type in a method call for the stop() method where you think it ought to go.

49 I think the best place to place the call would be as soon as the crab gets eaten by the lobster. At that point, Game Over.

50 Make it Interesting: Adding Sound
Before we go we need to add a few niceties to our scenario. We have a playable game but it could use some feedback in the form of sound. Greenfoot provides an extensive library of media to use in games. Greenfoot speaks .au and .wav files exclusively. (although support for .mp3 may have been added by now). We use the “playSound” method in Greenfoot to play the sound files. Sound files must be placed in the “sounds” directory where our Greenfoot project is saved. If you navigate there you will find a sound folder with sound files, an images folder for the various sprites, and a lot of class files. We want a slurping sound to play every time we eat a worm. Find the best place and enter Greenfoot.playSound(“slurp.wav”); Once you have added the line of code, recompile and run the game.

51 Getting Ready to Play One annoying factor about our game is the need to repopulate characters between rounds. We want our game to automatically reset when we want to replay. We need to use our world class to load the characters in automatically. Open up the CrabWorld class code and look for a method with the same name as the class. This method is called the constructor. It is called every time the world instantiates. This is where we put things we want to be automatically created when the game starts.

52 The New Keyword New To instantiate a class (create a new object from it) we use the “new” key word. We also need to tell our world where to put the object. We use left and top pixel counts to do that. For example, lets say we want our new crab to always appear in the center of the world. We would say addObject(new Crab(), 280, 280); because our world is 560 pixels by 560 pixels. Go ahead and add this code to the world constructor.

53 We add out new object into the constructor method of CrabWorld.
When we recompile we now find a crab sitting in the middle of our world. Go ahead and add a couple of lobsters to the top and bottom of our world. Now for a challenge. Add 5 worms to random locations within the world.

54 We can use the getRandomNumber() method to generate the random numbers
We can use the getRandomNumber() method to generate the random numbers. We feed it a parameter of 560 to make sure it never puts anything off the screen. Now when we recompile, the game is ready to go. The last feature we will add to our game is to make our Crab’s movement a little more realistic. Crabs tend to move with a jerky scuttle but ours glides across the sand like an Olympic figure skater. Lets use an old animation trick called “Persistence of Vision” to make him look alive.

55 new GreenfootImage(“crab2.jpg);
Now You See Him Greenfoot provides two crab images, one with legs extended and one with legs slightly bent. These two images, played in quick succession, make the crab look like he is walking. We will use the Greenfoot.image methods to swap the pictures quickly in the program. We must first create a new image and assign it the parameter of crab2.png. We use the “new” keyword and enter. new GreenfootImage(“crab2.jpg);

56 Now You See Him Once we have the new image created, we can use the setImage method to assign it to a Greenfoot actor. setImage(new GreenfootImage(“crab2.png”); Notice we are creating a new image and assigning it in the same line of code. Now we need to make the images switch. To do that we need a place to hold them. We will use a pair of fields. Fields are special variables called “instance variables”. They let us remember information as long as the object it is attached to exists in the game. Each crab will remember these two images. We declare them at the start of a class.

57 We declare two fields or instance variables in our Crab class and now we use the equal sign to assign them the value of the images we created. We assign the images to the crab object inside the Crab constructor.

58 Alternating the Image We use an IF/ELSE statement to switch the image.
We use the current image as the conditional on which to base our swapping. If, for example, the current image is image 1, we swap to image 2 and vice versa. We place this code in the act method which runs continuously and Greenfoot takes care of the rest

59 First we build a new method called imageSwap to handle the heavy lifting. It requires no parameters, although we could add the two images if we chose to. It has no return value, it just changes out the pictures. We use the getImage and setImage methods, which are build into the Actor class from which we inherit, to change the image. Next we place a call to this method into the Act() method of the crab. The Act() method continually runs and so our swapImage() method is continually called. If the current image is crab.png then we swap to crab2.png continuously as long as the crab still exists in our world.

60 And Finally: What We Need to Have a Real Game
Can anyone guess the last piece of the puzzle?

61 Score: We need to keep score if this is a game.
In order to do that we need to add the following constructs; an instance variable to remember how many worms we have eaten, a method to add the worms, and a call to the stop() method when we have eaten enough to win. We need to instantiate this code into our lookForWorm() method since this is where the eating occurs

62 We create a field of type “int” or integer to hold our worms eaten.
Next we add to our canSee(Worm.class) statement to add 1 to our eaten worm total every time we eat one. Finally, we end the game when our total equals 5. The double equal sign is not an assignment statement, it is a test. A single equal sign is an assignment. We set an object equal to a value, for example. We also toss in a sound file to let the user know less abruptly than just stopping the game.

63 What’s Next? The first thing we need to do is test our game to make sure it behaves exactly as we expect. Next we can look at some ideas to improve our game…

64 New Ideas Use different images to change to tone of the game
Use more different kinds of actors (add a boss or another prey animal) Instead of moving forward automatically, we might have to hold the up arrow. Build a two player game by setting up another keyboard control on the other side of the keyboard. Make new worms pop up when one is eaten.

Download ppt "Getting your Feet Green"

Similar presentations

Ads by Google