0% found this document useful (0 votes)
102 views

3 RD Activity PDF

This document discusses methods and random numbers in programming. It introduces the concept of random numbers to add unpredictability to programs. The Greenfoot programming environment has a getRandomNumber method that generates a random integer within a given range, which can be used to randomly alter an object's movement. The document provides exercises to practice using random numbers and reviewing concepts from the previous module.

Uploaded by

Vikram Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
102 views

3 RD Activity PDF

This document discusses methods and random numbers in programming. It introduces the concept of random numbers to add unpredictability to programs. The Greenfoot programming environment has a getRandomNumber method that generates a random integer within a given range, which can be used to randomly alter an object's movement. The document provides exercises to practice using random numbers and reviewing concepts from the previous module.

Uploaded by

Vikram Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

ISY00245

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;

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

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

ISY00245 Module 3 - Page 1


Objectives
On completion of this topic, you should be able to:
 use the inbuilt methods to produce random numbers in a range;
 identify static (class) and object methods;
 use the Greenfoot.getRandomNumber() method in code;
 create a new Actor subclass in Greenfoot;
 set the image for a new Actor subclass in Greenfoot;
 use inbuilt methods to handle collisions;
 create new methods within a class;
 use Greenfoot class documentation

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

ISY00245 Module 3 - Page 2


Review
Before we start on new material, complete the following activity to make sure you remember the
material from last week’s module.

Activity 3-1

Open the little-crab scenario in Greenfoot:


1. Identify the classes in this scenario.
_____________________________________________________________________
2. Create a crab in the world, using the Crab class.
3. Run the scenario and describe the movement of the crab.
_____________________________________________________________________
_____________________________________________________________________
_____________________________________________________________________
4. If the crab does not move (sideways and diagonally), and turn more when it reaches the
edge of the world, write code in the act() method to make the crab do these movements.
5. What method calls did you use?
__________________
__________________
__________________
6. You also used an if statement. An if statement looks like

if ( condition )
{
// code goes here
}
What is the part between the { } called?
_____________________________________________________________________
7. When is the code between the { } executed?
______________________________________________________________________

We will now continue on with this scenario this week.


Keep your little-crab scenario open to work on during this week's work.

ISY00245 Module 3 - Page 3


Random Numbers
The movement of the crab at the moment is very predictable. One way we can make the crab
move erratically, is to turn() the crab only sometimes. How do we decide when it’s going to turn?

One way would be to get the computer to come up with a guess.


me: Think of a number between 0 and 100
Computer: 74
me: if the number is less than 30, then turn(3)
Computer: does nothing

Next time act() is called:

me: Think of a number between 0 and 100


Computer: 25
me: if the number is less than 30, then turn(3)
Computer: turn(3)

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.

Activity 3-2 Guessing random numbers

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.

This method’s signature will look something like:


