What We Will Cover
Illuminations
Questions from last class or the Reading?
String review
Guild names due Thursday -- roll call with guild names
Remember that guilds sit together and help each other
Reminder: Challenges
Homework Questions?
Matching Relationships Game
Match the questions with the answers. Use the box on the left to write your choice. Then click on the Answers box to see if your answers are correct.
^ top
4.1: Forming Guilds
Learner Outcomes
At the end of the lesson the student will be able to:
Join a guild
Commit to a future guild meeting
Choose a name for their guild
Discuss how to work together in a guild
^ top
4.1.1: Introduction to Guilds
This week we want to form guilds
A guild is a small group of people with complementary skills who:
are committed to a common purpose, goals and approach
hold themselves and each other accountable to meet their goals
We want several guilds of four to five members
Guilds get to choose their own names, leaving out the usual words
Some quests, labeled "guild", are completed by all guild members
Guilds are given options on how they decide to complete the designated quests
An especially important set of quests is the final project, which covers multiple weeks and deliverables
The following are important characteristics of successful guilds
Small Group Size
Guilds usually work best with a small group of people
Smaller numbers make administrative tasks easier, such as deciding where and when to meet
Meetings are generally shorter when fewer people need to speak
Small size also makes it easier to develop a common purpose with mutual goals and mutual accountability
Also, small groups of people avoid the "herd" mentality of large groups
Large groups of people tend to go along with popular opinion rather than thinking for themselves
We will form guilds of four to five people
Complementary Skills
Complementary skills are also important for a guild
Complementary means that people work together in such a way as to enhance or emphasize the qualities of each other
Guilds need skills in multiple areas including:
Programming
Graphics creation and editing
Sound creation and editing
Effective communication and interpersonal relationship
Leadership and decision-making
We will look at these skills before forming guilds
Commitment and Accountability
Guilds need to have a strong commitment to a common purpose and goals
This is especially true when we develop the final project
The guild chooses a project which meets the final project requirements
If one member does not meet their commitment then the whole project suffers
For this reason, we have extra credit applied at the end of the final project (secret ballot):
Guild Leader: 20 pts. (major player in the guild; gets things done)
Raid Leader: 15 pts. (major contributor to the guild and its projects)
Solid Guild: 10 pts. (could be counted on to do their part, but not more)
Needs Rez: 5 pts. (coasting, minimal effort, needs resurrection as a player)
Leeroy Jenkins: 0 pts. (Usually AFK or minimal contribution)
To be successful, teams need to hold each other accountable for meeting commitments
^ top
4.1.2: Getting to Know Each Other
Today we will take some time to form guilds
Between now and Thursday, the guild needs to meet one time and choose a guild name
First we find out when guild members can meet outside of the classroom for at least an hour, like:
Before class
After class
Other times (write on board)
Let us start by getting to know each others interests and skills
Exploring Our Interests and Skills
Arrange yourself in a line based on your: (click line)
Interest in games vs simulations
Skills in programming
Skills creating and editing graphics
Skills creating and editing audio files
Skills in leadership, organization and decision-making
Next step is forming a guild
^ top
Exercise 4.1: Forming Guilds (10m )
In this exercise we start forming guilds.
Who can meet one hour before class?
Who can meet one hour after class?
What other times can people meet?
Specifications
Join a group in one of the time locations in the room
Find people NOT like you. Diversity creates better solutions.
Within your group, exchange names and email addresses, and then copy down everyone's information to turn in as guild.txt
.
In addition, list everyone's skills in the following areas a 1-5 scale with 5 being highly skilled
A udio
G raphics
P rogramming
For example:
Emma Gamer A1 G3 P5
In the above, A1, G3, P5 would be low audio, medium graphics, high programming skills.
Save all the information you collect in a file named guild.txt
.
Note that you can choose to have one person in your group record the information and email it to all the students in the group. However, every student in the guild must submit the list of guild members.
Arrange for a time to meet before the next class meeting.
During your meeting time, decide on the name of your guild.
Save the guild.txt
file so you can submit it to Canvas as part of the next lab.
^ top
4.2: Setting up a Scenario
Learner Outcomes
At the end of the lesson the student will be able to:
Prepare scenarios automatically
Code constructors
Construct new objects programmatically
^ top
4.2.1: World Construction
Scenario file: lesson4.gfar (or lesson4.zip ).
Recall how we "Save the World" in Greenfoot
To see the process we open the current World
subclass
Next we populate the scenario, right-click on the world background, and select "Save the World"
Looking at the source code, we now have a new method in the World
subclass named prepare
private void prepare()
{
// some code here
}
Notice where the prepare()
method is called:
public LessonWorld ()
{
super(600, 400, 1);
prepare();
}
The method LessonWorld is known as a constructor
Whenever an object is instantiated , the constructor for the object is called automatically
The Greenfoot IDE automatically calls the constructor of the current world
We use this property of being called automatically to set up our scenario
If we look at the LessonWorld source code before calling "Save the World", we see something like the following
Example LessonWorld
Code with Constructor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import greenfoot.*; // Greenfoot framework
/**
* Write a description of class LessonWorld here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class LessonWorld extends World
{
/**
* Constructor for objects of class LessonWorld.
*
*/
public LessonWorld()
{
super(600, 400, 1);
}
}
The first line is the import statement , which allows access to the Greenfoot framework
import greenfoot.*; // Greenfoot framework
followed by several lines of comments that the compiler ignores
Then comes the class header and another comment block
Then comes the part that controls how the world starts -- the constructor:
public LessonWorld()
{
super(600, 400, 1);
}
The purpose of a constructor is to prepare a new object for use
A constructor is coded like a method but there are some differences
By looking, can you identify two differences? answer
The first line in the body of the constructor sets up the size of the world
In our case, 600 pixels wide by 400 pixels high with 1 pixel per cell
We can add code to the constructor to automatically create actors:
public LessonWorld()
{
super(600, 400, 1);
Hero hero = new Hero(); // new expression
addObject(hero, 150, 100); // add hero to world
}
The added code automatically creates a new hero and places it in the specified (x, y) location
If we look at a prepare()
method, we see similar code
We have two statements added here:
the new
expression which creates an object and assigns it to the variable
the addObject()
method which adds an actor to the scenario
We will consider both in the following sections
Check yourself
True or false : the purpose of a constructor is to prepare a new object for use.
A constructor differs from a method in that the constructor has ________ and ________ . (answer )
The name of the class that contains this code is ________ . (why? )
private Hero hero;
private Food food;
public LessonWorld() {/* statements here */}
Hero
LessonWorld
Food
Cannot determine class name from the information given
^ top
4.2.2: The addObject()
Method
The method header for the addObject()
method is:
void addObject(Actor object , int x , int y )
Where:
object : the new object to add
x : the x coordinate of the location where the object is added
y : the y coordinate of the location where the object is added
For example:
addObject(new Hero(), 150, 100);
The addObject()
method belongs to the World
superclass
Since our world subclass inherits from the world, we just call the method directly
Check Yourself
True or false : use the addObject()
method to add objects to a scenario world.
When calling the addObject()
method, we specify the object location using the ________ and ________ coordinates of the scenario world.
True or false : you can call addObject()
from any World
subclass.
^ top
4.2.3: Creating New Objects
The addObject()
method lets us add an object to the world
However, we must first have an object to add
The Java keyword new
lets us create new objects:
new Hero()
We may create the new object within the addObject()
method call:
addObject(new Hero() , 150, 100);
Another way is to save the object in a variable and use the variable in the method call:
Hero myHero = new Hero() ;
addObject(myHero, 150, 100);
Notice that the data type of the variable is the name of the class: Hero
Since the first technique is more compact, it is most often used when typing code
We only use the second technique if we want to save the object for later use
For example, we may set an initial rotation of an object with code like:
Hero myHero = new Hero();
myHero.setRotation(45);
addObject(myHero, 150, 100);
The key point is that you must use the new
keyword to create a new object
If we save the actor in a variable, we may then apply more transformations to the actor
Check yourself
True or false : the purpose of the addObject()
method is to add objects to a scenario world.
For a class named Foo , you create a new object using the code ________ .
new Foo
Foo()
new() Foo
new Foo()
To place a Hero
object in the world at the coordinates (200, 300) use the statement ________ .
addObject(new Hero(), 200, 300);
addHero(200, 300);
addActor(new Hero(), 200, 300);
addObject(Hero.class, 200, 300);
^ top
4.2.4: Using Loops to Randomly Add Objects
Saving the world is nice but allows no variation in how a game starts
To make the game more interesting we add the food at random coordinates
We could a random food object using code like:
int x, y;
x = Greenfoot.getRandomNumber(600);
y = Greenfoot.getRandomNumber(400);
addObject(new Food(), x, y);
For ten food, we would need to repeat the last three lines nine more times
A better approach is to use a counting loop
Group Activity: Exploring Counting Loops
Clap your hands 5 times.
True or false : as you are clapping, you are repeating an action.
You know when to stop clapping because you ________ .
True or false : as you are counting, you are testing the count against the number 5.
Every time you clap, you update the count by ________ .
The for
-Loop
The counting loop to use in Java is the for
-loop
The syntax of the for-loop is:
for (int i = start ; i < end ; i = i + 1) {
...
}
Where:
i : the name of a counter variable
start : the initial starting value
end : the final ending value
As an example, we could add the ten food using this code:
int x, y;
for (int i = 0; i < 10; i = i + 1)
{
x = Greenfoot.getRandomNumber(600);
y = Greenfoot.getRandomNumber(400);
addObject(new Food(), x, y);
}
The parenthesis of a for loop has three parts:
Initialization: int i = 0;
Test condition: i < 10;
Update counter: i = i + 1
The first part of a for
-loop initializes a counting variable
for (int i = 0; i < 10; i = i + 1)
We use the counting variable to keep track of how many times the loop repeats
The middle section is a test condition, like in an if
-statement, that decides when to keep the loop going and when to stop
for (int i = 0; i < 10; i = i + 1)
As long as the test condition evaluates to true
, the loop continues
When the test condition evaluates to false
the loop exits
The last section updates the counting variable by adding one to the current value
for (int i = 0; i < 10; i = i + 1 )
After the loop statement we add the statements to repeat inside a pair of curly braces
When a loop exits the program continues with the statement after the loop's closing curly brace }
Diagram of for
Loop Operation
Execution Steps
❶ ⇛ ❷ ⇚ ❹
for (int i = start ; i < end ; i = i + 1) {
... ❸
}
❺
When for
loop is reached, execute the initialize
statement (example: int i = 0;
)
Check if condition
is true
(example: i < 10
;)
if true
then continue with Step 3
Otherwise, continue with Step 5
Execute the block containing the statements to repeat (body)
When end of loop body is reached, execute the update
statement (example: i = i + 1
) and return to Step 2
Loop is finished: continue with statements after the loop
Check Yourself
Map the following terms to the example code:
for (int i = 0; i < 10; i++)
{
x = Greenfoot.getRandomNumber(600);
y = Greenfoot.getRandomNumber(400);
addObject(new Food(), x, y);
}
Initialization: ________
Test condition: ________
Loop body: ________
Update: ________
^ top
Exercise 4.2: Scenario Setup (5m )
In this exercise, we automatically initialize our Hero scenario.
Specifications
Download and save the following scenario file and then double-click the file to extract it.
Scenario file: lesson4.gfar (or zip ).
Open the scenario (see lesson 1.3.4 ).
Open the source code editor of the LessonWorld class (see lesson 1.3.8 ).
Delete the prepare()
method and the method call to prepare()
.
In the constructor method, add code like the following to automatically add a hero to the scenario.
addObject(new Hero(), 150, 100);
Compile the class and verify there are no errors. Resolve any errors you find, getting help from a classmate or the instructor as needed.
Create seven Food objects and use a for
-loop to add them to the scenario at random coordinates using code like the following:
for (int i = 0; i < 7; i = i + 1)
{
int x = Greenfoot.getRandomNumber(600);
int y = Greenfoot.getRandomNumber(400);
addObject(new Food(), x, y);
}
Place the code in the LessonWorld
constructor.
Compile and run your scenario to verify all the changes work well.
If you have problems, ask a classmate or the instructor for help as needed.
In addition, add one or more predators to your scenario.
Compile the class and verify there are no errors. Resolve any errors you find, getting help from a classmate or the instructor as needed.
Save a copy of your scenario to upload to Canvas later as part of the next lab.
We will be adding more code to these files in subsequent exercises, so it is not time to submit them to Canvas yet. However, it is a good idea to have a backup copy in case of problems later in development.
When finished, check your code against the listing below and then help other students.
Listing of LessonWorld()
Constructor Method
public LessonWorld()
{
super(600, 400, 1);
Hero hero = new Hero();
addObject(hero,150,100);
for (int i = 0; i < 7; i = i + 1)
{
int x = Greenfoot.getRandomNumber(600);
int y = Greenfoot.getRandomNumber(400);
addObject(new Food(), x, y);
}
Predator predator = new Predator();
addObject(predator,304,329);
}
^ top
4.2.5: Summary
Constructors
Games and simulations need to place actors automatically
To automatically place an actor, you use the constructor of the World subclass (like LessonWorld )
The purpose of a constructor is to prepare a new object for use
A constructor is coded like a method but with two important changes:
No return type
Same name as the class name
Adding Actors
For Loops
Loops allow us to repeat statements in a program
One common use for loops is to count
When counting, we need to remember the number of the count
To remember a value, we use a variable
Thus, to count, we need both a loop and a counter variable
The for loop gives us a compact way to code program counter-controlled loops
for (int i = start ; i < end ; i = i + 1) {
...
}
The for
-loop executes as shown in the following diagrams:
We used for loops to add actors to our scenario
int x, y;
for (int i = 0; i < 10; i = i + 1)
{
x = Greenfoot.getRandomNumber(600);
y = Greenfoot.getRandomNumber(400);
addObject(new Food(), x, y);
}
Check Yourself
Answer these questions to check your understanding. You can find more information by following the links after the question.
True or false: scenarios should always have actors placed manually. (4.2.1 )
What is the purpose of a constructor? (4.2.1 )
Which of the following is NOT a difference between a method and a constructor? (4.2.1 )
A constructor name is always the same as the class name whereas a method name need not be the same.
A constructor cannot not return a value but a method can return a value.
A constructor is called automatically when the object is created whereas a method must be called explicitly.
All of these other answers are differences between a method and a constructor.
Which of the following is a difference between a method and a constructor? (4.2.1 )
The name is the same as the class name.
The name is the same as the class name, except lower case.
The name cannot start with a number.
The name cannot have spaces.
Which of the following is a difference between a method and a constructor? (4.2.1 )
A constructor cannot have parameters.
A method has a name but a constructor does not.
A method body is enclosed in curly braces but a constructor body is enclosed in parenthesis.
A method always has a return type, unlike a constructor.
True or false: the addObject()
method has three parameters. (4.2.2 )
For a class named Foo , which of the following is a valid expression for creating a new object? (4.2.3 )
new Foo
Foo()
new() Foo
new Foo()
A counting loop has the following three parts: (4.2.4 )
___________________
___________________
___________________
^ top
4.3: Animating Images
Learner Outcomes
At the end of the lesson the student will be able to:
Discuss animation using images
Write programs with animated images
Write code for instance variables
Assign values to instance variables
^ top
4.3.1: About Image Animation
Animation is the illusion of motion created by displaying a series of images or shapes
For example, the following animation displays at 10 frames per second (FPS):
The speed of the display is fast enough that you cannot easily see the individual frames
Contrast this with the following image that displays at 2 frames per second:
At 2 FPS, the animation is slow enough that you can see the individual frames
Both of these animations were produced by displaying these images, known as frames:
Note that these images are in the public domain and were obtained from Wikipedia
Check Yourself
Animation is the ________ of motion created by displaying a series of images or shapes.
True or false: if the animation is too fast, it appears jerky.
Each image in an animation is sometimes called a ________ .
^ top
4.3.2: Adding Images to a Scenario
We want to apply image animation to make our actors look more realistic
For this, we need to add more images to our hero scenario
We can use the following similar but slightly different images for our hero
The slight difference is in the position of the legs
Images for Animation
Bug with legs forward
Bug with legs sideways
Bug with legs back
Saving Images in a Scenario
We can save these images in our scenario
Right click the images and select, "Save Image As... " (or "Save Picture As..." in IE)
In the Save Image dialog, find the Greenfoot scenario folder for your project and save in the images folder
In Greenfoot, right click on the actor and select, "Set image... "
You will see the images on the left in the Scenario images area
Click the image to select it and press the OK button
Check Yourself
True or false : to create an animation effect we often change the images of an actor.
The name of the command for changing the image an Actor displays is ________ .
True or false : you cannot import new images into a Greenfoot scenario.
^ top
4.3.3: Greenfoot Images
Check yourself
To change the image of an Actor
call the method ________ .
True or false : in Greenfoot, the name of the class for storing images is called GreenfootImage
.
Of the following, ________ is NOT one of the methods of Actor that works with images.
getImage()
setImage(String)
setImage(GreenfootImage)
changeImage(GreenfootImage)
^ top
4.3.4: Instance Variables (Fields)
An instance variable, also called a field , is declared inside a class but outside any method
General syntax:
private dataType VariableName1 , VariableName2 , ...;
Where:
dataType : one of the Java data types
VariableNameX : the name of the variable
For example:
private int count;
private GreenfootImage image1;
The word private
is known as an access modifier
Technically, we can use words other than private
, but for now ALWAYS use private
Professional programmers use private
to ensure projects can be changed as they grow larger
Can you identify each of the syntax items in the examples above?
acess modifier
data type
variable name
Comparing Local Variables and Instance Variables
A local variable is like an instance variable but is a variable declared inside a method or other block
Like an instance variable, a local variable is a place in memory to store information
Also, like an instance variable we specify a data type and a name to declare a variable
Likewise, the naming rules of local and instance variables are the same
In addition, we assign values to both local and instance variables using an equals ("=
") sign
In contrast, a local variable is declared inside a method while an instance variable is declared outside of any method
Because of location, the memory for a local variable is associated with a method or block of code
With an instance variable, the variable is associated with the object
Every object you create (instantiate) of the class with the instance variable has memory space for the variable
Also, the instance variable has an accessibility modifier: private
Unless we assign a value to an instance variable, Java assigns a default value
Example of Three Instance Variables Declared in a Class
import greenfoot.*;
// comments omitted
public class Hero extends Mover
{
private GreenfootImage image1, image2, image3;
// methods omitted
}
Default Values for Instance Variables
Check yourself
True or false : an instance variable is a place to store data in memory.
True or false : A local variable is declared inside a method while an instance variable is declared outside a method, though still inside a class.
The three parts of this instance variable are known as a(n):
private GreenfootImage image1;
private
: ________
GreenfootImage
: ________
image1
: ________
^ top
4.3.5: Constructors and Reference Variables
Example of a Constructor in an Actor
Subclass
import greenfoot.*;
// comments omitted
public class Hero extends Mover
{
private GreenfootImage image1, image2, image3;
public Hero()
{
image1 = new GreenfootImage("bug-a.gif");
image2 = new GreenfootImage("bug-b.gif");
image3 = new GreenfootImage("bug-c.gif");
setImage(image1);
}
// methods omitted
}
Constructing Objects
Notice how we create multiple new GreenfootImage
objects and save the images for later use
The purpose of a constructor is to set up an object including instance variables
After the constructor finishes, we have four objects:
Three GreenfootImage
objects
One Hero
object
The instance variables are part of the Hero
object and allow us to refer to the GreenfootImage
objects
This is shown in the following diagram
The first object (Hero ) is constructed in the world constructor
addObject(new Hero() , 150, 100);
The image objects are constructed in the actor constructor
image1 = new GreenfootImage("bug-a.gif");
image2 = new GreenfootImage("bug-b.gif");
image3 = new GreenfootImage("bug-c.gif");
These variables are known as reference variables because they refer to an object
We can see how reference variables work in the following image
Hero Object With Variables Referring to Image Objects
Check yourself
The purpose of an Actor
constructor is to ________
True or false : a reference variable is a variable with a class name as the data type.
Of the following variable declarations, ________ is a reference variable.
int x;
double trouble;
float away;
String aling;
True or false : every object has a separate and unique set of instance variables.
^ top
4.3.6: Alternating Images with if-else
Statements
Now that we have multiple images available, it is time to sequence the animation
For the animation to work, we need to alternate between the images
In other words, whenever we are were showing image1
we now want to show image2
Also, whenever we are were showing image2
we now want to show image1
For this alternation we can use an if-else
statement
The if-else
statement alternates between two conditions:
If a condition is true
Otherwise it is false
Syntax:
if (test ) {
statements1
} else {
statements2
}
Where:
test : the test condition to evaluate
statementsX : the statements to execute depending on the test
For example:
if (getImage() == image1)
{
setImage(image2);
}
else
{
setImage(image1);
}
Diagram of if-else
Statement Operation
More Information
Check yourself
If the current image displayed is image1
, the image displayed after the following code fragment runs is ________ .
if (getImage() == image1)
{
setImage(image2);
}
else
{
setImage(image1);
}
True or false : there is a separate test condition for both the if
and the else
clause of an if-else
statement.
True or false : if alternation is taking place it is clearer to write an if-else statement.
What is wrong with the following if-else statement? (answer )
if (getImage() == image1)
{
setImage(image2);
}
else (getImage() == image2)
{
setImage(image1);
}
What is the value of x
after the following code segment? (answer )
int x = 5;
if (x > 3)
{
x = x - 2;
}
else
{
x = x + 2;
}
True or false : always indent inside the curly braces of an if-else -statement.
^ top
4.3.7: Multiple Alternatives
It is possible to extend the image sequence with multiple if-else
statements
We do this by nesting an if-else
statement inside another if-else
statement
We can nest in either the if
clause or the else
clause
When we want only one selection from a list then we should nest in the else
clause
When we nest in the else
clause, the else
clause does not execute if the test evaluates to true
The else
part executes only when the if
test condition evaluates to false
The if
statement inside the else
clause works in the same way
By continuing to nest in the else
clause, we can build a series of test conditions
The first test condition that evaluates to true
executes and the remainder of the clauses are skipped
Psuedocode
Implementing the Sequencing With if-else
Statements
When choosing between alternatives, we nest in the else
clause
Syntax:
if (test1 )
{
statements1
}
else if (test2)
{
statements2
}
else
{
statements3
}
Where:
testX : the test conditions to evaluate
statementsX : the statements to execute depending on the test
For example:
if (getImage() == image1)
{
setImage(image2);
}
else if (getImage() == image2)
{
setImage(image3);
}
else
{
setImage(image1);
}
The first test condition that evaluates to true is selected and no others
Notice that there is no test condition for the else
clause
The final else
clause serves as the default condition
Check yourself
True or false : psuedocode is a technique for working out the logic of a program.
True or false : we can choose among multiple alternatives by nesting an if
statements in an else
clause.
If the current image displayed is image1
, the image displayed after the following code fragment runs is ________ .
if (getImage() == image1)
{
setImage(image2);
}
else if (getImage() == image2)
{
setImage(image3);
}
else
{
setImage(image1);
}
In the above code, if the current image displayed is image2
, the image displayed after the code executes is ________ .
In the above code, if the current image displayed is image3
, the image displayed after the code executes is ________ .
^ top
Exercise 4.3: Adding Animation (7m )
In this exercise, we add animation to our hero scenario.
Specifications
Start Greenfoot and open the Hero scenario from the last exercise .
If you did not complete the last exercise, download the following project file and continue with this exercise. Then go back and finish the last exercise at a later time.
Scenario file: lesson4.gfar (or zip ).
Add the following images to the Hero scenario, saving the images with the names shown below the image:
bug-a.gif
bug-b.gif
bug-c.gif
For more information see lesson: 4.3.2: Adding Images to a Scenario .
Add three instance variables to the Hero class named image1
, image2
and image3
at the start of the class that are suitable for storing GreenfootImage
objects.
public class Hero extends Mover
{
private GreenfootImage image1, image2, image3; // add this line
// other code ommitted
For more information see lesson: 4.3.4: Instance Variables (Fields) .
Add a constructor to the Hero class after the instance variables as shown in the bold code below.
public class Hero extends Mover
{
private GreenfootImage image1, image2, image3;
public Hero()
{
// assign variables here
}
// other code ommitted
For more information see lesson: 4.3.5: Writing Actor Constructors .
Within the constructor, assign the following values to the instance variables as shown below:
image1 = new GreenfootImage("bug-a.gif");
image2 = new GreenfootImage("bug-b.gif");
image3 = new GreenfootImage("bug-c.gif");
Write a method named updateImage()
and call the method from the act()
method.
public void updateImage()
{
// add if-else statements here
}
Add if-else statements to the updateImage()
method to alternate between the images.
if (getImage() == image1)
{
setImage(image2);
}
else if (getImage() == image2)
{
setImage(image3);
}
else
{
setImage(image1);
}
For more information see lesson: 4.3.7: Multiple Alternatives .
Compile and run your scenario to verify the legs move on the hero.
If you have problems, ask a classmate or the instructor for help as needed.
Save a copy of your scenario to upload to Canvas as part of the next lab.
We will be adding more code to these files in subsequent exercises, so it is not time to submit them to Canvas yet. However, it is a good idea to have a backup copy in case of problems later in development.
When finished, check your code against the listing below and then help other students.
Partial Listing of Hero
Class
public class Hero extends Actor
{
private GreenfootImage image1, image2, image3;
public Hero()
{
image1 = new GreenfootImage("bug-a.gif");
image2 = new GreenfootImage("bug-b.gif");
image3 = new GreenfootImage("bug-c.gif");
}
/**
* Act - do whatever a Hero does.
*/
public void act()
{
checkKeyPress();
move(2);
turnAtEdge();
lookForFood();
updateImage();
}
public void updateImage()
{
if (getImage() == image1)
{
setImage(image2);
}
else if (getImage() == image2)
{
setImage(image3);
}
else
{
setImage(image1);
}
}
// other code omitted
^ top
4.3.8: Summary
Code Snippet With Instance Variables, Constructor and Image Update
public class Hero extends Actor
{
private GreenfootImage image1, image2, image3;
public Hero()
{
image1 = new GreenfootImage("bug-a.gif");
image2 = new GreenfootImage("bug-b.gif");
image3 = new GreenfootImage("bug-c.gif");
}
/**
* Act - do whatever a Hero does.
*/
public void act()
{
checkKeyPress();
move(2);
turnAtEdge();
lookForFood();
updateImage();
}
public void updateImage()
{
if (getImage() == image1)
{
setImage(image2);
}
else if (getImage() == image2)
{
setImage(image3);
}
else
{
setImage(image1);
}
}
// other code omitted
Check Yourself
Answer these questions to check your understanding. You can find more information by following the links after the question.
What is animation? (4.3.1 )
What is the name of the method for adding images to a scenario? (4.3.2 )
True or false: in Greenfoot, the name of the class for storing images is called GreenfootImage
. (4.3.3 )
Which of the following is NOT one of the methods of Actor that works with images? (4.3.3 )
getImage()
setImage(String)
setImage(GreenfootImage)
changeImage(GreenfootImage)
True or false: an instance variable is a place to store date in memory. (4.3.4 )
What is the difference between a local variable and an instance variable? (4.3.4 )
True or false: an instance variable is a variable defined in a class for which each object (instance) has a separate copy. (4.3.5 )
What is the purpose of a constructor? (4.3.5 )
If the current image displayed is image1
, what image is displayed after the following code fragment runs? (4.3.6 )
if (getImage() == image1)
{
setImage(image2);
}
else
{
setImage(image1);
}
True or false: there is a separate test condition for both the if
and the else
clause of an if/else statement. (4.3.6 )
^ top
4.4: Counting and Arithmetic
Learner Outcomes
At the end of the lesson the student will be able to:
Count in Java
Discuss the two ways that Java stores numbers
Code simple arithmetic
^ top
4.4.1: Counting Food
Scenario file: lesson4b.gfar (or lesson4b.zip ).
Games need a way to win and a way to loose and scenarios must end
We already have a way to loose our scenario -- the hero gets eaten by a predator!
However, we still need a way to win the scenario
One way we can win our scenario is to count the number of food objects eaten
When our hero eats some number of food objects, say 8, we win the game
We can also play a short success sound when this happens
Counting
To keep track of the number of food objects eaten, we need to count
In Java, we count with a variable, a little arithmetic and an assignment statement
We start by declaring a variable like:
public class Hero extends Mover
{
private GreenfootImage image1, image2, image3;
private int foodEaten;
// other code here
As we discussed in lesson 4.3.4 , we always start an instance variable with the word private
The data type int
means we are storing integer (whole number) data
As we learned before, we assign new values to variables using a single equal (=
) sign
foodEaten = 0; // initialize count to 0
Remember that the equal sign is really an assignment operator and does not denote equality
Thus, unlike math, we may have the same variable on both sides of an equals sign:
foodEaten = foodEaten + 1; // add to count
In an assignment statement, the right-hand side is always evaluated first
On the right-hand side, we read the value of foodEaten
from memory and add 1 to it
Then we assign the value back to the foodEaten
variable as the concluding step
As a result, the variable is incremented by 1
Increment and Decrement Operators
When Pre- and Post- Increment Matters (Optional)
Check yourself
True or false : the following variable is an instance variable.
private int count;
The value of count
after the following code executes is ________ .
int count = 0;
count = count + 1;
In the following assignment statement, the ________ side of the equals sign is evaluated first.
count = count + 1;
^ top
4.4.2: Winning the Game
Method lookForFood()
With Win Condition
/**
* Checks whether we have stumbled upon a food object.
* If we have, then eat it. Otherwise, do nothing.
*/
public void lookForFood()
{
if (isTouching(Food.class)) {
removeTouching(Food.class);
Greenfoot.playSound("slurp.wav");
foodEaten = foodEaten + 1;
World w = getWorld(); // w is a reference variable
w.showText("Score: " + foodEaten, 42, 12);
if (foodEaten >= 8) {
Greenfoot.playSound("success.wav");
w.showText("You Win!", 315, 200);
Greenfoot.stop();
}
}
}
Testing Our Code
We should always test our code after any change to make sure it works correctly
In general, we should test our code every time we make a change
To test our counting code, we inspect our Hero
object
When the scenario runs, notice how the foodEaten
variable increments each time the hero eats a food object
Displaying Text
One of the methods of the World
is showText()
The showText()
method will display text at a specified location in the world
The method has the following signature:
void showText(String text , int x , int y )
Where:
text : literal text (in double quotes) or a String
variable
x : the x coordinate of the location where the object is added
y : the y coordinate of the location where the object is added
To call the method, we supply arguments for the parameters like:
getWorld().showText("Score: " + foodEaten, 30, 100);
Since showText()
is a method of the world, we must prefix the method call with getWorld().
The Actor
method getWorld()
returns a reference to the world in which the actor exists
Check Yourself
True or false : when an object contains an instance variable, we can see the value of the instance variable by inspecting the object.
The three statements for counting food are:
________
________
________
After every change, one should ________ the code.
The world method for displaying text to the game screen is ________ .
^ top
4.4.3: More About Numbers
While we are working with numbers, lets discuss how Java handles them
Java has two general types of numbers: integers and floating-point (decimal)
Both integers and floating-point numbers cannot have any commas or other special symbols
Integer Numbers
An integer is zero or any positive or negative number without a decimal point
For example:
0 1 -1 +5 -27 1000 -128
We call numbers like these literal integers because they represent what they look like
Floating-Point Numbers
Storing numbers
Integers and floating-point numbers are stored in different ways
Java stores the integer types as a binary number
Image source: Dan Gookin
Java stores floating point numbers in a format known as IEEE 754
Image source: Dan Gookin
We must specify the data type of a variable so the computer can handle numbers correctly
Some Commonly Used Numerical Data Types
Type
Bytes
Use
int
4
Integers with a range from -2,147,483,648 to 2,147,483,647.
float
4
Single-precision, floating-point numbers with 6 or 7 significant digits, +/- range, and exponents from about 10-45 to 1038 .
double
8
Double-precision, floating-point numbers with 14 to 15 significant digits, +/- range, and exponents from 10-308 to 10308 .
Check yourself
The two types of numbers in Java are ________ and ________ .
Of the following literal numbers, the integer is ________ .
1
1.2
1.23
1.234
If you want to count with whole numbers, use the data type ________ .
^ top
4.4.4: Arithmetic
When we work with numbers, we often want to perform some simple arithmetic
Java uses the following operators for arithmetic:
+
for addition
-
for subtraction
*
for multiplication
/
for division
%
for modulus (remainder after division)
Modulus is a type of division operation for integer numbers
Precedence Rules
Examples of Expressions
Algebra Expression
Java Expression
Fully Parenthesized
2(10 + 5)
2 * (10 + 5)
(2 * (10 + 5))
1 12.2 + 3 · 7.3
1 / (12.2 + 3 * 7.3)
(1 / (12.2 + (3 * 7.3)))
10 - 7 3.2 + 9 · 1.6
(10 - 7) / (3.3 + 9 * 1.6)
((10 - 7) / (3.3 +(9 * 1.6)))
2 · 42
2 * 4 * 4
((2 * 4) * 4)
Integer Division and Remainder
More Information
Check yourself
The five arithmetic operators in Java are ________ .
+, -, /, *, %
+, -, \, *, %
+, -, /, *, ^
+, -, \, *, ^
The first operation performed in the following arithmetic expression is ________ .
1 + 2 * 3 / 4 % 5
If we wanted a different ordering of operations in the above example, we add ________ to the expression.
^ top
Exercise 4.4: Finishing the Game (5m )
In this exercise, we add a successful ending condition (win!) to our scenario.
Specifications
Start Greenfoot and open the Hero scenario from the last exercise .
If you do not have your exercise, start with this one: lesson4b.gfar (or zip ).
Add an instance variable to the Hero class named foodEaten
that is suitable for storing integer numbers:
private int foodEaten;
In the constructor of the Hero class, set the value of foodEaten
to zero (0
).
foodEaten = 0;
In the lookForFood()
method, add code to increment the value of foodEaten
.
foodEaten = foodEaten + 1;
For more information see lesson: 4.4.1: Counting Food .
Save the following sound file in the scenario "sounds" folder: success.wav
For more information see lesson: 3.5.3: Adding Sound .
In the lookForFood()
method, add code to test the number of food eaten and play both the success.wav sound and stop the game.
public void lookForFood()
{
// .. some code omitted here
foodEaten = foodEaten + 1;
if (foodEaten >= 7) {
Greenfoot.playSound("success.wav");
Greenfoot.stop();
}
}
For more information see lesson: 4.4.2: Winning the Game .
Save a copy of your completed lesson scenario to upload to Canvas as part of the next lab (Lab 4).
When finished, please help those around you and then try the following Crossword Puzzle.
Crossword Puzzle
Fill in the crossword which is based on concepts from this section.
As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 4.4.5: Summary .
^ top
4.4.5: Summary
Check Yourself
Answer these questions to check your understanding. You can find more information by following the links after the question.
What is the value of count after the following code executes? (4.4.1 )
int count = 0;
count = count + 1;
True or false: You should always test your code after making changes. (4.4.2 )
How can you tell the difference between an integer and a floating-point number? (4.4.3 )
Which of the following is an integer? (4.4.3 )
1
1.2
1.23
1.234
What are the five operators Java provides for arithmetic? (4.4.4 )
What is the first operation performed in the expression: 1 + 2 * 3 / 4 % 5? (4.4.4 )
^ top
4.5: Sharing Scenarios
Learner Outcomes
At the end of the lesson the student will be able to:
Share your scenarios with others
Publish scenarios on the web
^ top
4.5.1: Exporting Your Scenarios
When we finish a scenario, we may want to share it with others
Users of our work need to start and run the scenario, but not to see the class diagram or source code
Greenfoot has the capability to export a scenario so that others can use, but not change, our scenario
Also, we can decide whether to share our source code or not
Documenting Our Work
Exporting Scenarios
To export scenarios, we click the Share button
After this, we will have a choice of three export options:
Publish adds your scenario to the Greenfoot Gallery on the web at greenfoot.org/home
Application produces an executable JAR file that will run on any computer with Java installed
Project makes a zip-like project folder called a GFAR.
We will look at each of these options in the following sections
^ top
4.5.2: Publishing on the Greenfoot Gallery
The first export option lets you publish your scenario to the web at greenfoot.org
The Greenfoot gallery is a public site that lets anyone see and run your scenario
The Greenfoot site automatically converts scenarios using the TeaVM transpiler
To submit scenarios or post comments, we need to register
During our first quest (Q1: Getting Started ) we all registered using our Avatar name
Registration is to make sure everyone follows the rules of:
Be nice
Don't do anything stupid, offensive or illegal
When we choose this option, we will see a dialog like that shown below
We can change or even delete any scenarios that we upload
Dialog Options
Notice the "Cabrillo" tag
This lets us find other Cabrillo students
Another option is to lock your scenario
Locking a scenario removes the Act button and the speed slider
Typically you lock the scenario for games
However, if you have a more experimental simulation, you can export your scenario without locking
Export to Gallery Dialog
^ top
4.5.3: Exporting to an Application
The second option is to export as an application
An application is a program that users can run on any computer with Java installed
Java application files have a suffix of .jar
, which is short for J ava AR chive
To distribute your scenario, you just give people a copy of your executable JAR file and some install instructions
The instructions need to include the commands to run on their machine
Unfortunately, starting with Java 11 these commands are complicated
For more information see: Running Exported Standalone Scenarios
Export to Application Dialog
^ top
4.5.4: Exporting to a Greenfoot Project
Another option is to create a project .gfar
file
This allows the whole project to be given to someone as a single file
Then anyone with Greenfoot installed can open and run the project
This may be useful while working with other guild members
Export Project Dialog
^ top
Exercise 4.5: Exporting (5m )
In this exercise, we export our Hero scenario.
Specifications
Start Greenfoot and open the Hero scenario from the last exercise.
Press the Share button in the upper left-hand corner of the main screen.
Click the Project menu.
Export the Hero scenario as a Greenfoot Project and save the file to a convenient location like the Desktop.
For more information see lesson: 4.5.4: Exporting to Greenfoot Project .
There is no need to turn in the exported file.
As time permits, be prepared to answer the Check Yourself questions in the section: 4.5.5: Summary .
^ top
4.5.5: Summary
Greenfoot makes it easy to share your scenarios with others
We may publish on the web using the Greenfoot Gallery
The Greenfoot Gallery is a public web space that the makers of Greenfoot provide
Anyone can view and use the scenarios on the gallery
However, to submit scenarios or post comments, we first need to register
We may create an executable JAR file that people can run on any computer with Java installed
However, instructions for running can be complicated
We may also export to a project that anyone with Greenfoot installed can run
This option may be useful when working on projects with others
Check Yourself
Answer these questions to check your understanding. You can find more information by following the links after the question.
What are three ways to share your scenarios? (4.5.1 )
True or false : anyone can publish to the Greenfoot Gallery as long as you register. (4.5.2 )
True or false : exporting as an application creates a JAM file. (4.5.3 )
True or false : exporting as a project lets you share your complete scenario with others. (4.5.4 )
^ top
4.6: Guild Next Steps
Learner Outcomes
At the end of the lesson the student will be able to:
Describe the typical phases of a guild
Describe how to develop a high-perfoming guild
Develop an action plan for the guild
^ top
4.6.1: Phases of Guild Development
When guilds, or any team, develops they tend to go through stages
Forming: members learn about what they need to do
Storming: members form opinions about other members and often voice those opinions
Norming: guild members take responsibility to meet goals and work towards the group's success
Perfoming: with group norms and roles established, members focus on achieving goals
Forming
Guild members get to know each other during this stage
Most guild members are positive and polite
Some members are anxious to understand what the group will do
People make an effort to get to know each other
During this stage it is important to select a leader to help organize the group
Storming
In this stage, people start to push against the initial boundaries
Members often develop conflict because of different people's working style
People may become frustrated with differences in each other's approach
Some members may even refuse to complete their tasks, leaving the projects in disarray
Disagreements and personality clashes must be resolved so the team can progress
During this stage it is important to resolve conflicts quickly if and when they occur
By defining standards of behavior, the group can move past this stage
Norming
In this phase, members start to resolve their differences
Members start tolerating the whims and fancies of the other team members
They accept others as they are and make an effort to move on
People start to build on each other's strengths
Members are able to ask one another for help and provide constructive feedback
Perfoming
In this stage the team works hard without friction to achieve goals
The guild makes most of the necessary decisions to meet goals through consensus
More Information
^ top
4.6.2: Canvas Communication Tools
Canvas has a number of communication tools that can help your guild
People
The People page shows all the users enrolled in the course
The Groups tab shows all the current members of your guild
If a student member chooses to do so, the student can add information to their account profile
For example, a student could add contact information
More information: How do I use the People page as a student?
Chat
The Chat tool allows students and teachers to interact in real time
It is like texting but within Canvas
Everyone actively viewing the chat tool appears in the chat list
A guild could arrange to meet during a certain time through chat
More information: How do I use Chat as a student?
Collaborations
Canvas allows multiple people to work together on the same document at the same time
Documents are saved in real-time, meaning a change made by any of its users will be immediately visible to everyone
Google Docs is the default collaborations tool
Each collaborator will need a Google account to use this tool
A guild could use a collaboration to develop an action plan or game proposal
More information: How do I create a Google Docs collaboration as a student?
Pronto app is also available inside Canvas or on your phone
Google Drive
Non-Canvas Tools
Discord : free voice and text chat for gamers
Skype : free video and voice chat over the internet
Teamspeak : free voice and text chat for gamers
^ top
4.6.3: Guild First Goals
First guild goal: decide on a name for the guild (due today)
Second guild goal: get to know each other and choose a leader willing to help all the members
Third guild goal: Develop guild norms.
Fourth goal will be to work together to develop a scenario in Quest 6
What Sets Successful Groups Apart from Others?
Psychological safety : Can we try new things on this team without feeling insecure or embarrassed?
Dependability : Can we count on each other to do high quality work on time?
Structure and clarity : Are goals, roles, and execution plans on our team clear?
Meaning : Are we working on something that is personally important for each of us?
Impact : Do we fundamentally believe that the work we're doing makes a difference?
Good Guild Norms
Establish psychologically safe environments
No bullying. To succeed, each and every team member must feel confident speaking up and making mistakes. Each member must know they are being heard.Suggestion : Start team's first meeting by sharing something about yourself.
All teams members speak roughly the same amount
Otherwise the collective intelligence declines.
Member's listen to each other and are sensitive to member's feelings.
Chat before and after meetings. Joke around and have fun.
Express enthusiasm for one another's ideas.
Ask a lot of questions.
Always have goals and a plan to meet them.
Set clear action items so everyone knows what is expected and by when
Develop a culture of dependability.
We work as much as it takes to get things done on time.
More Information
^ top
Wrap Up
Due Next: Q3: Methodical Improvement (2/20/20)
B4: Thinking clearly (Canvas) (2/25/20)
Lab 4: White Blood Cell (2/25/20)
Q4: Finishing Touches (2/27/20)
When class is over, please shut down your computer
You may complete unfinished lesson exercises at any time before the due date.
^ top
Last Updated: April 05 2020 @21:21:59