Java Programming: Getting Your Feet Green

Getting your Feet Green
Teaching Java and Object Oriented Programming Techniques
With Greenfoot
Introduction: Basic Housekeeping
o Hello and Welcome to TCEA 2015.
o Please set all phones to vibrate. If
you have an important call, please
take it in the hall.
o During breaks, Please feel free to
share our experience on Social
Media. Tweets and likes are
appreciated. #TCEA2015
Background: Java and Greenfoot
oJava is one of the most widely used programming languages on Earth.
Refrigerators, thermostats, cars: many devices in the Internet of
Things speak java.
oGreenfoot 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.
oGreenfoot is an introductory and education IDE that is also capable of
some professional results.
oGreenfoot makes coding fun by allowing the new developer to
concentrate on creating. Greenfoot keeps the complicated stuff
“under the hood”.
How to Teach Code: Practice
oIn 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.
oThe 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.
oHaving said that…Let’s get started.
The Greenfoot IDE: Wombats Everywhere
oYou 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.
oYou 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.
Object Oriented Programming: Class In
oObject 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.
oOOP 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.
oIt 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
Object Oriented Programming: The Object of
the Game
oStart 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”.
oThe 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.
oFinally, 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.
oGreenfoot 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.
oThe 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.
oClick the “Compile” button and let’s see what happens…
oThe 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.
oWe 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.
Classes: Inheritance
oWe need to pause and look at an important
concept in OOP, Inheritance.
oJust as we receive features and tendencies from
our parents, classes can access methods and
other constructs from their parent classes.
oThe 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.
oNow lets see what these actors can do.
oIf 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.
oLEFT CLICK on the void act() method and see the results.
oThe wombat moves to the right by one square.
We have just called a METHOD and the object
oNow 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.
oThe 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.
oNow 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.
Source Code: Lets Look at the Instructions
oNow lets look at
the source code.
In the navigation
column, LEFT
CLICK on the
Wombat entry and
select “Open
Editor” from the
oThe lines that begin with
“import” allow us to use
libraries of code that have been
written for the Java language or
for Greenfoot itself.
oThe line public class Wombat
extends Actor is the class
declaration. It tells us what
class we have and what it
inherits from.
oOne 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
Break Time: Everyone take 10 minutes
oPlease be back on time so that we can make the most of your time
oDon’t forget to promote the class on social media. #Greenfoot #Java
#TCEA15 #TechnologyNEducation
oTwitter: @ReganWhite222
New Scenario: The Little Crab Game
oIn 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.
oOur 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.
oOur 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.
oYou’ll notice that the class icons are crosshatched. Go ahead and click the compile
button to build them into usable classes.
oOnce you have the classes compiled, put a
crab into the world.
Crab class in the
navigation panel.
Select “Open Editor”
from the context
menu. Lets start
adding code to our
crab class.
oCurrently 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.
oIf 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.
oObviously 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.
oHaving our crab stuck at the edge of the world is not very
useful. Fortunately there is another method from the
oIf 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.
oNotice 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.
oNow, run the code and see the changes.
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.)
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.
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.
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.
Back to Business: Random is Good
oMuch 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
oTo 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.)
oAdd the following code in another IF statement:
if (Greenfoot.getRandomNumber(100) < 10)
o 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
o In this case we want a random number between 0
and 100. 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.
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.
oTo create a new class, simply fill
in the appropriate box with a
name, in this case, Worm as all
class names should be capitalized.
oSelect 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
oNow, see if you can add some
worms to your world. Don’t forget
to recompile.
o OK we have worms. What do we DO
with them?
o 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.
o 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.
o 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.
o We will need another IF statement
and we will be putting this in the
CRAB code editor, not worm. (WHY?)
o Add the following code to the act() method of the Crab class
If (canSee(Worm.class))
o 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
More Random Behavior: Our Crab is
oCan anyone tell me what is wrong with our crab? It incorporates
random motion in the frequency of its turns but something is not
oIf 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.
oIn our already random IF statement, add the following:
turn(Greenfoot.getRandomNumber(90) – 45);
o What could this code possibly
o 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.
o Notice that 45 is half of 90. 50%
the time the answer we get will
positive and the other half of the
time the number will be negative.
o Therefore, 50% of the time our
will be right and 50% of the time,
our turn will go left. Recompile,
some worms and a crab, and run
the code.
Creating Our Own Methods
oWe can create methods in Greenfoot as easily as we can use methods
already created for us.
oWe 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.
oLets move our looking and eating code into its own method. First we
need to declare the method.
Well I Declare: Making Methods
oMethod 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.
oWe 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.
oWe create the skeleton of
our method below the last
closing curly bracket of the
“act()” method.
oWe 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
oWe include the open and
closing curly brackets to
place the code
o Now we go back in to the act method and
replace all that code with a simple
call. We use the name of the function
followed by parenthesis and a semi colon.
o We don’t need anything in the parenthesis
because our method does not have a
o 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.
Now It’s Your Turn: Create a Method
oCreate 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.
oCreate 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.
oYou should have three new methods,
each public and each with no return or
oYou should also have three new method
calls in the act() method after move()
oNow is a good time to mention
COMMENTING your code.
oA comment is a note to yourself or
another developer about what a method
is supposed to be or do.
oThe 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.
oThere are two types of comments;
in-line and multiple line.
oIn-line comments are used to
document a single line of code. They
are designated with a pair of forward
slashes as shown here.
oMultiline 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.
Behavior: Our Program has a Problem
oSo far so good but our game has a couple of problems.
oWe need an enemy. In this case, the EVIL LOBSTER (a known crab
will play the part of the villain of this picture.
oOur 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.
oIn 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
Let’s See What You’ve Learned
oGo 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
oRIGHT CLICK on Animal and select New Subclass; In the dialog box,
name the class Lobster and select the lobster image.
oClick OK.
oRIGHT CLICK on Animal, Select
New subclass from the menu
oName the class “Lobster” and
select an appropriate image.
oFinally, click OK to add the class
to our program.
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.
o We will need to modify the new
code slightly. First, we change the
name of the class to Lobster.
o 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.
o And finally, we change the method
name and method call to reflect
the new target.
Lets get the Player Involved
oWe are going to use a Greenfoot method called
static boolean isKeyDown(“string”);
oto control the movement of our crab.
oThe 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.
oWe 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.
o We replaced the randomTurn() method with a
checkKeyPress() method to see what key is being
o 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.
o We also added a call to this method in place of the
randomTurn() method call in act()
o And finally, we got rid of the turnAtWorldEdge()
method. I mean…you are driving this thing right?
o Recompile and make sure everything works and
then it will be time to try it out.
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.
oI think the stop() fits the bill nicely. It requires no parameters and
simply brings an ongoing scenario to a halt when called.
oWhere 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.
oI 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.
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.
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
• 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.
The New Keyword New
oTo instantiate a class (create a new object from it) we use the “new”
key word.
oWe also need to tell our world where to put the object. We use left
and top pixel counts to do that.
oFor 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.
oWe add out new object into the
constructor method of CrabWorld.
oWhen we recompile we now find a
sitting in the middle of our world.
oGo ahead and add a couple of
lobsters to the top and bottom of
our world.
oNow for a challenge. Add 5 worms
to random locations within the
oWe 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.
oNow when we recompile, the game is ready to go.
oThe last feature we will add to our game is to make our Crab’s movement a little more realistic.
oCrabs tend to move with a jerky scuttle but ours glides across the sand like an Olympic figure skater.
oLets use an old animation trick called “Persistence of Vision” to make him look alive.
Now You See Him
oGreenfoot 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.
oWe will use the Greenfoot.image methods to swap the pictures
quickly in the program.
oWe 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);
Now You See Him
oOnce we have the new image created, we can use the setImage method to
assign it to a Greenfoot actor.
setImage(new GreenfootImage(“crab2.png”);
oNotice we are creating a new image and assigning it in the same line of
oNow we need to make the images switch. To do that we need a place to
hold them. We will use a pair of fields.
oFields 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.
oWe 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.
oWe assign the images to the crab object inside
the Crab constructor.
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
• 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
oFirst 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.
oWe use the getImage and setImage methods,
which are build into the Actor class from which we
inherit, to change the image.
oNext 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.
And Finally: What We Need to Have a
Real Game
• Can anyone guess the last piece of the puzzle?
oWe need to keep score if this is a game.
oIn 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.
oWe need to instantiate this code into our lookForWorm() method
since this is where the eating occurs
oWe create a field of type “int” or integer to hold
our worms eaten.
oNext we add to our canSee(Worm.class)
statement to add 1 to our eaten worm total every
time we eat one.
oFinally, 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
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…
New Ideas
• Use different images to change to tone of the game
• Use more different kinds of actors (add a boss or another prey
• 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.
Related flashcards
Draughts variants

10 Cards

Chess officials

47 Cards

Create flashcards