5
academy

Getting Started with Java Using Greenfoot

Overview

Purpose

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
  • Install necessary software for the course

What is Java?

Java

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!

Visit this link to see videos of Java in Action: http://www.java.com/en/java_in_action/

Watch this video to learn more about Java technology: http://www.java.com/en/download/whatis_java.jsp

What is Greenfoot?

Greenfoot

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.

Java Eclipse EE

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.

2D Demo

Program execution controls

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.

2D Demo

The class display is used to display the Actor object names, known as classes, in a hierarchical fashion.

2D Demo Class Display

Example: Object, class, and instance

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.
2D Instances

 

Terminology

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.
Greenfoot API

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.

Visit the Greenfoot website to learn more about Greenfoot: http://www.greenfoot.org/overview

Check system requirements

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:

  1. Review the system requirements checklist below.
  2. 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
  • 3D video card recommended

Sound Card

Required

Software

*Note: This is required to view the videos in this course. It is not required to use Greenfoot.

Download the Java Development Kit

The Java Development Kit (JDK) is required to use Greenfoot. You should download and install it first before downloading and installing Greenfoot.

Steps to download the Java Development Kit

  1. Open any Internet Browser and type the following URL in the address bar:
  2. http://www.oracle.com/technetwork/java/javase/downloads/index.html
  3. From the Oracle Technology Network website, click Java Platform (JDK).
  4. From the Java SE Development Kit 7 Downloads page, review the License Agreement.
  5. Accept or Decline the License Agreement (if you decline, the software will not download).
  6. Locate and select the Java SE Development Kit for your computer operating system.
  7. When prompted, save the file to a location you easily remember. Click OK.

Steps to launch the JDK executable file

  1. Locate the executable file and double click it to execute.

  2. Launch Executable Screenshot
  3. When prompted to run the executable file, click Run

  4. Run Executable Screenshot

Steps to run the JDK Installation Wizard

  1. From the Installation Wizard dialog box, click Next>.

    JDK Wizard Screenshot
  2. To accept the default settings, Click Next>.
  3. When prompted for installation location, click Next>. If prompted, close the Internet browser window.
  4. Click Continue to acknowledge the successful installation.
  5. You will be prompted to set-up the Software Developer Kit (SDK). Click Next>.
  6. When prompted for the installation location, click Next>.
  7. When the set-up is complete, click Close.

 

Demo: Downloading and installing the JDK

Watch this video to see an example installation of the Java Development Kit (JDK).


Try it: Download and install the JDK

Instructions:
Visit this link to download and install the Java Development Kit: http://www.oracle.com/technetwork/java/javase/downloads/index.html


Download Greenfoot

The Java Development Kit (JDK) is required to use Greenfoot. Ensure that you download and installed the JDK prior to downloading and installing Greenfoot.

Steps to download Greenfoot

  1. Open any Internet Browser and type the following URL in the address bar: http://www.greenfoot.org
  2. Select The Software link.

    Greenfoot Software
  3. Locate and select the correct version for your computer.

    Software Version
  4. When prompted, click Save to save the Greenfoot Installer file.

Steps to launch the Greenfoot Installer Wizard

  1. When the download is complete, either select Run or Open Folder, then double-click the executable file.

    Download Complete
  2. A Greenfoot Setup window will appear.

Steps to install Greenfoot

  1. From the Installer Wizard, select the Next option.
  2. You may be asked who to install this for. Select the required installation setting, then select the Next option.

    Installation Setting
  3. Review the file Associations settings and select the Next option.

    File Associations Settings
  4. To accept the default setting for the installation Destination Folder, select the Next> option.
  5. To begin the installation, click Install. A progress window will display while Greenfoot is installed on your computer.
  6. To complete the installation, click Finish.

Steps to launch Greenfoot

  1. After Greenfoot is installed, the Greenfoot icon will appear on your desktop.

    Alice 3 Icon Screenshot
  2. Double-click the icon to launch Greenfoot.

Greenfoot download and installation support links

Join the forum to get help from other users:hhttp://www.greenfoot.org/topics

 

Demo: Downloading and installing Greenfoot

Watch this video to see an example installation of the Greenfoot software.


Try it: Download and install Greenfoot

Instructions:

Visit this link to download and install Greenfoot: http://www.greenfoot.org/


Summary

In this lesson you have learned to:

  • 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:

  • The non-moving background image
  • The non-moving flower, mushroom and grass objects
  • The moving bee and butterfly objects

  • Initial Scene

 

Demo: Understanding the Scene editor

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.

Greenfoot Icon

Greenfoot IDE

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.

Greenfoot IDE

The World

The world is where the action for your scenario will take place and where the user will interact with your scenario.

Greenfoot World

The Greenfoot World coordinate system starts at (0,0) at the top left. You can write code that specifies the size, height, and cell size of the world.

Coordinate System

The class display

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.

Class Display
Terminology

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.

Class Display

Execution controls:

  • Act: Runs all actions in the scenario once.
  • Run/pause: Runs all actions in the scenario repeatedly until Pause is clicked.
  • Reset: Pauses the scenario or resets the scenario back to its starting position.
  • Speed: Executes actions faster or slower.

Open a scenario in Greenfoot

Steps to open a scenario in Greenfoot:

  1. Double-click the Greenfoot icon to launch Greenfoot.

  2. Class Display
  3. Locate the folder on your computer where you store your Greenfoot scenarios. Select the scenario, then click Open.
  4. 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.

