In this tutorial you learn how to create 2D games using basic Java
programming in this self-paced, online course. No programming
experience required! We will define and program a game using the
Greenfoot development software.
Time to Complete
Approximately 12
hours to complete the lessons.
Prepare for this course
This lesson will provide an overview of system requirements, show
you how to download necessary software, and describe the purpose
for using Greenfoot tools to learn Java.
Lesson Objectives
In this lesson you will learn to:
Describe the reasons Greenfoot is an excellent tool to
learn Java Programming
Check your system requirements to ensure that they support
this course
Have you ever wanted to build a video game or make an
animated movie? Are you interested in making your own
smartphone application? Many of today’s video games,
movies, and smartphone applications are created using the
Java programming language.
Java is a programming language and computing platform
developed by Sun Microsystems in 1995. Java runs on more
than 850 million personal computers worldwide, and on
billions of devices worldwide, including mobile and TV
devices.
Java allows you to play online games, chat with people
around the world, use interactive maps, and view images in
3D. From laptops to datacenters, game consoles to
scientific supercomputers, cell phones to the Internet,
Java is everywhere!
Greenfoot is a visual and interactive computer program
that uses Java to build games, simulations and other
graphical programs. Java uses object orientation, a
programming paradigm that represents concepts as objects.
The objects have data fields that describe the object as
well as associated procedures referred to as methods. An
object oriented program can be thought of as a collection
of interacting objects whereas a conventional programming
model is seen as a list of tasks that are performed
programmatically.
Java is designed for production systems
The Java programming language, like C++ and other languages,
is designed for creating code that runs in production systems
like Amazon.com, Facebook, and Instagram.
The language and syntax can be hard to learn, especially for
beginners. Below is some sample Java code in the Eclipse
development environment.
The Greenfoot interactive development environment can be
used to learn object orientated Java programming without
having to set up a programming environment that uses
complex language and rules. Using Greenfoot, you can
create objects and then create programming statements to
give the objects the ability to interact with other
objects in the Greenfoot window.
2d Actor objects
Greenfoot uses two-dimensional (“2D”) Actor objects.
Programmers define the Actor objects and then drags an
instance of them onto a world to create a scenario. Putting
a visual representation of an object onto the world is
referred to as creating an instance of an object. Look at
the image below. In this image you can see that bee and
butterfly instances have been placed onto the Greenfoot
world. The world in this example is displayed as a grid with
vertical and horizontal lines. The bee and butterfly objects
are programmed in a game-like fashion to move around the
world. The objects, the world, and the programming rules are
what defines the scenario.
There are two other important areas in the Greenfoot image
above: The program execution controls and the class display.
The program execution controls let you run, pause, stop, or
step through a scenario.
To better understand the terms objects, classes, and
instances, consider this example:
We want to create a scenario where a bee eats flowers to
earn points.
In this scenario, there is a rule that says the bee
cannot touch the mushrooms or butterflies.
The programming statements that control the actions of the
instances are actually written in each of the 3 classes. For
example, you write the programming statements to move the
butterflies around the scenario in the butterfly class.
Every butterfly instance will execute the programming
statements within the butterfly class.
To create this scenario, we will add many flower, mushroom,
and butterfly objects to the world. We will also add one bee
object to the world that will be controlled by the person
playing the game. The three actor objects that need to be
created are Bee, Flower, Mushroom, and Butterfly. There will
also be grass objects in the world that act as the scenery,
as well as an object to tell us what the instructions are
for the game.
Objects are instances of a class.
When we add many flowers to the world, we are actually
creating instances of the flower class.
When we add many butterflies to the world, we are
actually creating instances of the butterfly class.
When we add a bee to the world, we are actually creating
a single instance of the bee class.
Object orientation is a
programming paradigm that represents concepts as
objects that have attributes and methods.
Syntax is the term used to
describe the symbols and words that form a
programming statement.
Code is a term used to refer to
one or more programming statements or programs.
A scenario is the term used to
define the objects, the world, and the programming
rules for a graphical program created in Greenfoot.
A world in Greenfoot is the area
in which objects interact.
A class is a defined object that
is shown in the Greenfoot class display.
Programming Actor objects
You use the Greenfoot Application Programming Interface (API)
to write the programming statements for the Actor objects.
Clicking twice on an actor object will display the API for the
object.
View Image
Summary
Greenfoot is a visual and interactive program that uses object
orientation with Java to build games, simulations, and other
graphical programs. Students who are new to the Java
programming language enjoy using Greenfoot because the
interactive development environment is fun and easy to use. By
learning Greenfoot, you are actually learning how to program!
Greenfoot is also used at many colleges and universities in
Introduction to Programming courses.
This online course includes practice exercises that you can
work on to reinforce the concepts being taught. You will need
to have the Java Development Kit (JDK) and Greenfoot installed
on your machine. You will also need ZIP file extraction
software to view the example scenarios provided in this
course. Use the checklist below to ensure that your system
meets the minimum system requirements for using Greenfoot.
Try it: Check System Requirements
Instructions:
Review the system requirements checklist below.
Check your system to ensure it meets the system
requirements listed in the checklist.
Category
Requirement
Processor
Pentium 4 or higher
Operating System
One of the following:
Windows XP
Windows Vista (32, 64-bit)
Windows 7 (32, 64-bit)
Windows 8 (32, 64-bit)
Apple OS X
Browsers
Any modern browser that supports Java:
Internet Explorer 6 (or higher)
Firefox 3 (or higher)
Chrome
Safari
Opera 4.x (or higher)
Memory
1 GB
Free Disk Space
Required: 1.5 GB
Recommended: 8 GB
Graphics
Capable of high (16-bit) color and 1024 X 768
resolution
The Java Development Kit (JDK) is required to use Greenfoot.
Ensure that you download and installed the JDK prior to
downloading and installing Greenfoot.
Describe the reasons Greenfoot is an excellent tool to
learn Java programming
Check your system requirements to ensure that they support
this course
Install necessary software for the course
You are now ready to continue learning about Greenfoot. You
can practice all of the actions described in this course using
Greenfoot. If you continue through the lessons sequentially,
you can use the Greenfoot files you are creating and saving as
instructed. If you want to jump to a specific lesson and
practice the actions described, you will need to download the
practice file provided, as many of the actions in each lesson
build upon a previous lesson.
A single example will be used throughout the course to
demonstrate the actions in Greenfoot. Another single example
will be used to complete all practice activities.
Get started with Greenfoot
Lesson Objectives
In this lesson you will learn to:
Identify Greenfoot scene components
Open an existing Greenfoot scenario
Add an instance of a class to a scenario
Describe the value of saving multiple versions of a
scenario
Demo: Lesson preview
Watch this video to see a preview of what you will
learn in this lesson.
Understand the Scene editor
An initial scene is the starting point of
your game. It has three components:
A background image which provides the background.
One or more non-moving scenery objects which provide the
setting.
One or more moving objects which provide the action.
Terminology
The initial scene is the first
scene of a game where you select the background
template for the world and position the moving and
non-moving objects.
Below is a graphic depicting components of an initial scene.
The components include:
Watch this video to better understand the components
of the Scene editor.
Open and examine an existing scenario
By opening an existing scenario, we can examine its
components.
Launch Greenfoot
To launch Greenfoot, double-click the Greenfoot icon on your
desktop. If you do not have a Greenfoot icon on your desktop,
locate the Greenfoot program file in the folder in which you
downloaded the Greenfoot software.
The Greenfoot interactive development environment (IDE) is
made up of three main areas: the class display, the world, and
the execution controls. Below is the Greenfoot IDE.
The class display is where all of the Actor objects, or
classes, involved with the scenario are displayed. Each class
has a Code editor where you will program the objects in your
scenario to move and perform other actions.
A class contains the specifications
that define the appearance and movement of an object.
The class provides instructions to Greenfoot on how to
create and display instances (also called objects)
when they are added to your scenario.
The execution controls
The execution controls are used to run and control the
scenario.
Locate the folder on your computer where you store your
Greenfoot scenarios. Select the scenario, then click Open.
The scenario will open in a new window.
Demo: Opening and examining an existing scenario
Watch this video to learn how to open an existing
scenario in Greenfoot.
Try it: Open and examine an existing scenario
Download:
The activity below requires that you start with the
Jungle_L1S3 scenario. Download this file and extract
its contents to a folder on your computer before you
complete this activity.
Create a folder on your computer, hard drive, or
USB drive named “Greenfoot Course Scenarios” where
you will save all of the scenarios that you create
in this course.
Download the L1S3_Jungle.zip file.
Open the zip file. Copy the L1S3_Jungle folder
contained inside of the zip file to the Greenfoot
Course Scenarios folder on your computer.
Locate the Greenfoot program on your computer.
Double-click the Greenfoot icon to launch Greenfoot.
From the Scenario menu, select Open.
Locate the L1S3_Jungle scenario that you
downloaded to your computer. Select the file, then
select Open.
Locate and examine the execution controls, class
display, and world. Count how many classes are in
this scenario.
Add an instance to a scenario
After opening an existing scenario, the next step is to add
the instances that will move and act into the scenario.
Scene editor
The Scene editor is where you will add and position the
instances that will move and act in the scenario.
A class defines the actions and the attributes of an object.
Every object placed in a scenario is an instance of the class
from which it was created.
In the Scene editor, you can:
Create classes of non-moving scenery instances and moving
instances that you will use in your scenario.
Add new instances of a class to the scenario.
Position and rearrange instances in the scene using your
mouse.
Below, the scene contains non-moving scenery instances
(trees, rocks, bananas) and moving instances (elephant, hippo,
lemur).
A class contains the specifications
that define the actions and attributes of an object.
The class provides instructions to Greenfoot for how
to create and display instances when they are added to
the world.
Instances are the objects from a
class that act in the scenario.
Watch this video to learn how to add an instance of a
class to the world.
Try it: Add an instance of a class to the world
Download:
The activity below requires that you start with the
project file that was saved in the previous topic.
Download this Greenfoot project file if you did not
complete the previous topic's Try it activity.
Open the Jungle scenario you saved in the previous
topic. If you did not complete the Try It activity
from the previous topic, download the scenario file
by clicking the download link above (make sure to
copy the contents of the zip file to the Greenfoot
Course Scenarios folder on your computer).
Once the scenario is opened in Greenfoot, add one
hippo, one elephant, and one lemur to the world.
Then, add several bananas, rocks, and trees to the
world.
Save the scenario.
Write a programming instruction and run the scenario
The Code editor is where you will program the instructions
for how the instances of a class should act in your scenario.
Opening the Code editor for a class displays all of the
programming instructions for the class. Programming
instructions are organized into methods in the class display.
A method defined in a class comprises one or more programming
statements.
By default, each class has a method called act(). This method
contains all of the actions that will execute when the
execution controls are selected in the scenario. These actions
can be simple programming statements, such as move forward, or
they could also be others that you create, such as a method to
control an object using keyboard keys.
For example, below is the Code editor for a Bee class. Right
now, the programmer has not written any code for the bee in
the act() method. If we clicked the Run button in the
scenario, the bee would stand still.
For example, if we programmed a Bee to fly around the world,
the bee instance would need to receive those instructions on
how to fly through the act() method. Below, we have programmed
the bee to continuously move forward 5 steps and turn 5
degrees when the scenario is run. This commands the bee to
turn in circles.
The act() method comprises a method signature and a body. The
method signature for the act() method is the name act,
followed by an open and closed parentheses. The method body is
contained within the curly braces. Programming statements
within the curly braces are called the body of the method.
move(int distance): Move
this actor the specified distance in the direction it is
currently facing.
turn(int amount): Turn
this actor by a specified amount in degrees.
getX(): Return the
x-coordinate of the actor's current location.
getY(): Return the
y-coordinate of the actor's current location.
Example: Coding the act() method
Enter methods in the act() method to program the instances of
the class to act. For example, you can program an instance to
move a certain number of steps forward, then turn a certain
number of degrees.
Before you can run the scenario to see what happens, you have
to click the Compile button that displays below the class
display.
Terminology
The process of compilation
translates the code you write into machine code that
the computer can understand.
Compilation
Compilation is required whenever the code of a class is
modified or when a new class is created. You can identify when
compilation is required by the striped appearance of one or
more classes. After successful compilation, the striped
appearance of a class will be removed. When the compile button
generates an error message, you need to go back to your code
to determine what has been typed incorrectly. Correct any
mistakes, then click the compile button again to obtain a
successful compilation.
After you have added and positioned instances in your world,
the next step is to run the scenario to test how the
programming instruction causes the objects in the scenario to
move. In the Execution Controls area, click the Run button to
run the scenario. It will run all actions in the scenario
repeatedly until Pause is clicked.
Demo: Coding a programming instruction and running the
scenario
Watch this video to learn how to code a programming
instruction in the act() method and then run the
scenario to see the results of the programming
instruction.
Try it: Code a programming instruction and run the
scenario
Download:
The activity below requires that you start with the
project file that was saved in the previous topic.
Download this Greenfoot project file if you did not
complete the previous topic's Try it activity.
In the act() method, program the elephant to move
8 steps, then turn 2 degrees.
Open the Code editor for the Hippo class. Program
the hippo to move 8 steps, then turn 2 degrees.
Compile the scenario.
Run the scenario. Observe how the elephant and
hippo move.
Save the scenario.
Save versions of a scenario
It is good practice to save a scenario frequently as you
work. Each time you close Greenfoot, it saves your current
work, but while working in Greenfoot it is advised to save
multiple versions of scenarios.
As your scenarios become more complex, you may wish to have
multiple versions of your scenario so that you can revert back
to a version. You may also want to save two versions to test
out different actions without impacting your original
scenario.
Steps to save a version of a scenario:
From the opened scenario, select Save As… from the
Scenario menu.
Save a copy to a folder on your computer or USB drive.
Demo: Saving versions of a scenario
Watch this video to learn how to save a version of a
scenario.
Try it: Save versions of a scenario
Download:
The activity below requires that you start with the
project file that was saved in the previous topic.
Download this Greenfoot project file if you did not
complete the previous topic's Try it activity.
Reposition the objects in the scenario with your
cursor. Add additional objects to the scenario.
From the Scenario menu, select Save As...
Save a copy of the scenario. The scenario will
open in a new window.
Summary
In this lesson you have learned to:
Identify Greenfoot scene components
Open an existing Greenfoot scenario
Add an instance of a class to a scenario
Describe the value of saving multiple versions of a
scenario
Add and position objects
Lesson objectives
In this lesson you will learn to:
Create and save a new scenario
Create a new world subclass and compile
Create a new actor subclass and import an image into the
Greenfoot gallery
Add an instance of a world subclass to a scenario
Change the position of an instance in the world
Demo: Lesson preview
Watch this video to see a preview of what you will
learn in this lesson.
Create and save a new scenario
Now that you have learned how to open, compile, and run a
previously-created scenario, you will learn how to create one
of your own. When you create a new scenario, Greenfoot will
open a window displaying the world, the class display, and the
execution controls. This is where you will set up your scene,
adding classes to create instances for the background image,
non-moving scenery objects, and moving objects.
Greenfoot has two primary perspectives within which you will
build a game: the Edit Code perspective and the Scene Setup
perspective. These perspectives will be referred to as the
Code editor and the Scene editor from this point on.
Watch this video to learn how to create and save a
scenario in Greenfoot.
Try it: Create and save a new scenario
Instructions:
From the Scenario menu in Greenfoot, select New.
Navigate to the Greenfoot Course Scenarios folder
on your computer.
Name the scenario FrogFly_L2S2.
Click the Create button. The scenario will open in
a new window.
Create a new world subclass and compile the scenario
What is a class?
A class contains the specifications that define the
appearance and movement of an object. The class provides
instructions to Greenfoot for how to create and display
instances when they are added to the world.
Inherited characteristics
In nature, a bee inherits some characteristics that are
common to all bees: two wings, a black and yellow color, and a
stinger.
The bee may also inherit the characteristics of its breed
that gives it a specific color, shape and size.
In Greenfoot, a class, such as the Bee class, defines the
characteristics of all bee objects that act in the scenario,
such as how they look and ways they can act.
You can have as many Classes within your scenario as you
require for your game to meet your concept and design.
You can add as many instances of the class as you wish to the
world and they will all look and act based on the programming
statements you add to the class.
Superclass types
The term superclass is used to describe the overarching class
of a group of classes. A superclass is basically the same as
any other class in Java, except that other subclasses created
from the superclass inherit all of its characteristics.
For example, Insect is a superclass. Bees, butterflies, ants,
and flies are all subclasses of the Insect superclass. All
programming statements defined in the Insect superclass are
inherited by the bee, butterfly, ant, and fly subclasses.
World: Supports the subclass defined to provide the
background image for the scenario’s world. It also defines
the size and resolution of the world.
Actor: Holds the subclasses that produce the instances
that act in the scenario.
You can add as many instances of the class as you wish to the
world and they will all look and act based on the programming
statements you add to the class.
Subclasses
A subclass is a child of the parent class and is created from
the superclass. Subclasses are a specialization of a class.
For example, in Greenfoot, the Butterfly class is a subclass
of the Actor superclass.
Inherits all of the properties of the Actor superclass,
such as a pre-defined set of actions that Actor subclasses
can perform. For example, all Butterfly classes inherit the
ability to move and turn.
Has an “is-a” relationship to a superclass (Butterfly is a
subclass of the Actor superclass).
Has properties specific to its subclass, such as the image
that gives butterfly objects their appearance.
Can receive new properties that the programmer creates
specifically for the subclass, such as images or behaviors.
An arrow in the class hierarchy shows the subclass’s
relationship to the superclass.
Create a world subclass
To create a background for your new scenario you will need to
create a world subclass. The world subclass will hold the
background image for the scenario.
Compilation is required when a subclass or superclass is
created or modified. It is also required when you create or
modify the source code for a class. To compile a scenario,
click the Compile button.
Watch this video to learn how to create a World
subclass.
Try it: Create a world subclass
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
Right-click on the World superclass. Select new
subclass...
Name the class FrogWorld.
In the Backgrounds image category, select the
sand.jpg background image.
Click OK.
Compile the scenario.
Save the scenario.
Create a new actor subclass and import images into the gallery
You can create a new actor subclass and assign your own image
to the object. Actor subclasses hold the objects that we place
in the world. In this example illustrated below there is a Bee
subclass and a Butterfly subclass.
These subclasses inherit, or possess, all of the behaviors
from the Actor superclass. Right-clicking on a an instance
object that is placed in the world enables you to see the
methods inherited from the Actor superclass.
In addition to the many images that Greenfoot provides in its
Gallery, you can import your own images into the gallery to
use with your classes. When a new class is created you can
select the option to import a file which lets you adds the
image to the gallery.
For example, you may create an image with instructions for
how to play your game. You can save this image to your
computer, then import the image into Greenfoot for use in a
subclass named Instructions. Adding an instance of
Instructions to the world will display the instructions for
your game.
When a new scenario is created, it displays one instance of
the World subclass, as it provides the background template
for your scenario. A scenario may display multiple Actor
instances - as many Actor instances as you choose.
Steps to add an Instance of an Actor subclass to a world:
Demo: Creating a new subclass and importing images
into the gallery
Watch this video to learn how to create a new
subclass and import images into the Greenfoot
gallery.
Try it: Create new subclass and import images into
the gallery
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open
this Greenfoot scenario file if you did not
complete the previous topic's Try it activity.
In your computer's paint program, create an
image with instructions for your game that says
“Control the Frog with the arrow keys on your
keyboard. You must eat 10 flies to win the game.
Avoid the ants and rocks.”
Create an Actor subclass and import the image
file into the subclass.
Name the new subclass “Instructions”. Click OK.
Create Frog, Fly, Ant, and Rock classes. Note
that these classes have images in the Greenfoot
gallery that you can use.
Compile the scenario.
Save the scenario.
Steps to add an instance of a class to the world
Right click on the name of the class.
Select the new [class name()] option.
You should be able to see the instance on your cursor.
Drag the instance into the world with your cursor and drop
it onto the world.
Position instances
Instances added to a world can be positioned when they are
created or positioned later as you continue to define the
scenario. There are two ways to position instances:
Imprecise positioning: Drag and drop instances with your
cursor.
Precise positioning: Use methods to instantly re-position
the instances.
Drag and drop instances with your cursor
To drag and drop an instance with your cursor, click the
instance with your cursor, and drag it to the position you
want in the world.
You will notice that each time you open the scenario, you
have to re-add all of the Actor instances to the world.
To save the positioning of the instances placed in the world
so that they appear in the same position each time you open
the scenario, right-click on the world, and select Save the
World.
The next time you open that scenario, the instances will
automatically appear in the world. You can always reposition
the instances and save the world again.
Demo: Positioning instances
Watch this video to learn how to position instances
in a scenario.
Try it: Position instances
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
Add 2 rocks, 2 ants, 1 frog, 10 flies, and 1
instructions instance to the scenario.
Position the flies using your cursor. Also,
position the flies using the setRotation() method so
they are all facing different directions.
Position the frog at x = 50 y = 50.
Position the instructions at the bottom of the
world.
Position the ants and rocks anywhere you wish in
the world.
Save the world so that when you re-open the
scenario, the instances are automatically positioned
in the world.
Save the scenario.
Summary
In this lesson you have learned how to:
Create and save a new scenario
Create a new actor subclass and Import an image into the
Greenfoot gallery
Add an instance of a world subclass to a scenario
Change the position of an instance in the world
Explore the Code editor
Lesson objectives
In this lesson you will learn how to:
Edit the source code of a class and identify the class
components
Add methods to the act() method of a class
Create a programming error to view the error message and
error highlighting
Demo: Lesson preview
Watch this video to see a preview of what you will
learn in this lesson.
What is source code?
Source code defines what all instances of each class are
capable of doing. The behavior of each instance is determined
by the source code of its class. Think of source code as a
program's DNA. DNA gives humans certain characteristics, such
as appearance, mobility, and communication. Like DNA, source
code is written to tell the class how its instances can act in
the world.
The Code editor displays the source code of a class. This is
where you add programming instructions that enable instances
of the class to act. When you select Open editor, the Code
editor for the class will open in a new window.
You can tell that you are in the Code editor when you see
Java syntax.
Each class inherits methods it can use. However, you can call
a method that is inherited or defined (created) in a different
class. There are many class libraries for programmers to use
when writing class source code. You can always refer to the
Greenfoot Class Documentation, which is a complete library of
all of the methods you can use in Greenfoot. To use methods
from another class in the source code of a class, you must
ensure that you reference the Library containing the class.
From the Help menu in the Scene editor, select Greenfoot
Class Documentation. This will show you all of the methods
that you can use in Greenfoot.
Source code has several components that describe the class,
define the actions that the class's instances will perform
when the scenario is run, and describe any programmer-defined
methods that you will create for the class to use. Learning
what each means will help you understand how to properly write
code for your scenarios.
Class description
The class description is a set of comments that can be
modified to describe the class. The description includes:
The Java libraries that must be imported to support the
class.
These are optional, but for Greenfoot projects an import
statement for the Greenfoot libraries must be included.
The import statement must be specified as import
greenfoot.*;
The variables (or fields) that store data persistently
within an instance.
The methods that provide the behaviors for an instance.
The constructor that initially sets up an instance.
A constructor is a specific method that defines how an
instance should be programmatically created.
A constructor is not required for every class.
Be sure to use a consistent format when you define a class.
For example, define variables first, constructors second, and
methods third. The import statement(s) must always be the
first line of code, and must be outside of the class
definition curly braces.
act() method
The act() method is the part of the class definition that
tells objects which methods to perform when the Act or Run
execution controls are clicked in the scenario.
Comments are used to create the class description and are
also used in other areas to provide a description of the code,
or to clarify a difficult concept. It is good practice to
include comments in your code so that others can understand
the purpose of the code.
Locate the class definition and list its
components.
Open the Code editor for the Lemur class.
Identify the variables, constructors, and methods
in the source code.
Locate a method. Identify the components of the
method.
Locate the act() method and describe what it
commands the class's instances to do.
The act() method
Each Actor subclass object has a act() method. Whenever the
Act or Run execution controls are clicked in the environment,
the object will do what is programmed in the act() method. An
object's behavior is defined by the programmer and is executed
through the act() method.
Methods are a set of programmed
operations or tasks that instances of a class can
perform. When a method is invoked (written in the body
of the act() method), it will perform the operation or
task specified in the source code.
Body of the act() method
The curly braces and coding statements within them are the
body of the method. Inside of the curly braces is where you
write programming statements to instruct instances of the
class to act when the Act or Run buttons are clicked. To
learn more about writing the programming statements of a
method, you can review the Greenfoot Class Documentation.
Any Actor subclass can use any of the Actor methods that
you see in the Greenfoot Class Documentation. You can enter
any of the Actor methods in the class you are editing.
Entering a method name is often referred to as invoking or
calling a method.
Example: Coding the act() method
For example, you can program an instance to move a certain
number of steps forward, turn a certain number of degrees,
then display its current location. Methods must be written
correctly with no typos, missing characters, or incorrect
capitalization. Errors will keep the source code from
compiling. An error message will display when source code
compilation fails. You need to fix the errors and compile
the source code again in order to continue coding the
scenario.
To invoke methods in the act() method, write them in
sequence as follows:
Name of the method in lowercase characters.
Parentheses, with parameter list if required, or empty
if no parameter list is used.
Methods must be invoked to command instances to act in your
game. Invoking methods programmatically means to write the
methods in the body of the act() method between the curly
braces.
Enter the move(5) and turn(2) methods into the
body of the act() method. This will command the
fly to move forward 5 steps, then turn 2
degrees.
Compile the scenario.
Run the scenario. Observe how the flies move.
Save the scenario.
Test and debug code
Every key stroke in source code counts. One missing or
incorrect character could cause your program to fail.
In Greenfoot, the compiler highlights errors and informs you
how to correct them. Identifying and correcting errors in
source code helps you to develop good programming techniques.
Errors in the syntax of a computer program are referred to as
bugs. To debug a program you must identify and correct the
errors and then compile the source code again.
Steps to debug your program:
Click Compile to compile the code.
If there are no errors, the message “Class compiled – no
syntax errors” displays.
In the following example we should have coded the Act method
to perform the following:
move(1);
turn(15);
However when the move statement was typed, the move method
was spelled incorrectly. This will not compile successfully
and a descriptive error message will appear at the bottom of
the screen with the incorrect code highlighted.
Here are some additional steps you can take to intentionally
cause errors to see the applicable messages:
Add the semicolon to the code, and remove the “e” in the
word move. Compile again and view your error message.
Add the e back to the word move. Remove one of the curly
braces. Compile again and view your error message.
It is often difficult to find an error in your code. Saving
multiple versions of your program will allow you to revert
back to a version that executes successfully. Doing so will
help you narrow down the error in the current version.
Demo: Testing and debugging code
Watch this video to learn how to test and debug
Greenfoot code.
Try it: Test and debug code
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
Remove the curly brace at the end of the class
definition. Compile the code and review the error
message. Re-add the curly brace, then compile the
code.
Incorrectly type the name of the turn method.
Compile the code and review the error message. Debug
the error, then recompile the code.
Create and debug two more errors in the code.
Ensure that your scenario compiles succesfully when
you are finished.
Save the scenario.
Summary
In this lesson you have learned how to:
Edit the source code of a class and identify the class
components
Add methods to the act() Method of a class
Create a programming error to view the error message and
error highlighting
Explore methods
Lesson objectives
In this lesson you will learn to:
View the methods of a class in source code
Define the components of a method declaration
Identify a method using a return type
Identify a method using a parameter list
View inherited methods
Demo: Lesson preview
Watch this video to see a preview of what you will
learn in this lesson.
Methods described
What are methods?
Methods are programming containers. Methods can contain one
or more programming instructions. Methods tell an instances of
a class how to perform a task. Methods listed within an act()
method will execute in sequential order. When a method
executes, or is invoked, the programming statements within the
method are performed.
In programming, each object has a set of operations (or
tasks) it can perform.
Write methods to tell an object how and when to perform
tasks, such as:
Command an object to perform an action.
Ask an object a question to learn more about what it does.
Examples of methods
You can write methods for the Bee class to perform tasks such
as:
Increase the size of the bee's image
Return the current x and y position of the bee.
Command the bee to move, turn, or make a sound such as
“buzz”.
Interact with other objects, such as making a flower
change color when the bee lands on it.
The Greenfoot API contains a list of all of the methods
available for use by the different classes in Greenfoot. You
will refer to this documentation often as you try to locate
methods to use in your scenarios. The Greenfoot API is located
at:http://www.greenfoot.org/files/javadoc/
Demo: Methods
Watch this video to learn more about Greenfoot
methods.
Try it: Examine methods
Instructions:
Go to the Greenfoot API and view the methods available
for use by the different classes in Greenfoot. The
Greenfoot API is located at:http://www.greenfoot.org/files/javadoc/
Locate three methods in the Actor class that tell you
more about an object's orientation.
Go to the World class in the Greenfoot API. Which
method tells you the number of objects in a scenario?
Go to the GreenfootImage class in the Greenfoot API.
Which method tells you the height of an image?
Method declaration
Programmers write methods to tell an object how and when to
perform tasks, such as commanding an object to perform an
action or asking an object a question to learn more about what
it does. When a method is declared, specific information is
included in the method declaration. A Method returns program
execution to the code that invoked it when all statements
within the method complete or when it reaches a return
statement.
Examine the components of the method declaration:
Access Modifier: For now you will focus on public, but
note that there are also access modifiers called private,
protected, and default.
Return type: The type of information that goes back to the
method call.
If the return type is void, the method does not return
information
If the method returns a value the return type must be
specified.
Method name: A unique name that should describe what the
method does.
Parameter list: Specifies within parenthesis the type of
variables that can be sent to the method.
Method body: The code that will be executed when the
method is called.
The Greenfoot Class Documentation highlights many methods
that can be used in Greenfoot. Taking time to view methods
listed in the documentation will help you program more quickly
by using methods that already exist instead of taking time to
write your own.
Let's look at some examples to examine the method
declarations.
Examples of method declarations
Method
Description
void move(4)
A move method that does not return anything and that
has a parameter list for how far to move.
void turn(25)
A turn method that does not return anything and that
has a parameter list for how many degrees to turn.
public int getArea()
A getArea method that is public and returns an
integer (whole number) value.
Watch this video to learn more about the components
of a method.
Method return types and signatures
When a method is programmed to return a value after
execution, the method declaration must indicate what type of
data is being returned. To indicate the type of information
that is returned, the word identifying the type of data
(referred to as the return type) is placed at the beginning of
the method declaration. For example, to return an integer
value, the word int is placed before the method name. To
return a true or false boolean value, the word boolean is
placed before the method name.
There are two categories of return type declarations for a
method:
Void: A value is not being returned by the method.
Non-void: A value is being returned from the method.
As a programmer, you will ask objects questions by invoking
methods with non-void return types to learn what an object can
do, or has done in the past. For example, in a gaming
scenario, you may ask an object what its position is in the
world, or if it is in the same position as another object.
Depending on the object's position, you may command it to do
something (such as eat another object, change its image, or
make a sound). The response received will be in the form of a
non-void return type, or data type.
Examples of non-void return types
int (Short for integer)
Refers to whole numbers
Can be a negative whole number
Example: To get the distance to something
boolean
Returns a true or false value
Questions it may ask an object: Can you move? Are you near
another object?
Examples of invoking methods with non-void return types
Examples:
int getX() – Returns to the getX() method the position of
an Actor
boolean isTouching(cls Actor) – Returns true if touching
another Actor
int getWidth() – Returns the width of an image
Method parameter lists
A parameter list is used to provide a method additional data
needed to execute the programming statements within the method
body. Parameter list values are listed within the parenthesis
that follow the method name. A parameter list can contain one
or more parameters. The order in which parameters are listed
in a parameter list is important. When a method is invoked, it
uses the parameters identified in the parameter list during
execution (Using a method, calling a method, and invoking a
method are interchangeable phrases).
A parameter list can contain one or more parameters separated
by a comma. It is defined by three components:
Parameter type (For example: int, boolean)
Parameter name
Position of each parameter type and name in the parameter
list (for example, x coordinate value, y coordinate value)
Parameter list examples:
Example
Parameter type
Parameter name
void move(int distance)
int
distance
void turnTowards(int x, int y)
int, int
x, y (position: int x is before int y)
void act()
none
no parameters (empty)
Parameter lists typically have two states:
Empty: No data expected to invoke the method (getX method).
getX(); This will return the current X position of the
object.
Non-empty: Have data and expect one or more parameters to
invoke the method (move method).
move(1); This will move the Object 1 pixel in the
direction it is currently facing.
Demo: Method return types and signatures
Watch this video to learn more about method return
types and signatures.
Identify inherited methods
When we state that a subclass can use the methods defined in
its superclass, we are defining inheritance. Inheritance
transcends down the hierarchy of objects.
For example, a Flower class created from the Actor superclass
would inherit the methods of Actor.
Any instance of Flower would have access to the methods of
Flower, and would also inherit all methods from Actor.
Steps to use the Greenfoot documentation to display all of
the inherited methods of all classes:
From the Help menu, select Greenfoot Class Documentation.
The menu on the left-hand side lists Java classes that can be
inherited by subclasses in your Greenfoot scenarios. Click on
individual classes to see the inherited methods.
Watch this video to learn how to view inherited
methods in Greenfoot.
Try it: View inherited methods
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
In the world, view the methods that the Frog
inherits from the Actor superclass. Invoke 2 methods
to change the frog's position in the world.
Right-click on the Frog class and select Open
Editor.
In the Code editor, select Documentation. View the
list of inherited methods for the Frog class.
From the Help menu, select Greenfoot Class
Documentation. Find 3 methods that tell you more the
location of Actor objects in the world.
Save the scenario.
Summary
In this lesson you have learned how to:
View the methods of a class in source code
Define the components of a method declaration
Identify a method using a return type
Identify a method using a parameter list
View inherited methods
Add randomization and conditional behavior
Lesson objectives
In this lesson you will learn to:
Create programming statements to randomize instance
behaviors
Call a method using dot notation
Define and create IF-ELSE conditional programming
statements
Define and create conditional behaviors
Demo: Lesson preview
Watch this video to see a preview of what you will
learn in this lesson.
Create randomized behaviors
If you always know how a game is going to behave, you would
master the game and become bored with it quickly. Game
designers use a randomization technique to make their games
interesting. Randomization allows the computer to randomly
pick a value, from a range of values, and present them in no
pre-defined order. The combination of randomly generated and
predetermined content, if planned correctly, can make
interesting game play possible. In Greenfoot, the
getRandomNumber() method can generate random numbers, within a
specified range, that can be used to create randomly generated
behavior.
The getRandomNumber() method
The getRandomNumber method is a static method that returns a
random number between zero and a parameter limit. This method
is used to eliminate predictability in your program and can be
used to create randomly generated content for our scenario.
A static method is a method that does not have a relationship
to the class where it is defined. Think of a static method as
a “utility” method that can be used by any class when a random
number is needed. To use a static method you need to call the
method using specific syntax. You need to:
precede the method name with the class name where it is
defined.
place a “dot” between the name of the class and the name
of the method.
The getRandomNumber() method is a method within the Greenfoot
class of the API. To use the getRandomNumber() method, we must
provide the Greenfoot class call, the getRandomNumber() method
call and the upper limit of the range we wish to generate the
random number within.
The code below means we will generate a random number between
0 (inclusive) and 6 (exclusive) meaning we will generate a
random number in the range from 0,1,2,3,4,5.
You can invoke both the move() and turn() methods with a
fixed distance to move, and degrees to turn, or you can use
the getRandomNumber() method to feed random numbers to both
the move() and turn() methods.
Watch this video to learn how the getRandomNumber()
method works.
Try it: Create randomized behaviors
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
Instead of the Fly always turning a specific
number of degrees, the Fly should turn a random
number between 0 and a parameter limit of 20. Code
this behavior in the act() method, replacing the
turn method that is already there.
Open the Code editor for the Fly class again.
Change the parameter limit in the method from 20 to
15. Compile the code.
Run the scenario and observe how this changes the
flies' movements.
Save the scenario.
Recognize and describe dot notation
When you want to use a method but it is not inherited by the
class you are programming, specify the class or object that
has the method before the method name. Separate the class name
and the method name with a dot. This naming convention used to
call methods from a class is called dot notation.
When we use dot notation after the name of the class to which
the method belongs, we will have access to all of the
available methods within that class.
Understanding dot notation, and the ability to call methods
defined in other classes, helps you to understand how you can
use the Greenfoot documentation to understand all of the
methods in the following classes:
Actor
Greenfoot
GreenfootImage
GreenfootSound
MouseInfo
World
Steps to view the Greenfoot Class Documentation:
From the Help menu, select Greenfoot Class Documentation.
The documentation will open in your default browser.
The Greenfoot Class Documentation contains all of the methods
in all classes that are available to a programmer within
Greenfoot.
Demo: Recognizing and describing dot notation
Watch this video to learn how to recognize and
describe dot notation.
The IF decision statement
Performing sequential tasks in programming and in Greenfoot
is straightforward - we create each statement one after the
other. But what if the task we wish to execute is not
sequential in nature? Many things around us have a cause and
effect relationship, or “if-then” relationship.
If your cell phone rings, you answer it. If it doesn't
ring, you do not answer it.
If a flower starts to wilt, you give it water. If the
flower looks healthy, you do not give it water.
IF decision statements
An if statement is written to tell your program to execute a
set of programming statements only if and when a certain
condition is true.
Watch this video to learn how to code an if statement
in the act() method.
Try it: Program the IF decision statement
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
Write an if statement in the act() method that
will move the Frog forward one step when the “up”
arrow is pressed.
Write an if statement in the act() method that
will move the frog forward and turn it to the right
5 degrees if the “right” arrow key is pressed.
Write an if statement in the act() method that
will move the frog forward and turn it to the left 5
degrees if the “left” arrow key is pressed.
Compile and run the scenario. Test that the frog
moves as expected when you press the up, left, or
right arrow keys.
Save the scenario.
Conditional behavior
Conditional behavior is often decided on an if or else basis,
for example if it is raining then take an umbrella - else
leave the umbrella at home. In Greenfoot, An IF-ELSE statement
can be used in a similar way to determine the behavior of an
instance depending on one or more conditions.
An IF-ELSE statement executes its first code segment if a
condition is true, and its second code segment if a condition
is false, but never both.
Instances can be programmed to perform specific behaviors if
a condition is not met, using an IF-ELSE statement. For
example, if an instance is programmed to turn 6% of the time,
what does it do the other 94% of the time?
IF-ELSE statement execution
The IF-ELSE statement executes as follows:
Evaluate the condition:
If a condition is true, execute associated code.
Else a condition is false, execute associated code.
The format (syntax) of the IF-ELSE statement follows the same
pattern every time. The if keyword followed by a condition in
parentheses, with the statement to execute between the curly
braces. All execution statements must end with a semicolon.
In the example above we use the < symbol to compare the
randomly generated number to the value of 7. The < symbol
is known as a less than
comparison operator.
Define comparison operators
Comparison operators are symbols that compare two values.
There are a number of comparison operators in Greenfoot which
can be used to determine game play decisions when combined
with control statements.
Comparison operator symbols
Comparison operator symbol
Description
<
Less than
>
Greater than
<=
Less than or equal
>=
Greater than or equal
==
Equal
!=
Not equal
Example: Comparison operators
Use comparison operators to compare a randomized value to
another value in a control statement.
The example below determines if the random number is less
than 20. If it is, then the object turns 10 degrees.
Watch this video to learn how to create a statement
that uses comparison operators with randomization.
Try it: Conditional behavior
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
Write an IF-ELSE statement to program the ants to
move and then turn up to 20 degrees 10% of the time,
else move and turn up to 10 degrees.
Compile and run the scenario.
Save the scenario.
Summary
In this lesson you have learned how to:
Create programming statements to randomize instance
behaviors
Call a method using dot notation
Define and create IF-ELSE conditional programming
statements
Define and create conditional behaviors
Automate game creation
Lesson objectives
In this lesson you will learn to:
Identify a constructor
Create an instance of a class using a World constructor
Identify an object's properties and instance variables
Demo: Lesson preview
Watch this video to see a preview of what you will
learn in this lesson.
Constructors
Arguments
Adding an instance of an actor subclass to the world is
accomplished when you right-click on the subclass name and
choose the new option. Although it is not difficult to add the
instance of the Actor subclasses manually, it can affect the
game play of the scenario.
To improve the game play, you can program instances to be
automatically added to the world, or constructed, when the
scenario is initialized. Using the World subclass, actor
instances can be programmed to automatically appear in the
world at exact specified positions. Defining the creation of
the instances to appear is known as creating a constructor. A
constructor is made
up of one or more programming instructions that specify how to
automatically display instances in the world.
The World constructor
There is a difference between a world constructor and a
constructor for an object.
The World subclass instance is automatically added to the
environment after compilation or initialization of the
scenario.
The Actor subclass instances must be manually added by the
player.
World class source code
To better understand how to automate creation of Actor
instances, you need to understand how the World class source
code is structured. The World constructor is used to automate
creation of Actor instances when the scenario is initialized.
The import statement imports the following Greenfoot Classes
from the API, giving the World class access to the methods of
the following classes: World, Actor, GreenfootImage, Greenfoot
and MouseInfo.
The class header provides the name of the class (BeeWorld)
and the superclass from which it is inherited (World). The
extends keyword is used to create a subclass. In this example,
BeeWorld extends World, meaning BeeWorld is a subclass of the
superclass World.
Using the World constructor, actor instances can be
programmed to automatically appear in the world at exact
specified positions so that the player does not have to
manually add the objects to the game in order to play the
game.
Demo: Using constructors
Watch this video to learn how to view the world
constructor in the Greenfoot API and modify it in a
scenario.
Try it: Modify the size of the world
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
Modify the World constructor to change the size of
the world to 700x500, with a cell size of 1 pixels.
Compile the scenario. Notice how the size of the
world has changed.
Save the scenario.
Set up the scenario for gameplay
Once you position the Actor instances in the world, use the
Save the World feature to save the Actor instances and their
coordinate positions. Then, each time you open and compile the
scenario, those Actor instances will automatically appear in
the scenario at the coordinates you specified. This makes it
easy to prepare your scenario for gameplay so that the player
does not have to manually add the objects to the game in order
to play the game.
Steps to use the Save the World feature:
Add the Actor instances to the world and position them
with your mouse.
The world is now saved. Each time you open and compile the
scenario, the instances will appear at the same position and
coordinates.
Open the World subclass's Code editor and examine the method
prepare() that automatically creates and places the instances
in the world. This method is called in the World constructor
to create and place those instances in the world at the
specified coordinates.
Watch this video to learn how to set up the
scenario's instances for gameplay using the Save the
World menu option.
Try it: Set up the scenario for gameplay
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
Right-click on the world, then select Save the
World.
Compile the scenario. Notice how the instances are
automatically added to the world.
Save the scenario.
Add and modify instances in the World constructor
Using the World constructor, actor instances can be
programmed to automatically appear in the world at exact
specified positions so that the player does not have to
manually add the objects to the game in order to play the
game.
This requires two main components:
The addObject method
The new keyword
The addObject method is used to automatically add Actor
instances, which requires the Actor class name and the x and y
coordinates of the location in the world where the instance
should be placed. A new instance is specified using the new
keyword.
addObject method
The addObject method is a World class method that adds a new
object to the world at specific x and y coordinates. It
includes:
The Keyword new to
tell Greenfoot to create a new object of a specific class.
Method parameters (integer values of X and Y coordinate
positions).
The method signature of the addObject method is as follows:
This BeeWorld constructor calls the prepare() method, which
adds an instance of the Bee class, the Instructions class, and
several instances of the Mushroom, Flower, Grass, and
Butterfly class at specified X and Y coordinates using the
addObject method.
The new keyword
creates new instances of existing classes. It starts with the
keyword new, followed by the Actor class to create. When the
new keyword is used and the actor class is specified, the
constructor of the actor class is called.
In the above example, we are creating an instance of the Bee
at specified x and y positions in the world. The parenthesis
() after the keyword new and the actor class Bee are used to
accept parameters that are passed to the Bee constructor. The
parameter list would pass arguments (values) to the
constructor that are needed to initialize the object's
properties. The Bee class does not require parameters. A
constructor without parameters is called a defaultconstructor. A default
constructor sets the object's properties to their default
values.
Demo: Adding and modifying instances in the World
constructor
Watch this video to learn how to add and modify
instances in the World constructor.
Try it: Add and modify instances in the World
constructor
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
Right-click on the world, then select Save the
World.
Compile the scenario. Notice how the instances are
automatically added to the world.
Save the scenario.
Identify an object's position in the world
When adding instances to a world manually you can simply drag
and drop the instance to the exact location desired. When
programmatically adding instances to a world using a
constructor, you will need to know the x and y coordinates of
the desired object location. The x and y coordinate values of
an instance are stored in instance variables.
Variables
A variable, or
field, allows the instance to store information to use
immediately or later. For example, object properties are
variables that store information about the instance, such as
its position in the world or the direction it is facing.
Object properties
Object properties describe the instance's appearance and
abilities, such as:
Size
Color
Range of movements
Object properties can be viewed and modified in the source
code of the class. You can view the properties of an object in
the class documentation.
For example, an Actor object would have properties such as:
Image - the image used to represent this actor
Rotation - the current rotation of this actor
X - the current x co-ordinate of this actor
Y - the current x co-ordinate of this actor
Instance variables
Instance variables can be viewed using the Object Inspector.
You can view the instance variables for any instance of any
class in the World.
Steps to view instance variables using the object inspector:
Right click on an instance in the world.
Click Inspect to view.
The instance's object inspector will display the instance
variables.
Watch this video to learn how to view the instance
variables of an object.
Invoking methods directly
As we move about the world we live in, it's important for us
to know our orientation, or sense of direction.
Methods can tell us how an object is positioned in the world,
relative to itself and other objects. This is important in our
game to know if an object is close enough to another object to
eat it, or if an object has reached the edge of the world and
needs to turn in order to keep moving.
Methods that return information about object orientation
Invoke a method directly to display an object's orientation
To find out information about an object, you can invoke a
method from the scenario environment by right-clicking on the
Actor subclass and choosing inherited methods. This will give
you immediate information about the instance when the scenario
is not running and will not impact the movement you are
programming into your game.
You can invoke an inherited method:
With a specific return data type, such as integer, to ask
the object a question about its orientation.
In the environment to learn how the object is oriented in
the scenario.
Steps to invoke a method directly:
Make sure that you have an Actor subclass in the world,
and that the scenario is not running.
Right click on an Actor subclass instance in the World.
Select Inherited from Actor to view its methods.
Invoke (select) a method with a specific data type to ask
the object a question about its orientation.
The method result will display. Note the value returned,
then click Close.
Watch this video to learn how to view an object's
orientation, how to turn, and how to move an object by
invoking a method directly.
Try it: Viewing instance variables and invoking
methods
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
Run the scenario for a few seconds, then pause the
scenario.
Right-click on a fly, then select Inherited from
Actor.
Select the getWorld() method. It will return the
world that the fly is in.
Right-click on another fly, then select the
getRotation() method. This will return the rotation
of the fly.
Right-click on an ant, then select the getX()
method. This will return the x coordinate of the
ant.
Save the scenario.
Summary
In this lesson you have learned how to:
Identify a constructor
Create an instance of a class using a World constructor
Identify an object's properties and instance variables
Program user interactions and sounds
Lesson objectives
In this lesson you will learn to:
Write a method to program keyboard interaction in a
scenario
Write a method to move instances about the world
Write mouse methods to program mouse interaction in a
scenario
Write a method to include sound in a scenario
Demo: Lesson preview
Watch this video to see a preview of what you will
learn in this lesson.
Program keyboard interaction
The Greenfoot API provides you with methods you can use to
program keyboard interaction in your scenario.
Many modern games are controlled by a human or computer
player using a remote control, mouse, or the keyboard. To turn
your scenario into a game, you will write programming
statements to control actions based on keyboard keys pressed.
The isKeyDown() Method
The isKeyDown() method is used to determine if a key on the
keyboard has been pressed.
The isKeyDown() method:
Is defined in the Greenfoot class.
Is a static method (associated with a class).
Returns a true or a false value.
Expects a String argument in the parameter list.
Can be used as a condition in an IF statement.
Method signature and description:
public static boolean isKeyDown(java.lang.String keyname)
When you are in the Code editor and your cursor is positioned
where you want to insert a new method, you can hold down the
Control key on your keyboard while simultaneously pressing the
Space bar to display a list of available methods. Selecting a
method name and pressing the Enter key will insert the method
into the Code editor.
Examine the isKeyDown() Method in this example. This method,
in the act() method, uses the left and right keys on the
keyboard to allow the player to control the object's direction
as it moves.
To insert an isKeyDown() method into the act() method of a
class:
Write an if decision statement, entering the isKeyDown()
method from the Greenfoot class inside of the condition.
Remember, you must use dot notation to call the isKeyDown()
method from the Greenfoot class.
Within the curly braces of the if statement, enter the
programming statements for the actions that should occur
when the keyboard key is pressed. For example, enter
move(5); to have the object move forward 5 units if the up
arrow key is pressed.
Watch this video to learn how to program keyboard
interaction in your scenario using the isKeyDown()
method.
Try it: Program keyboard interaction
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
Program the Frog to move forward 4 steps when the
“up” arrow key is pressed.
Program the Frog to move 2 steps and turn left
when the “left” arrow key is pressed.
Program the Frog to move 2 steps and turn right
when the “right” arrow key is pressed.
Program the Frog to spin when the “s” key is
pressed.
Save the scenario.
Programming mouse interaction using the setLocation() method
In addition to using the move() and turn() methods and
keyboard keys to move an instance in the world, you can use
the setLocation() method and mouse interaction to achieve the
same results.
The setLocation() method
The setLocation() method moves an Actor to a precise location
on the World. Using this method requires awareness of the
Greenfoot World Coordinate System. The World starts at (0,0)
at the top left and is built to the parameters for worldWidth,
worldHeight and cellSize specified in the constructor.
The setLocation() method expects a number argument in the
parameter list for the x-position and y-position where the
item is to be located.
Example: setLocation() method and keyboard controls
A combination of turn() and move() methods is often used to
change the location of an instance when a key is pressed on
the keyboard.
In the following example, the setLocation() method is used to
move the object in place of the turn method. This will move
the object to a precise location in the world when a key is
pressed. A calculation based on the object's current position
on the grid will determine where the object will move. Recall
that the grid uses X and Y coordinate values to determine a
location on the grid.
Evaluate this syntax:
To move the object up, determine the X and Y coordinates of
the object's location, then move -5 pixels from the current Y
coordinate value.
Demo: Programming precise keyboard interaction using
the setLocation() method
Watch this video to learn how to program precise
keyboard interaction using the setLocation() method.
Try it: Program precise keyboard interaction using the
setLocation() method
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
Open the Code editor for the Frog. Remove the turn
method from the “left”, “right”, and “up” if
statements and replace them with programming
statements that will create precise movements in
those directions.
Add an if statement for a “down” motion. Program
the frog to move 2, then precisely move down.
Compile and run the scenario. Use the keyboard
keys to control the movements of the frog.
Save the scenario.
Methods and classes for mouse interaction
As an alternative to keyboard interaction, the Greenfoot API
provides us with methods we can use to program mouse
interaction in our scenario. We can program statements that
include mouse controls, so the player can control one or more
objects in the game using their mouse. There are methods in
the Greenfoot class that provide us with information about the
player's mouse movements in the scenario.
To program the mouse interactions in a scenario, we must be
able to check the current position and state of the mouse. To
do this, Greenfoot provides us with a getMouseInfo() method in
the Greenfoot class which will return a MouseInfo object that
can be used to check the current state of the mouse in the
scenario.
In the following example, we declare a local variable of type
MouseInfo called mouse in the act() method. This calls the
getMouseInfo() method to return a mouse info object with
information about the state of the mouse at that point in the
scenario.
The mouseDragged() method will return true if the mouse has
been dragged onto the object specified in the parameter. This
method uses a parameter to specify the object.
Note that if the mouse is dragged over more than one object
only the first object will be evaluated.
An if statement is used to check if the mouse is being
dragged onto the current object.
This if statement would be written in the act() method of
the Actor object.
If the mouse is being dragged onto the current object, the
location of the current object is then set to the x (getX())
and y (getY()) position of the mouse object.
The position of the object is returned by the previous
getMouseInfo() method.
An if statement is used to check if the mouse drag has
ended on the current object.
This would be written in the act() method of the object.
If the mouse drag on the current object has ended, then
set the location of the current object to the x (getX()) and
y (getY()) position of the mouse object.
The position of the object is returned by the previous
getMouseInfo() method.
Examine the following code in the act() method. The code
allows a player to control the object's direction using drag
and drop interaction. The X and Y position of the object is
updated as a result of the mouse movement.
Watch this video to learn how to program mouse
interaction.
Try it: Programming mouse interaction
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
Save a copy of your scenario prior to working on
this scenario, as the programming statements for
keyboard interaction will be replaced by mouse
interaction.
Open the Code editor for the Frog. Remove the
programming statements for keyboard interaction from
the act() method.
Write programming statements to have the Frog's
movements controlled using drag and drop
interaction.
Compile and run the scenario. Click and drag the
frog around the world with your mouse.
Save the scenario.
Importing sounds
The use of sounds in any scenario can enhance gameplay.
Sounds can be used for background sound or to give feedback to
a player when an event like winning, losing, or achieving
minor victories occurs throughout a game. Sounds used in a
scenario must be stored in the sounds directory of the
scenario. Acceptable formats for sound files include: WAV,
AIFF, and AU.
The playSound() method
The playSound() method is used to play sounds in a scenario.
The playSound() method:
is located in the Greenfoot class.
expects the name of a sound file (as String) as an
argument.
does not return data.
The method signature for the playSound() method is as
follows:
Consider a scenario where you want a sound to play when the
space key is pressed on the keyboard. Add the playSound()
method to the act() method of the Actor object. The code in
the act() method example below uses the space key on the
keyboard to allow the player to control the object’s random
moves. Each time the space bar is pressed the object will move
and the sound file spin.wav will play.
Watch this video to learn how to import pre-recorded
sounds into Greenfoot.
Try it: Import sounds
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
Watch this video to learn how to record a sound file
in Greenfoot.
Try it: Record sounds in Greenfoot
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
Record a sound file in your scenario using the
Greenfoot Sound Recorder.
Program an if statement in the act() method that
plays a sound when the “h” key is pressed.
Compile and run the scenario. Press the h key on
your keyboard to test that the sound plays.
Save the scenario.
Summary
In this lesson you have learned how to:
Write a method to program keyboard interaction in a
scenario
Write a method to move instances about the world
Write mouse methods to program mouse interaction in a
scenario
Write a method to include sound in a scenario
Working with Greenfoot images
Lesson objectives
In this lesson you will learn to:
Create images for an object using a constructor
Write programming statements to use the new keyword
Define the purpose and syntax of a variable
Write programming statements to switch between two images
Demo: Lesson preview
Watch this video to see a preview of what you will
learn in this lesson.
Use many images for an instance
When a subclass is created in Greenfoot, we specify the image
that represents the instance when it is added to the scenario.
Greenfoot offers many images to choose from when creating a
subclass. During program execution the image for the instance
will remain the same unless changed programmatically.
When the new() method is used to manually add an instance
to the world, Greenfoot references the image specified when
the subclass was created, and puts that image onto the
world.
When a constructor creates the instances in the world,
Greenfoot references the image specified when the subclass
was created, and puts one or more of those images onto the
world.
Using either method, adding instances to the world using the
new() method, or adding instances to the world using a
constructor causes Greenfot to reference the image specified
for the class.
When creating a subclass, you can specify an image from the
available Greenfoot image listing or you can import an image
from your computer, hard drive, or USB drive into the
Greenfoot image gallery. Image files imported can be jpeg,
gif, or png format types.
To make instances appear animated in a game, they need to
change from one image to another during program execution.
Changing from one image to another can show movement or event
change during program execution. Let's examine a few examples.
To change the color of an instance: A flower subclass may
use different types and colors of flowers that change if the
Bee lands on the flower.
To make the instance appear to walk, fly, or swim: A bee
subclass may use multiple images, each with wings that are
slightly rotated, so that when the images are quickly
flipped it appears that the bee is flying.
To flip cards: In a vocabulary game, the Card subclass may
hold multiple card images. One image may hold a vocabulary
word, and another may hold a vocabulary term. When the
player clicks the card with their mouse, it flips the card
(changes the image), displaying the vocabulary term.
To face different directions when the left, right, up, and
down keys are pressed on the keyboard. When the butterfly
instance flies around the scene, if the right arrow key is
pressed, it turns and faces the right edge of the world. If
the left arrow key is pressed, it turns and faces the left
edge of the world.
Image changes can be used to improve the look and feel of
your scenarios and to enhance game play.
Changing the image of an instance summarized
To change the image of an instance for a scenario you need
to:
Create two images of the instance, each facing a different
direction.
Store the two images in the Greenfoot scenario's images
folder.
Code the subclass to alternate between the two images that
are displayed when the appropriate keyboard key is pressed.
To change the image of an instance programmatically, use the
setImage() methods. There are two setimage() method parameters
that can be used to set an image for an instance
programmatically.
The setimage() method accepts an image argument for the
parameter that is of the type GreenfootImage.
The setimage() method accepts a String argument for the
parameter. The String argument is the name of an image file
and must be written within double quotes.
Either setimage() method can be used to change an image for
an instance, however; it should be noted that an image with a
Greenfootimage image type is more efficient when multiple
instances are created in a world.
Viewing the images stored in the scenario
Using either setImage() method parameter, you must have an
image to specify. You can view the images you have currently
stored for use by the instances in your scenario two ways:
Go to the folder where you stored the scenario. This
contains an images folder where you can view and store
images for use in your scenario.
From the Scene editor, right-click on the Actor class,
then click the new Subclass… menu option. In the gallery,
the Scenario Images list on the left displays all of the
Greenfoot images that are stored in your scenario.
Consider a scenario where a bee is controlled with the arrow
keys on the keyboard, but the image displayed is always
static, meaning that it never changes.
Above you see the original bee image (bee.png). This file is
stored in the images directory of the scenario and can be
assigned to an actor using the setImage() method.
To turn the Bee to face the same direction as the direction
pressed with the keyboard keys, you will need a second image
of the Bee facing the other direction. You can create another
image of the Bee by opening the current Bee image in a paint
or image editing program, rotate the image, and then save the
image resulting in 4 total image files (one image file for
each direction).
Now you can use the setImage() method to assign the correct
image to the key that is pressed, giving the illusion that the
bee is facing different directions. For example, if the left
arrow is pressed, the Bee faces left and if the right arrow is
pressed, the Bee faces right.
Watch this video to learn how to set an image using
the image's file name.
Try it: Set image using the image file name
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
Right-click on the Frog class and select set
Image...
From the Scenario images list, select the frog
image. Then from the editing tools below the
Scenario images list, select Edit.
In your computer's paint or drawing program,
rotate and/or flip the image so there is a total of
four images, one for each direction the frog will
face (left, right, up and down).
Save the four images to the images folder in your
Greenfoot scenario. Ensure that you provide each
image with a descriptive name for the direction it
is facing.
Open the Code editor for the Frog class. Using the
setLocation() method, code the Frog class to move
left, right, up, or down if the arrow keys on the
keyboard are pressed.
Add a programming statement to the body of each if
statement to set the image that displays when that
keyboard key is pressed. For example, for the
programming statement that turns the frog to the
right, it should display the image of the frog
facing the right.
Compile the code. Run the scenario and test how
the code works by pressing the arrow keys on your
keyboard. Ensure that the frog's image changes based
on the direction it is facing.
Save the scenario.
Set an image using a GreenfootImage object
The same results can be obtained by using a GreenfootImage
object to set an image.
Edit the code for the Bee in the act() method for the if
conditions:
There is not an advantage to using either of these setImage()
methods, but when you learn about variables, you will see how
to save an image as a GreenfootImage object so that only one
image is used to create all of the instances using the image.
If you create 50 bees in a scenario using the images you just
created, there would be 50 images using the setImage() methods
as shown above.
Demo: Setting an image using a GreenfootImage object
Watch this video to learn how to set an image using a
Greenfoot Image object.
Try it: Set an image using a GreenfootImage object
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
Remove the code that currently sets the image
using the image file name. Replace it with code that
sets the image using a GreenfootImage object.
Compile the code. Run the scenario and test that
the images change when the arrow keys on the
keyboard are pressed.
Save the scenario.
What is a variable?
A variable is a
container that is used to store information for later use, or
to pass information from one programming statement to another.
It can store objects or values. Creating a new variable is
referred to as declaring a variable. Variables are declared
within a class.
Variables can be used to store the images in the class.
Storing images in variables makes it easier for the class to
access and use the images during program execution.
Declare a variable of type GreenfootImage to store each
image. These variables should be declared after the class
header and before any constructors and the act() method. Note
that declaring a variable does not automatically populate the
variable. It simply defines the variable container.
Watch this video to learn how to declare variables.
Try it: Declare variables
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
Declare four variables named image1, image2,
image3, and image 4 of type GreenfootImage that will
hold each of the four frog images.
Compile the code.
Save the scenario.
Assign images to variables
Variable assignment statements
An assignment statement is needed to tell the variable what
value, in this case an image, to store. Some variables contain
simple values, such as numbers like 5 or 10. Other variables
contain objects, such as an image or an Actor.
When an object is assigned to a variable, the variable
actually only contains a reference (or pointer) to the object,
not the actual object itself.
In Java, this symbol means that a value is being assigned to
a variable. This may seem a little confusing, since the equals
symbol is frequently used in mathematics.
Components of an assignment statement
An assignment statement for image objects includes:
Variable: Name of variable to store object or value.
Equals symbol (=), which is the assignment symbol (set
equal to).
Expression
An expression for an image variable contains:
An instruction that the object or value is new.
The class to which the image belongs (GreenfootImage).
Name of object or value to assign (the image
“bee_left.png”).
In the example above you see the use of the GreenfootImage
constructor to construct a new GreenfootImage using the images
“bee_up.png” and “bee_down.png”, which are stored in the
images folder of your scenario. The next step is to create the
assignment statements for these images.
Option 1 - In the act() method of the Bee class
If an initial variable assignment is written in the Act
method, the images get assigned repeatedly each time the act()
method is called. This is not an efficient way to perform this
operation - it uses memory each time the new image is created.
Option 2 – In the constructor of the Bee class
If an initial assignment is written in the Constructor of the
Bee class, only one variable would be assigned when the World
is constructed and the addObject() method is executed. This
method for assigning variables is a more efficient way to
perform this operation.
Constructors to create instances and set images
Greenfoot executes a constructor that creates an instance of
the World subclass which then displays in the scenario. The
constructor tells Greenfoot to display the scenario background
based on the size specified.
Terminology
Constructors are special methods
that are executed automatically whenever a new
instance of the class is created.
Constructors set up an instance and establish an initial
state, such as the size and resolution of the instance. For
example, the World constructor sets up the world's background
image and the instances that should be displayed in the world
when the game starts.
Constructors have no return type.
Their name, immediately following the word “public,” is
the same as the class in which they are defined. For
example, a constructor for the BeeWorld class would be
called public BeeWorld(). The World subclass has a
constructor that specifies the size and resolution of the
world.
When an Actor subclass is created, it does not automatically
have code written in its constructor like the World subclass
does. Constructors can be added to the Actor class to perform
initial assignments of the instance's image, location in the
world, or anything else the instance needs when the game
starts.
Terminology
Initializing an Actor instance is
the process of creating the instance and its initial
values. The new instance contains a reference to the
images or values contained in the variables.
Actor constructor guidelines:
Signature does not include a return type.
Name of constructor is the same as the name of the class.
Constructor is automatically executed to initialize the
instance when an instance of the class is created.
Constructor is placed after the Class header and before
any methods.
For example, a constructor for an Actor subclass may create
the instance and then set the image of the instance,
initialize any other variables the instance may be using,
position the instance in a specific location, or change its
size.
Example: Constructor in an Actor subclass
The following actor constructor tells Greenfoot to
automatically create a new Bee instance and initialize the
image variables for the instance.
Watch this video to learn how to create a constructor
in an Actor subclass and initialize the image
variables.
Try it: Create a constructor in the Actor subclass
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
In the body of the Frog constructor, assign each
image variable to its respective image.
Write the code to set the first image that the
frog displays as image2.
In the act() method, replace the code within the
setImage parameters to the name of the variable that
holds the image you want to display when the
respective keyboard key is pressed.
Compile the code. Run the scenario and test that
it works. Ensure that the Frog starts facing to the
right, and changes its image appropriately when the
left, right, up and down arrow keys are pressed.
Save the scenario.
Summary
In this lesson you have learned how to:
Create images for an object using a constructor
Write programming statements to use the new keyword
Define the purpose and syntax of a variable
Write programming statements to switch between two images
Defining methods
Lesson objectives
In this lesson you will learn to:
Define and call methods
Simplify programming by creating and calling defined
methods
Demo: Lesson preview
Watch this video to see a preview of what you will
learn in this lesson.
Programmer-defined methods
At times, many lines of code are required to program a
behavior. Writing all of this code in the act() method may
cause it to become very long and difficult to read. To better
organize your code, as the programmer, you can write separate
methods within the class for each command. For example, you
can write methods to specify keyboard controls, an object's
movements, or an object's actions such as eating another
object. This is referred to as defining a method.
Below is an example of defining a method that will check the
keyboard controls. Notice that the method is now called
in the act() method.
Define a new method for an action below the act() method.
You should define new methods below the act() method so that
the act() method is easy to find.
Call the new method in the act() method. This is the only
way that the instance knows to use the method when the
scenario is running.
If your Actor subclass is a superclass for other classes,
you should define the method in the superclass so subclasses
can inherit the method.
Terminology
Programmer-defined methods are new
methods written by a programmer that a class did not
already possess. In Greenfoot, these methods are
written in the class's source code below the act()
method.
Programmer-defined methods:
Can be executed immediately, or stored and called later.
Do not change the behavior of the class until called from
the act() method.
Separate code into shorter methods, making it easier to
read.
Steps to define a method:
Select a descriptive name for the method.
Open the Code editor for the class that will use the
method.
Add the code for the method definition below the act()
method.
Call the new method from the act() method to use it
immediately, or store it for use later.
Example: Defined method for random movements
Instead of having all of the random movements for the
butterfly instance in the Butterfly's act() method, the code
could be better organized by having all of these programming
instructions placed in a programmer-defined method. The
example below shows that a method was created called
butterflyMoves() and all of the random movements for the
butterfly are written in the method.
In order to command the butterfly instance to use these
movements, you need to call the method in the act() method.
Now the act() method only has this one statement instead of
many statements that became difficult to read.
Creating methods and calling them in the act() mthod is
referred to as procedural abstraction.
Creating separate methods not only supports clean and simple
programming, it supports method reuse.
Demo: Defining methods
Watch this video to learn how to define a method.
Try it: Define a method
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
Define a method called frogSound() that plays a
sound if the “s” key is pressed on the keyboard.
Note: You will need to either save a sound file in
the sounds folder of your scenario, or record a
sound using the Greenfoot Sound Recorder.
Call the frogSound() method in the act() method.
Compile the scenario. Run the scenario and test
how it works. Press the “s” key and test that the
sound is played.
Save the scenario.
Define a method to turn objects at the edge of the world
Consider the scenario where a butterfly flies randomly around
the world, but is unable to move correctly when it reaches the
edge of the world. To change this behavior and have the
butterfly turn when it reaches the edge of the world, define a
method in the butterfly class to check if the butterfly is at
the edge of the world, then turn the butterfly around if it
is. Then, in the act() method, call the new method so that the
instances of the Butterfly class may use it.
The || symbol is known as a logic operator and is used to
test multiple boolean expressions to determine if one or both
conditions are true or false. This particular logic operator
is an OR operator. The result of the code inside the () of
each if statement will be a boolean response of either true or
false. The remaining programming code will execute based on
the result of being at the edge of the world or not.
Example: Define a method to check an object's position and
turn it if it is at the edge of the world
The method atWorldEdge() was defined for the Butterfly class.
This method will check if the butterfly is at the edge of the
world. If the Butterfly is at the edge of the world, the
butterfly will turn 180 degrees.
Demo: Defining and calling the atWorldEdge() method
Watch this video to learn how to define and call the
atWorldEdge() method.
Demo: Using logic operators and viewing documentation
Watch this video to learn how to use logic operators
and view documentation.
Try it: Define and call the atWorldEdge() method
Download:
The Try it activity below requires that you
start with the project file that was saved in the
previous topic. Download and open this Greenfoot
scenario file if you did not complete the previous
topic's Try it activity.
Define a method called atWorldEdge() that commands
the ant instances to turn 180 degrees if they reach
the edge of the world. Ensure that you write
comments for this method that describes what it
does.
Call the atWorldEdge() method in the act() method.
Copy the atWorldEdge() method and paste the method
in the source code for the Fly class.
Call the atWorldEdge() method in the act() method
for the Fly class.
Compile the scenario. Run the scenario and test
how it works. Ensure that the ants and flies both
turn 180 degrees when they reach the edge of the
world.
Save the scenario.
Define a collision detection method
Popular games are based around the interaction of objects and
the actions the objects take when a specific interaction is
detected.
You could write code in your game so that a predator object
is able to eat prey objects, or when objects intersect they
bounce off or stick to each other.
Consider a scenario where you want to move your bee using the
keyboard to each flower to eat the flower. If the bee passes
over the flower it will remove the flower that is there.
Let's examine how to define a method to check if the bee is
colliding with a flower. If the bee collides with the flower,
the flower is removed from the world.
The steps required to define this method include:
Define a method to check if the bee is colliding with the
flower.
Declare a local variable inside of the method body to
collect the intersecting flower object.
Write an if statement inside of the method body that
checks if the bee is colliding with a flower. If the
condition is true, the flower is removed from the world.
Call the defined method in the bee class to command the
bee to use the method.
Test if an object is at the same coordinates (colliding)
with another object
To test if an object is colliding (or near colliding) with
another object, write the following in the defined method:
Define a variable that holds an Actor value type to
collect the colliding object.
Write an if statement to test if the object is colliding
with a specific class type.
Use the getWorld() method to access the world method
removeObject(), removing the intersecting object from the
world.
Define the method
First, define the method eatFlower() below the act() method.
Next, declare a variable with an Actor value type that will
look for the Actor objects from the class that we want to
collect. In this case, the variable should hold the Flower
Actor type.
This variable will use the getOneIntersectingObject() method
to look for a specific class that the bee is intersecting
with, in this case, the Flower class. The parameter must
specify the name of the class, also referred to as the Actor
type that will intersect with the bee.
Demo: Defining a method to detect and remove
intersecting objects
Watch this video to learn how to define a method to
detect and remove intersecting objects.
Try it: Define a method to detect and remove
intersecting objects
Download:
The Try it activity below requires that you start
with the project file that was saved in the previous
topic. Download and open this Greenfoot scenario file
if you did not complete the previous topic's Try it
activity.
Declare an eatFlies() method that will detect and
remove intersecting fly objects.
Call the eatFlies() method in the act() method.
Compile the code. Run the scenario to test that it
works.
Move the frog around the world and try to collide
with a fly. Test that the fly is removed from the
world if it collides with the frog.
Save the scenario.
Summary
In this lesson you have learned how to:
Define and call methods
Simplify programming by creating and calling defined
methods
Create scorekeeping functionality and end the game
Lesson objectives
In this lesson you will learn to:
Describe an infinite loop
Recognize an infinite loop in code
Describe the scope of a local variable in a method
Describe the difference between == and = in Java
Import a Java package
Demo: Lesson preview
Watch this video to see a preview of what you will
learn in this lesson.
The while loop
Have you ever listened to a song or watched a movie that
played again and again and never ended? In programming you can
create the same situation with a loop. A loop is a statement
that can execute a section of code multiple times. When a loop
executes all of the statements within the loop one time, this
is called an iteration. When a loop executes all of the
statements within the loop more than one time, and stops based
on a condition, this is called a conditional iteration.
Terminology
A while loop executes a statement
(or set of statements) a number of times while a
condition is true. This form of loop is known as conditional
iteration.
For example, with a while loop, you could:
Create 50 instances of a class using a single programming
statement.
Execute a method a certain number of times, such as have a
method play a sound file 3 times.
Execute a method until a certain condition is false.
The components of a while loop include:
Java keyword while
A condition in parentheses
One or more statements that are executed
Curly braces { } to enclose the statements (Note: Curly
braces are optional if only one statement is inside the
loop, but it is recommended to always use them for
readability.)
A condition is a boolean
(true/false) expression which will be evaluated with
each iteration of the loop until it is false.
Using a loop variable to control execution of a while loop
How does a program know how many times to execute the while
loop? It uses a loop variable to control how many times the
while loop is executed while a condition is true.
A loop variable is used to control
how many times the while loop is executed while a
condition is true. The loop variable is a counter,
most often named i, which stores how many times the
loop has executed. A loop variable is a type of local
variable (declared inside the body of a method) and
must be created as part of programming the loop.
A loop variable, like a local variable:
Is declared inside of the method body right before the
while loop (instead of at the beginning of a class before
the act() method). This is because the variable is not used
by the whole class, only the specific method that contains a
while loop.
Does not have a visibility modifier (public or private) in
front of its definition.
Exists only until the current method finishes running, and
is then erased from memory.
To declare a loop variable:
Declare the variable type (integer or object reference).
Name the variable.
Initialize the variable to a number (usually zero).
There needs to be a way to change the value of the loop
variable each time the loop is executed in order to count how
many times the loop has been executed. This is referred to as
incrementing the variable. If you do not change the value of
the loop variable by counting up each time the loop is
executed, the loop will never end.
First, create the condition in the while loop that specifies
how many times the body of the loop should be executed. For
example, if it is true that the variable i has been
executed less than 5 times, execute the programming
statements in the body of the while loop.
Another simple way to increment a loop variable in Java is
to use the syntax shown below. Note that this syntax will
always increment the loop value by 1.
This example will execute the body of the loop while the
number of executions is less than, but not equal to, 10. When
the loop has been executed 10 times (0-9), it stops.
Insert statements to execute in the body of the while loop
Between the curly braces of the while loop, insert the
programming statements to execute. For example, to create a
while loop that executes a method 5 times, insert a single
programming statement with the method in the body of the while
loop. Remember, the condition of the while loop and loop
variable will control how many times the while loop executes
that single programming statement.
In the example, the loop variable is declared and initialized
to 0 (int i = 0). The condition to end the loop uses the loop
variable i (while i < 10).
The programming statements to execute in the loop body add a
flower object to the world at a random x and y position. The
code gets the height and width of the world so the flowers
appear within the boundaries of the world.
It is important to note that if you do not increment the
local variable i, the loop would never reach the end
condition, creating an infinite loop that would never end.
Example: Invoking a method using a while loop
Create a while loop that plays a sound file 3 times. In the
example below, when the player presses the b key, the bee will
buzz 3 times.
Watch this video to learn how to create a while loop.
Try it: Create a while loop
Download:
The Try it activity below requires that you start
with the project file that was saved in the previous
topic. Download and open this Greenfoot scenario file
if you did not complete the previous topic's Try it
activity.
Edit the frogSound() method so that the sound is
played 3 times when the “s” key is pressed.
Compile the code. Run the scenario to test that it
works.
Save the scenario.
Infinite loops
An infinite loop is described as a loop that continues to
execute forever because the end to the loop isn't established.
Infinite loops are considered to be a logic error, and are a
common problem in programming. The common reasons for a loop
to execute infinitely include:
Most games end because a specific condition has been met or
because the player specifies that they want to stop the game.
The Greenfoot class has a stop() method that you can use to
end your game at a point that you designate.
You may want to end the game when:
The player achieves a milestone.
Time runs out on the clock.
The instance touches a certain coordinate or object.
Let's examine a scenario where the object of the game is for
the Bee to eat 10 flowers while avoiding the butterflies and
mushrooms. All of the code that you will write to end the game
will be written in the Bee class.
There are three possible endpoints to the game:
When the Bee collects 10 flowers.
When the Bee collides with a butterfly 3 times.
When the Bee collides with a mushroom 3 times.
The game will end when any of these endpoints occur.
If the player wins, the Bee image will change to an image
that says “You win!” and using a while loop, 10 flowers will
randomly display on the screen using a while loop.
If the player loses, the Bee image will change to an image
that says “Game over!” Using a while loop, 10 butterflies or
10 mushrooms will randomly display on the screen, depending on
whether the butterflies or mushrooms caused the player to
lose.
Define a method to remove a flower from the world if the bee
collides with it. This method programs the appearance of the
bee eating a flower. Within this method, a counter is needed
to increment the variable that manages the number of flowers
eaten. Remember, the variable was defined at the top of the
class, before the act() method.
Define a method to manage collisions with the mushroom
Define a method to make the bee move to a specific location
(100, 100) if it collides with an instance of the Mushroom
class. Within this method, a counter is needed to increment
the variable that manages the number of times the bee collides
with a mushroom.
Define a method to manage collisions with the butterfly
Define a method to make the Bee move to a specific location
(100, 100) if it collides with an instance of the Butterfly
class. Within this method, a counter is needed to increment
the variable that manages the number of times the bee collides
with a butterfly.
Define a method to keep score and manage the end of the game
Define a method to manage under what conditions the game is
over.
This defined method will need to contain a separate if
statement for each of the three ways in which the game could
end. Let's examine those three if statements:
Using the == relational operator to check if the variable
equals the totals to end the game
The programming statements that instruct the instance to
check for the number of flowers eaten and the number of
collisions with mushrooms or butterflies contains:
An if statement
== operator (two equals signs)
The == relational operator:
Compares one value with another.
Returns a boolean (true or false) result.
Remember that = is the assignment symbol, and is used to
assign a value to a variable. The == is a relational operator
that will test to see if two values are the same.
The Try it activity below requires that you start
with the project file that was saved in the previous
topic. Download and open this Greenfoot scenario file
if you did not complete the previous topic's Try it
activity.
Declare a variable named countFliesEaten to hold
the number of Fly objects eaten by the Frog.
Declare a variable named countAntCollisions to
hold the number of times the Frog collides with an
Ant.
Declare a variable named countRockCollisions to
hold the number of times the Frog collides with a
Rock.
In the eatFlies() method (the method that will
remove a Fly from the world if it collides with the
Frog), include a counter to increment the
countFliesEaten variable.
Define an antCollisions() method that will make
the Frog move to a static position in the world if
it collides with the Ant. The method should include
a counter to increment the countFliesEaten variable.
Define a rockCollisions() method that will make
the frog move to a static position in the world if
it collides with a rock. The method should include a
counter to increment the countRockCollisions
variable.
Define a scoreKeeper() method to control the end
of the game.
If the Frog eats 10 Flies, the player wins the
game. The image of the Frog should change to an
image that you create that says “You Win!”
If the Frog collides with the Ant 5 times, the
player loses the game. The image of the Frog
should change to an image that you create that
says “Game Over”, and 10 Ants should display at
random locations in the world.
If the Frog collides with the Rock 5 times,
the player loses the game. The image of the Frog
should change to an image that you create that
says “Game Over”, and 10 Rocks should display at
random locations in the world.
Note: You will need to create the You Win and
Game Over images in your computer's paint or
drawing program, then save the images in the
images folder of your scenario.
Compile the scenario. Run the scenario to test
that it works. Both win and lose the game so that
you can test the different functionality that needs
to occur.
Save the scenario.
Displaying dynamic text instructions
Another way to provide information to the players of a game
is to display dynamic text in the game. Dynamic text means
that we can write code to change what text is displayed
throughout the course of the game.
You may wish to:
Provide instructions for our game, such as what they need
to do to win the game.
Provide messages to the players, such as “You Win!” or
“Game Over”.
You can create an Actor subclass named Instructions to
display the dynamic text.
Display dynamic instructions
Instructions can be used in any scenario to provide the user
with instructions on how to play the game and to give
on-screen information.
Steps to create dynamic instructions:
Create an Actor subclass named Instructions.
Import the java.awt.Color package to provide the
instructions text with a background color and text color.
Create a constructor in the subclass to display a dynamic
text image in the world.
Compile the code.
Create the Instructions class
To display any type of instance in the world, it must be an
instance of an Actor subclass. To display instructions, first
create an Actor subclass named “Instructions”. Do not assign
an image to the subclass. The image that the instance displays
will be coded in the constructor of the Instructions class.
Import the java.awt.Color package which is a standard package
that contains a variety of colors in which to display the
instructions text. You can write code to access the different
colors from this package. To import the java.awt.Color
package, write the import declaration at the top of the
Instructions class, after the package declaration.
Since this class does not have a default image, create a
constructor that will create the dynamic instructions image
when the Instructions instance is added to the world.
In a display class, it is normal to create a constructor to
display the required text. This text will be assigned as an
image when the Instructions instance is created.
Steps to create a constructor:
Open the Code editor for the class.
Create the constructor before the act() method, but after
any variables.
Add the code required for the constructor to create the
image as a GreenfootImage class.
The GreenfootImage class has a number of constructors that
can be used to retrieve a new image when creating an instance
of a class. The following constructor is used to set a dynamic
image from a String.
The constructor above creates the new image by providing the
following information:
Display String: The text to display in the image. A String
is a piece of text (character, word, sentence, or more)
enclosed in double quotes. For example: “This is a String”,
“a”, “3”.
Font size: The size of font to display.
Background color: The background color of the image.
Font color: The font color of the String characters in the
image.
The background and text colors are selected from the Java
package jawa.awt.Color which was imported into the class.
An instance of the Instructions class is automatically added
to the world each time the world is initialized.
Example: Create a constructor to assign an image
To create a message that displays “Collect the flowers and
avoid the butterflies and mushrooms” with a font size of 18, a
font color of green and a background color of yellow, we would
use the following setImage() statement. The code can be
modified to change the instructions, font size, or color.
Watch this video to learn how to display dynamic text
in a scenario.
Try it: Display dynamic text instructions
Download:
The Try it activity below requires that you start
with the project file that was saved in the previous
topic. Download and open this Greenfoot scenario file
if you did not complete the previous topic's Try it
activity.
Right-click on the existing Instructions class and
select set Image… From the scenario images menu on
the left, select No Image. Click OK.
In the Instructions class, import the
java.awt.Color package at the top of the class below
the Greenfoot import statement.
Create a constructor that will create the new
Instructions image with the text “Collect the flies
and avoid the ants and rocks to win the game.” The
font should be black color, size 20, with a yellow
background.
Compile the code. The scenario will automatically
display the text.
Modify the source code in the Instructions class
to change the instructions, font size, or font color
to observe how this changes the Instructions
instance.
Save the scenario.
Summary
In this lesson you have learned how to:
Describe an infinite loop
Recognize an infinite loop in code
Describe the scope of a local variable in a method
Describe the difference between == and = in Java
Import a Java package
Summary
In this tutorial you learnt how to create 2D games using basic
Java programming in this self-paced, online course.
Additional resources
Greenfoot textbook scenarios
The Greenfoot Textbook Scenarios provide some basic scenarios to
explore the features of Greenfoot.
Steps to download the Greenfoot textbook scenarios:
When prompted, click Save to save the Greenfoot Textbook
Scenarios zip file to your computer, hard drive, or USB drive.
You should create a folder where you will store all of your
Greenfoot scenarios.
When the download is complete, open the zip file. Extract the
files to a folder on your computer, hard drive, or USB drive.
The Joy of Code video blog is hosted by Michael Kolling, creator
of Greenfoot. Visit his blog for more instructional videos on how
to use Greenfoot to create fun and engaging games.