Anda di halaman 1dari 17

ISY00245

Principles of Programming

Module 4
Module 4
Interactivity
Introduction
Last week we looked at random numbers, static methods and the Greenfoot API documentation.

We created a new sub-class or two, set images for them and built code that allowed us to handle
simple collisions between objects, using built-in Greenfoot methods.

One of the most important parts of the last module was the concept of refactoring although you
probably didn’t find it very exciting. Refactoring is very important to help maintain your code,
and happens frequently when we are programming. Get used to refactoring your code when
necessary.

We also looked at how to initialise the world with objects already in it, and how to
programmatically stop the world playing – when the poor Crab was eaten by a Lobster. Finally we
covered exporting your work as a playable application, and saving it as a Greenfoot archive.
As you can see, we covered a lot of ground in the last module. This module we will be adding
some interactivity in your game: letting the player control the crab by using left and right arrow
keys on the keyboard. We will also add sounds, and introduce the concept of variables to count
the worms that have been eaten (I know you will have been wondering how to do this).
.

Study materials

Materials required:
 The free Greenfoot programming environment;

 Files in "Module04" 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 4 - Page 1


Objectives
On completion of this topic, you should be able to:
 use String variables
 write code that uses inbuilt key handling methods
 add sound to Greenfoot scenarios
 explore the folder structure of a scenario
 add sounds and images from outside Greenfoot
 use the Greenfoot sound recorder
 use code completion
 create constructor methods for classes
 understand the common uses for constructors
 declare integer, boolean and String variables
 use assignment to store values in variables
 use assignment to update values in variables
 create methods with a return type

Concepts
 String
 key-handling
 Greenfoot.isKeyDown
 Greenfoot.playSound
 trimming sounds
 code completion
 constructor
 variable
 assignment
 declaring a variable
 scope of variables
 inspector
 return

ISY00245 Module 4 - Page 2


A new type: String
Until now we have been only using two data types: int and boolean. We are now going to
introduce another type (which I’ve hinted at previously) – String.

A String is just a piece of text (such as a word or a sentence), surrounded by double-quotes. Here
are some examples of Strings:
“This is a String”

“Raina”

“A A A”
“B”

“7”

“ “

The last two examples maybe need some explanation. The last example looks like a blank but
actually has 3 spaces. Remember that computers are stupidvery literal and they have to reduce
everything down to exact steps.
A computer will see “Raina” as a string that is made up of an R character, followed by an a
character followed by an i character followed by a n character followed by an a character.
The last example would be seen as a string that is a space character followed by a space character
followed by a space character.

How is “7” different to 7?


The simple answer is that the computer sees the “7” as a string that has a 7 character. The
computer can only use this (as it is) as a String. In contrast, the integer 7 is a number, and can be
added to, subtracted from, and used in all sorts of other calculations.

Activity 4-1 Types

1. Classify the following data into types:


a. "Augusta Ada"
b. True
c. -157
d. 0
e. False
f. "8"
g. 8
h. "This is an integer"
i. "Hello World. This is a very long sentence that will probably wrap around and go
onto the next line. Hmmm I wonder what type this is?"
j. 123456789

2. Write down your own example of a String


_______________________________________________________________________

ISY00245 Module 4 - Page 3


Interactivity - keyboard control
Back to our crab and worm scenario – we would now like to get the player involved by being able
to control the crab with the keyword.

As we will be controlling things within the World with something outside the game, we would
expect that any pre-built methods would not be tied to an Actor.
Let’s start looking for methods in the World class. If we open the World class code, we will see
the documentation for that class:

There are no methods that will help us with keyboard control.

We found the getRandomNumber() method in the Greenfoot class, so lets look in the Greenfoot
API documentation.

Reminder: to find the Greenfoot API, go to Help menu > Greenfoot Class Documentation.

In the methods in the Greenfoot class, there is an isKeyDown method. Its method signature is:
static boolean isKeyDown(String key)

Recall that static means we must use the classname when we are using this method.
It returns a boolean value (true or false) so it can be used in an IF statement.

This method also expects a String value as an argument to the method call. This means we can
use it in a test, to see if a particular key has been pressed, and do some action in response.
ISY00245 Module 4 - Page 4
In pseudocode,