Instructions:

  1. 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.
  2. Download the L1S3_Jungle.zip file.
  3. Open the zip file. Copy the L1S3_Jungle folder contained inside of the zip file to the Greenfoot Course Scenarios folder on your computer.
  4. Locate the Greenfoot program on your computer. Double-click the Greenfoot icon to launch Greenfoot.
  5. From the Scenario menu, select Open.
  6. Locate the L1S3_Jungle scenario that you downloaded to your computer. Select the file, then select Open.
  7. 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).

Jungle Scenario

 


Terminology

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.


Steps to add an instance of a class to the world


  1. Right click on the name of the class.
  2. Select the new [class name()] option.

  3. Select Class
  4. 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.

  5. Drag Instance

 

Demo: Add an instance of a class to the world

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.


Instructions:

  1. Open Greenfoot.
  2. 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).
  3. 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.
  4. 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.


Code Editor

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.


Act Method

The act() method described


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.


Act Method Body

Example: Methods


For example, the Actor class has methods such as:

  • 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.


Act Method Coded

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.


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.


Run Button

 

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.


Instructions:

  1. Open the Code editor for the Elephant class.
  2. In the act() method, program the elephant to move 8 steps, then turn 2 degrees.
  3. Open the Code editor for the Hippo class. Program the hippo to move 8 steps, then turn 2 degrees.
  4. Compile the scenario.
  5. Run the scenario. Observe how the elephant and hippo move.
  6. 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:

  1. From the opened scenario, select Save As… from the Scenario menu.
  2. 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.


Instructions:

  1. Reposition the objects in the scenario with your cursor. Add additional objects to the scenario.
  2. From the Scenario menu, select Save As...
  3. 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.

The Code editor


Code Editor

The Scene editor

Scene Editor

Create a new scenario

To create a new scenario follow these steps:

  1. Select New from the Scenario menu.

  2. New Scenario
  3. Navigate to the folder where you wish to save the scenario.
  4. Enter the name of the Scenario in the Folder name text box.
  5. Click Create.

  6. Scenario Name

The new scenario will open in Greenfoot. The only classes that appear in the Class Display are World and Actor.

Scenario New Clean

Save the scenario

Periodically save the scenario that you are working on to minimize loss of work due to system crashes or other unforeseen events.

To save a scenario, click Save from the Scenario menu.

Scenario Saved

If you wish to save a copy with a new name, select the Save As… option from the Scenario menu, then enter a new name.

Save Scenario As...

 

Demo: Creating and saving a new scenario

Watch this video to learn how to create and save a scenario in Greenfoot.


Try it: Create and save a new scenario

Instructions:

  1. From the Scenario menu in Greenfoot, select New.
  2. Navigate to the Greenfoot Course Scenarios folder on your computer.
  3. Name the scenario FrogFly_L2S2.
  4. 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.


Bee Class

Classes in Greenfoot

When you add a class to your scenario, it appears in the class display (to the right of the world).


Class Display

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.


Inheritance

Two types of superclasses appear in the Greenfoot class display: World and Actor. These two superclasses are always visible in the class display.


Superclasses
  • 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.


Butterfly Class

The butterfly subclass:

  • 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.

Steps to create a new world subclass:

  1. Right-click on the World superclass.
  2. Select New subclass...

  3. New World Subclass
  4. In the New Class dialog box, name the subclass a descriptive name.
  5. Select an image that the class will display. This is the background for the world. Select the backgrounds category, then select an image.
  6. Click OK.

  7. Select Image
  8. The world subclass will appear in the class hierarchy.

  9. New World Subclass Display

Compile 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.

Compile

 

Demo: Creating a world subclass

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.


Instructions:

  1. Right-click on the World superclass. Select new subclass...
  2. Name the class FrogWorld.
  3. In the Backgrounds image category, select the sand.jpg background image.
  4. Click OK.
  5. Compile the scenario.
  6. 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.

Bee Butterfly

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.

Inherited Methods

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.

Instructions

Steps to create a new subclass with an image imported from your computer:

  1. Right-click on the Actor superclass.
  2. Select New subclass...

  3. New Subclass

  4. In the New class window, click the Import From File... button.

  5. Import File
  6. Select the image file to import from your computer.

  7. Instructions

  8. Name the new subclass, then click OK.

  9. Instructions

  10. The subclass with the new image appears in the class hierarchy. Click the Compile button to compile the scenario.

  11. Instructions Class

Add an Actor subclass instance to the scenario

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:

  1. Right click on the class.
  2. Click the new [class name] option.

  3. New Instructions
  4. Drag the instance into the scenario with your cursor.

  5. Instructions Instance

 

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.


Instructions:

  1. 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.”
  2. Create an Actor subclass and import the image file into the subclass.
  3. Name the new subclass “Instructions”. Click OK.
  4. Create Frog, Fly, Ant, and Rock classes. Note that these classes have images in the Greenfoot gallery that you can use.
  5. Compile the scenario.
  6. Save the scenario.

Steps to add an instance of a class to the world

  1. Right click on the name of the class.
  2. Select the new [class name()] option.
  3. 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.

Drag and Drop

To use methods to re-position instances:

  1. Right-click on an instance in the world. In the Inherited from Actor menu, you will see a list of methods available to position your object.
  2. Select one of the methods (such as move(), turn(), setLocation(), setRotation(), or turnTowards()) to reposition the instance.

  3. Position Methods

