3 RD Activity PDF
3 RD Activity PDF
Principles of Programming
Module 3
Module 3
More about methods
Introduction
Last week we covered some big ideas – inheritance (subclasses and superclasses), method calls
with arguments, the sequencing of commands, and using conditions to let our program make
choices between two alternatives.
It may feel like we didn’t do much hands-on programming – as in typing code. That’s ok at this
point, you are learning some big concepts without getting bogged down in the syntax - the
structure of statements in a computer language. Of course to become a programmer, you will
need to learn the programming language as well, and this week we will be adding to your
knowledge of syntax and object-oriented coding generally.
We will continue with our ‘little-crab’ scenario, adding random movement to our crab, adding a
new class for a food source for our crabs, and adding an ‘enemy’. You will be able to start on your
assignment 2 program after this week’s work. In next week’s work we will add keyboard control
for our crab, to make this scenario more interactive.
For the rest of this unit, I will be adding sections for those students who are curious about a
particular concept and want to go more ‘in-depth’. These sections are surrounded by an aqua
(greeny-blue) rounded rectangle, and are optional. If you are finding the current work challenging
enough, please feel free to ignore these optional sections.
Study materials
Materials required:
The free Greenfoot programming environment;
Files in "Module03" folder on MySCU site;
Concepts
random numbers
dot notation
static methods
class methods
compilation
less-than operator
greater-than operator
comparison operators
range of numbers
packages (optional)
method definition
Greenfoot API
refactoring
saving projects
Activity 3-1
if ( condition )
{
// code goes here
}
What is the part between the { } called?
_____________________________________________________________________
7. When is the code between the { } executed?
______________________________________________________________________
and so on. We would expect that 30% of the time, the crab would be turned.
For this to work, the ‘guesses’ of the computer need to be random. If we want to add any level of
unpredictability to our programs, we need to use random numbers in them.
Write down 5 numbers between 1 and 100, with no pattern to the numbers.
___________________________________________________________________________
Random numbers have no pattern, and it is equally likely to get any number in the range. As we
are humans, we can relatively easily think of 5 random numbers, but thinking of large amounts of
random numbers, with no discernible pattern, and having each number equally likely (on
average) to occur is difficult.
It’s very unlikely that you will ever have to write a program to generate random numbers. Nearly
all programming languages already have a method that will produce a random number in a range.
Java has a random number generating method as well, as part of its Math class. Greenfoot has
used this method to create its own method for producing random numbers, which is a little easier
to remember.
The Greenfoot method for generating a random number is called getRandomNumber and it
expects an integer argument that is the limit of the number. It will return a value between 0 and
the limit.
Optional:
Java's random number generator is Math.random() and produces a random number
between 0 and 1. As we haven’t dealt with other numbers other than integers yet, and the
use of the Java function causes some issues with fractional numbers as results, we will stick
with the Greenfoot adaption for the time being.
How do random number generators work? Random number generating methods don't
actually generate truly random numbers.
If we look in the Actor class, there is no getRandomNumber() method. There is also none in the
World class documentation (please check this).
In fact, we have to use the Greenfoot documentation to find out about this method.
In Greenfoot, click on the Help menu and then "Greenfoot Class documentation". Click on
Greenfoot. This class has a number of methods that will help in code for Actors and the World.
Scroll through the methods, until you find the getRandomNumber method. Write down what this
method does:
_____________________________________________________________________________
_____________________________________________________________________________
If we try to use this method as getRandomNumber(20) in our crab code, to find a random number
between 0 and 20, then the compiler will throw an error.
The reason this happens is that Greenfoot will look for a method called getRandomNumber in the
Crab methods. When it doesn’t find it, it will look for this method in the superclass (Actor). In this
case it won’t find the method there either.
The static identifier at the beginning of the getRandomNumber() method signature in the
Greenfoot documentation tells us how to use this method. The “static” means that this method
belongs to the class (rather than objects as we have seen so far). Both static methods and object
methods are defined within a class. The difference between them is the ‘static’ keyword at the
front of the method signature.
We use static methods by identifying the class they come from like this:
class-name.method-name (parameters);
With the Greenfoot documentation open, find another five static methods in the Greenfoot class
that return either a boolean or an int. Write an example of how you might call each.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
ISY00245 Module 3 - Page 5
Activity 3-5 Random Number expressions
Write a Greenfoot method call to find the following (the first is done for you):
1. a number between 0 and 10 Greenfoot.getRandomNumber(10)
2. a number between 0 and 2169 ____________________________________________
3. a number between 1 and 11 _______________________________________________
4. a number between 5 and 15 _______________________________________________
5. an even number between 0 and 20 __________________________________________
(remember the multiplication sign in Java is * )
6. a number between -5 and 5 ________________________________________________
7. a number between -45 and 45 ______________________________________________
8. a number between -10 and 415 _____________________________________________
9. a number between -10 and 0 _______________________________________________
10. an even number between -20 and +20 ________________________________________
So far, we can’t actually USE the getRandomNumber() method, because we need some more
information about the Java language. It turns out that we will need some maths to do this. If you
don’t like maths, please don’t get disturbed by this, we will take it one step at a time.
If you are comfortable with maths, we will summarise the information first, and then you can skip
to the activity.
It turns out its easy to remember which is which. The small end (pointy end) of the < is the end
that goes to the smallest number when this condition is True.
The <= and >= operators are true if the numbers are equal or less-than/greater-than.
For example, 7 <= 7 is true and 6 >= 6 is true.
Using the table above, determine whether the following are true or false:
1. 7 < 10
2. 66 > 88
3. 15 == 10 + 5
4. 98 >= 89
5. 50 <= 20
6. 70 != 2 * 35
7. 7 + 2 < 20 - 6
8. 7 + 2 != 20 - 6
Now you have an understanding of random numbers, and comparison operators, we are in a
position to create a condition for our test (the “if” code).
/* turn the crab randomly */
if ( Greenfoot.getRandomNumber(100) < 10 )
{
turn(4);
}
Implement the above code in your crab scenario. Test and make sure your crab is turning
randomly around once every 10 moves. Place a second crab and see if it is turning as well.
At the moment the crab only turns 4 degrees each time, always in the same direction. It would be
great if the crab turned a random number of degrees, say between 0 and 45 degrees.
What would you need to change in the current code, to make this happen?
At the moment, the crab only turns right. This is because we have only a positive number in our
random number for the turn.
turn(Greenfoot.getRandomNumber(45));
To make it turn right and left, we will need to find a random number between -45 and 45. You
should be able to find this from Activity 3.5.
Change your code and test it.
We now have a crab that is moving around the screen quite erratically. Well done!
The Worm class is going to be visible in the World, so we need to make it a subclass of Actor.
Greenfoot makes creating subclasses of Actor very easy.
Add the Worm class. Add some worms to your world, as well as some crabs. Run the scenario.
What do the worms do? _________________________________________________________
What happens when a crab meets a worm? _________________________________________
The Actor class again provides some useful methods that we could inherit for the Crab class, to do
this. There are two methods that are useful:
boolean isTouching(java.lang.Class cls)
void removeTouching(java.lang.Class cls)
The first of these can be used in an if statement, as it returns true or false. The second one can
remove the worm if it’s touching.
In pseudocode:
if (crab isTouching a worm) then
remove the worm
end if
Both of the methods expect a class as an argument – that is, they expect a type of object in the
world.
Remember that you should always READ first, without doing the exercises, and try to understand
what you are reading. You can then try it out on the computer. Don’t sit by the computer with the
text while reading it for the first time.
Implement the code for eating worms. Try this out with one crab and at least 10 worms on your
world.
Refactoring Code
Sometimes we write code and then realise later that we could have written it in a better way.
Refactoring code is a programming technique used to make code easier to read and easier to
debug (find errors) and edit. We often refactor code after we start to get ‘too many’ lines of code
within a method and/or when we see a common task that can be placed into a method.
As part of our refactoring, we can write new methods, which we can then call from inside other
methods.
Instead, we are going to refactor the code, to make a new method that checks if we have found a
worm, and if we have, eats it. We will call this method lookforWorm().
When we create a new method, we need to think about what are the inputs and outputs to this
method.
In this case, there are no inputs, and in fact, there are no outputs either.
It is good practice to always comment above a new method, so we can start with that:
Under the act() method, after the closing bracket of the act() body, we can add the following:
/* Check whether we have found a worm.
If we have, eat it. If we haven’t, do nothing.
*/
Start with the definition line and body brackets of the method:
public void lookForWorm()
{
The body of the method is then what we have already completed in our act() method – we just
need to move it here.
public void lookForWorm()
{
if ( isTouching(Worm.class))
{
removeTouching(Worm.class);
}
}
The new method exists, but we haven’t called it from the act method. Methods will not do
anything by themselves, they need to be called to be activated.
The act() method is called by the RUN button (again and again). At the moment, nothing is calling
our lookForWorm() method.
If we add the call to our act() method, it will call the method once every time the crab acts. We
probably need to check for worms after the crab moves each time, so the code will be…
public void act()
{
/* other code goes here */
move(5);
lookForWorm();
}
1. Add a new class called Lobster to your scenario. This will be a subclass of Actor and can
use the preprepared image lobster.png.
2. Copy the complete act() method from the Crab class into the Lobster class.
3. Also copy the complete lookForWorm, turnAtEdge, and randomTurn methods.
4. Change the Lobster code so that it looks for crabs rather than worms. Change the name of
the method to lookForCrab. Make sure to update comments, and your call to the method.
5. Test your code.
6. Place a crab, three lobsters and many worms into the world. Run the scenario. Does the
crab manage to eat all worms before it is caught by a lobster?
7. How could you make this easier (programmatically) for the crab?
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
8. How could you make this more difficult (programmatically) for the crab?
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
1. In Greenfoot, choose Greenfoot Class Documentation from the Help menu. This shows the
documentation for all the Greenfoot classes. This is also called the Greenfoot API
(Application Programmers' Interface). It shows all available classes, and for each class, all
the available methods.
2. Write down the nine classes provided by Greenfoot (the first is Actor):
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
_______________________________________________________________________.
3. Select the Greenfoot class, and find the section called "Method Summary". Find a method
that stops the execution of the running scenario. What is this method called?
________________________________________________________________________
4. Does this method expect any arguments? What is its return type?
________________________________________________________________________
5. We can use this method by writing Greenfoot.stop();
Initialising a scenario
It is beginning to become tedious to set up the world after each time we compile a class.
Greenfoot has a way of initialising the world with objects in it, so that when the Reset button is
hit, the scenario will return to a prior state.
Watch the screencast 0306 Saving the World, in the Module 03 folder.
In Greenfoot, set up a crab world with one crab, at least two lobsters and many worms. Save this
world.
You will be exporting this world in the next exercise, as part of your portfolio.
Saving as an application:
In Greenfoot, choose "Share …" from the Scenario menu.
Choose the Application tab, and choose a place to save your application. This creates an
executable JAR file (Java Archive) which can be executed on many operating systems, as long as
the user has Java installed.
Complete the activities to this point in the study guide. In Greenfoot, export your resulting program,
as an application. Save in your portfolio folder.
In Greenfoot, export the program in Activity 3-16 as a Greenfoot Archive. Save in your portfolio
folder.
Summary
During this topic we have used random numbers and built-in methods to create random
behaviour in our Actors. We have learned some complex topics such as static methods. We used
comparison operators in IF statements to test conditions, and also created new Actor classes.
We handled simple collisions and used built-in methods to remove objects from the world.
One of the most important parts of this module was the section on refactoring code. Refactoring
code is a constant task in programming. Whenever we believe that a method is getting too
complex, or has code that is likely to be repeated, we should refactor that code, by creating a new
method.
Finally we did some Greenfoot housekeeping – learning how to initialise the world, and how to
export our projects to executables, as well as creating project archives.
Remember that the more practice you get in these first weeks, the easier you will find the second
half of the unit. Continue to practice practice practice.
Next module we will be continuing to program with our little crab scenario. We will add
interactivity (keyboard control), sounds, and work on your first programming assignment.
Activity R3-1
Think of three situations (not necessarily games) where you would use random numbers.
_______________________________________________________________________
_______________________________________________________________________
Activity R3-2
Activity R3-3
When you are using the Greenfoot.getRandomNumber(int) method, are you using inheritance?
Why or why not? _________________________________________________________
_______________________________________________________________________
_______________________________________________________________________
Activity R3-4
1. Ensure you have completed the previous activities before going further.
2. Change your code so that if the cat ends up at the edge, the program stops.
3. Export your project as a stand-alone application.
4. Save your project as a Greenfoot archive, in your portfolio folder. This will become part of
your portfolio.