In this tutorial you learn how to create 2D games using basic Java programming in this self-paced, online course. No programming experience required! We will define and program a game using the Greenfoot development software. Approximately 12 hours to complete the lessons.
This lesson will provide an overview of system requirements, show you how to download necessary software, and describe the purpose for using Greenfoot tools to learn Java.
In this lesson you will learn to:
Have you ever wanted to build a video game or make an animated movie? Are you interested in making your own smartphone application? Many of today’s video games, movies, and smartphone applications are created using the Java programming language. Java is a programming language and computing platform developed by Sun Microsystems in 1995. Java runs on more than 850 million personal computers worldwide, and on billions of devices worldwide, including mobile and TV devices. Java allows you to play online games, chat with people around the world, use interactive maps, and view images in 3D. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere! Visit this link to see videos of Java in Action: http://www.java.com/en/java_in_action/ Watch this video to learn more about Java technology: http://www.java.com/en/download/whatis_java.jsp
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. 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 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.
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 controlsThere 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 instanceTo better understand the terms objects, classes, and instances, consider this example:
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.
Programming Actor objectsYou 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.SummaryGreenfoot is a visual and interactive program that uses object orientation with Java to build games, simulations, and other graphical programs. Students who are new to the Java programming language enjoy using Greenfoot because the interactive development environment is fun and easy to use. By learning Greenfoot, you are actually learning how to program! Greenfoot is also used at many colleges and universities in Introduction to Programming courses.Visit the Greenfoot website to learn more about Greenfoot: http://www.greenfoot.org/overview
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
Steps to launch the JDK executable file
Steps to run the JDK Installation Wizard
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
Steps to launch the Greenfoot Installer Wizard
Steps to install Greenfoot
Steps to launch Greenfoot
Greenfoot download and installation support linksJoin the forum to get help from other users:hhttp://www.greenfoot.org/topics
In this lesson you have learned to:
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.
In this lesson you will learn to:
An initial scene is the starting point of your game. It has three components:
Below is a graphic depicting components of an initial scene. The components include:
By opening an existing scenario, we can examine its components. Launch GreenfootTo 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 IDEThe 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 WorldThe 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 displayThe 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.
The execution controlsThe execution controls are used to run and control the scenario. Execution controls:
Open a scenario in GreenfootSteps to open a scenario in Greenfoot:
After opening an existing scenario, the next step is to add the instances that will move and act into the scenario. Scene editorThe 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:
Below, the scene contains non-moving scenery instances (trees, rocks, bananas) and moving instances (elephant, hippo, lemur).
Steps to add an instance of a class to the world
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 describedThe 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: MethodsFor example, the Actor class has methods such as:
Example: Coding the act() methodEnter 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.
CompilationCompilation 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.
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:
In this lesson you have learned to:
In this lesson you will learn to:
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 scenarioTo create a new scenario follow these steps:
The new scenario will open in Greenfoot. The only classes that appear in the Class Display are World and Actor. Save the scenarioPeriodically 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.
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 characteristicsIn 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 GreenfootWhen 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 typesThe 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.
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. SubclassesA 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:
An arrow in the class hierarchy shows the subclass’s relationship to the superclass. Create a world subclassTo 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:
Compile the scenarioCompilation 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.
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:
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:
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:
Drag and drop instances with your cursorTo 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:
Save the worldYou 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.
In this lesson you have learned how to:
In this lesson you will learn how to:
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 classSteps to view the source code of a class:
Code editorThe 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 classesEach 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 codeSource 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 descriptionThe class description is a set of comments that can be modified to describe the class. The description includes:
Class definition componentsThe class definition includes:
Defining classesThe class definition defines:
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() methodThe 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 signatureThe 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. CommentsComments 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:
DocumentationDocumentation describes the properties of the class. Steps to view the documentation:
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.
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:
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() methodFor 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:
Invoking methods programmaticallyMethods 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
Methods contained in the class body are executed in sequential order. In the following example, both the move() and turn() methods are invoked, but they will be executed sequentially, one after the other. move(1); turn(15);
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:
Example: Syntax errorIn 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:
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.
In this lesson you have learned how to:
In this lesson you will learn to: Watch this video to see a preview of what you will learn in this lesson.
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:
Examples of methodsYou can write methods for the Bee class to perform tasks such as:
The Greenfoot API contains a list of all of the methods available for use by the different classes in Greenfoot. You will refer to this documentation often as you try to locate methods to use in your scenarios. The Greenfoot API is located at:http://www.greenfoot.org/files/javadoc/
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:
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
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:
Method with void return typesMethods with void return types typically issue one or more commands that carry out an action.
Invoking methods with void return typesYou will invoke methods with void return types:
Methods with non-void return typesMethods with non-void return types typically ask the object to obtain information and return the information.
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 typesint (Short for integer)
boolean
Examples of invoking methods with non-void return typesExamples:
Method parameter listsA 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 list examples:
Parameter lists typically have two states:Empty: No data expected to invoke the method (getX method).
Non-empty: Have data and expect one or more parameters to invoke the method (move method).
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 methodsThere are a number of ways to identify inherited methods:
Steps to use the Object Menu to display all of the inherited methods of an instance:
Steps to identify inherited methods in the Code editor:
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.
In this lesson you have learned how to:
In this lesson you will learn to:
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() methodThe 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:
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.
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 formatThe format for dot notation code includes:
Dot notation exampleThe getRandomNumber() method shown below:
Class methodsWhen 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:
Steps to view the Greenfoot Class Documentation:
The Greenfoot Class Documentation contains all of the methods in all classes that are available to a programmer within Greenfoot.
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 decision statementsAn 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 componentsAn 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 worldIn 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 pressedIn the following example:
Remember, the act() method is called once when the Act button is pressed. It is called repeatedly when the Run button is pressed. isKeyDown methodThe isKeyDown method is a pre-existing Greenfoot method that listens to determine if a keyboard key is pressed during program execution.
Conditional behavior is often decided on an if or else basis, for example if it is raining then take an umbrella - else leave the umbrella at home. In Greenfoot, An IF-ELSE statement can be used in a similar way to determine the behavior of an instance depending on one or more conditions. An IF-ELSE statement executes its first code segment if a condition is true, and its second code segment if a condition is false, but never both. Instances can be programmed to perform specific behaviors if a condition is not met, using an IF-ELSE statement. For example, if an instance is programmed to turn 6% of the time, what does it do the other 94% of the time? IF-ELSE statement executionThe IF-ELSE statement executes as follows: Evaluate the condition:
IF-ELSE statement formatThe format (syntax) of the IF-ELSE statement follows the same pattern every time. The if keyword followed by a condition in parentheses, with the statement to execute between the curly braces. All execution statements must end with a semicolon. The condition is enclosed in parenthesis() and must equate to a boolean value (i.e., true or false). The associated code to be executed for each IF-ELSE statement is enclosed in curly brackets {}: IF-ELSE statement exampleThe following IF-ELSE statement executes as follows:
In the example above we use the < symbol to compare the randomly generated number to the value of 7. The < symbol is known as a less than comparison operator. Define comparison operatorsComparison operators are symbols that compare two values. There are a number of comparison operators in Greenfoot which can be used to determine game play decisions when combined with control statements. Comparison operator symbols
Example: Comparison operatorsUse comparison operators to compare a randomized value to another value in a control statement. The example below determines if the random number is less than 20. If it is, then the object turns 10 degrees. Gaming problem solved with conditional behaviorProblem: A butterfly object should move randomly so it is more challenging for the keyboard-controlled object, a bee, to avoid it. Solution:
Conditional behavior formatThe programming statement below includes:
In this lesson you have learned how to:
In this lesson you will learn to:
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 constructorThere is a difference between a world constructor and a constructor for an object.
World class source codeTo 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 statementThe 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 headerThe 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.
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:
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.
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 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 methodThe addObject method is a World class method that adds a new object to the world at specific x and y coordinates. It includes:
The method signature of the addObject method is as follows: Example: addObject() methodThis 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 KeywordThe 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.
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. VariablesA 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 propertiesObject properties describe the instance's appearance and abilities, such as:
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:
Instance variablesInstance 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:
Invoking methods directlyAs 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 orientationInvoke a method directly to display an object's orientationTo 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:
Steps to invoke a method directly:
In this lesson you have learned how to:
In this lesson you will learn to:
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() MethodThe isKeyDown() method is used to determine if a key on the keyboard has been pressed. The isKeyDown() method:
Method signature and description: public static boolean isKeyDown(java.lang.String keyname) String Parameter in isKeyDown() MethodA String is a piece of text (character, word, sentence, or more) enclosed in double quotes. For example:
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:
Shortcut to the Greenfoot DocumentationWhen 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() methodExamine 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:
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() methodThe 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 controlsA 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.
Methods and classes for mouse interactionAs an alternative to keyboard interaction, the Greenfoot API provides us with methods we can use to program mouse interaction in our scenario. We can program statements that include mouse controls, so the player can control one or more objects in the game using their mouse. There are methods in the Greenfoot class that provide us with information about the player's mouse movements in the scenario. To program the mouse interactions in a scenario, we must be able to check the current position and state of the mouse. To do this, Greenfoot provides us with a getMouseInfo() method in the Greenfoot class which will return a MouseInfo object that can be used to check the current state of the mouse in the scenario. 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() methodIn 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() methodThe 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() methodExamine the following example:
Example: Using the mouseDragEnded() methodExamine the following example:
Example: Using mouse drag and drop interactionExamine 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.
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() methodThe playSound() method is used to play sounds in a scenario. The playSound() method:
The method signature for the playSound() method is as follows: Example: Using the playSound() methodConsider 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.
Greenfoot offers the ability to record your own sounds within the IDE. Steps to record original sounds in Greenfoot:
In this lesson you have learned how to:
In this lesson you will learn to:
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.
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.
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 summarizedTo change the image of an instance for a scenario you need to:
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.
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 scenarioUsing 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:
Set an image using the image file nameConsider 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”);
The same results can be obtained by using a GreenfootImage object to set an image. Edit the code for the Bee in the act() method for the if conditions: if(Greenfoot.isKeyDown(“left”)) this.setImage(new GreenfootImage(“bee_left.png”)); if(Greenfoot.isKeyDown(“right”)) this.setImage(new GreenfootImage(“bee_right.png”)); if(Greenfoot.isKeyDown(“up”)) this.setImage(new GreenfootImage(“bee_up.png”)); if(Greenfoot.isKeyDown(“down”)) this.setImage(new GreenfootImage(“bee_down.png”)); There is not an advantage to using either of these setImage() methods, but when you learn about variables, you will see how to save an image as a GreenfootImage object so that only one image is used to create all of the instances using the image. If you create 50 bees in a scenario using the images you just created, there would be 50 images using the setImage() methods as shown above.
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 formatA variable’s format includes:
Common data types in Greenfoot
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 variablesVariables are declared in the source code of the class before the constructors and before the act() method. The format for declaring a variable includes:
Example: Declaring variablesThe 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.
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:
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 statementAn assignment statement for image objects includes:
An expression for an image variable contains:
Assignment Statement example for image variables: Initial assignment statement placementIn 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.
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.
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.
Initializing an actor instanceWhen 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.
Actor constructor guidelines:
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 subclassThe 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.
In this lesson you have learned how to:
In this lesson you will learn to:
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:
Programmer-defined methods:
Steps to define a method:
Example: Defined method for random movementsInstead 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.
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:
Check an instance's position in the worldTo check if an object is near the edge of the world you need:
Logic operators in Java
Methods used to test an instance's position in the world
Example: Check an instance's position in the worldIn 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 worldThe 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:
Call the atWorldEdge() methodFor 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.
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:
Test if an object is at the same coordinates (colliding) with another objectTo test if an object is colliding (or near colliding) with another object, write the following in the defined method:
Define the methodFirst, define the method eatFlower() below the act() method. Declare a local variable inside of the methodNext, 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 typeThe 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() methodIn order for the bee to use the eatFlower() method, we must call this method in the act() method.
In this lesson you have learned how to:
In this lesson you will learn to:
Have you ever listened to a song or watched a movie that played again and again and never ended? In programming you can create the same situation with a loop. A loop is a statement that can execute a section of code multiple times. When a loop executes all of the statements within the loop one time, this is called an iteration. When a loop executes all of the statements within the loop more than one time, and stops based on a condition, this is called a conditional iteration.
For example, with a while loop, you could:
The components of a while loop include:
Using a loop variable to control execution of a while loopHow does a program know how many times to execute the while loop? It uses a loop variable to control how many times the while loop is executed while a condition is true.
A loop variable, like a local variable:
To declare a loop variable:
Incrementing the loop variableThere needs to be a way to change the value of the loop variable each time the loop is executed in order to count how many times the loop has been executed. This is referred to as incrementing the variable. If you do not change the value of the loop variable by counting up each time the loop is executed, the loop will never end. First, create the condition in the while loop that specifies how many times the body of the loop should be executed. For example, if it is true that the variable i has been executed less than 5 times, execute the programming statements in the body of the while loop. Next, write code to increment the loop variable. There are two ways to increment a loop variable:
The condition that is evaluated at the beginning of the while loop uses a comparison operator to control the number of loop executions.
Comparison Operators
Example: Incrementing a loop variableThis example will execute the body of the loop while the number of executions is less than, but not equal to, 10. When the loop has been executed 10 times (0-9), it stops. Insert statements to execute in the body of the while loopBetween the curly braces of the while loop, insert the programming statements to execute. For example, to create a while loop that executes a method 5 times, insert a single programming statement with the method in the body of the while loop. Remember, the condition of the while loop and loop variable will control how many times the while loop executes that single programming statement. Example: Create instances using a while loopWhen a player wins the Bee game, 10 flowers should be placed in the world. Create a while loop that automatically generates 10 flowers in the world. In the example, the loop variable is declared and initialized to 0 (int i = 0). The condition to end the loop uses the loop variable i (while i < 10). The programming statements to execute in the loop body add a flower object to the world at a random x and y position. The code gets the height and width of the world so the flowers appear within the boundaries of the world. The loop variable was incremented using i++; to control the loop execution. It is important to note that if you do not increment the local variable i, the loop would never reach the end condition, creating an infinite loop that would never end. Example: Invoking a method using a while loopCreate a while loop that plays a sound file 3 times. In the example below, when the player presses the b key, the bee will buzz 3 times.
An infinite loop is described as a loop that continues to execute forever because the end to the loop isn't established. Infinite loops are considered to be a logic error, and are a common problem in programming. The common reasons for a loop to execute infinitely include:
Most games end because a specific condition has been met or because the player specifies that they want to stop the game. The Greenfoot class has a stop() method that you can use to end your game at a point that you designate. You may want to end the game when:
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:
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:
Define variables to hold the integer values for the gameAt the top of the Bee class, you will define three variables that hold integer values.
Define a method to manage the bee eating flowersDefine 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 mushroomDefine 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 butterflyDefine 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 gameDefine 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.
This executes the programming statements inside of the if statement.
The second if statement above manages what happens if the player loses the game due to 3 collisions with a mushroom.
This executes the programming statements inside of the if statement.
The third if statement above manages what happens if the player loses the game due to 3 collisions with a butterfly.
This executes the programming statements inside of the if statement.
Examine the complete code: Using the == relational operator to check if the variable equals the totals to end the gameThe programming statements that instruct the instance to check for the number of flowers eaten and the number of collisions with mushrooms or butterflies contains:
The == relational operator:
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.
Displaying dynamic text instructionsAnother 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:
You can create an Actor subclass named Instructions to display the dynamic text. Display dynamic instructionsInstructions 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 the Instructions classTo 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 packageImport 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 imageSince 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:
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:
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 imageTo 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.
In this lesson you have learned how to:
In this tutorial you learnt how to create 2D games using basic Java programming in this self-paced, online course. Additional resourcesGreenfoot textbook scenariosThe Greenfoot Textbook Scenarios provide some basic scenarios to explore the features of Greenfoot. Steps to download the Greenfoot textbook scenarios:
The Greenfoot forumJoin the forum to get help from other users: http://www.greenfoot.org/topics Joy of Code videosThe Joy of Code video blog is hosted by Michael Kolling, creator of Greenfoot. Visit his blog for more instructional videos on how to use Greenfoot to create fun and engaging games. Access the blog at: http://blogs.kent.ac.uk/mik/category/joy-of-code/ CreditsPut credits here
To navigate this Oracle by Example tutorial, note the following: Topic List: Click a topic to navigate to that section. Expand All Topics: Click the button to show or hide the details for the sections. By default, all topics are collapsed. Hide All Images: Click the button to show or hide the screenshots. By default, all images are displayed. Print: Click the button to print the content. The content that is currently displayed or hidden is printed.
To navigate to a particular section in this tutorial, select the topic from the list. Help OLL About Oracle Contact Us Terms of Use |