Save 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.

Save 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.


Instructions:

  1. Add 2 rocks, 2 ants, 1 frog, 10 flies, and 1 instructions instance to the scenario.
  2. Position the flies using your cursor. Also, position the flies using the setRotation() method so they are all facing different directions.
  3. Position the frog at x = 50 y = 50.
  4. Position the instructions at the bottom of the world.
  5. Position the ants and rocks anywhere you wish in the world.
  6. Save the world so that when you re-open the scenario, the instances are automatically positioned in the world.
  7. 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.

Source Code

View the source code of a class

Steps to view the source code of a class:

  1. Right click on a class in the class menu.
  2. Select Open editor.

Source Code

Code editor

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.

Code Editor

You can tell that you are in the Scene editor when you see the execution controls, world, and class display.

Scene Editor

Using methods from other classes

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.

Class Documentation

Components of source code

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:

  • A description of what the class does.
  • The name of the person who authored the code.
  • The date the source code was last modified.
Class Description

Class definition components

The class definition includes:

  • Java keywords or reserved words.
  • The name of the class as defined by the programmer.
  • The name of the superclass that the subclass extends.
Class Description

Defining classes

The class definition defines:

  • 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.

Act Method

Method signature

The method signature describes what the method does. The signature contains a return type, method name and parameter list.

Method Signature

The method name describes what the method does.

Method Name

The return type indicates whether the method will return something after execution.

Method Name

The parameter list allows values to be passed to a method. The parameters are typically used during the execution of the method.

Method Parameter List

Comments

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.

Comments

Comments:

  • Describe what the source code does.
  • Do not impact the functionality of the program.
  • Blocks of comments start with a forward slash and one (or two) asterisk /*.
  • Blocks of comments end with a forward slash and one asterisk */.
  • Blocks of comments are displayed in blue font (in Greenfoot).
  • Single line comments start with two forward slashes //.
  • Single line comments are displayed in Grey font (in Greenfoot).

Documentation

Documentation describes the properties of the class.

Steps to view the documentation:

  1. Right-click on a class.
  2. Select Open editor.
  3. Select Documentation from the drop-down menu at the top right of the Code editor.
Documentation

 

Demo: Components of source code

Watch this video to review the components of source code.


Try it: Components of source code

Download:

Download and open this Greenfoot scenario before you complete this Try it activity.


Instructions:

  1. Open the scenario.
  2. Open the Code editor for the Bananas class.
  3. Locate the class definition and list its components.
  4. Open the Code editor for the Lemur class.
  5. Identify the variables, constructors, and methods in the source code.
  6. Locate a method. Identify the components of the method.
  7. 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.

Act Method

 


Terminology

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.

Act Method Body

For example, the Actor class has methods such as:

  • move(int distance):  Move this actor the specified distance in the direction it is currently facing.
  • turn(int amount):  Turn this actor by the 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.
  • setImage(GreenfootImage image):   Set the image for this actor to the specified image.
Actor 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.
  • Semicolon, to end the statement.
Act Method Coded

Invoking methods programmatically

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.

Invoke Methods

Sequential execution

Methods contained in the class body are executed in sequential order.

In the following example, both the move() and turn() methods are invoked, but they will be executed sequentially, one after the other.

move(1);

turn(15);

 

Demo: The act() method

Watch this video to learn how to code the act() method.


Try it: The act() method

Download:

Download and open this Greenfoot scenario before you complete this Try it activity.


Instructions:

  1. Open the Code editor for the Fly class.
  2. 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.
  3. Compile the scenario.
  4. Run the scenario. Observe how the flies move.
  5. 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:

  1. Click Compile to compile the code.
  2. If there are no errors, the message “Class compiled – no syntax errors” displays.

    No Error Message
  3. If there are errors, the incorrect syntax is highlighted and a message attempts to explain the error.

    Error Message
  4. Click the question mark icon to display additional information about the error.

    Error Message

Example: Syntax error

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.

Error Message

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.


Instructions:

  1. Open the code editor for the Fly subclass.
  2. 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.
  3. Incorrectly type the name of the turn method. Compile the code and review the error message. Debug the error, then recompile the code.
  4. Create and debug two more errors in the code. Ensure that your scenario compiles succesfully when you are finished.
  5. 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:

  1. 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/
  2. Locate three methods in the Actor class that tell you more about an object's orientation.
  3. Go to the World class in the Greenfoot API. Which method tells you the number of objects in a scenario?
  4. 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.
Method Components

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.

Method Declaration Examples

 

Demo: Method declarations

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.
Return Type

Method with void return types

Methods with void return types typically issue one or more commands that carry out an action.

  • Includes the word “void”.
  • Does not return information about the object.

  • Void Return Type

Invoking methods with void return types

You will invoke methods with void return types:

  • To precisely position objects in your initial scenario (the starting point of the game).
  • To command objects to perform actions in your game.
  • Example: command the frog to hop or to eat another object.

Methods with non-void return types

Methods with non-void return types typically ask the object to obtain information and return the information.

  • Does not include the word “void”.
  • Returns information about the object.

  • Non-Void Return Type

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.

Inheritance

Identify inherited methods


There are a number of ways to identify inherited methods:

  1. The Object Menu displays all of the inherited methods of an instance.
  2. The Code editor displays all of the inherited methods of a Class.
  3. The Greenfoot Documentation displays all of the inherited methods of all classes.

