Download Image Editor For Java Phones
Magic Photo Editor, free and safe download. Magic Photo Editor latest version: Make original edits of your photos. Magic Photo Editor is an easy-to-use photo editing software. Oracle Technology Network is the ultimate, complete, and authoritative source of technical information and learning about 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: Watch this video to learn more about Java technology: What is 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. 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. 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.
The class display is used to display the Actor object names, known as classes, in a hierarchical fashion. 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. 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.
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: 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: • Review the system requirements checklist below. • Check your system to ensure it meets the system requirements listed in the checklist. Category Requirement Processor Pentium 4 or higher Operating System One of the following: • Windows XP • Windows Vista (32, 64-bit) • Windows 7 (32, 64-bit) • Windows 8 (32, 64-bit) • Apple OS X Browsers Any modern browser that supports Java: • Internet Explorer 6 (or higher) • Firefox 3 (or higher) • Chrome • Safari • Opera 4.x (or higher) Memory 1 GB Free Disk Space • Required: 1.5 GB • Recommended: 8 GB Graphics • Capable of high (16-bit) color and 1024 X 768 resolution • 3D video card recommended Sound Card Required Software • • • File archive software to extract.zip files (ex. ) • JDK 7 (see JDK download instructions below) • Greenfoot (see Greenfoot download instructions below) *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 • Open any Internet Browser and type the following URL in the address bar: • From the Oracle Technology Network website, click Java Platform (JDK). • From the Java SE Development Kit 7 Downloads page, review the License Agreement. • Accept or Decline the License Agreement (if you decline, the software will not download). • Locate and select the Java SE Development Kit for your computer operating system. • When prompted, save the file to a location you easily remember.
Steps to launch the JDK executable file • Locate the executable file and double click it to execute. • When prompted to run the executable file, click Run Steps to run the JDK Installation Wizard • From the Installation Wizard dialog box, click Next. • To accept the default settings, Click Next. • When prompted for installation location, click Next. If prompted, close the Internet browser window.
• Click Continue to acknowledge the successful installation. • You will be prompted to set-up the Software Developer Kit (SDK). • When prompted for the installation location, click Next. • 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: 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 • Open any Internet Browser and type the following URL in the address bar: • Select The Software link.
• Locate and select the correct version for your computer. • When prompted, click Save to save the Greenfoot Installer file. Steps to launch the Greenfoot Installer Wizard • When the download is complete, either select Run or Open Folder, then double-click the executable file. • A Greenfoot Setup window will appear. Steps to install Greenfoot • From the Installer Wizard, select the Next option. • You may be asked who to install this for.
Select the required installation setting, then select the Next option. • Review the file Associations settings and select the Next option. • To accept the default setting for the installation Destination Folder, select the Next>option. • To begin the installation, click Install. A progress window will display while Greenfoot is installed on your computer. • To complete the installation, click Finish.
Steps to launch Greenfoot • After Greenfoot is installed, the Greenfoot icon will appear on your desktop. • Double-click the icon to launch Greenfoot. Greenfoot download and installation support links Join the forum to get help from other users: 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: 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. 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 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 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. The World The world is where the action for your scenario will take place and where the user will interact with your scenario. 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.
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.
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.
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: • Double-click the Greenfoot icon to launch Greenfoot.
• Locate the folder on your computer where you store your Greenfoot scenarios. Select the scenario, then click Open.
• The scenario will open in a new window. Demo: Opening and examining an existing scenario Watch this video to learn how to open an existing scenario in Greenfoot. Try it: Open and examine an existing scenario Download: The activity below requires that you start with the Jungle_L1S3 scenario.
Download this file and extract its contents to a folder on your computer before you complete this activity. Instructions: • Create a folder on your computer, hard drive, or USB drive named “Greenfoot Course Scenarios” where you will save all of the scenarios that you create in this course. • Download the L1S3_Jungle.zip file. • Open the zip file. Copy the L1S3_Jungle folder contained inside of the zip file to the Greenfoot Course Scenarios folder on your computer. • Locate the Greenfoot program on your computer. Double-click the Greenfoot icon to launch Greenfoot.
• From the Scenario menu, select Open. • Locate the L1S3_Jungle scenario that you downloaded to your computer. Select the file, then select Open. • Locate and examine the execution controls, class display, and world. Count how many classes are in this scenario.
Add an instance to a scenario. After opening an existing scenario, the next step is to add the instances that will move and act into the scenario.
Scene editor The Scene editor is where you will add and position the instances that will move and act in the scenario. A class defines the actions and the attributes of an object. Every object placed in a scenario is an instance of the class from which it was created.
In the Scene editor, you can: • Create classes of non-moving scenery instances and moving instances that you will use in your scenario. • Add new instances of a class to the scenario. • Position and rearrange instances in the scene using your mouse. Below, the scene contains non-moving scenery instances (trees, rocks, bananas) and moving instances (elephant, hippo, lemur). 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 • Right click on the name of the class. • Select the new [class name()] option.
• You should be able to see the instance on your cursor. Drag the instance into the world with your cursor and drop it onto the world. 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: • Open Greenfoot. • Open the Jungle scenario you saved in the previous topic.
If you did not complete the Try It activity from the previous topic, download the scenario file by clicking the download link above (make sure to copy the contents of the zip file to the Greenfoot Course Scenarios folder on your computer). • Once the scenario is opened in Greenfoot, add one hippo, one elephant, and one lemur to the world. Then, add several bananas, rocks, and trees to the world. • Save the scenario. Write a programming instruction and run the scenario. The Code editor is where you will program the instructions for how the instances of a class should act in your scenario. Opening the Code editor for a class displays all of the programming instructions for the class.
Programming instructions are organized into methods in the class display. A method defined in a class comprises one or more programming statements. By default, each class has a method called act(). This method contains all of the actions that will execute when the execution controls are selected in the scenario.
These actions can be simple programming statements, such as move forward, or they could also be others that you create, such as a method to control an object using keyboard keys. For example, below is the Code editor for a Bee class. Right now, the programmer has not written any code for the bee in the act() method. If we clicked the Run button in the scenario, the bee would stand still. For example, if we programmed a Bee to fly around the world, the bee instance would need to receive those instructions on how to fly through the act() method.
Below, we have programmed the bee to continuously move forward 5 steps and turn 5 degrees when the scenario is run. This commands the bee to turn in circles. The act() method 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. 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.
Before you can run the scenario to see what happens, you have to click the Compile button that displays below the class display. Terminology The process of compilation translates the code you write into machine code that the computer can understand. Compilation Compilation is required whenever the code of a class is modified or when a new class is created. You can identify when compilation is required by the striped appearance of one or more classes. After successful compilation, the striped appearance of a class will be removed. When the compile button generates an error message, you need to go back to your code to determine what has been typed incorrectly.
Correct any mistakes, then click the compile button again to obtain a successful compilation. After you have added and positioned instances in your world, the next step is to run the scenario to test how the programming instruction causes the objects in the scenario to move. In the Execution Controls area, click the Run button to run the scenario. It will run all actions in the scenario repeatedly until Pause is clicked. Demo: Coding a programming instruction and running the scenario Watch this video to learn how to code a programming instruction in the act() method and then run the scenario to see the results of the programming instruction.
Try it: Code a programming instruction and run the scenario Download: The activity below requires that you start with the project file that was saved in the previous topic. Download this Greenfoot project file if you did not complete the previous topic's Try it activity. It is good practice to save a scenario frequently as you work. Each time you close Greenfoot, it saves your current work, but while working in Greenfoot it is advised to save multiple versions of scenarios.
As your scenarios become more complex, you may wish to have multiple versions of your scenario so that you can revert back to a version. You may also want to save two versions to test out different actions without impacting your original scenario.
Steps to save a version of a scenario: • From the opened scenario, select Save As from the Scenario menu. • Save a copy to a folder on your computer or USB drive. Demo: Saving versions of a scenario Watch this video to learn how to save a version of a scenario. Try it: Save versions of a scenario Download: The activity below requires that you start with the project file that was saved in the previous topic.
Download this Greenfoot project file if you did not complete the previous topic's Try it activity. 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 The Scene editor Create a new scenario To create a new scenario follow these steps: • Select New from the Scenario menu. • Navigate to the folder where you wish to save the scenario. • Enter the name of the Scenario in the Folder name text box. • Click Create. The new scenario will open in Greenfoot. The only classes that appear in the Class Display are World and Actor. 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. 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. 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: • From the Scenario menu in Greenfoot, select New. • Navigate to the Greenfoot Course Scenarios folder on your computer. • Name the scenario FrogFly_L2S2.
• Click the Create button. The scenario will open in a new window. Create a new world subclass and compile the scenario. What is a class? A class contains the specifications that define the appearance and movement of an object.
The class provides instructions to Greenfoot for how to create and display instances when they are added to the world. Inherited characteristics In nature, a bee inherits some characteristics that are common to all bees: two wings, a black and yellow color, and a stinger. The bee may also inherit the characteristics of its breed that gives it a specific color, shape and size. In Greenfoot, a class, such as the Bee class, defines the characteristics of all bee objects that act in the scenario, such as how they look and ways they can act. Classes in Greenfoot When you add a class to your scenario, it appears in the class display (to the right of the world).
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. Two types of superclasses appear in the Greenfoot class display: World and Actor. These two superclasses are always visible in the class display. • 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. 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: • Right-click on the World superclass. • Select New subclass. • In the New Class dialog box, name the subclass a descriptive name.
• Select an image that the class will display. This is the background for the world. Select the backgrounds category, then select an image. • The world subclass will appear in the class hierarchy. 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. 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. You can create a new actor subclass and assign your own image to the object.
Actor subclasses hold the objects that we place in the world. In this example illustrated below there is a Bee subclass and a Butterfly subclass. These subclasses inherit, or possess, all of the behaviors from the Actor superclass. Right-clicking on a an instance object that is placed in the world enables you to see the methods inherited from the Actor superclass. In addition to the many images that Greenfoot provides in its Gallery, you can import your own images into the gallery to use with your classes. When a new class is created you can select the option to import a file which lets you adds the image to the gallery.
For example, you may create an image with instructions for how to play your game. You can save this image to your computer, then import the image into Greenfoot for use in a subclass named Instructions. Adding an instance of Instructions to the world will display the instructions for your game.
Steps to create a new subclass with an image imported from your computer: • Right-click on the Actor superclass. • Select New subclass. • In the New class window, click the Import From File.
• Select the image file to import from your computer. • Name the new subclass, then click OK. • The subclass with the new image appears in the class hierarchy. Click the Compile button to compile the scenario.
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: • Right click on the class.
• Click the new [class name] option. • Drag the instance into the scenario with your cursor. 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: • In your computer's paint program, create an image with instructions for your game that says “Control the Frog with the arrow keys on your keyboard. You must eat 10 flies to win the game.
Avoid the ants and rocks.” • Create an Actor subclass and import the image file into the subclass. • Name the new subclass “Instructions”. • Create Frog, Fly, Ant, and Rock classes. Note that these classes have images in the Greenfoot gallery that you can use. • Compile the scenario. • Save the scenario.
Steps to add an instance of a class to the world. • Right click on the name of the class. • Select the new [class name()] option. • You should be able to see the instance on your cursor. Drag the instance into the world with your cursor and drop it onto the world. Position instances Instances added to a world can be positioned when they are created or positioned later as you continue to define the scenario. There are two ways to position instances: • Imprecise positioning: Drag and drop instances with your cursor.
• Precise positioning: Use methods to instantly re-position the instances. Drag and drop instances with your cursor To drag and drop an instance with your cursor, click the instance with your cursor, and drag it to the position you want in the world. To use methods to re-position instances: • 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. • Select one of the methods (such as move(), turn(), setLocation(), setRotation(), or turnTowards()) to reposition the instance.
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.
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: • Add 2 rocks, 2 ants, 1 frog, 10 flies, and 1 instructions instance to the scenario. • Position the flies using your cursor.
Also, position the flies using the setRotation() method so they are all facing different directions. • Position the frog at x = 50 y = 50.
• Position the instructions at the bottom of the world. • Position the ants and rocks anywhere you wish in the world.
• Save the world so that when you re-open the scenario, the instances are automatically positioned in the world. • Save the scenario.
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. View the source code of a class Steps to view the source code of a class: • Right click on a class in the class menu. • Select Open editor.
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. You can tell that you are in the Scene editor when you see the execution controls, world, and class display. 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. 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 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. 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. Method signature The method signature describes what the method does. The signature contains a return type, method name and parameter list.
The method name describes what the method does. The return type indicates whether the method will return something after execution. The parameter list allows values to be passed to a method. The parameters are typically used during the execution of the method.
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: • 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: • Right-click on a class. • Select Open editor. • Select Documentation from the drop-down menu at the top right of the Code editor.
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. 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.
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.
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. 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. 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. Sequential execution.
Every key stroke in source code counts. One missing or incorrect character could cause your program to fail. In Greenfoot, the compiler highlights errors and informs you how to correct them.
Identifying and correcting errors in source code helps you to develop good programming techniques. Errors in the syntax of a computer program are referred to as bugs.
To debug a program you must identify and correct the errors and then compile the source code again. Steps to debug your program: • Click Compile to compile the code. • If there are no errors, the message “Class compiled – no syntax errors” displays. • If there are errors, the incorrect syntax is highlighted and a message attempts to explain the error.
• Click the question mark icon to display additional information about the error. 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. 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.
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: Demo: Methods Watch this video to learn more about Greenfoot methods. Try it: Examine methods Instructions: • Go to the Greenfoot API and view the methods available for use by the different classes in Greenfoot. The Greenfoot API is located at: • Locate three methods in the Actor class that tell you more about an object's orientation. • Go to the World class in the Greenfoot API.
Which method tells you the number of objects in a scenario? • Go to the GreenfootImage class in the Greenfoot API. Which method tells you the height of an image? Method declaration.
Programmers write methods to tell an object how and when to perform tasks, such as commanding an object to perform an action or asking an object a question to learn more about what it does. When a method is declared, specific information is included in the method declaration. A Method returns program execution to the code that invoked it when all statements within the method complete or when it reaches a return statement. Examine the components of the method declaration: • Access Modifier: For now you will focus on public, but note that there are also access modifiers called private, protected, and default. • Return type: The type of information that goes back to the method call.
• If the return type is void, the method does not return information • If the method returns a value the return type must be specified. • Method name: A unique name that should describe what the method does.
• Parameter list: Specifies within parenthesis the type of variables that can be sent to the method. • Method body: The code that will be executed when the method is called.
The Greenfoot Class Documentation highlights many methods that can be used in Greenfoot. Taking time to view methods listed in the documentation will help you program more quickly by using methods that already exist instead of taking time to write your own. Let's look at some examples to examine the method declarations. Examples of method declarations Method Description void move(4) A move method that does not return anything and that has a parameter list for how far to move.
Void turn(25) A turn method that does not return anything and that has a parameter list for how many degrees to turn. Public int getArea() A getArea method that is public and returns an integer (whole number) value. 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. 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.
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.
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. Identify inherited methods There are a number of ways to identify inherited methods: • The Object Menu displays all of the inherited methods of an instance. • The Code editor displays all of the inherited methods of a Class. • 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: • Open or create a new scenario that has an Actor subclass.
• Add one instance of the Actor subclass to the World. • Right-click on the instance to display the menu. • Click inherited from Actor to display a list of the methods that the subclass inherits from the Actor superclass. Steps to identify inherited methods in the Code editor: • Right click on a subclass. • Click Open editor. • In the Code editor, select Documentation (instead of Source Code) from the drop-down menu.
• Scroll down to the Method Summary and review the class's 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. 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.
If you always know how a game is going to behave, you would master the game and become bored with it quickly. Game designers use a randomization technique to make their games interesting. Randomization allows the computer to randomly pick a value, from a range of values, and present them in no pre-defined order. The combination of randomly generated and predetermined content, if planned correctly, can make interesting game play possible.
In Greenfoot, the getRandomNumber() method can generate random numbers, within a specified range, that can be used to create randomly generated behavior. The getRandomNumber() method The getRandomNumber method is a static method that returns a random number between zero and a parameter limit. This method is used to eliminate predictability in your program and can be used to create randomly generated content for our scenario.
A static method is a method that does not have a relationship to the class where it is defined. Think of a static method as a “utility” method that can be used by any class when a random number is needed. To use a static method you need to call the method using specific syntax. You need to: • precede the method name with the class name where it is defined. • place a “dot” between the name of the class and the name of the method. The getRandomNumber() method is a method within the Greenfoot class of the API. To use the getRandomNumber() method, we must provide the Greenfoot class call, the getRandomNumber() method call and the upper limit of the range we wish to generate the random number within.
The code below means we will generate a random number between 0 (inclusive) and 6 (exclusive) meaning we will generate a random number in the range from 0,1,2,3,4,5. You can invoke both the move() and turn() methods with a fixed distance to move, and degrees to turn, or you can use the getRandomNumber() method to feed random numbers to both the move() and turn() methods. 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: • Open the Code editor for the Fly class.
• Instead of the Fly always turning a specific number of degrees, the Fly should turn a random number between 0 and a parameter limit of 20. Code this behavior in the act() method, replacing the turn method that is already there. • Open the Code editor for the Fly class again. Change the parameter limit in the method from 20 to 15. Compile the code.
• Run the scenario and observe how this changes the flies' movements. • Save the scenario. Recognize and describe dot notation. When you want to use a method but it is not inherited by the class you are programming, specify the class or object that has the method before the method name. Separate the class name and the method name with a dot. This naming convention used to call methods from a class is called dot notation. Examine the getRandomNumber() method below: 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. 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: • From the Help menu, select Greenfoot Class Documentation. • The documentation will open in your default browser.
The Greenfoot Class Documentation contains all of the methods in all classes that are available to a programmer within Greenfoot. Demo: Recognizing and describing dot notation Watch this video to learn how to recognize and describe dot notation. The IF decision statement. Performing sequential tasks in programming and in Greenfoot is straightforward - we create each statement one after the other. But what if the task we wish to execute is not sequential in nature? Many things around us have a cause and effect relationship, or “if-then” relationship. • If your cell phone rings, you answer it.
If it doesn't ring, you do not answer it. • If a flower starts to wilt, you give it water. If the flower looks healthy, you do not give it water. IF decision statements An if statement is written to tell your program to execute a set of programming statements only if and when a certain condition is true.
Java syntax for writing an 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. 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. 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. 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: • Write an if statement in the act() method that will move the Frog forward one step when the “up” arrow is pressed. • Write an if statement in the act() method that will move the frog forward and turn it to the right 5 degrees if the “right” arrow key is pressed.
• Write an if statement in the act() method that will move the frog forward and turn it to the left 5 degrees if the “left” arrow key is pressed. • Compile and run the scenario. Test that the frog moves as expected when you press the up, left, or right arrow keys. • Save the scenario. Conditional behavior. 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. 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. 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. 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. Once you position the Actor instances in the world, use the Save the World feature to save the Actor instances and their coordinate positions. Then, each time you open and compile the scenario, those Actor instances will automatically appear in the scenario at the coordinates you specified. This makes it easy to prepare your scenario for gameplay so that the player does not have to manually add the objects to the game in order to play the game.
Steps to use the Save the World feature: • Add the Actor instances to the world and position them with your mouse. • Right click on the world. • Select the Save the World menu option.
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. 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. 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: 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. 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. 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. 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. When adding instances to a world manually you can simply drag and drop the instance to the exact location desired. When programmatically adding instances to a world using a constructor, you will need to know the x and y coordinates of the desired object location. The x and y coordinate values of an instance are stored in instance variables. Variables A variable, or field, allows the instance to store information to use immediately or later. For example, object properties are variables that store information about the instance, such as its position in the world or the direction it is facing.
Object properties Object properties describe the instance's appearance and abilities, such as: • Size • Color • Range of movements Object properties can be viewed and modified in the source code of the class. You can view the properties of an object in the class documentation. For example, an Actor object would have properties such as: • Image - the image used to represent this actor • Rotation - the current rotation of this actor • X - the current x co-ordinate of this actor • Y - the current x co-ordinate of this actor Instance variables Instance variables can be viewed using the Object Inspector. You can view the instance variables for any instance of any class in the World. Steps to view instance variables using the object inspector: • Right click on an instance in the world. • Click Inspect to view. • The instance's object inspector will display the instance variables.
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 Invoke a method directly to display an object's orientation To find out information about an object, you can invoke a method from the scenario environment by right-clicking on the Actor subclass and choosing inherited methods. This will give you immediate information about the instance when the scenario is not running and will not impact the movement you are programming into your game. You can invoke an inherited method: • With a specific return data type, such as integer, to ask the object a question about its orientation.
• In the environment to learn how the object is oriented in the scenario. Steps to invoke a method directly: • Make sure that you have an Actor subclass in the world, and that the scenario is not running.
• Right click on an Actor subclass instance in the World. • Select Inherited from Actor to view its methods. • Invoke (select) a method with a specific data type to ask the object a question about its orientation. • The method result will display. Note the value returned, then click Close.
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.
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) 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. 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. To insert an isKeyDown() method into the act() method of a class: • Write an if decision statement, entering the isKeyDown() method from the Greenfoot class inside of the condition. Remember, you must use dot notation to call the isKeyDown() method from the Greenfoot class.
• Enter the String of the keyboard key as the parameter of the isKeyDown() method. For example, “up”, “down”, “left”, or “right”. • 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. 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. In addition to using the move() and turn() methods and keyboard keys to move an instance in the world, you can use the setLocation() method and mouse interaction to achieve the same results. The setLocation() method The setLocation() method moves an Actor to a precise location on the World. Using this method requires awareness of the Greenfoot World Coordinate System. The World starts at (0,0) at the top left and is built to the parameters for worldWidth, worldHeight and cellSize specified in the constructor.
The method signature for the setLocation() method contains: public void setLocation(int x, int y) The setLocation() method expects a number argument in the parameter list for the x-position and y-position where the item is to be located. Example: setLocation() method and keyboard controls A combination of turn() and move() methods is often used to change the location of an instance when a key is pressed on the keyboard. In the following example, the setLocation() method is used to move the object in place of the turn method. This will move the object to a precise location in the world when a key is pressed. A calculation based on the object's current position on the grid will determine where the object will move. Recall that the grid uses X and Y coordinate values to determine a location on the grid. Evaluate this syntax: To move the object up, determine the X and Y coordinates of the object's location, then move -5 pixels from the current Y coordinate value.
Demo: Programming precise keyboard interaction using the setLocation() method Watch this video to learn how to program precise keyboard interaction using the setLocation() method. Try it: Program precise keyboard interaction using the setLocation() method Download: The Try it activity below requires that you start with the project file that was saved in the previous topic. Download and open this Greenfoot scenario file if you did not complete the previous topic's Try it activity. Instructions: • Open the Code editor for the Frog. Remove the turn method from the “left”, “right”, and “up” if statements and replace them with programming statements that will create precise movements in those directions. • Add an if statement for a “down” motion.
Program the frog to move 2, then precisely move down. • Compile and run the scenario. Use the keyboard keys to control the movements of the frog. • Save the scenario. Methods and classes for mouse interaction As an alternative to keyboard interaction, the Greenfoot API provides us with methods we can use to program mouse interaction in our scenario. Carcassonne Die Katharer Pdf Creator. 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.
Greenfoot also provides a MouseInfo class which has many methods available to set the state of the mouse in the scenario. There are also many methods available in the Greenfoot class which we can use to program mouse interactions in our scenarios.
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(); 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. 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. 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. 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. 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: • Save a copy of your scenario prior to working on this scenario, as the programming statements for keyboard interaction will be replaced by mouse interaction.
• Open the Code editor for the Frog. Remove the programming statements for keyboard interaction from the act() method.
• Write programming statements to have the Frog's movements controlled using drag and drop interaction. • Compile and run the scenario. Click and drag the frog around the world with your mouse. • Save the scenario. Importing sounds. The use of sounds in any scenario can enhance gameplay.
Sounds can be used for background sound or to give feedback to a player when an event like winning, losing, or achieving minor victories occurs throughout a game. Sounds used in a scenario must be stored in the sounds directory of the scenario. Acceptable formats for sound files include: WAV, AIFF, and AU. The playSound() method The playSound() method is used to play sounds in a scenario.
The playSound() method: • is located in the Greenfoot class. • expects the name of a sound file (as String) as an argument. • does not return data. The method signature for the playSound() method is as follows: 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. 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. Record sounds in Greenfoot Greenfoot offers the ability to record your own sounds within the IDE. Steps to record original sounds in Greenfoot: • In the Controls menu in the Scene editor, select Show Sound Recorder.
• Press Record, and then talk into your computer's microphone to record sound. • Press Stop Recording when finished. • Press Play to play back the sound. • Re-record if necessary.
• Enter a file name, and then click Save to save the file to your scenario. • The file is now stored in the sounds directory of your scenario and is ready to reference in your code. 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.
When a subclass is created in Greenfoot, we specify the image that represents the instance when it is added to the scenario. Greenfoot offers many images to choose from when creating a subclass.
During program execution the image for the instance will remain the same unless changed programmatically. • When the new() method is used to manually add an instance to the world, Greenfoot references the image specified when the subclass was created, and puts that image onto the world. • When a constructor creates the instances in the world, Greenfoot references the image specified when the subclass was created, and puts one or more of those images onto the world.
Using either method, adding instances to the world using the new() method, or adding instances to the world using a constructor causes Greenfot to reference the image specified for the class. When creating a subclass, you can specify an image from the available Greenfoot image listing or you can import an image from your computer, hard drive, or USB drive into the Greenfoot image gallery. Image files imported can be jpeg, gif, or png format types. To make instances appear animated in a game, they need to change from one image to another during program execution. Changing from one image to another can show movement or event change during program execution. Let's examine a few examples. • To change the color of an instance: A flower subclass may use different types and colors of flowers that change if the Bee lands on the flower.
• To make the instance appear to walk, fly, or swim: A bee subclass may use multiple images, each with wings that are slightly rotated, so that when the images are quickly flipped it appears that the bee is flying. • To flip cards: In a vocabulary game, the Card subclass may hold multiple card images. One image may hold a vocabulary word, and another may hold a vocabulary term. When the player clicks the card with their mouse, it flips the card (changes the image), displaying the vocabulary term. • To face different directions when the left, right, up, and down keys are pressed on the keyboard.
When the butterfly instance flies around the scene, if the right arrow key is pressed, it turns and faces the right edge of the world. If the left arrow key is pressed, it turns and faces the left edge of the world. Image changes can be used to improve the look and feel of your scenarios and to enhance game play.
Changing the image of an instance summarized To change the image of an instance for a scenario you need to: • Create two images of the instance, each facing a different direction. • Store the two images in the Greenfoot scenario's images folder.
• Code the subclass to alternate between the two images that are displayed when the appropriate keyboard key is pressed. To change the image of an instance programmatically, use the setImage() methods. There are two setimage() method parameters that can be used to set an image for an instance programmatically. • The setimage() method accepts an image argument for the parameter that is of the type GreenfootImage. • The setimage() method accepts a String argument for the parameter. The String argument is the name of an image file and must be written within double quotes.
Either setimage() method can be used to change an image for an instance, however; it should be noted that an image with a Greenfootimage image type is more efficient when multiple instances are created in a world. Viewing the images stored in the scenario Using either setImage() method parameter, you must have an image to specify. You can view the images you have currently stored for use by the instances in your scenario two ways: • Go to the folder where you stored the scenario. This contains an images folder where you can view and store images for use in your scenario. • From the Scene editor, right-click on the Actor class, then click the new Subclass menu option.
In the gallery, the Scenario Images list on the left displays all of the Greenfoot images that are stored in your scenario. 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. 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. 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”); 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: • Right-click on the Frog class and select set Image. • From the Scenario images list, select the frog image. Then from the editing tools below the Scenario images list, select Edit.
• In your computer's paint or drawing program, rotate and/or flip the image so there is a total of four images, one for each direction the frog will face (left, right, up and down). • Save the four images to the images folder in your Greenfoot scenario. Ensure that you provide each image with a descriptive name for the direction it is facing. • Open the Code editor for the Frog class. Using the setLocation() method, code the Frog class to move left, right, up, or down if the arrow keys on the keyboard are pressed. • Add a programming statement to the body of each if statement to set the image that displays when that keyboard key is pressed.
For example, for the programming statement that turns the frog to the right, it should display the image of the frog facing the right. • Compile the code. Run the scenario and test how the code works by pressing the arrow keys on your keyboard. Ensure that the frog's image changes based on the direction it is facing. • Save the scenario. Set an image using a GreenfootImage object. The same results can be obtained by using a GreenfootImage object to set an image.
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 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.
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. In this example, a variable named key is declared to hold a String value: the name of a keyboard key.
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. 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 Example: Declaring variables The bee has four image files, one for each direction it will face. 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. 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.
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: 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: 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. 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. 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. 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: • Open the Code editor for the Frog class.
• Create a Frog constructor. • In the body of the Frog constructor, assign each image variable to its respective image. • Write the code to set the first image that the frog displays as image2. • In the act() method, replace the code within the setImage parameters to the name of the variable that holds the image you want to display when the respective keyboard key is pressed. • Compile the code.
Run the scenario and test that it works. Ensure that the Frog starts facing to the right, and changes its image appropriately when the left, right, up and down arrow keys are pressed. • Save the scenario. 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. Steps to define a new method: • Define a new method for an action below the act() method. You should define new methods below the act() method so that the act() method is easy to find. • Call the new method in the act() method. This is the only way that the instance knows to use the method when the scenario is running.
• If your Actor subclass is a superclass for other classes, you should define the method in the superclass so subclasses can inherit the method. Terminology Programmer-defined methods are new methods written by a programmer that a class did not already possess. In Greenfoot, these methods are written in the class's source code below the act() method. Programmer-defined methods: • Can be executed immediately, or stored and called later. • Do not change the behavior of the class until called from the act() method. • Separate code into shorter methods, making it easier to read. Steps to define a method: • Select a descriptive name for the method.
• Open the Code editor for the class that will use the method. • Add the code for the method definition below the act() method. • Call the new method from the act() method to use it immediately, or store it for use later. Example: Defined method for random movements Instead of having all of the random movements for the butterfly instance in the Butterfly's act() method, the code could be better organized by having all of these programming instructions placed in a programmer-defined method. The example below shows that a method was created called butterflyMoves() and all of the random movements for the butterfly are written in the method.
In order to command the butterfly instance to use these movements, you need to call the method in the act() method. Now the act() method only has this one statement instead of many statements that became difficult to read. Creating methods and calling them in the act() mthod is referred to as procedural abstraction. Creating separate methods not only supports clean and simple programming, it supports method reuse. Drivers D Link Dwl G122 E1g44htblk.
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: • Open the Code editor for the Frog class. • Define a method called frogSound() that plays a sound if the “s” key is pressed on the keyboard.
Note: You will need to either save a sound file in the sounds folder of your scenario, or record a sound using the Greenfoot Sound Recorder. • Call the frogSound() method in the act() method. • Compile the scenario. Run the scenario and test how it works. Press the “s” key and test that the sound is played. • Save the scenario.
Define a method to turn objects at the edge of the world. Consider the scenario where a butterfly flies randomly around the world, but is unable to move correctly when it reaches the edge of the world. To change this behavior and have the butterfly turn when it reaches the edge of the world, define a method in the butterfly class to check if the butterfly is at the edge of the world, then turn the butterfly around if it is. Then, in the act() method, call the new method so that the instances of the Butterfly class may use it. The steps required to define and call this method include: • Test the object's position in the world. • Define a method for the action in the class. • 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. In the example below, the syntax is checking if the object is within 20 pixels of either side of the height of the world. 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.
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. The Butterfly class documentation shows the new atWorldEdge() method after it is defined. 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: • Open the Code editor for the Ant class.
• Define a method called atWorldEdge() that commands the ant instances to turn 180 degrees if they reach the edge of the world. Ensure that you write comments for this method that describes what it does. • Call the atWorldEdge() method in the act() method. • Copy the atWorldEdge() method and paste the method in the source code for the Fly class.
• Call the atWorldEdge() method in the act() method for the Fly class. • Compile the scenario. Run the scenario and test how it works. Ensure that the ants and flies both turn 180 degrees when they reach the edge of the world. • Save the scenario.
Define a collision detection method. Popular games are based around the interaction of objects and the actions the objects take when a specific interaction is detected. You could write code in your game so that a predator object is able to eat prey objects, or when objects intersect they bounce off or stick to each other.
Consider a scenario where you want to move your bee using the keyboard to each flower to eat the flower. If the bee passes over the flower it will remove the flower that is there.
Let's examine how to define a method to check if the bee is colliding with a flower. If the bee collides with the flower, the flower is removed from the world. The steps required to define this method include: • Define a method to check if the bee is colliding with the flower. • Declare a local variable inside of the method body to collect the intersecting flower object.
• Write an if statement inside of the method body that checks if the bee is colliding with a flower. If the condition is true, the flower is removed from the world. • Call the defined method in the bee class to command the bee to use the method. Test if an object is at the same coordinates (colliding) with another object To test if an object is colliding (or near colliding) with another object, write the following in the defined method: • Define a variable that holds an Actor value type to collect the colliding object. • Write an if statement to test if the object is colliding with a specific class type. • Use the getWorld() method to access the world method removeObject(), removing the intersecting object from the world.
Define the method First, define the method eatFlower() below the act() method. 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. 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. Create the if statement to check if the object is colliding with a specific class type The if statement is as follows: The condition of the if statement will check whether the variable getFlower is empty or not empty (null or!= null).
The body of the if statement programs the scenario to remove the Flower.class object contained within the getFlower variable from the world. Call the eatFlower() method In order for the bee to use the eatFlower() method, we must call this method in the act() method. 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.
Most games end because a specific condition has been met or because the player specifies that they want to stop the game. The Greenfoot class has a stop() method that you can use to end your game at a point that you designate. You may want to end the game when: • The player achieves a milestone. • Time runs out on the clock. • The instance touches a certain coordinate or object.
Let's examine a scenario where the object of the game is for the Bee to eat 10 flowers while avoiding the butterflies and mushrooms. All of the code that you will write to end the game will be written in the Bee class. There are three possible endpoints to the game: • When the Bee collects 10 flowers. • When the Bee collides with a butterfly 3 times. • When the Bee collides with a mushroom 3 times. The game will end when any of these endpoints occur. If the player wins, the Bee image will change to an image that says “You win!” and using a while loop, 10 flowers will randomly display on the screen using a while loop.
If the player loses, the Bee image will change to an image that says “Game over!” Using a while loop, 10 butterflies or 10 mushrooms will randomly display on the screen, depending on whether the butterflies or mushrooms caused the player to lose. 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 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.
Define a method to manage collisions with the mushroom Define a method to make the bee move to a specific location (100, 100) if it collides with an instance of the Mushroom class. Within this method, a counter is needed to increment the variable that manages the number of times the bee collides with a mushroom. Define a method to manage collisions with the butterfly Define a method to make the Bee move to a specific location (100, 100) if it collides with an instance of the Butterfly class.
Within this method, a counter is needed to increment the variable that manages the number of times the bee collides with a butterfly. Define a method to keep score and manage the end of the game Define a method to manage under what conditions the game is over. This defined method will need to contain a separate if statement for each of the three ways in which the game could end. Let's examine those three if statements: 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. 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. 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: 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.
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: • Open the Code editor for the Frog class. • Declare a variable named countFliesEaten to hold the number of Fly objects eaten by the Frog. • Declare a variable named countAntCollisions to hold the number of times the Frog collides with an Ant.
• Declare a variable named countRockCollisions to hold the number of times the Frog collides with a Rock. • In the eatFlies() method (the method that will remove a Fly from the world if it collides with the Frog), include a counter to increment the countFliesEaten variable. • Define an antCollisions() method that will make the Frog move to a static position in the world if it collides with the Ant. The method should include a counter to increment the countFliesEaten variable. • Define a rockCollisions() method that will make the frog move to a static position in the world if it collides with a rock.
The method should include a counter to increment the countRockCollisions variable. • Define a scoreKeeper() method to control the end of the game.
• If the Frog eats 10 Flies, the player wins the game. The image of the Frog should change to an image that you create that says “You Win!” • If the Frog collides with the Ant 5 times, the player loses the game. The image of the Frog should change to an image that you create that says “Game Over”, and 10 Ants should display at random locations in the world. • If the Frog collides with the Rock 5 times, the player loses the game. The image of the Frog should change to an image that you create that says “Game Over”, and 10 Rocks should display at random locations in the world.
• Note: You will need to create the You Win and Game Over images in your computer's paint or drawing program, then save the images in the images folder of your scenario. • Compile the scenario. Run the scenario to test that it works. Both win and lose the game so that you can test the different functionality that needs to occur. • Save the scenario. Displaying dynamic text instructions Another way to provide information to the players of a game is to display dynamic text in the game. Dynamic text means that we can write code to change what text is displayed throughout the course of the game.
You may wish to: • Provide instructions for our game, such as what they need to do to win the game. • Provide messages to the players, such as “You Win!” or “Game Over”. You can create an Actor subclass named Instructions to display the dynamic text. Display dynamic instructions Instructions can be used in any scenario to provide the user with instructions on how to play the game and to give on-screen information. Steps to create dynamic instructions: • Create an Actor subclass named Instructions. • Import the java.awt.Color package to provide the instructions text with a background color and text color. • Create a constructor in the subclass to display a dynamic text image in the world.
• Compile the code. Create the Instructions class To display any type of instance in the world, it must be an instance of an Actor subclass. To display instructions, first create an Actor subclass named “Instructions”. Do not assign an image to the subclass.
The image that the instance displays will be coded in the constructor of the Instructions class. 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. 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: • Open the Code editor for the class. • Create the constructor before the act() method, but after any variables.
• Add the code required for the constructor to create the image as a GreenfootImage class. The GreenfootImage class has a number of constructors that can be used to retrieve a new image when creating an instance of a class. The following constructor is used to set a dynamic image from a String. The constructor above creates the new image by providing the following information: • Display String: The text to display in the image. A String is a piece of text (character, word, sentence, or more) enclosed in double quotes. For example: “This is a String”, “a”, “3”.
• Font size: The size of font to display. • Background color: The background color of the image. • Font color: The font color of the String characters in the image. The background and text colors are selected from the Java package jawa.awt.Color which was imported into the class. An instance of the Instructions class is automatically added to the world each time the world is initialized.
Example: Create a constructor to assign an image To create a message that displays “Collect the flowers and avoid the butterflies and mushrooms” with a font size of 18, a font color of green and a background color of yellow, we would use the following setImage() statement. The code can be modified to change the instructions, font size, or color.
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: • Right-click on the existing Instructions class and select set Image From the scenario images menu on the left, select No Image.
• In the Instructions class, import the java.awt.Color package at the top of the class below the Greenfoot import statement. • Create a constructor that will create the new Instructions image with the text “Collect the flies and avoid the ants and rocks to win the game.” The font should be black color, size 20, with a yellow background. • Compile the code.
The scenario will automatically display the text. • Modify the source code in the Instructions class to change the instructions, font size, or font color to observe how this changes the Instructions instance. • Save the scenario.
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: • Open any Internet Browser and type the following URL in the address bar: • When prompted, click Save to save the Greenfoot Textbook Scenarios zip file to your computer, hard drive, or USB drive. You should create a folder where you will store all of your Greenfoot scenarios. • When the download is complete, open the zip file. Extract the files to a folder on your computer, hard drive, or USB drive. The Greenfoot forum Join the forum to get help from other users: 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: Credits Put credits here • Lead Curriculum Developer: Dimpi Sarmah • Other Contributors.
Romantic photo frames for quick download. Easy to use format. Different specially designed beautiful romantic photo frames for you to choose from.
Just select any of the wide collection of romantic picture frames and shoot your lovely romantic pictures. A must- have camera photo frame app for your android smartphone to capture all your memorable pictures any time anywhere. Have all your valentine photos, love photos and wedding photos beautifully crafted with lovely romantic frames •. Birthday of your loved one is approaching. Looking for an easy to use mobile camera app to create beautiful pictures with your loved one in his or her coming birthday party. With this birthday frames camera photo frames app you can take pretty photos of your loved ones or cute babies or kids anytime anywhere.
Wide range of beautifully designed birthday frames and kids frames available to decorate photos taken of your loved ones, children or baby for your family photo albums. Besides birthday ph •. Get birthday photo frames for download. Easy to use format. Different beautiful birthday frames available for you to choose from. One of the best camera apps you can have fun with on your mobile smartphone and devices.
Just select any of the wide collection of picture frames and shoot your lovely pictures. Included too are some beautiful flower frames and romantic love frames. Use the app to capture beautiful party or romantic pictures for your photo albums.
Photos with frames can be saved and s •. Birthday Photo Frames for Instagram is full of cool and funny photo frames, which will definitely make your birthday images awesome. You can create beautiful photos of your birthday or you can create funny photos of the good time you had; just pick the photo frames you like the most. Create a slideshow of your lovely photos as a surprise for your friend's birthday party or as a memory of your own happy day. One thing is certain- you will all enjoy putting those funny photos into these cool photo •.