int getRandomNumber(int 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.

ISY00245 Module 3 - Page 4


They generate numbers that are ‘pseudo-random’ – close enough to random that we cannot
discern a pattern between them. Some use complex mathematical formulae, some use the
computer’s clock as a starting point to feed into the formula, some use the computer’s IP to
feed into the formulae. Basically the function is applied to some hidden internal state of the
generator and its output is used to compute the output of the random method.

Where is the method?

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.

Activity 3-3 Greenfoot documentation

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:
_____________________________________________________________________________
_____________________________________________________________________________

How to use Greenfoot class (static) methods

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

For example, getRandomNumber is used with the Greenfoot class name:


Greenfoot.getRandomNumber(20);

Activity 3-4 Static Methods

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 ________________________________________

Back to the crab


We can now start to think about what we might include in the crab’s act() method to give random
turning times.

public void act()


{
move(5);

/* turn the crab randomly */


if ( code-to-use-random-numbers-goes-here )
{
turn(4);
}

/* if the crab is at the edge, then turn a fair bit */


if ( isAtEdge() )
{
turn(45);
}
}

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.

ISY00245 Module 3 - Page 6


Comparison operators
Java has a number of operators to compare two values. They are:

< less than >= greater than or equal to

> greater than == equal

<= less than or equal to != not equal

Quite a few students have trouble distinguishing < from >.

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.

eg: 5 < 22 is true “5 is less than 22”

700 > 500 is true “700 is greater than 500”

143 < 120 is false “143 is smaller than 120” (false)

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

 == is the equivalence operator.


Using just one equals sign as an operator is a syntax error – a really common one!
For example: 7 == 3 + 4 is true. Note: This isn’t an equation, it is a comparison.

 ! means “Not”, so != means “not equal to”.


You will need to become very familiar with these comparison operators throughout your
programming.

Activity 3-6 Random Number expressions

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

This will turn the crab 10% of the time.

Write an expression that will be true 7% of the time:


_____________________________________________________________________________

ISY00245 Module 3 - Page 7


In your textbook, read pages 31 to 33.

Watch the screencast 0301 Random Movement, in the Module 03 folder.

Activity 3-7 Turning randomly

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?

Try out your changes.

Activity 3-8 Turning randomly right and left

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!

In your textbook, read pages 34 to 35 (down to Adding Worms).

Watch the screencast 0302 Random Turning, in the Module 03 folder.

ISY00245 Module 3 - Page 8


Worms - adding a class
The next thing we are going to do is to add a new class – Worm.

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.

Read the section "Adding Worms" - page 35 and 36 in your text.

Watch the screencast 0303 Adding Worms, in the Module 03 folder.

Activity 3-9 Adding worms

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? _________________________________________

Eating worms (more methods)


This game will not be much fun if the crabs can’t eat the worms. What we would like to happen is
that if a crab touches a worm, it eats it.

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.

Converting this to code:


if (isTouching(Worm.class))
{
removeTouching(Worm.class);
}

ISY00245 Module 3 - Page 9


Read the section "Eating worms" on pages 36 to 37 of your text.

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.

Watch the screencast 0304 Eating Worms, in the Module 03 folder.

Activity 3-10 Eating worms

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.

Starting the crab code


Our act() method in the Crab code is getting quite long:

ISY00245 Module 3 - Page 10


We could keep adding tests and code to make the crab react, but we will end up with a very long
act() method, that will be hard to maintain and modify.

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.
*/

We then need to write the actual method.

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

Of course we need to remove this code in the act() method.


Your act() method should look like:
public void act()
{
/* if the crab is at the edge, then turn a fair bit */
if ( isAtEdge() )
{
turn(45);
}
/* turn at random times */
if (Greenfoot.getRandomNumber(100)<10)
{
turn(Greenfoot.getRandomNumber(90)-45);
}
/* move the crab */
move(5);
}

ISY00245 Module 3 - Page 11


and the lookForWorm() method should look like:
public void lookForWorm()
{
if ( isTouching(Worm.class))
{
removeTouching(Worm.class);
}
}

Activity 3-11 Creating a new method

1. Refactor your code so the new method is created.


2. Run your scenario. Does the crab 'eat' the worms?
3. Explain this behaviour: _________________________________________________
___________________________________________________________________

Calling our new method

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

Read pages 38 - 40 (down to "Adding a Lobster") in your text.

Watch the screencast 0305 Refactoring Code, in the Module 03 folder.

Activity 3-12 Calling the new method

1. Modify your code to call the lookForWorm() method.


2. Test your code.
3. Refactor your code by creating two more methods: turnAtEdge() and randomTurn().
4. Test your code.

ISY00245 Module 3 - Page 12


Adding an enemy
You now have all the information that you need to add an enemy to make the game a little more
exciting. The enemy of a crab is a Lobster.

Read pages 40-41 (down to "Keyboard Control") in your text.

Activity 3-13 Lobsters

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?
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________

Ending execution of a scenario


At the moment, the lobsters keep going after catching the crab. Ideally, we should stop the game
once the crab is caught and eaten by the lobster.

Activity 3-14 Ending execution

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

ISY00245 Module 3 - Page 13


6. Decide where this code will need to be added. Add this line of code there.
7. Test your scenario.

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.

Activity 3-15 Initialise the crab world

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 your work


We are now going to look at two ways of saving your work – saving as an application (which
cannot be modified, it can only be played), and saving as a Greenfoot archive (gfar) which is how
the sample scenarios are distributed.

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.

*** Activity 3-16 **** Crabworld Application

Complete the activities to this point in the study guide. In Greenfoot, export your resulting program,
as an application. Save in your portfolio folder.

Export to Greenfoot Archive:


In the same “Share ..” section, there is a Project tab. Use this to create a standalone project gfar
file. This project file saves all media, code, etc in a project. From now on you will be saving gfar
archives and exporting to applications to add to your portfolio.

ISY00245 Module 3 - Page 14


*** Activity 3-17 **** Crabworld Archive

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.

ISY00245 Module 3 - Page 15


Workshop activities

Activity R3-1

Think of three situations (not necessarily games) where you would use random numbers.
_______________________________________________________________________
_______________________________________________________________________

Activity R3-2

When we find a random number in Greenfoot, we use Greenfoot.getRandomNumber(int).


Why do we use the Greenfoot in front of the method call, and dot notation?
_______________________________________________________________________
_______________________________________________________________________
_______________________________________________________________________

Activity R3-3

When you are using the Greenfoot.getRandomNumber(int) method, are you using inheritance?
Why or why not? _________________________________________________________
_______________________________________________________________________
_______________________________________________________________________

Activity R3-4

1. Open your fatcat scenario on which you worked in Module 2.


2. Change your code so that the cat performs some of the following actions:
a. waits for a random time
b. walks a random distance to the left
c. walks a random distance to the right
d. shouts hooray randomly (about 1% of the time)
e. sleeps for a random amount of time
f. does a dance randomly (about 5% of the time)
3. You may have to experiment with some values to make your program work well.
4. You can combine these in any order and intersperse with your other code about being tired
and bored.
5. What happens if the cat randomly walks to the right several times in a row and ends up at
the edge?
6. Can you work out what you could do in this case?

ISY00245 Module 3 - Page 16


Activity R3-5

1. The fatcat's act() method will be very long.


2. Refactor the code so it is more modular.

*** Activity R3-6 **** (PORTFOLIO ACTIVITY)

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.

ISY00245 Module 3 - Page 17

You might also like