Académique Documents
Professionnel Documents
Culture Documents
Principles of Programming
Module 5
Module 5
Variables
Introduction
We begin this week with reviewing some of the things you have been learning in the first four
modules. You need to have a really strong grasp on these before you can go further.
This week we will also be creating new objects from Classes using code, rather than using drag
and drop or <Shift>+Click as you have previously. We will also put some animation in place, using
the GreenfootImage class, and use the count of the worms that we implemented last time, to
work out when the player wins the game. Along the way, we will introduce some more Java
concepts. This week you should be able to add animation to your assignment, if you wish to do
so.
Study materials
Materials required:
The free Greenfoot programming environment;
Files in "Module05" folder on MySCU site;
Concepts
modifier
private
public
double
static methods
method signatures
parameter
return type
return
new keyword
animation
GreenfootImage
constructor
instance variable
if – else
object inspector
This memory location has a name and a type. When we create a variable, we say we are
declaring the variable, or making a variable declaration. The variable declaration does three
things:
1. it gives the new variable a name;
2. it specifies the type of value that will be stored within the memory location (eg: String, int
or boolean); and
3. it specifies whether this variable will be used just within the class/objects (“private”) or
whether other classes will be able to see it and use it (“public”).
We would expect that this “declaration” was going to be complicated as it does all these three
things, however it’s quite simple.
For example, a new variable of type “int” with name userAge that we wish to use only inside the
class could be declared by:
private int userAge;
A boolean value that we would like other classes’ code to be able to use, called “isFinished’ would
be declared as:
public boolean isFinished;
Modifiers
In fact, in some cases we can leave off the ‘public’ or ‘private’ – if we do this, then it will default to
another modifier “protected”. In this case this variable would only be able to be accessed by this
class’s code and code in any classes which are subclasses of it. If this is too complex at the
moment, that’s fine – you just need to know that it is legal to leave off the modifier – although we
don’t recommend it at the moment.
Storing Values
Note that the code above doesn’t actually store anything in the variable (memory location). To
do that, we need to assign a value to the variable – called initialising the variable.
userAge = 10;
isFinished = false;
Optional:
If you don’t initialise the variable, what is stored in it? By the Java documentation, it is “a
reasonable default”. For int this is usually 0, and boolean it is false, but you can’t count on
this being the case, so please make sure you initialise your variables.
For example:
void setDirection(int direction)
Other method signatures show that a value is returned from the method when it’s called – we
have said previously that methods like this are really asking a question. Examples of this are:
boolean canMove();
boolean foundLeaf();
int getLeavesEaten();
For each of the following method signatures, identify the name, return type, parameter type (or
types if there is more than one parameter) and parameter names.
7. void act()
8. int getRotation()
9. boolean isAtEdge()
10. boolean isTouching(Class cls)
11. void move(int distance)
12. void setImage(String filename)
13. void turnTowards(int x, int y)
14. World getWorld()
15. boolean intersects(Actor otherActor)
16. int getRandomNumber(int limit)
17. boolean isKeyDown(String keyname)
18. boolean mouseClicked(Object obj)
Static methods
In Module 4 we also discussed class or static methods - methods that could not be used unless
we specify the class from which they originate.
For example, getRandomNumber is a static method that belongs to the Greenfoot class. We
know this because if we look at the documentation, it says under "Modifier and Type" ..
Find four static methods in the Greenfoot class. Identify their names, return type, parameters and
give an example of how you would use them.
Methods start with a modifier – either private or public – depending on whether we want to be
able to call them from within this class’s code, or we think another object’s code might call the
method.
The method signature follows the modifier, and this is followed by the body of the method – the
code that actually makes the method do something.
For example:
Modifier
Body of method
The method in this particular example doesn’t return any value (that’s why it has void in the
method signature).
In Module 4 we also looked at methods that return a value. The only differences are that we need
to
identify the type of value they will return, in the method signature; and
have at least one “return” statement in the method.
For example:
We specify the type of value returned – an int – and we have a return statement in the body of
the method.
This is the end of our review, and we are now going to extend these concepts into new concepts.
Java distinguishes between primitive types and object types. Object types can be recognised
because, by convention, they always start with a capital letter. Every String you use is actually an
object created from the String class. We can use it like a primitive type (as we have been doing)
but it has its own methods which help us to manipulate Strings.
For example, the String class has methods to compare strings, to convert to all upper case letters,
to find a substring of a string, to find the length of a string, and more. These are all very useful, as
we don’t need to code any of these ourselves!
We won’t be going any more into the String class in this Module, but it is an example of an object
class, rather than a primitive class.
To create a new object from a class (type) we need to use declaration and initialisation. We also
have to use another Java keyword – new.
Let’s set up our CrabWorld so we can work through this with an example.
Open your little-crab scenario (the one where you saved the world with some lobsters, worms and
a crab). Open the CrabWorld class, and delete the prepare method, and the call to the prepare
method in the CrabWorld constructor.
That’s great – we have a Crab variable – but we haven’t put anything in it! We need to create a
new actual Crab using the constructor of the Crab class, and put it in the variable. Remember the
constructor is a method that is named the same as the class. We also use the ‘new’ keyword:
Crab myCrab = new Crab();
In the little-crab scenario, under the existing code in the constructor, add the above line:
The ‘x’ and ‘y’ are the coordinates where we want the object in the world. Coordinates are
measured from the top left corner.
What is the ‘object’ we are using? It’s the variable myCrab, which we just declared and initialised.
Crab myCrab = new Crab();
addObject(myCrab, 250, 200);
Add the extra line of code, compile, and make sure this is working for you.
Try other values of x and y.
Animating Images
To make the game a little more realistic, we will animate the image of the crab, using the two
images we found in the last module in the images folder (crab.png and crab2.png). If you recall,
when we create a new sub-class of Actor, we choose an image for the new class. This image is
then used to represent the objects that are created from the class.
A simple animation will be to switch the crab’s image back and forward between the two images
crab.png and crab2.png. Our eyes will fill in the in-between images.
You will notice that the getImage() method returns a GreenfootImage object, and setString()
expects either a String (representing a filename) or a GreenfootImage.
Don't be too concerned about the fact that there is two setString methods - we will go more into
this in further topics. In this topic we will use the setString version that expects a GreenfootImage
object as the parameter.
3. This is all the ways that we can construct a new GreenfootImage. Which one should we
use if we have a filename (eg: "crab.png") ?
______________________________________________________________________
4. To create a new GreenfootImage object, we can use the new keyword - in the same way
as we used new to create a new Crab object called myCrab.
5. Open little-crab if you don't already have it open.
To declare a variable that we can use in all the methods of a class, we need to declare it outside
all the methods, but in the class. This is called an instance variable or a property or a field.
wormsEaten is a variable that is declared outside the Crab() constructor and can be used in the
constructor and in the act() method and in all other methods of the class Crab.
In the same way, we can declare two GreenfootImage objects called “image1” and “image2”
without having to initialise them yet. All this does is set up the memory locations ready to be
filled with GreenfootImage objects.
public class Crab extends Actor
{
private int wormsEater;
private GreenfootImage image1;
private GreenfootImage image2;
Our next job is to initialise these GreenfootImages with our files. The best place to do this (since it
is only done once at the beginning of this object’s lifetime) is in the constructor.
public class Crab extends Actor
{
private int wormsEater;
private GreenfootImage image1;
private GreenfootImage image2;
/* constructor */
public Crab()
{
wormsEaten = 0;
image1 = new GreenfootImage(“crab.png”);
image2 = new GreenfootImage(“crab2.png”);
}
created from the files “crab.png” and “crab2.png” that are in the images folder.
We can now use these two GreenfootImage variables called image1 and image2, to set the crab’s
image using the inherited-from-Actor method setImage().
So where do we do this? We would like it to change from image1 to image2 and vice-versa pretty
quickly, over and over again. The act() method is called over and over again when the Run button
is pressed, so this looks like a likely candidate!
In pseudocode:
if (the image of the crab is image1) then
set the image to image2
otherwise
set the image to image1
end if
The “otherwise” can only happen if image2 is showing, as either one or the other must be true.
Java uses “else” for the alternative. We could rewrite our pseudocode as:
if (the image of the crab is image1) then
set the image to image2
else
set the image to image1
end if
This code will go in the act() method. Make sure you understand this before going further.
has enemies (lobsters) which can eat the crab and cause the player to lose the game
We already have a variable which counts the number of worms that have been eaten. If we set
another variable that stores the total number of worms, we can compare the number eaten to
the total number of worms, and if they are the same, we can play a sound (fanfare?) and stop the
game.
1. Read the previous section "Finishing the Game" if you haven't already. You already know
how to do all these tasks, from previous work in this module and other modules.
2. In your program from Activity 5-10, do the following activities:
3. Declare a variable with an appropriate name that will store the total number of worms
4. Initialise the number of worms, in a method that will be useful for this job
5. Find the spot in the code where you should do a test to see if the game has been won.
6. Code the test and make sure that if the crab has eaten all the worms, the sound plays, and
then the game stops.
7. Save your game as a Greenfoot archive in your portfolio folder.
During this week you will be completing your assignment, so the workshop activities are less than
in previous weeks. Some of these activities may be useful to extend your assignment.
Ask your tutor if you are having problems with any of the material in this week’s topic.
Workshop activities
Activity R5-1
1. Using your program in Activity 5-11 make the lobsters a bit more dangerous. The Actor
class has a method called turnTowards. Use this method to make the lobsters turn towards
the centre of the screen occasionally. Experiment with the frequency of doing this, and
also with different walking speeds for lobsters and the crab.
Activity R5-2
Activity R5-3
Modify your game's time counter to be a game timer. That is, initialise the time variable to some
value (for example, 500), and count down (decrement the variable by 1) at every act step. If the
timer reaches zero, make the game end with a "time is up" sound. Experiment with different values
for the game time.
1. Investigate the showText method of the World class. How many parameters does it have?
What are they? What does it return? What does it do?
2. Display the game timer on screen using the showText method. You can do this in the
CrabWorld's act method. You need a statement similar to this:
showText(“Time left: “+ time, 100, 40);
where time is the name of your timer variable.