Steps to use the Object Menu to display all of the inherited methods of an instance:


  1. Open or create a new scenario that has an Actor subclass.
  2. Add one instance of the Actor subclass to the World.
  3. Right-click on the instance to display the menu.
  4. Click inherited from Actor to display a list of the methods that the subclass inherits from the Actor superclass.

  5. Object Menu

Steps to identify inherited methods in the Code editor:


  1. Right click on a subclass.
  2. Click Open editor.
  3. In the Code editor, select Documentation (instead of Source Code) from the drop-down menu.

  4. Documentation

  5. Scroll down to the Method Summary and review the class's inherited methods.

  6. Inherited Methods

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.

Class Documentation

 

Demo: Viewing 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.


Instructions:

  1. 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.
  2. Right-click on the Frog class and select Open Editor.
  3. In the Code editor, select Documentation. View the list of inherited methods for the Frog class.
  4. From the Help menu, select Greenfoot Class Documentation. Find 3 methods that tell you more the location of Actor objects in the world.
  5. 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.
getRandom Signature

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.

getRandom Method Call

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.

getRandom Method Call

 

Demo: Creating randomized behaviors

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.


Instructions:

  1. Open the Code editor for the Fly class.
  2. 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.
  3. Open the Code editor for the Fly class again. Change the parameter limit in the method from 20 to 15. Compile the code.
  4. Run the scenario and observe how this changes the flies' movements.
  5. 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.

Examine the getRandomNumber() method below:

getRandom Method Call

This method must be called from the Greenfoot class using dot notation. New subclasses that you create do not inherit the getRandomNumber() method.

Dot notation format

The format for dot notation code includes:

  • Name of class or object to which the method belongs
  • Dot
  • Name of method to call
  • Parameter list
  • Semicolon

Dot notation example

The getRandomNumber() method shown below:

  • Calls a random number between 0 and up to, but not including 6.
  • Returns a random number between 0 and 5.

  • Dot Notation Example

Class methods

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:

  1. From the Help menu, select Greenfoot Class Documentation.
  2. The documentation will open in your default browser.

  3. Greenfoot Documentation

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.

Java syntax for writing an if statement:

IF Statement

IF decision statement components

An if statement condition, which is a true or false expression, determines whether or not the programming statements in one or more methods execute.

IF Statement

Example: IF decision statement to turn at edge of the world

In the following example, if the butterfly reaches the edge of the world, the butterfly will turn 180 degrees.

Turn At Edge

Example: IF decision statement to turn if a keyboard key is pressed

In the following example:

  • The left and right arrow keys on the keyboard make the object turn left or right.
  • If the condition is false (the arrow keys have not been pressed), the method calls defined in the if statement are not executed.
  • The move() method is executed regardless of the IF statement.

Remember, the act() method is called once when the Act button is pressed. It is called repeatedly when the Run button is pressed.

isKeyDown method

The isKeyDown method is a pre-existing Greenfoot method that listens to determine if a keyboard key is pressed during program execution.

isKeyDown

 

Demo: Using the IF decision statement

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.


Instructions:

  1. Write an if statement in the act() method that will move the Frog forward one step when the “up” arrow is pressed.
  2. 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.
  3. 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.
  4. Compile and run the scenario. Test that the frog moves as expected when you press the up, left, or right arrow keys.
  5. 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.

  • IF ELSE Structure

IF-ELSE statement format

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.

IF ELSE Format

The condition is enclosed in parenthesis() and must equate to a boolean value (i.e., true or false).

The associated code to be executed for each IF-ELSE statement is enclosed in curly brackets {}:

IF-ELSE statement example

The following IF-ELSE statement executes as follows:

  • Evaluate the condition (Is the random number in the range 0 to 99 less than 7?)
  • if true turn(10)
  • if false turn(5)
IF ELSE Example

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.

Random IF Statement

Gaming problem solved with conditional behavior

Problem: A butterfly object should move randomly so it is more challenging for the keyboard-controlled object, a bee, to avoid it.

Solution:

  • The butterfly should turn a small amount as it moves.
  • To code this solution, turn the butterfly a random number of degrees, up to 20 degrees, 6% of the time as it moves.

  • Random IF Solution

Conditional behavior format

The programming statement below includes:

  • IF control statement with the getRandomNumber() method.
  • Parameter limit of 100.
  • Comparison operator <.
  • Number 6 to limit the range of values to return to 0-5.
  • Method body with statement to indicate that the object should turn up to 20 degrees if the condition is true.
  • else condition that specifies that the object should turn 5 degrees if the condition is false.

  • Random IF Solution 2

 

Demo: Conditional behavior

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.


Instructions:

  1. 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.
  2. Compile and run the scenario.
  3. 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.

World Source Code

Import statement

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.

Import Statement

Class header

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.

Class Header

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.


Instructions:

  1. Modify the World constructor to change the size of the world to 700x500, with a cell size of 1 pixels.
  2. Compile the scenario. Notice how the size of the world has changed.
  3. 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:

  1. Add the Actor instances to the world and position them with your mouse.
  2. Right click on the world.
  3. Select the Save the World menu option.

  4. Save World

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.

Prepare Method

 

Demo: Setting up the scenario for gameplay

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.


Instructions:

  1. Right-click on the world, then select Save the World.
  2. Compile the scenario. Notice how the instances are automatically added to the world.
  3. 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:

addObject Method

Example: addObject() method

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.

addObject Method Example

