What We Will Cover
Illuminations
Questions from last class or the reading?
Homework Questions?
- A2: First Program (2/22/12)
- Download your original programming project scenario from Blackboard and open it on your computer.
- The instructor will briefly review each project and answer questions
- Students can view each others projects as well
^ top
3.1: Creating New Methods
Learner Outcomes
At the end of the lesson the student will be able to:
- Define methods with and without parameters
|
^ top
3.1.1: Writing Methods
- In the previous sections we added new behavior to the Bug class, like:
- Turning at the edge of the world
- Occasional random turns
- Eating flowers
- Notice that the
act() method is getting longer and longer as we add code
- If we continue adding code as we have, the method will become really long and hard to understand
- We can improve the situation by organizing the code into smaller pieces
- The way to organize code within a class is to write new methods
About Methods
Method -- a named sequence of statements defined inside a class.
- We have looked at methods before, such as the
canSee() method:
/**
* Return true if we can see an object of class 'clss'
* right where we are.
* False if there is no such object here.
*/
public boolean canSee(Class clss)
{
Actor actor = getOneObjectAtOffset(0, 0, clss);
return actor != null;
}
Method Syntax
Check Yourself
- True or false: people write methods to organize code into small understandable pieces.
- A method is a ________ sequence of ________ defined inside a class.
- For the following code, match the syntax item with the code
public boolean canSee(Class clss)
{
Actor actor = getOneObjectAtOffset(0, 0, clss);
return actor != null;
}
^ top
3.1.2: Example of Writing a New Method
Comments
- The first four lines are a comment
- Comments are ... comments -- notes to people reading the code
- The computer ignores comments entirely
- We write comments to explain our code to human readers
- Every method should have a comment block like the example
Method signature
Method Body
- The last few lines -- the curly braces and anything between them -- is called the method body
- The method body contains the list of statements executed when the method is invoked (called)
Check Yourself
- True or false: The compiler ignores method comments.
- True or false: method names are case sensitive.
- What is wrong with the following method name?
public void 4flowers() { }
- What is wrong with the following method name?
public void switch() { }
^ top
3.1.3: Calling Methods
- When we define a method, the code does not immediately get executed
- In fact, defining a method does not guarantee it is ever executed
- To execute the code in a method, we must code a method call
- We can call our example method from inside the
act() method using the code:
lookForFlower();
- Notice that the method call has an empty parameter list
- The number and order of parameters must match the parameters defined in the method
- In this case, there are no parameters defined and so the method call has an empty parameter list
Organizing with Methods
Check Yourself
- True or false: defining a method means it will be executed.
- True or false: method calls always have parenthesis, even when a method does not define any parameters.
- True or false: defining short methods makes it easier to understand the logic of a program.
^ top
Exercise 3.1
In this exercise, we write new methods for our scenario.
Specifications
- Download the following scenario file and save it in the scenario folder of Greenfoot.
Scenario file: bugs2.zip.
- Start Greenfoot and open the scenario by choosing Scenario > Open and then selecting the zip file.
Greenfoot unzips the file for us.
- Open the source code editor of the Bug class and add the following method:
/**
* Checks whether we have stumbled upon a flower.
* If we have, then eat it. Otherwise, do nothing.
*/
public void lookForFlower()
{
if (canSee(Flower.class)) {
eat(Flower.class);
}
}
For more information see lesson: 3.1.2: Example of Writing a New Method.
- Change the
act() method of Bug to call this new method.
For more information see lesson: 3.1.3: Calling Methods.
- Change the
act() method as follows and then add the two new methods needed for your program to function.
public void act()
{
turnAtEdge();
randomTurn();
move();
lookForFlower();
}
When completed, compile the class and verify there are no errors. Resolve any errors you find, getting help from a classmate or the instructor as needed.
- Organize the code in the Lizard class in a similar way.
However, instead of looking for and eating flowers, look for and eat bugs.
- Compile and run your scenario to verify all the changes work well.
If you have problems, ask a classmate or the instructor for help as needed.
- Save a copy of your scenario to upload to Blackboard later as part of assignment 3.
We will be adding more code to these files in subsequent exercises, so it is not time to submit them to Blackboard yet. However, it is a good idea to have a backup copy in case of problems later in development.
As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 3.1.4: Summary.
^ top
3.1.4: Summary
Check Yourself
Answer these questions to check your understanding. You can find more information by following the links after the question.
- Why do programmers write methods? (3.1.1)
- What is a method? (3.1.1)
- How can you tell the difference between a method name and a variable name? (3.1.1)
- What are three items always present in a method signature? (3.1.1)
- What is the purpose of comments? (3.1.2)
- True or false: The compiler ignores comments. (3.1.2)
- What is wrong with the following method name? (3.1.2)
public void 4flowers() { }
- What is wrong with the following method name? (3.1.2)
public void switch() { }
- Which of the following is a method definition and which is a method call? (3.1.3)
public void lookForFlower() { }
lookForFlower();
- True or false: Within reason, shorter methods are easier to understand than longer methods. (3.1.3)
- How can you use methods to make your code easier to understand? (3.1.3)
^ top
3.2: Bells and Whistles
Learner Outcomes
At the end of the lesson the student will be able to:
- Write code for keyboard interaction
- Describe the
String data type
- Write code to produce sound effects
- Write code to end a scenario
- Find class and method documentation in the Greenfoot API
|
^ top
3.2.1: Keyboard Interaction and Strings
Strings
Check Yourself
- To check whether a key on the keyboard has been pressed, call the
Greenfoot class method ________.
- A(n) ________ is a sequence of character data.
- The name of the data type for storing strings in variables is ________.
String
string
str
Text
^ top
3.2.2: Using Strings to Specify Key Presses
Key Names
- Every key on the keyboard has a name
- For keys that produce a visible character, that character is their name
- For example, the A-key is named "A" (or "a")
- The number keys are: "0", "1", ..."9"
- Other keys have names as well
- The cursor keys are named: "up", "down", "left", "right"
- Other control characters include: "enter", "space", "backspace"
- The function keys are: "F1", "F2", .., "F12"
- For more information, see the Class Greenfoot documentation
Using isKeyDown()
- If we want to test for the right-cursor key, we write an
if-statement like:
if (Greenfoot.isKeyDown("right"))
{
// do something
}
- For example, to make an actor turn right by 10 degrees we would write:
if (Greenfoot.isKeyDown("right")
{
turn(10);
}
- We can add this code to a method and call the method from the
act() method
- For instance:
/**
* Check if a control key has been pressed and react.
*/
public void checkKeyPress() {
if (Greenfoot.isKeyDown("right"))
{
turn(10);
}
}
- Then the
act() method would look like:
public void act()
{
checkKeyPress();
move();
}
Check Yourself
^ top
3.2.3: Adding Sound
Getting Sounds
- To play sampled sound, you will need some sound files
- You can get free sound effects files from the Internet like:
- You can search for sounds on the web using:
- However, make sure you verify the licensing
- Also you can create your own sounds using the microphone on your cell phone or other device
- Then you can edit the sounds using a sound editing program
- Some free sound editing programs you might try are:
Sound File Size
- Sound files can become quite large
- When developing a game, we need to find or develop sound files that convey the effect we want without becoming overly large
- As a rule of thumb, we want no sound file larger than one megabyte
- Also, the sum total of all sound files should be no larger than three megabytes
- If we find our sound files are too large, we can use a sound editing program to reduce the size
Check Yourself
- To play sounds, first add the sound files to the ________ folder of your scenario.
- To play a sound file, call the
Greenfoot class method ________.
- True or false: you can use any sound file you can find on the Internet.
^ top
3.2.4: Ending the Scenario
- One last "bell and whistle" we can add to our scenario is to end execution when the bug is caught by a lizard
- Again, the Greenfoot class has a method to help us
- We just need to find the method
- To find out what methods are available, we look in the Greenfoot API
The Greenfoot API
Finding the Method
- The method we are interested in is in the Greenfoot class
- We click on a hyperlink for the Greenfoot class
- When we get to the class, scroll down and look through the methods
- Each method is listed and the one we are interested in has an explanation that says
Pause the execution.
- You can follow the hyperlink of the method name and often get more detailed information about the method
Check Yourself
- The acronym API stand for A________ P________ I________.
- True or false: the name of the documentation for Greenfoot classes is called the Greenfoot API.
- To end a scenario, call the
Greenfoot class method ________.
^ top
Exercise 3.2
In this exercise, we add keyboard controls and sounds to our scenario. In addition, we add a stopping condition.
Specifications
- Start Greenfoot and open the Bug scenario from the last exercise.
- Open the source code editor of the Bug class and remove the
randomTurn() method call and method.
- In the Bug class, add code to turn right pressing the right-cursor key and left by pressing the left-cursor key.
For more information see lesson: 3.2.2: Using Strings to Specify Key Presses.
- Compile the class and verify there are no errors. Then test your scenario to verify the bug changes direction under keyboard control.
Resolve any errors you find, getting help from a classmate or the instructor as needed.
- Save the following sound file in the scenario sounds directory: slurp.wav
For more information see lesson: 3.2.3: Adding Sound.
- In the source code of the Bug class and add the following code to the
lookForFlower() method after the eat() method call:
Greenfoot.playSound("slurp.wav");
When completed, compile the class and verify there are no errors. Resolve any errors you find, getting help from a classmate or the instructor as needed.
- Compile the class and verify there are no errors. Then test your scenario to verify the lizard eats a bug when they meet.
Resolve any errors you find, getting help from a classmate or the instructor as needed.
- Save the following sound file in the scenario sounds directory: au.wav
For more information see lesson: 3.2.3: Adding Sound.
- Change the code in the Lizard class to play au.wav sound and the stop the scenario after eating the bug.
For more information see lesson: 3.2.4: Ending the Scenario.
- Compile and run your scenario to verify all the changes work well.
If you have problems, ask a classmate or the instructor for help as needed.
- Save a copy of your final scenario with all the changes made to upload to Blackboard as part of assignment 3.
As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 3.2.5: Summary.
^ top
3.2.5: Summary
- In this section we looked at several features that add interest and excitement to a game or simulation
- First we looked at how to control actors using the keyboard
- The important method was found in the Greenfoot class:
static boolean isKeyDown(String keyName)
- The method checks to see if a particular key is pressed
- The particular key is specified using a
String parameter
- A string is a sequence of characters and you can specify the characters by placing them in double quotes
- For instance:
"This is a string"
"A"
"left"
"right"
- Another way to send the parameter information is to use a
String variable like:
String leftKey;
leftKey = "left";
String rightKey = "right";
- When a method parameter expects a
String, we must provide either characters in double quotes or a variable
- Every key on the keyboard has a name
- For keys that produce a visible character, that character is their name
- For example, the A-key is named "A" (or "a")
- The number keys are: "0", "1", ..."9"
- The cursor keys are named: "up", "down", "left", "right"
- Other control characters are: "enter", "space", "tab", "escape", "backspace"
- The function keys are: "F1", "F2", .., "F12"
- Since the
isKeyDown() method returns a boolean type, we can use it in an if-statement like:
- If we want to test for the right-cursor key, we write an
if-statement like:
if (Greenfoot.isKeyDown("right"))
{
// do something
}
- Another "bell and whistle" we can make to our scenario is the addition of sound
- We must first place the sound file in the sounds folder of our scenario
- Then to play the sound, we use the command:
Greenfoot.playSound("filename.wav");
- Finally we discussed how to look up classes and method in the Greenfoot API
- You can find the class documentation from within Greenfoot using the help menu
- Selecting the Greenfoot Class Documentation from the Help menu opens the documentation in a browser
- Once you have opened the document ion, you follow the hyperlinks to find the information you want
Check Yourself
Answer these questions to check your understanding. You can find more information by following the links after the question.
- What method checks whether a key on the keyboard has been pressed? (3.2.1)
- What is a string? (3.2.1)
- The name of the data type for storing strings in variables is: (3.2.1)
String
string
str
Text
- What is the name of the B-key? (3.2.2)
- What is the name of the left-cursor key? (3.2.2)
- Where do you place sound files that you want to play in a scenario? (3.2.3)
- What is the name of the method that plays sounds? (3.2.3)
- True or false: the name of the documentation for Greenfoot classes is called the Greenfoot API. (3.2.4)
- What is the name of the method that ends a scenario? (3.2.4)
^ top
Wrap Up
Due Next: A3: Methodical Improvement (2/29/12)
- When class is over, please shut down your computer
- You may complete unfinished lesson exercises at any time before the due date.
^ top
Home
| Blackboard
| Schedule
| Syllabus
| Room Policies
Help
| FAQ's
| HowTo's
| Links
Last Updated: May 25 2012 @19:47:09
|