Sunteți pe pagina 1din 16

ISY00245

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;

 "Introduction to Programming with Greenfoot" textbook and support files;


 Internet access to access your lecture, and any other material.

ISY00245 Module 5 - Page 1


Objectives
On completion of this topic, you should be able to:
 declare, initialise and use primitive int, boolean and double variables
 declare, initialise and use object variables
 identify modifiers
 identify the parts of a method signature
 identify return types and parameters
 use static methods
 create new methods that return primitive types
 create new GreenfootImage variables
 use GreenfootImage variables to create animation
 use the object inspector to monitor variables

Concepts
 modifier
 private
 public
 double
 static methods
 method signatures
 parameter
 return type
 return
 new keyword
 animation
 GreenfootImage
 constructor
 instance variable
 if – else
 object inspector

ISY00245 Module 5 - Page 2


Review: Declaring and using variables
You will recall from the content of Module 4 that a variable is a named memory location within
the computer. If it helps, think of memory location as a “box” that will contain one value (and
only one value).

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;

modifier: type: name:


this variable will this variable will the value in this
only be used store a value that variable will be
within the class is an integer. referred to by this
code. name in our code.

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.

ISY00245 Module 5 - Page 3


A new type: double
You may have been wondering how we represent decimal numbers such as 0.5 or -123.8037. Java
provides several other types, which we will meet during this unit, but the most common for these
kinds of numbers is the type double. To declare a public double called “speedFactor” we would
write:
public double speedFactor;

and to assign the value 0.4 to it, we could write:


speedFactor = 0.4;

Shortcutting declaring and initialising


We can actually shortcut this process a little by putting this all on one line:
public double speedFactor = 0.4;

Just remember what this is actually doing is two steps:


1. declaring a public variable of type double and name speedFactor; and

2. storing the value 0.4 in the new variable.

Activity 5-1 Declaring and Initialising variables

Write code to declare and initialise the following variables:


1. a public variable called numberSquare with initial value 4
2. a private variable called isEmpty with initial value false
3. a public variable called score with initial value 0
4. a public variable called checkCollision with initial value true
5. a private variable called asteroidSpeed with initial value 1.3
6. a public variable called messageString with initial value "Hello World"

Review: Method Signatures


We have been working with method signatures since Module 1. You may recall that we first
encountered method signatures in our object menu, where we saw what the wombat objects
could do.
The method signatures showed three things:
returnType methodName(parameters)

For example:
void setDirection(int direction)

return type: name: parameter type: parameter name:


this shows what (if this is the name of the type of value the name of the
anything) will be the method – how that this method is value – this will
returned from the we will call it in the expecting. ‘catch’ the value
method. code. that is fed in.

ISY00245 Module 5 - Page 4


The method signatures are just for our information. They tell us lots of information (see the
previous page). They tell us how we can use this method – what the method expects to receive,
and what type of value it will return, if any.
If the return value is “void” then the method won’t return anything.

Examples of this type of method are (from the wombat):


void act();
void eatLeaf();
void setDirection (int direction);
void turnLeft();

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();

Activity 5-2 Method signatures

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

To use it we need to type: Greenfoot.getRandomNumber(10).

ISY00245 Module 5 - Page 5


Activity 5-3 Static methods

Find four static methods in the Greenfoot class. Identify their names, return type, parameters and
give an example of how you would use them.

Review - Writing methods


In Module 3, we looked at refactoring code, by creating our own methods.

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:

Comment method signature

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.

ISY00245 Module 5 - Page 6


Primitive and Object types
Three of the variable types we have used so far are what Java calls primitive types. These types
are double, int and boolean. You may have wondered why the type String has a capital letter,
while double, int and boolean are all lowercase.

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.

Creating new objects in code


Until now, we have been creating new objects in the world by either using the class menu or
<SHIFT>clicking in the world. This has disadvantages, as we cannot create new objects during the
execution of our programs. Our game starts with a certain number of actors and (so far) cannot
have more created after it is exported as a JAR file.

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.

Activity 5-4 Resetting CrabWorld

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.

Your code should look like this:

We are now ready to create our objects via code.

ISY00245 Module 5 - Page 7


The new keyword
When we create a new variable of any type, we have to tell Java what type it is. This time we
want to create a new variable of type Crab. We also have to give it a name – in this case we will
call it “myCrab”. Notice the naming of the object is lower camelCase, and the class is Upper
camelCase.
Crab myCrab;

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();

Activity 5-5 Declaring and initialising our object (Crab)