new Keyword

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.

New Keyword

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 default constructor. A default constructor sets the object's properties to their default values.

New Keyword Example

 

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.


Instructions:

  1. Right-click on the world, then select Save the World.
  2. Compile the scenario. Notice how the instances are automatically added to the world.
  3. 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:

  1. Right click on an instance in the world.
  2. Click Inspect to view.
  3. The instance's object inspector will display the instance variables.

  4. Instance Variables

 


Demo: Viewing 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

Instance Variables

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:

  1. Make sure that you have an Actor subclass in the world, and that the scenario is not running.
  2. Right click on an Actor subclass instance in the World.
  3. Select Inherited from Actor to view its methods.
  4. Invoke (select) a method with a specific data type to ask the object a question about its orientation.
  5. The method result will display. Note the value returned, then click Close.

  6. Instance Variables

 

Demo: Invoking methods directly

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.


Instructions:

  1. Run the scenario for a few seconds, then pause the scenario.
  2. Right-click on a fly, then select Inherited from Actor.
  3. Select the getWorld() method. It will return the world that the fly is in.
  4. Right-click on another fly, then select the getRotation() method. This will return the rotation of the fly.
  5. Right-click on an ant, then select the getX() method. This will return the x coordinate of the ant.
  6. 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)

isKeyDown() Method Signature

String Parameter in isKeyDown() Method

A String is a piece of text (character, word, sentence, or more) enclosed in double quotes. For example:

  • “This is a String”
  • “A”
  • “name”

The String parameter in the isKeyDown() method expects the name of the key pressed on the keyboard.

Find a key’s name by looking at your keyboard. Sometimes the name isn't evident (right arrow key is called “right”).

The list of keys which can be used with the isKeyDown() method are as follows:

  • “a”, “b”, .., “z” (alphabetical keys), “0”..“9” (digits), most punctuation marks.
  • “up”, “down”, “left”, “right” (the arrow keys)
  • “enter”, “space”, “tab”, “escape”, “backspace”, “shift”, “control”
  • “F1”, “F2”, .., “F12” (the function keys)

Shortcut to the Greenfoot Documentation

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.

Shortcut

Example: Using the isKeyDown() method

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.

isKeyDown() method example

To insert an isKeyDown() method into the act() method of a class:

  1. 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.

  2. isKeyDown() method example
  3. Enter the String of the keyboard key as the parameter of the isKeyDown() method. For example, “up”, “down”, “left”, or “right”.

  4. isKeyDown() method example
  5. 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.

  6. isKeyDown() method example

 

Demo: Programming keyboard interaction

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.


Instructions:

  1. Program the Frog to move forward 4 steps when the “up” arrow key is pressed.
  2. Program the Frog to move 2 steps and turn left when the “left” arrow key is pressed.
  3. Program the Frog to move 2 steps and turn right when the “right” arrow key is pressed.
  4. Program the Frog to spin when the “s” key is pressed.
  5. 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.

Coordinate System


World Constructor

The method signature for the setLocation() method contains:

public void setLocation(int x, int y)

World 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.

setLocation() method and keyboard controls

 

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.


Instructions:

  1. 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.
  2. Add an if statement for a “down” motion. Program the frog to move 2, then precisely move down.
  3. Compile and run the scenario. Use the keyboard keys to control the movements of the frog.
  4. 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.

Mouse Methods

Greenfoot also provides a MouseInfo class which has many methods available to set the state of the mouse in the scenario.

MouseInfo Class

There are also many methods available in the Greenfoot class which we can use to program mouse interactions in our scenarios.

Mouse Methods

Example: Using The getMouseInfo() method

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.

MouseInfo mouse = Greenfoot.getMouseInfo();

getMouseInfo Example

The mouseDragged() method

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.

Mouse Methods

Example: Using the mouseDragged() method

Examine the following example:

  • 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.

  • mouseDragged() Method Example

Example: Using the mouseDragEnded() method

Examine the following example:

  • 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.

  • mouseDragged() Method Example

Example: Using mouse drag and drop interaction

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.

Mouse Drag and Drop

 

Demo: Programming mouse interaction

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.


Instructions:

  1. 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.
  2. Open the Code editor for the Frog. Remove the programming statements for keyboard interaction from the act() method.
  3. Write programming statements to have the Frog's movements controlled using drag and drop interaction.
  4. Compile and run the scenario. Click and drag the frog around the world with your mouse.
  5. 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:

playSound() Method Signature

Example: Using the playSound() method

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.

playSound() Example

 

Demo: Importing sounds

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.


Instructions:

  1. Find and save a sound file to the sounds folder in your Greenfoot scenario's folder.
  2. Program an if statement in the act() method that plays a sound when the space key is pressed.
  3. Compile and run the scenario. Press the space key on your keyboard to test that the sound plays.
  4. Save the scenario.

Record sounds in Greenfoot

Record sounds in Greenfoot


Greenfoot offers the ability to record your own sounds within the IDE.

Steps to record original sounds in Greenfoot:

  1. In the Controls menu in the Scene editor, select Show Sound Recorder.

  2. Show Sound Recorder
  3. Press Record, and then talk into your computer's microphone to record sound.
  4. Press Stop Recording when finished.
  5. Press Play to play back the sound.
  6. Re-record if necessary.
  7. Enter a file name, and then click Save to save the file to your scenario.
  8. The file is now stored in the sounds directory of your scenario and is ready to reference in your code.

  9. Sound Recorder

 