IF (left key has been pressed)


turn to the left
END IF
The method has this help available:

The method has one parameter which is of type “String” and it needs to be a keyName. So what
are the key names?
Your text gives us this information: the keys that produce visible characters are just called by that
character name: eg: the A key is called “A”. The other keys have names, and the left cursor key is
called “left” and the right cursor key is called “right”.

Converting our pseudocode to Java then …


if (Greenfoot.isKeyDown(“left”))
{
// do something to make the crab turn left
}

As it is the crab object that we want to affect, we need to place this code in the Crab code,
instead of the random turning code.

In your textbook, read pages 41 to 42.

Watch the screencast 0401 Keyboard Control, in the Module 04 folder.

Activity 4-2 Turning left and right

In your little-crab program, remove the turning code from the crab.
Do you need the code that checks for the edge of the world, and automatically turns? If not,
remove this code.
Add code to make the crab turn left 4 degrees every time the left cursor key is pressed.
Add code to make the crab turn right 4 degrees every time the right cursor key is pressed.
Refactor your code if necessary to make sure that there is a call to a method in act() called
checkKeyPress. (Hint: you will have to create a new method with this name).

You may need to adjust the move(5) method call in either the lobster or the crab to make the game
more playable. Try making them faster or slower. Choose a good speed for the crab and for the
lobster.
ISY00245 Module 4 - Page 5
Adding Sounds
Our game is now looking quite good, but is silent. Our next task is to add some sounds to our
game.

Greenfoot has quite sophisticated sound handling via its GreenfootSound class, but also includes
a simple utility sound handler in the Greenfoot class.
Opening the Greenfoot API documentation again will show us the method we need:

The method signature is


static void playSound(String soundFile)

You should be getting quite good at reading these method signatures by now, but let’s go through
it.
static means that this is a class method, and needs the class name before the method name
to use it.

void means that this method won’t return anything

playSound is the name of the method, we will use this to call the method

String is the type of parameter that the method needs in order to work
soundFile means we need to provide the name of the sound file that we wish to use.

So to play a sound, we would use


Greenfoot.playSound(“slurp.wav”);

This scenario includes two sound files – slurp.wav and au.wav.

Optional:
Greenfoot accepts sound file formats of MP3, AIFF, AU and WAV (some, depending on
encoding). When you save your own recorded sounds, save as “signed 16 bit PCM WAV”
files. If you convert other sounds to this format they will be playable in Greenfoot.

When the crab eats a worm, the ‘slurp’ sound should be played, and when the lobster eats a crab,
the “au.wav” file should be played – although it could more correctly be named aww.wav.

In your textbook, read pages 45 to 46.

ISY00245 Module 4 - Page 6


Activity 4-3 Adding sounds

In Greenfoot, add the playing of sounds to your scenario.


 When a crab eats a worm, play "slurp.wav" and
 When a lobster eats the crab, play "au.wav".

Scenario folder structure

If you have a look at your folders for the little-crab scenario you will see something like this:

Each scenario will have a project.greenfoot file, various class files (dependent on the classes you
create), java files, and a folder called sounds, and another called images.

If we look at the images folder, it has the media we have used in this scenario, as well as one
image that we haven’t used yet (that’s coming soon):
crab.png, crab2.png, lobster.png, sand.png (for the background) and worm.png

The “sounds” folder contains au.wav, fanfare.wav and slurp.wav. We haven’t used fanfare.wav
yet but it’s there ready for us to use. If you wanted to add more sounds, this is where you would
add them.
ISY00245 Module 4 - Page 7
Optional:
If you want to add your own images into the images folder of a scenario, you can do that
too. Images should be in the format .png for transparency (Actors) or jpg for backgrounds.
The file size should be kept small, otherwise it will slow everything down.

Creating your own sounds


You can always use sounds that you have found in public domain sound libraries on the net, or
produce your own outside Greenfoot.

Greenfoot also includes a mini sound-recorder with a ‘trim’ function for some basic editing. This
will allow you to create your own sounds. All sounds created by Greenfoot are saved in the
‘sounds’ folder of the current scenario.