In the little-crab scenario, under the existing code in the constructor, add the above line:

Compile and run your code - what happens?

Adding objects to the world


Greenfoot’s World class has a method to add objects to the world (so they can be seen).

Read the method signature.

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

Activity 5-6 Adding the crab to the world

Add the extra line of code, compile, and make sure this is working for you.
Try other values of x and y.

ISY00245 Module 5 - Page 8


Activity 5-7 Worms and Lobsters

Add two lobsters and 8 worms to the world.

Refactor your code.

In your textbook, read pages 52 to 59.

Watch the screencast 0501 Adding Objects, in the Module 05 folder.

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.

Actor methods and the GreenfootImage class


We will use the provided methods of the Actor class and the helper GreenfootImage class to
handle our images.

Activity 5-8 Open the Greenfoot documentation.

1. Look at the methods of the Actor class.


2. Identify the two methods that are used to manipulate the image of an actor object. Write
down their method signatures.
______________________________________________________________________
______________________________________________________________________
3. Write down the return type, names and parameters (if any) of the two methods.
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________

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.

ISY00245 Module 5 - Page 9


The important takeaway is that to set the image of the crab, programmatically, we need a
“GreenfootImage” object to use as a parameter. So how do we create new GreenfootImage
objects?

Activity 5-9 With the Greenfoot documentation open -

1. Look at the documentation of the GreenfootImage class.


2. If we look at the part under "Constructor Summary" you will see the following:

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.

Instance variables (or properties)


You may recall that in Module 4 we declared the “wormsEaten” variable outside all the Crab’s
methods, in the class itself.
If we had declared this variable in the constructor code, it would have been only available to the
constructor code. If we had declared the variable in the act() method, it would have only been
available to that method. Greenfoot scope colouring helps us to understand this.

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.

ISY00245 Module 5 - Page 10


Our code starts with this:

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;

/* make our crab act */


public void act()
{
….
// all the rest of the code
}

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”);
}

// all the rest of the code


}

ISY00245 Module 5 - Page 11


Now, remembering what we know about variables:

 we have two memory locations, called image1 and image2,

 which are both of type GreenfootImage, and

 we have placed an image in each,

 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

and we are very close to the actual Greenfoot/Java code.

Translating this to code:


if (getImage()== image1)
{
setImage(image2);
}
else
{
setImage(image1);
}

This code will go in the act() method. Make sure you understand this before going further.

**** Activity 5-10 **** Portfolio Activity

1. Complete the work up until this point to animate the crab.


2. Use the act button to test, then use Run.
3. Refactor your code to make it more maintainable. Test again.
4. Save your work as a Greenfoot archive in your porfolio folder.

ISY00245 Module 5 - Page 12


Finishing the game
Let’s take a step back. We have come a long way. We now have a game which:

 has a crab that can be controlled by the player and is animated

 has enemies (lobsters) which can eat the crab and cause the player to lose the game

 has worms that can be eaten by the player’s crab.

The only thing that we can’t do so far is to WIN the game!


We are going to find a very simple way of finishing the game if the crab eats all the worms before
being eaten by the lobster.

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.

**** Activity 5-11 **** Portfolio Activity

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.

Using the inspector


We can also see the values of our variables as we run our programs. This can help us to work out
errors in our code, if something is not working as expected. Before you run a program, choose
“Inspect …” from the object menu for an object you wish to inspect. Move the inspector window
somewhere where you can watch the program run and see the inspector at the same time. Run
the program and you will see the values of the variables change. Try it out.

ISY00245 Module 5 - Page 13


Summary
During this topic we have revised and extended some important concepts. You have learned how
to create new objects in code, how to initialise those objects, and how to read the documentation
to find out how to create new objects of a particular type.

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

1. Add a time counter to the crab.


2. You can do this by adding an int variable that is incremented each time the crab acts. You
are, in effect, counting act cycles. Think carefully about where you will put the code.
3. Play the game, Once you manage to win, inspect the crab object and check how long you
took. How many act cycles did it take?
4. Move your time counter from the Crab class to the Crabworld class. It makes more sense
for the world to manage time than an individual crab. The variable is easy to move. To
move the statement that increments the time, you need to define an act method in the
CrabWorld class. World subclasses can have act methods just like Actor subclasses. Just
copy the signature of the crab's act method to create a new act method in Crabworld and
place your time counting statement there.

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.

ISY00245 Module 5 - Page 14


Activity R5-4

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.

ISY00245 Module 5 - Page 15

S-ar putea să vă placă și