Demo: Recording sounds in Greenfoot

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.


Instructions:

  1. Record a sound file in your scenario using the Greenfoot Sound Recorder.
  2. Program an if statement in the act() method that plays a sound when the “h” key is pressed.
  3. Compile and run the scenario. Press the h key on your keyboard to test that the sound plays.
  4. 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.

  • Flower Color

  • 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.

  • Flower Color

  • 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.

  • Flower Color

  • 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.

  • Change Direction

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:

  1. Create two images of the instance, each facing a different direction.
  2. Store the two images in the Greenfoot scenario's images folder.
  3. 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.

  1. The setimage() method accepts an image argument for the parameter that is of the type GreenfootImage.

  2. setImage() Method
  3. 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.

  4. setImage() Method

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:

  1. 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.

  2. View Image Folder

  3. 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.

  4. Scenario Images Menu

Set an image using the image file name

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.

View Image Folder

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.

Use setImage() Method

Add the code for the Bee in the act() method for the if condition. For:

if(Greenfoot.isKeyDown(“right”))

this.setImage(“BeeRight.png”);


Repeat for the other three directions.

if(Greenfoot.isKeyDown(“right”))

this.setImage(“BeeRight.png”);


if(Greenfoot.isKeyDown(“left”))

this.setImage(“BeeLeft.png”);


if(Greenfoot.isKeyDown(“up”))

this.setImage(“BeeUp.png”);


if(Greenfoot.isKeyDown(“down”))

this.setImage(“BeeDown.png”);


Code act() Method

 

Demo: Setting an image using the image file name

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.


Instructions:

  1. Right-click on the Frog class and select set Image...
  2. From the Scenario images list, select the frog image. Then from the editing tools below the Scenario images list, select Edit.
  3. 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).
  4. 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.
  5. 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.
  6. 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.
  7. 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.
  8. 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:


if(Greenfoot.isKeyDown(“left”))

this.setImage(new GreenfootImage(“bee_left.png”));


if(Greenfoot.isKeyDown(“right”))

this.setImage(new GreenfootImage(“bee_right.png”));


if(Greenfoot.isKeyDown(“up”))

this.setImage(new GreenfootImage(“bee_up.png”));

if(Greenfoot.isKeyDown(“down”))

this.setImage(new GreenfootImage(“bee_down.png”));

setImage Greenfoot Image

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.


Instructions:

  1. Open the Code editor for the Frog class.
  2. 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. 
  3. Compile the code. Run the scenario and test that the images change when the arrow keys on the keyboard are pressed.
  4. 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.

Variable

Variable format

A variable’s format includes:

  • Keyword private (to indicate that the variable is only available within this Actor class).
  • Variable type: The type of data to store in the variable.
  • Variable name: A programmer-assigned, descriptive name of the variable so that it can be referenced later.
Variable Structure

Common data types in Greenfoot


Data type Description

String

  • A set of characters enclosed within quotation marks.
  • Examples: “apple”, “a”, “3”/li>

boolean

  • A true or false value.
  • Examples: true, false

char (Character)

  • Any of the 65,535 characters of the Unicode character set.
  • Examples: “A”, “5”, “#”

int (Integer)

  • A whole number.
  • Examples: 1, 300, 20

Actor

  • An Actor object in Greenfoot.
  • Examples: Bee, Flower

World

  • A World object in Greenfoot.
  • Examples: BeeWorld, JungleWorld

GreenfootImage

  • A GreenfootImage object.
  • Examples: image1, beeimage2

GreenfootSound

  • A Greenfoot sound file.
  • Examples: buzz.wav, hello.wav

MouseInfo

  • A MouseInfo object.

In this example, a variable named image1 is declared to hold an image value. The variable type is GreenfootImage.

Variable Example 1

In this example, a variable named key is declared to hold a String value: the name of a keyboard key.

Variable Example 2

In this example, a variable named isDown is declared to hold a boolean value. This value will display whether a key is pressed on the keyboard.

Variable Example 3

Declaring variables

Variables are declared in the source code of the class before the constructors and before the act() method.

The format for declaring a variable includes:

  • Keyword private (to indicate that the variable is only available within this Actor class)
  • Data type for the variable
  • Name for the variable
Variable Format

Example: Declaring variables

The bee has four image files, one for each direction it will face.

Bee Images

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.

Bee Images Variables

 

Demo: Declaring variables

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.


Instructions:

  1. Open the Code editor for the Frog class.
  2. Declare four variables named image1, image2, image3, and image 4 of type GreenfootImage that will hold each of the four frog images.
  3. Compile the code.
  4. 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.

An assignment statement:

  • Stores the object or value inside the variable.
  • Is written with an equals symbol.

Format of an assignment statement:

Assignment Statement

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”).

Assignment Statement example for image variables:

Assignment Statement Example

Initial assignment statement placement

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.

  • Constructors

Initializing an actor instance

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.

Constructor Example

The last line of the constructor, setImage(image2), indicates the first image to be displayed when the instance is added to the scenario.

The setImage() and the variable name can be used to change the image when the isKeyDown() method is called.

Constructor Example

 

Demo: Creating a constructor in an Actor subclass

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.


Instructions:

  1. Open the Code editor for the Frog class.
  2. Create a Frog constructor.
  3. In the body of the Frog constructor, assign each image variable to its respective image.
  4. Write the code to set the first image that the frog displays as image2.
  5. 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.
  6. 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.
  7. 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.