You can then save and name the file, and use it in your code using the playSound method.

Pew pew!

The Sound Recorder is accessed via the Controls menu > Show Sound Recorder.

In your textbook, read pages 46 to 48.

Watch the screencast 0402 Creating Sounds, in the Module 04 folder.

Activity 4-4 Making your own sounds

Make your own sounds to use when the worms or the crab gets eaten. Record them and then use
them in your code.

How do I remember all this?


You may be wondering how you are possibly going to remember all the method names and how
to use them, throughout this unit. This is especially daunting when you realise that a computer
won’t understand a method name if you use the wrong spelling, or capitalisation.

One way we can make sure our code is correct is to use code completion to enter method
names/calls.

If you are about to write a method name, you can press <CTRL> + <SPACEBAR> and a dialog box
will pop up with all the methods you can call at that spot. This gets really useful if you remember
the first couple of letters of a method name but can’t remember the rest.

ISY00245 Module 4 - Page 8


Activity 4-5 Code Completion

Using code completion, find out four static methods of the Greenfoot class.
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________
___________________________________________________________________________

Constructors
In Topic 3, we learned how to initialise (save) the world with a number of objects in it. That was
really useful to be able to test some methods. You may recall that Greenfoot automatically
created some code in the CrabWorld class to initialise the world.

If we open the CrabWorld code at the moment, we will see this:

Going through this code line by line:


public class CrabWorld extends World

This line is naming the class, and making it a sub-class of the World class. The body of this class
follows, surrounded by { }.

Next is a comment, followed by a method named ….. CrabWorld. (How confusing!)


public CrabWorld()
{
// some stuff here
}

This method has no parameters and doesn’t even HAVE a return type, not even void. The
strangest thing about this method is that it is named the same name as the Class.

ISY00245 Module 4 - Page 9


This method is a special method called a CONSTRUCTOR.

A constructor is always named the same name as the class and it is automatically called when an
object is made from the class.

This is a perfect place for us to put code that has to happen when the game starts, or when a new
piece is created.

A common use for constructors is to set the initial value of something, like setting the score to
zero, or an initial speed of a player.

Activity 4-6 Check your understanding

1. When is a constructor called? _______________________________________


2. What relationship does the constructor name have to the name of its class?
_______________________________________________________________
_______________________________________________________________
3. What is a common use for constructor methods? ________________________
_______________________________________________________________
_______________________________________________________________

How many worms?


Our next task is to build a method that will return the number of worms that have been caught by
the crab, before it gets eaten. To code this, we are going to need some new concepts: variables
and assignment.

Variables
Computers store a large amount of data, both in their long term storage (hard-drives etc) and in
short-term storage (RAM). Computers store data in RAM by giving each memory location a name.

The best way to think about this is to think of a variable as a box that can only hold one data value
of a particular data type. Each box has a name so we can store data and also get it out of the box
when we need it.

22 410 “Raina” True

We can store values of the right type, in these boxes (memory locations). Each one can only hold
one value, so if we put another value in there, the first value is lost.
Our first step is to find out how to set up one of these memory locations, to store information - in
this case, the number of worms eaten.

ISY00245 Module 4 - Page 10


Activity 4-7 Types of variables

Based on the values above, what TYPE are the four variables above?
age: _____________________
score: ___________________
name: ___________________
isOpen: __________________

Creating a new variable