Defined Method

Steps to define a new method:

  1. 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.
  2. 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.
  3. 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:

  1. Select a descriptive name for the method.
  2. Open the Code editor for the class that will use the method.
  3. Add the code for the method definition below the act() method.
  4. 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.

Random Butterfly

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.

Random Butterfly Act Method

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.


Instructions:

  1. Open the Code editor for the Frog class.
  2. 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.
  3. Call the frogSound() method in the act() method.
  4. Compile the scenario. Run the scenario and test how it works. Press the “s” key and test that the sound is played.
  5. 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.

Butterfly World Edge

The steps required to define and call this method include:

  1. Test the object's position in the world.
  2. Define a method for the action in the class.
  3. Call the method in the act() method of the class.

Check an instance's position in the world

To check if an object is near the edge of the world you need:

  • An if statement to check if an object is at the edge of the World using the getX() and getY() methods in the Actor class.
  • Boolean expressions to check if conditions are true or false.
  • Logic operators to connect the boolean expressions.

 

Terminology

Logic operators can combine multiple boolean (true or false) expressions into one boolean expression.


Logic operators in Java

Logic operator symbol Logic operator name Description

Exclamation mark (!)

    NOT

    Reverses the value of a boolean expression (if b is true, !b is false. If b is false, !b is true).

Double ampersand (&&)

    AND

    Combines two boolean values, and returns a boolean value which is true if and only if both of its operands are true.

Two lines (||)

    OR

    Combines two boolean variables or expressions and returns a result that is true if either or both of its operands are true.


Methods used to test an instance's position in the world

Method Description

getX()

    An Actor method that returns the x-coordinate of the actor's current location.

getY()

    An Actor method that returns the y-coordinate of the actor's current location.

getWorld()

    An Actor method that returns the world where the actor lives.

getHeight()

    A GreenfootImage class method that returns the height of the world (in number of cells).

getWidth()

    A GreenfootImage class method that returns the width of the world (in number of cells).

The || Symbol

    This isn't a method, but it’s a logic operator in a conditional statement that means “or”.


Example: Check an instance's position in the world

In the example below, the syntax is checking if the object is within 20 pixels of either side of the width of the world.

getX

In the example below, the syntax is checking if the object is within 20 pixels of either side of the height of the world.

getY

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.

atWorldEdge Method

Let's examine the atWorldEdge() components:

  • public – Visible to all classes everywhere.
  • boolean – The data type of the value returned by the method (true or false).
  • atWorldEdge() - The method name.
  • The method body returns true or false, the boolean value to return according to the method signature.

Call the atWorldEdge() method

For the atWorldEdge() method to command the instance to turn at the edge of the world, the method must be called in the act() method.

To call the atWorldEdge() method, simply write the name of the method, then empty parenthesis, then a semicolon to end the statement.

Act Method

The Butterfly class documentation shows the new atWorldEdge() method after it is defined.

Documentation

 

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.


Instructions:

  1. Open the Code editor for the Ant class.
  2. 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.
  3. Call the atWorldEdge() method in the act() method.
  4. Copy the atWorldEdge() method and paste the method in the source code for the Fly class.
  5. Call the atWorldEdge() method in the act() method for the Fly class.
  6. 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.
  7. 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.

Bee Flower

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:

  1. Define a method to check if the bee is colliding with the flower.
  2. Declare a local variable inside of the method body to collect the intersecting flower object.
  3. 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.
  4. 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:

  1. Define a variable that holds an Actor value type to collect the colliding object.
  2. Write an if statement to test if the object is colliding with a specific class type.
  3. 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.

eatFlower Method

Declare a local variable inside of the 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.

Declared Variable

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.

getOneIntersectingObject Method

Create the if statement to check if the object is colliding with a specific class type

The if statement is as follows:

If Statement

The condition of the if statement will check whether the variable getFlower is empty or not empty (null or != null).

If getFlower Empty

The body of the if statement programs the scenario to remove the Flower.class object contained within the getFlower variable from the world.

Remove Object

Call the eatFlower() method

In order for the bee to use the eatFlower() method, we must call this method in the act() method.

eatFlower Method Called

 

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.


Instructions:

  1. Open the Code editor for the Frog class.
  2. Declare an eatFlies() method that will detect and remove intersecting fly objects.
  3. Call the eatFlies() method in the act() method.
  4. Compile the code. Run the scenario to test that it works.
  5. 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.
  6. 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.)


While Loop Components

 

Terminology

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.

While Loop Variable

 

Terminology

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).

  • Declare Loop Variable

Incrementing the loop variable

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.

Increment Loop Variable

Next, write code to increment the loop variable. There are two ways to increment a loop variable:

  1. Write a programming statement to add 1 to the loop variable at the end of each loop iteration.

    Increment Loop Variable

  2. 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.

    Increment Loop Variable

 The condition that is evaluated at the beginning of the while loop uses a comparison operator to control the number of loop executions.

 

Terminology

Comparison operators are used with loops as part of the condition to control the number of loop executions.


Comparison Operator

Comparison Operators

Comparison operator symbol Description
< Less than
< Less than or equal to
> Greater than
> Greater than or equal to
= = Equal to
!= Not equal to

Example: Incrementing a loop variable

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.

Declare Loop Variable

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.

While Loop Body

Example: Create instances using a while loop

When a player wins the Bee game, 10 flowers should be placed in the world. Create a while loop that automatically generates 10 flowers in the world.

While Loop Flower Example

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.

While Loop Add Flower Code Example

The loop variable was incremented using i++; to control the loop execution.

While Loop Add Flower Code Increment Loop

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.

While Loop Sound Example


 

Demo: Creating a while loop

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.


Instructions:

  1. Open the Code editor for the Frog class.
  2. Edit the frogSound() method so that the sound is played 3 times when the “s” key is pressed.
  3. Compile the code. Run the scenario to test that it works.
  4. 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:

  • The loop variable never changes.
  • The condition always remains true.
  • The loop continues looping forever.

  • Infinite Loop Example

 

Demo: Infinite loops

Watch this video to learn about infinite loops.

Ending the game

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:

  1. When the Bee collects 10 flowers.
  2. When the Bee collides with a butterfly 3 times.
  3. 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.

Player Wins

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.

Player Loses

When designing a game, you need to identify all of the game specifications. Examine the following game specifications:

  • Provide a count of the total flowers eaten.
  • Provide a count of the number of times the Bee collides with a mushroom.
  • Provide a count of the number of times the Bee collides with a flower.
  • Stop the game when 10 flowers are collected.
  • Stop the game when the Bee collides with a mushroom 3 times.
  • Stop the game when the Bee collides with a butterfly 3 times.

Define variables to hold the integer values for the game

At the top of the Bee class, you will define three variables that hold integer values.

  • The first variable holds the number of flowers eaten by the bee.
  • The second variable holds the number of times the bee collides with a butterfly.
  • The third variable holds the number of times the bee collides with a mushroom.
Define Variables

Define a method to manage the bee eating flowers

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.

flowersEaten 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.

MushroomCrash Method

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.

butterflyCrash Method

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:

IF Statement 1

The first if statement above manages what happens if the player wins the game.

  • The condition inside of the if statement checks if the value inside of the variable equals 10.
  • If the condition is true, the player wins.

This executes the programming statements inside of the if statement.

  • The Bee's image changes and is set to an image that says “You Win!”
  • 10 Flowers are randomly displayed on the screen.
  • The game stops.
IF Statement 2

The second if statement above manages what happens if the player loses the game due to 3 collisions with a mushroom.

  • The condition inside of the if statement checks if the value inside of the variable equals 3.
  • If the condition is true, the player loses.

This executes the programming statements inside of the if statement.

  • The Bee's image changes and is set to an image that says “Game Over!”
  • 10 Mushrooms are randomly displayed on the screen.
  • The game stops.
IF Statement 3

The third if statement above manages what happens if the player loses the game due to 3 collisions with a butterfly.

  • The condition inside of the if statement checks if the value inside of the variable equals 3.
  • If the condition is true, the player loses.

This executes the programming statements inside of the if statement.

  • The bee's image changes and is set to an image that says “Game Over!”
  • 10 butterflies are randomly displayed on the screen.
  • The game stops.

Examine the complete code:

End Game Complete

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.

Relational Operator

 

Demo: Ending the game

Watch this video to learn how to end the game.


Try it: End the game

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.


Instructions:

  1. Open the Code editor for the Frog class.
  2. Declare a variable named countFliesEaten to hold the number of Fly objects eaten by the Frog.
  3. Declare a variable named countAntCollisions to hold the number of times the Frog collides with an Ant.
  4. Declare a variable named countRockCollisions to hold the number of times the Frog collides with a Rock.
  5. 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.
  6. 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.
  7. 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.
  8. 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.
  9. 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.
  10. 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:

  1. Create an Actor subclass named Instructions.
  2. Import the java.awt.Color package to provide the instructions text with a background color and text color.
  3. Create a constructor in the subclass to display a dynamic text image in the world.
  4. 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.

Instructions Class Display

Importing the java.awt.color package

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.

Color Import Statement

Create a constructor to assign an image

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:

  1. Open the Code editor for the class.
  2. Create the constructor before the act() method, but after any variables.
  3. 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.

Instructions Constructor

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.

Instructions Constructor Example

 

Demo: Displaying dynamic text instructions

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.


Instructions:

  1. Right-click on the existing Instructions class and select set Image… From the scenario images menu on the left, select No Image. Click OK.
  2. In the Instructions class, import the java.awt.Color package at the top of the class below the Greenfoot import statement.
  3. 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.
  4. Compile the code. The scenario will automatically display the text.
  5. 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.
  6. 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:

  1. Open any Internet Browser and type the following URL in the address bar: http://www.greenfoot.org/book/material/book-scenarios.zip
  2. 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.
  3. When the download is complete, open the zip file. Extract the files to a folder on your computer, hard drive, or USB drive.
The Greenfoot forum

Join the forum to get help from other users: http://www.greenfoot.org/topics

Joy of Code videos

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.

Access the blog at: http://blogs.kent.ac.uk/mik/category/joy-of-code/

Credits

Put credits here

  • Lead Curriculum Developer: Dimpi Sarmah
  • Other Contributors:

To navigate this Oracle by Example tutorial, note the following:

Topic List:
Click a topic to navigate to that section.
Expand All Topics:
Click the button to show or hide the details for the sections. By default, all topics are collapsed.
Hide All Images:
Click the button to show or hide the screenshots. By default, all images are displayed.
Print:
Click the button to print the content. The content that is currently displayed or hidden is printed.

To navigate to a particular section in this tutorial, select the topic from the list.