We need a new variable called “wormsEaten” which will be type int. When we create a new
variable like this, we say we are declaring a new variable.
When we create a new variable (“box”), we also need to decide whether it is private (can be only
seen within this class) or public (can be accessed from outside the class. At the moment we will
only be using private variables.

The syntax for declaring a new integer variable is:


private int nameOfVariable;

This means to declare an integer variable called wormsEaten, we will need the code:
private int wormsEaten;

All this does is create and name the ‘box’ – the variable location where we will store values.

Where does this code go?


Remember that the coloured borders show the scope of each method/code block. Anything in a
code block can only be accessed through method names etc from outside that code block.

If we put this code in the act() method, then it will keep creating this variable over and over again,
each time the act() method is called.

You may think that our work on constructors this week will help us, as that is a method that is
called ONCE when the crab is created. This actually is a good first step.

A constructor for the crab


The code for the crab constructor will look like this:
public Crab()
{
// code here
}

We can then put our code to declare the wormsEaten variable:


public Crab()
{
private int wormsEaten;
}

ISY00245 Module 4 - Page 11


Watch the screencast 0403 Crab constructor, in the Module 04 folder.

Activity 4-8 Scope of variables

Based on the scope shown by the colouring in the Greenfoot environment, which methods can
access this variable (for example, to put values in it, or retrieve values from it)?
____________________________________________________________________________
____________________________________________________________________________

Watch the screencast 0404 Scope of variables, in the Module 04 folder.

Now we have set up the variable, with a name and a type, we can start to use it.

Assignment
Once we have a variable, we are ready to store things in it. This is done using an assignment
statement.

An assignment is a Java instruction written as an equals sign =. Make sure you don’t confuse it
with equals, it means “becomes”
For example:
age = 12;

means that the age variable becomes 12. The old value that was stored in the “age” memory
location is lost. You can also read this as the value 12 is stored in the variable age (reading right to
left). I think “becomes” is easier as generally we read from left to right in English-speaking
countries.

Our constructor can now be used to set an initial value for the variable wormsEaten.
public Crab()
{
wormsEaten = 0;
}

Counting worms
We are now almost there – we can now add some code to our “lookForWorm” method to add 1
to the wormsEaten variable each time we catch a worm.
wormsEaten = wormsEaten + 1;

Does this make sense to you? If I read this out, I would say
“WormsEaten becomes the old value stored in wormsEaten + 1”
Where does this code go? After you have thought about it, watch the following screencast.

ISY00245 Module 4 - Page 12


Watch the screencast 0405 Counting worms, in the Module 04 folder.

Activity 4-9 Counting Worms

Implement the above code in your crab scenario. Test by running your game, pausing, and then
using "inspect" on the object menu to find out the value of wormsEaten.

Getting the value of wormsEaten


We can tell the value of wormsEaten by using “inspect” within Greenfoot. Another way would be
to set up a method that returns the number of worms eaten.

We have created methods before, and we know how to read method signatures, so let’s look at
what is expected of this method.

 It should return an int (the number of worms eaten);


 It doesn’t need any inputs (the number of worms eaten are already in the crab);
 A good name would be getWormsEaten.
We now have enough to write the outline of the method:
public int getWormsEaten()
{
// code goes here
}

The way that we can actually return a value via the ‘return type’ of the method is to use the
return keyword.
public int getWormsEaten()
{
return wormsEaten;
}

This will return the value that is currently stored in the “wormsEaten” memory location/variable.

Text

In your textbook, read pages 55 to 56 (down to Object Variables) and then section 4.6 "Using
variables" on page 58.

Activity 4-10 Returning the number of worms eaten

Implement the above code in your crab scenario. Test and when your crab is caught by the lobster,
check how many worms it has eaten by using the object menu for the crab..

ISY00245 Module 4 - Page 13


Summary
During this topic we have built a foundation which you will use for the rest of your time
programming. The concepts of variables, assignment, variable scope and constructors are vitally
important to programming, and we will build on these for the rest of this unit. Make sure you do
the workshop activities for this week (some will be placed in your portfolio) and ask your tutor if
you have any questions about any of these topics.

Workshop activities

Activity R4-1

1. Write a variable declaration for a variable of type in where the variable has the name
"score".

2. Declare a variable named "isHungry" of type boolean and assign the value true to it.

3. Declare a variable named "year" and assign the value 2017 to it. Then assign the value
2018.

*** Activity R4-2 *** PORTFOLIO ACTIVITY

Complete the following activity, under the heading "Activity R4-2", on a new page in your portfolio
Word document.
1. Declare a variable called children of type int. Then write an assignment statement that
assigns to this variable the sum of two of variables named daughters and sons.
2. Declare a variable named area of type int. Then write an assignment statement that
assigns to area the product of two variables called width and length. Remember that the
multiplication operator in Java is *.
3. Declare two variables x and y of type int. Assign the values 23 to x and 17 to y.
Then write some code to swap those values (so that afterwards x contains 17 and y
contains 23). BE CAREFUL NOT TO LOSE THE VALUES while you are doing this!

*** Activity R4-3 *** PORTFOLIO ACTIVITY

Note: you will need a microphone for this activity. If you do not have a microphone, please
complete the alternative activity (Activity R4.4).
Only the scenario part of this activity is to be submitted as part of your portfolio. The first questions
will help you to find the correct answers and code for the scenario. The parts marked with a *** are
to be completed as part of your portfolio.
1. Open the stickman scenario provided ***
2. The Greenfoot class has a method to get the noise level from the computer's microphone.
Find this method in the API documentation. How many parameters does it have?

ISY00245 Module 4 - Page 14


3. What is the return type of this method? What does this tell us? ______________________
________________________________________________________________________
________________________________________________________________________
4. What are the possible values returned from this method? __________________________
________________________________________________________________________
5. Is this method static or not? What does that tell us? ______________________________
________________________________________________________________________
________________________________________________________________________
6. How do we call this method? Write down a correct method call to this method:
________________________________________________________________________
________________________________________________________________________
________________________________________________________________________
7. In your stickman scenario, make the stickman move to the RIGHT, so that when you run
your scenario, he walks over to the right side of the screen. Note: no keyboard input is
required. ***
8. Using an if-statement and the microphone input method you found above, make the
stickman move RIGHT only when you make some noise. Experiment with different values
for the noise level. This will depend on your microphone and your environment. A good
starting point is to make him move when the microphone level is greater than 3. Test. ****
9. Make the stickman move LEFT when you make some noise, but move continuously
RIGHT if there is no noise. Test. Try to keep him near the centre of the screen by shouting.
****
10. Move the code that moves left when you make noise into its own method. Call this method
moveLeftIfNoise. Test. Make sure it works as before ***
11. Add another method to your class called gameOver. This method should be called if the
stickman reaches the edge of the screen. When called, the method plays a game-over
sound and stops the scenario. ***
12. Move the check for the game-over condition itself into a separate method called
checkGameOver. The act method should call checkGameOver which in turn calls
gameOver if appropriate. ***
13. Save your game as a JAR application ****
14. Save your game as a Greenfoot Archive file ****
15. Save both of these into your Portfolio folder. ****

*** Activity R4-4 *** PORTFOLIO ACTIVITY

Note: Only complete this activity IF you have no microphone for the previous activity. You
do not have to complete both activities for your portfolio.
Only the scenario part of this activity is to be submitted as part of your portfolio. The first questions
will help you to find the correct answers and code for the scenario. The parts marked with a *** are
to be completed as part of your portfolio.
1. Open the stickman scenario provided ***
2. We have previously used the move(distance) method in our actors to move to the right or
left. How would we move a random distance between 0 and 10 units,
a. to the left? ________________________________________________________
b. to the right? ______________________________________________________
3. In your stickman scenario, make the stickman move to the RIGHT, so that when you run
your scenario, he walks over to the right side of the screen. Note: no keyboard input is
required. ***
ISY00245 Module 4 - Page 15
4. Using an if-statement and the keyboard handling you learned in this module, make the
stickman move RIGHT only when you press the space bar. Test. ****
5. Change your code to make the stickman move LEFT a random amount between 0 and 10
when the space bar is pressed, but move continuously RIGHT (again, random distances) if
it is not pressed. Test. Try to keep him near the centre of the screen. ****
6. Move the code that moves left when you press the key into its own method. Call this
method moveIfSpace. Test. Make sure it works as before ***
7. Add another method to your class called gameOver. This method should be called if the
stickman reaches the edge of the screen. When called, the method plays a game-over
sound and stops the scenario. ***
8. Move the check for the game-over condition itself into a separate method called
checkGameOver. The act method should call checkGameOver which in turn calls
gameOver if appropriate. ***
9. Save your game as a JAR application ****
10. Save your game as a Greenfoot Archive file ****
11. Save both of these into your Portfolio folder. ****

ISY00245 Module 4 - Page 16

Anda mungkin juga menyukai