GridWorld AP CompScience
GridWorld AP CompScience
A Curriculum Module
for AP® Computer
Science
2010
Curriculum Module
The College Board
The College Board is a not-for-profit membership association whose mission is to
connect students to college success and opportunity. Founded in 1900, the College Board
is composed of more than 5,700 schools, colleges, universities and other educational
organizations. Each year, the College Board serves seven million students and their
parents, 23,000 high schools, and 3,800 colleges through major programs and services in
college readiness, college admission, guidance, assessment, financial aid and enrollment.
Among its widely recognized programs are the SAT®, the PSAT/NMSQT®, the Advanced
Placement Program® (AP®), SpringBoard® and ACCUPLACER®. The College Board is
committed to the principles of excellence and equity, and that commitment is embodied
in all of its programs, services, activities and concerns.
For further information, visit www.collegeboard.com.
Overview............................................................................................. 5
Judy Hromcik
Introduction
Fran Trees
“A case study describes a programming problem, the process used by an expert to solve the
problem, and one or more solutions to the problem. Case studies emphasize the decisions
encountered by the programmer and the criteria used to choose among alternatives.” 1
Case studies have been part of the AP® Computer Science curriculum since 1995. These
studies allow students the benefits of an apprenticeship by being able to work with large
programs written by experts. Students can be guided through programming design issues
early in your course rather than postponing the complexity of program design until the
language has been mastered. Case studies also provide an excellent vehicle for assessing a
student’s knowledge and are great tools for promoting teamwork and active learning.
The teaching modules included here provide instructional strategies and
presentation suggestions related to the GridWorld case study
(http://www.collegeboard.com/student/testing/ap/compsci_a/case.html). The authors
of the modules are experienced AP teachers and university professors who have used
case studies in an introductory Java course and are excited about sharing their favorite
activities with you.
After an overview of the GridWorld case study, highlighting ways to incorporate
the case study into an AP Computer Science course, each of the five parts of the case
study are addressed by supplying you with a variety of ideas and tools. The instructional
units include teaching strategies, presentation suggestions and activities (including lab
assignments) that are designed to address the various ability levels and learning styles
of the students in your class. Throughout the document there are student worksheets
that can be printed and distributed to students at various times in your course, either as
reviews of GridWorld concepts or as exercises and homework assignments while working
with GridWorld.
1. M.J. Clancy, and M.C. Linn, “Case Studies in the Classroom,” Proceedings of the 23rd SIGCSE Technical
Symposium on Computer Science Education (Kansas City, Mo., March, 1992).
Overview
Judy Hromcik
GridWorld is a great tool for teaching inheritance to computer science students. In the
past, many of us have taught the case study as an add-on at the end of the course, just
before the AP Exam. In this article, I suggest ways to integrate the case study throughout
the year by using it as a vehicle to teach students inheritance, to teach students how to
create and use objects, and to facilitate the instruction of other non-OOP computer
science concepts. I will also discuss some of the technical issues with setting up and
running the case study code.
Import statements
The GridWorld case study uses packages. This requires the programmer to use import
statements or use a very long class name when declaring and instantiating actors, bugs,
critters, etc. For example, the Bug class is a part of the info.gridworld.actor
package. The fully qualified name of the Bug class is actually info.gridworld.
actor.Bug. To be able to just type Bug when declaring and instantiating a bug, the
programmer must write the following import statement:
import info.gridworld.actor.Bug;
The following chart lists the classes and interfaces in each package:
but I have since changed my mind; I am now using GridWorld to help reinforce the use
of objects and inheritance. I am also using GridWorld to help teach loops and conditional
statements, ArrayList, classes, and anything else I can think of as I teach the
curriculum throughout the year.
I introduce my students to OOP using Jeroo (Jeroo:
http://home.cc.gatech.edu/dorn/jeroo), a wonderful book and program by Dean Sanders
and Brian Dorn from the University of Missouri. In Jeroo, students make one kind of
object, a Jeroo, and then send messages to the Jeroos to make them act. They also modify
the Jeroo class by adding new methods. Once this unit is finished, I introduce the students
to Java. Early in the Java introduction, it is difficult to keep students in the OO frame of
mind. Java does not have a lot of simple classes that students can easily use as they are
introduced to the language basics. It is difficult to leverage what the students learned
about creating and using objects in Jeroo as they move into Java.
Stacey Armstrong (http://apluscompsci.com) from Cypress Woods High School in
Houston, Texas, has solved this problem by using GridWorld as a key curriculum component
in AP Computer Science, developing GridWorld lessons and labs for students to use from the
very beginning of the course and throughout the year. These labs allowed me to seamlessly
move from Jeroo to Java and keep OO alive. After students finish Part 1 of the case study, the
Actor, Location and ActorWorld classes can be introduced. Introductory labs have
students write a runner class that simply creates a world and adds actors to the world.
public class ActorRunner
{
public static void main(String[] args)
{
ActorWorld world = new ActorWorld();
Actor a1 = new Actor();
world.add(a1);
world.add(new Location(2,2), new Actor());
world.show();
}
}
The first labs only require that students know how to call the constructors for the
Actor and Location classes and the constructor, add, and show methods for the
ActorWorld class. Students are essentially doing the same tasks in these programs as
they did at the beginning of the Jeroo unit.
After the GridWorld introduction, the Java language basics can be taught:
primitive variables, references, input, output, assignment statements, arithmetic, etc.
While teaching these basics, students can input row and column values to make new
Location objects, and then create Actor objects to place in an ActorWorld.
After the Java language basics have been covered, you could begin teaching
simple inheritance by making new types of actors. One such actor from Armstrong’s
materials is the MoveLeftActor. Only the Actor act method is overridden and the
getDirection and moveTo methods of Actor are used. The Location class
methods getAdjacentLocation, getRow, getCol and the Location constants
are also introduced. Students learn how to get the adjacent location to the left of the actor
and then move to that location. No checks are added to keep the actor from going out of the
grid. The focus of this lab and others like it is to introduce inheritance and to learn how to use
some of the methods found in the Actor and Location classes. Later on, after conditional
statements have been taught, this lab is redone to check for boundaries. The Actor’s
getGrid method is introduced along with the Grid interface’s isValid, getNumRows
and getNumCols methods. Before Part 2 is taught, students are introduced to a substantial
number of methods found in the case study’s interacting classes. Many of these methods
are not introduced in the narrative until Part 3. This simplifies teaching Part 3 and gives the
teacher some good classes to use early in the AP Computer Science curriculum.
Once conditionals are taught, students can begin on Part 2. New instance variables,
constructors, super() and super.method() can be taught using the Bug class as a
base class. Essentially, Part 2 can be taught as is in the narrative. The 2007–2008 AP Computer
Science Special Focus Edition: GridWorld Case Study has additional Bug labs as well that can
also be added to the exercises found in the narrative. Parts 3 and 4 can be taught after loops
and ArrayList. Part 4 is a great unit to help you teach the intricacies of inheritance.
GridWorld can be used to enhance your teaching of other programming concepts
such as conditionals and loops. Cay Horstmann has a Web page
(http://www.horstmann.com/gridworld/extending-gridworld.html) that shows how to use
the GridWorld environment to teach other concepts in AP Computer Science. My favorite
is LoopWorld. Using this project, students can place Actor objects in the grid with a
loop and see the objects appear one at a time. Students can “see” loops and nested loops in
action, and they can continue to instantiate and use objects. The graphical nature of this
code can assist your visual learners. Additional extensions of the GridWorld case study
can also be found at the above-referenced website. If you and your students visit this page,
you will find that you can also use the GridWorld framework to create games.
As I work with GridWorld, I see more ways to integrate worlds, locations, grids
and actors to help reinforce object instantiation and object use, and to help teach classes,
inheritance, conditionals, loops, input, etc. The GridWorld classes help me to teach
objects first and to teach them often.
Postcondition:
(1) The state of all actors in the grid other than this critter and the
elements of <code>actors</code> is unchanged.
processActors (2) The location of this critter is unchanged.
For actors currently in the grid, only this critter and the actors in
the getActors() ArrayList can change. New actors can be added to
unoccupied locations.
Suppose you have a new type of critter that keeps a log of all of the places that it
visits. It contains an ArrayList private instance variable to store these locations. Which
method should update the ArrayList? You might choose selectMoveLocation.
This is a reasonable place to update the list, but the postconditions do not allow any changes
to be made to the critter. The ArrayList should be updated in makeMove. Be sure to
teach these postconditions to your students. Students who violate the postconditions when
writing free-response answers may not receive full credit for their solutions.
The GridWorld case study can and should be used throughout the year to
introduce and enhance numerous topics, such as OOP fundamentals, decision making,
looping and inheritance. GridWorld can be used to help students better understand
and grasp any of the AP Computer Science A topics. The graphical nature of GridWorld
makes it very attractive to visual learners, and it also serves as a game creation platform,
thus making it an incredible recruiting tool. GridWorld is robust and has a rich source of
materials to help us teach AP Computer Science.
10
11
12
13
Lesson Objectives
• Given a working version of GridWorld and an investigative worksheet, the
student will be able to activate the GUI in Step and Run modes and determine
the characteristics and capabilities of the GUI, a bug, a flower and a rock with 100
percent accuracy.
• Given a working version of GridWorld and a set of questions to be explored, the
student will be able to work cooperatively with another student to investigate
adding actors to the grid and to determine what those actors can and cannot do
and how the grid can be used with 100 percent accuracy.
Materials
• GridWorld Case Study Part 1: Observing and Experimenting with GridWorld
(http://www.collegeboard.com/student/testing/ap/compsci_a/case.html)
• “Running the Demo” Reading Worksheet (see Appendix C)
• “Exploring Actor” Reading Worksheet (see Appendix D)
Anticipatory Set
Assuming this lesson is taught on the first day of the unit, one of the introductory
activities listed above may serve as the anticipatory set for this lesson. If, however, this
lesson is not taught on the first day, the following introduction may be used.
Play the game, Find the Route, found at http://math2.eku.edu/Greenwell/MAT303.
In this game, an individual player must find a route from the upper left-hand corner to
the lower right-hand corner of a grid according to prescribed rules. This activity focuses
the students’ attention on the grid. Ask them to contrast the grid in this game with the
Cartesian coordinate system.
Lesson Development
Project the instructor’s computer screen and demonstrate how to open and run the
GridWorld demo program. Instruct the students to follow the steps with you, making
sure they are able to open and run GridWorld. Hand out Part 1 of the case study and the
above-referenced worksheets. Instruct the students to complete the Running the Demo
worksheet independently, following the instructions and answering the questions, then
compare answers with another student. The pairs of students should then work on the
Exploring Actor worksheet activities and questions. Students may refer to Part 1 of the
case study as needed. Circulate about the classroom, answering students’ questions and
helping as needed, but allowing the students to do their own investigation. Monitor the
students to be sure that they are finding the worksheet answers through their investigation.
This is your formative assessment, the time during which you determine to what extent
each student is mastering the material.
14
Accommodations
Students who need extra help may receive it by working with a partner and by the teacher
circulating about the room to provide feedback and guidance regarding their work. Those
who finish early can investigate features of the case study further.
Closure
At the close of class, take a few minutes to ask the students to summarize what they
learned. Ask them not only for the facts that they learned about the GUI and the actors,
but also ask them to discuss the investigative strategies they used to find answers to the
worksheet questions.
Assignment
Read Part I and answer of the GridWorld Student Manual and complete “Do You Know? Set
1.” For homework and as a summative assessment, tell the students to write a short letter to
their best friend describing five things they learned about the GUI, five things they learned
about a bug, two things they learned about a rock and three things they learned about a flower.
Rubric for a Letter to a Friend
Points
Topic Evaluation Point Value
Earned
Content:
Five valid things learned about a Bug 5
10
Two valid things learned about a Rock 2
Three valid things learned about a Flower 3
Style:
Correct friendly letter style 5 10
Free of spelling and grammar errors 5
Instruct the students to begin keeping a GridWorld journal. The first entry is to describe
what they learned in this lesson and what it means to them in terms of the AP Computer
Science course. (See Appendix E.)
Assessment
• Diagnostic assessment occurs by asking questions during the anticipatory set in
order to find out what the students already know about a grid.
• Formative assessment occurs through questioning and observation during lesson
development.
• Summative assessment occurs with the letter written to a friend. Give the students
a rubric for the letter and grade according to the rubric.
15
Evaluation
Formulate questions you will ask yourself after teaching this lesson, such as the following:
• Was my anticipatory set effective in activating prior knowledge and motivating the
lesson?
• Do the students understand how to use the features of the GUI?
• Do the students understand what the objects in the grid can do?
• Do the students know how to instantiate Actors, Bugs and Rocks in the GUI?
• Do the students understand the difference between accessor and modifier method
calls?
• In teaching this lesson, what did I do well?
• What could I have done differently?
16
Do not expect to complete one iteration of the Role Play in a single class period,
unless your school is on block scheduling. This lesson typically takes two class periods.
To do justice to the lessons learned from this activity, it can’t be rushed. Taking time now
pays big dividends in students’ subsequent understanding of the case study concepts.
Learning Goal
• Students will understand the GridWorld design.
Lesson Objective
• Given a role in the GridWorld Role Play, the student will act out the role to the
best of his or her ability.
Materials
• GridWorld Role Play scripts
• Copies of GridWorld Role Play accompanying notes pages for the roles
• Ball of yarn or string
• Hats or other props to signify roles
17
• Large grid drawn on erasable plastic sheet for the Display to use
• Erasable markers or stick-on bugs, flowers and rocks for the Display to use
Anticipatory Set
Minimally, one iteration of the role play requires approximately 90 minutes. For many
teachers this means allowing at least two class days. The role play includes many tips for
success, not the least of which is the teacher’s considered decision about which students
should take on the most active roles. To maximize the use of classroom time, hand out
the roles the day before the role play is to be done and tell the students to become familiar
with their scripts prior to class.
Students have observed GridWorld in action from Part 1, but they haven’t looked
at any code up to this point. They soon will do so, but by experiencing the role play first
they will understand the code better when they examine it. Some teachers believe that the
opposite is true — that students should study the code and then role play it. This has not
been my experience.
When students come into the classroom, tell them to get into character and
review their scripts.
Lesson Development
Once again have the students sit in a circle for the role play. If there are more students
than roles, have the “extra” students act as a “buddy” for each role, helping the player to
find his or her part when told to take an action. If the class is small, a student could take
on more than one of the smaller roles. In that case, there should be a way for the student
to identify himself or herself in the current role. Signs hung around the students’ necks
(see Materials list above) help to identify their roles. You might find hats that signify the
part being played as well (again, see Materials).
An effective method for keeping track of the hierarchy of method calls is tossing
a ball of yarn. The first student to begin the role play holds an end of the yarn. As each
object is called upon to execute a method, the ball is tossed to the person playing that role.
Along the way the object making the method call hangs on to his or her spot on the yarn.
As an object completes its method, the ball is returned to the player who made the call.
Eventually the complex hierarchy of method calls is completed and the ball goes back to
the player who started the whole chain of event calls. This dynamic illustration of how the
objects interact is effective in helping students understand GridWorld code. Later, when
studying the code, students are reminded of who did what and in what order during the
role play.
The GridWorld Role Play includes Time-for-a-Commercial-Break intervals, during
which the teacher and students review what has occurred up to that point. This is an
opportunity to check on student understanding.
18
Closure
Debriefing is a critical part of any role play. Activate the students’ higher learning skills of
analysis, synthesis and evaluation by asking questions and initiating a discussion of what
occurred during the role play. What do they see as the overall GridWorld design? Which
responsibilities belong to which objects? Why? Does this make sense? What did they learn
about object instantiation? What did they observe about object interaction? From their
observations, what can they say about parameters and return values? More questions will
come to mind as you watch the role play in action.
Accommodations
The role play involves students in the Social Interaction and Information Processing
models of education. Students are actively involved in their education. Visual, auditory
and kinesthetic learners are all engaged during the role play. Repetition of steps provides
reinforcement for those who need extra practice to understand concepts, while discussion
and debriefing questions challenge those who are ready for enrichment.
Assessment
• Diagnostic assessment occurs as the students recall what they learned from
GridWorld Part 1.
• Formative assessment takes place during the “commercial breaks” in the role play.
• Summative assessment consists of each student writing a journal entry
commenting on his or her role, what he or she learned from participation, five
elements of GridWorld each observed during the role play, and two questions they
plan to investigate as they study the Java code.
Evaluation
Formulate questions you will ask yourself after teaching this lesson, such as the following:
• Did my anticipatory set actually activate prior knowledge in the students?
• Did I implement the role play effectively?
• Did the students understand what a Bug, Rock and Flower can do?
• Did the students understand responsibilities and the hierarchy of method calls?
• Was the debriefing effective?
• Is there anything I could have done better or anything I would change the next
time I teach this lesson?
19
• Is there anything I did particularly well and would repeat the next time I teach this
lesson?
Lesson Objective
• Given the BoxBug and BoxBugRunner classes as templates, the student will
design and implement a variation of a subclass of Bug with 100 percent accuracy.
Materials
• GridWorld Student Manual Part 2: Bug Variations (page 10)
(http://www.collegeboard.com/student/testing/ap/compsci_a/case.html)
• GridWorld Student Manual Testable Code for APCS A/AB
(http://www.collegeboard.com/prod_downloads/student/testing/ap/compsci_a/
compsci_a_exam_appendix.pdf)
• “Bug Class” Reading Worksheet (see Appendix F)
• “Runner Class” Reading Worksheet (see Appendix G)
Anticipatory Set
Tell the students they have one minute to jot down one thing they have in common with
everyone else in the class and one thing they can do that is unique about them, something
that sets each one apart from everyone else in the class. After one minute the students will
find a partner and share what they wrote. After another minute ask the pairs to share their
ideas of what is common to the students in the class. Write their ideas on the board. Then ask
each one to share what their partner’s unique ability is. Tell the students that while we have
common characteristics, in some way we are all unique variations of the Student class, and
that in this lesson they will learn about a variation of the Bug class called a BoxBug. Inform
the students that they will work in pairs to design and implement another variation (that you
assign), and then they will use their experience and creativity to design a Bug variation of
their own. Inform the students that this code is testable on the AP Computer Science Exam.
20
Lesson Development
Demonstrate the BoxBugRunner class that instantiates a BoxBug. Students will
imitate the teacher’s steps, observing how a BoxBug behaves. They will be given copies
of Part 2 and Appendix C. Introduce the BoxBug class and discuss the code line by line,
explaining that BoxBug is a subclass of (extends) the Bug class, to be studied in Part 3.
The constructor, private instance variables and act method will be carefully discussed. In
addition, a runner class must be created for each Bug variation. The BoxBugRunner
class provides a template. There should be continuous didactic questioning of the students
to assess how well they understand the new material. These questions are short and
factual, aimed at the lowest level of learning. Think of this as the “I do” part of the lesson,
in which the teacher does most of the talking and demonstrates what is to be learned.
After studying BoxBug, students will work in pairs, one computer per pair,
adapting the BoxBug code to create a CircleBug, as described in Part 2. Generally
during this process (the “we do” part of the lesson), the instructor and the students
work together. In this instance, the model has been modified to involve the students
in pair programming. Students will take turns being the “programmer,” the person at
the keyboard actually typing the code, and the “navigator,” the person studying the
modifications for errors and making suggestions about additional modifications to
be made. It is important that students swap roles midstream; insist that each person
experiences both roles. During this part of the lesson, walk around the room observing
student interaction and progress, offering suggestions, and keeping the pairs on task.
When a pair has successfully completed CircleBug, they will separate and
work independently during the third part of the lesson. In this, the “you do” part, each
student will again adapt the BoxBug code to create his or her own variation. If they are
having a hard time coming up with ideas, try a short brainstorming session in which
variations are called out and recorded on the board.
The resulting BoxBug variation constitutes the summative assessment for each
student. The instructor’s usual grading rubric for programs will be applied. (See Materials
list above for an example.)
Accommodations
For students who need extra help, the instructor will be available to discuss programming
concepts and techniques. Students who are ready for a greater challenge may work on
more complex variations or instantiate two objects of the same or different types to see
how they interact on the grid.
Closure
Review with the students what they learned from studying the BoxBug and
BoxBugRunner code. Ask them to think about how these concepts apply to
programming aside from the case study.
21
Assignment
Students will complete the Bug class “Bug Reading Worksheet” and the “Runner Class
Reading Worksheet ” on concepts from Part 2. The worksheets will be collected and
graded as a summative assessment.
Assessment
• Diagnostic assessment occurs during the anticipatory set when the instructor
determines if students understand the concept of variation.
• Formative assessment will be ongoing with questioning and observation during
the “I do” and “we do” parts of the lesson.
• Summative assessment will be based on the students’ individual variations based
on BoxBug and the Part 2 worksheets.
Evaluation
Formulate questions you will ask yourself after teaching this lesson, such as the following:
• Did my anticipatory set grab the students’ attention and help me to diagnose prior
knowledge?
• Was my demonstration and explanation clear?
• Were the students able to work together successfully to practice the concepts?
• Did I provide enough help?
• Is there anything I could have done to improve the lesson?
• Is there anything I did well and would like to repeat?
22
Lesson Objectives
• Given Part 3 and the GridWorld Student Manual Appendix B, the student will
complete a worksheet on the Location class with 90 percent accuracy.
• Given the Location class, the student will work with a small group to design an
application for Location in a situation different from the case study.
Materials
• GridWorld Part 3: GridWorld Classes and Interfaces (page 16)
• GridWorld Student Manual Testable Application Programming Interface (API)
(http://www.collegeboard.com/prod_downloads/student/testing/ap/compsci_a/
compsci_a_exam_appendix.pdf)
• Location Reading Worksheet (see Appendix H)
Anticipatory Set
Give each student a compass (see Appendix B). Tell them to use the compass to face in
various directions, then pick one direction and turn a half-circle from there. Ask them to
describe in degrees the direction they are facing upon each turn. Ask them to tell you how
many degrees they have turned with each new move.
Inform the students that in this lesson they will investigate the Location class in
GridWorld. Tell them that they will complete a worksheet based on the Location class
and then design an application for the Location class different from GridWorld.
23
Lesson Development
Arrange students into pairs and give each pair a compass. Have them follow a set of directions
to find an object hidden in the classroom. Each pair will have a unique set of directions and
object to find (toy or edible rock, flower, or bug). The directions given in terms of objects,
constants and methods of the Location class instruct the pairs to face different compass
directions, turn through different compass angles and move a specified number of steps to
find their hidden object. This part of the activity should take 5 to 7 minutes.
When students have found their hidden objects, discuss the meaning of the
instructions and the constant values from Location. Give the students a copy of Part
3 and the GridWorld Testable Application Programming Interface (API) containing
the Location class. They will continue working in pairs to understand Location.
Ask them to write down any questions they have and submit them to you. Address the
questions one at a time during a class discussion.
Student pairs will then design an application of the Location class other than
the case study. The design phase is the focus in this exercise. Student pairs will present
their application designs to the class, specifying the problem being solved and how
Location is used in the design. The class will question the presenters, who are expected
to defend and justify their applications.
The design process does not require actual coding and implementation. Extra credit
could be awarded to pairs that develop a running program within the following 10 days.
Accommodations
Pairs will be formed in such a way that students who need extra help are paired with students
who are likely to help them without taking over. Students who are more capable may be
selected to help others in the pairs or may work on coding and implementing their designs.
Closure
Students will be asked to explain strategies they used find their hidden object. Discuss
how the pairs investigated the Location class. Review the Location class methods
and constants.
Assignment
Students will complete the “Location Reading Worksheet” and turn it in at the beginning
of the next class.
Assessment
• Diagnostic assessment occurs through the anticipatory set activity, which allows
the instructor to assess the students’ prior knowledge of compass locations.
24
• Formative assessment takes place during the lesson as the instructor observes and
questions the students’ progress in completing the assignment.
• Summative assessment is achieved through the worksheet.
Evaluation
Formulate questions you will ask yourself after teaching this lesson, such as the following:
• Did the compass activity at the beginning of class activate students’ prior
knowledge of compass directions and angles?
• Did the search for the hidden objects cause the students to use and understand
Location class objects, constants and methods?
• Did I perform my role as facilitator in a way that was helpful but not interfering?
• What worked well with this lesson?
• Is there anything I would change when I present this lesson again?
Learning Goals
• Students will understand the purpose and appreciate the design advantages of
creating Grid as an interface.
• Students will understand the implications of preconditions.
• Students will work together to develop skills for reading an API and analyzing
method signatures.
25
Lesson Objectives
• Given the “Grid Reading Worksheet,” the student will complete the worksheet with
90 percent accuracy.
• Given the GridWorld Testable API, the student will be able to describe what must
be true when a method is invoked from examining the precondition with 100
percent accuracy.
• Given the GridWorld Testable API, the student will work with a small group to
list the methods, preconditions, parameters, parameter types and return types
of the Grid interface and the Location class, describing the differences between
methods whose names are nearly the same with 100 percent accuracy.
Materials
• First Day Role Play
• GridWorld Classes and Interfaces Grid Reading Worksheet (see Appendix I)
• GridWorld Student Manual Testable API (http://www.collegeboard.com/prod_
downloads/student/testing/ap/compsci_a/compsci_a_exam_appendix.pdf)
Anticipatory Set
Begin the class by recalling one aspect of the First Day Role Play. Have one student be a
Calculator and another, a Lazy Calculator with a Helper. (Both of these are classes in the First
Day Role Play.) Issue the same command to each player (“Alex, add 2, 4.” “Pat, add 2, 4.”).
Each should return the correct value, determined in different ways. Remind the class that the
command and the parameters were the same in both cases, so you didn’t have to change the
way the request was made, and in both cases the result was predictable and consistent.
Now ask the students if they recall the choices they have for a grid when they run
any of the bug runner classes. They should reply “a bounded grid and an unbounded grid.”
Ask them if Bug behavior is predictable and consistent in either grid, and how the two
grids are alike and different; then have them list their responses on the board. They may
run BugRunner or some other runner class with each grid and test out their answers.
Inform the students that the grid in GridWorld is an interface, not a class, and that the
bounded grid and the unbounded grid are classes that are said to “implement” the Grid
interface. Inform them that in this lesson they will learn about interfaces in Java and study
the Grid interface as an example of how to design and use an interface.
Lesson Development
Explain that interface types are used to express operations which are common to
related classes. The interface specifies a set of methods and their signatures but does
not provide implementation. Each class that implements the interface must include
the common methods and their signatures, but each class most likely implements the
26
methods differently. Continue along these lines, discussing how an interface works and
emphasizing the design advantages of creating an interface. Tell the students that an
interface is not a class because there is no constructor and there are no instance variables,
only method signatures. An interface doesn’t have “state” and the behavior isn’t completely
specified. Talk about the ease with which a student can select the bounded or unbounded
grid and how the Grid interface allows this to happen. The methods in the interface are
invoked the same way for either type of grid, and the result is consistent and predictable.
All of this is direct instruction, but you should continually ask questions to check for
student understanding. Encourage your students to express in their own words the points
you have made, and use any misunderstandings you hear as an opportunity to activate
their higher-level thinking skills and help them synthesize the concepts.
With the students, draw a high-level diagram of the interface and the classes that
implement it. Show the method signatures but no code. This is “we do” component of
direct instruction.
Introduce the students to the purpose of a precondition. Think of a precondition
as a promise made to the method, a guarantee that a given condition will be true when
the method is invoked. Ask the class how that guarantee can be made. Ask them about the
responsibility of the code that calls the method. Only if the precondition is met does the
method guarantee a correct result.
In terms of the AP Exam (or good programming, for that matter), remind students
that when they write code that invokes a method having a precondition, they must make
sure their code assures that the precondition is met before making the method call.
Discuss method signatures in the Grid interface. (This is more of the “we do” part
of the lesson.) Look only at the signatures, the part they need to know how to use from
the GridWorld Testable API.
For the “you do” part of the lesson, have the students complete the Grid worksheet.
Move about the room, checking to see how they are doing, offering suggestions or
answering questions as needed.
Form small cooperative-learning groups of three or four students. The groups
will analyze the Grid interface method signatures and, for each signature, list the name,
number of parameters, type and name of each parameter, and return type. For similar
signatures, have the groups write down exactly what each method does and how the
return values differ. If groups complete their analysis of the Grid method signatures early,
ask them to analyze the Location class methods in the same way.
Accommodations
Groups will be assigned in such a way that a less knowledgeable or able student will
have the support of a more knowledgeable peer. All students will be responsible for
understanding the interface. Those who catch on quickly will be expected to help anyone
in the group who struggles with the concepts. Monitor groups to be sure this is happening.
27
Closure
Ask students to summarize what they learned about interfaces in today’s lesson. Randomly
select a spokesperson from each cooperative learning group to list the group’s findings
about one of the method signatures. Check for agreement between groups. Remind the
students to always be aware of the properties of a method signature, especially when
reading or writing code on the AP Exam.
Assignment
For homework, students will complete a similar analysis of the Comparable interface.
The homework will be collected and graded.
Assessment
• Diagnostic assessment occurs during the anticipatory set when students are asked
to recall their observations about the role play and the grid.
• Formative assessment is ongoing during the lesson. Didactic questioning during
the direct instruction segment, followed by teacher observation as the groups
analyze the Grid interface, provides continuous feedback to the teacher.
• Summative assessment is met through the Grid worksheet, group reports and
individual homework assignments.
Evaluation
Formulate questions that you will ask yourself after teaching this lesson:
• Did I get the students’ attention and activate their prior knowledge through my
introduction to the lesson?
• Did the students understand the differences between an interface and a class that
implements the interface?
• Were the students able to analyze the Grid interface and understand the method
signatures? Do they understand the significance of the preconditions? Will they be
able to use the methods correctly?
• Is there anything I would change about this lesson in the future?
• What did I do right that I would like to remember and repeat?
28
Lesson Objectives
• Given Part 3 of the Student Manual and Student Manual Appendixes B and C, the
student will be able to investigate inheritance and class design and make two lists,
each containing five important ideas they have found.
• Given the Actor Reading Worksheet, the student will complete the worksheet with
90 percent accuracy.
• Given the Extending Actor Reading Worksheet, the student will complete the
worksheet with 90 percent accuracy.
Materials
• GridWorld Part 3: GridWorld Classes and Interfaces (page 16)
(http://www.collegeboard.com/student/testing/ap/compsci_a/case.html)
• GridWorld Student Manual Testable API (http://www.collegeboard.com/prod_
downloads/student/testing/ap/compsci_a/compsci_a_exam_appendix.pdf)
• GridWorld Student Manual Testable Code for APCS A/AB (http://www.
collegeboard.com/prod_downloads/student/testing/ap/compsci_a/compsci_a_
exam_appendix.pdf)
• Actor Reading Worksheet (see Appendix J)
• Extending Actor Reading Worksheet (see Appendix K)
29
Anticipatory Set
When the students arrive in the classroom, they will find small containers of Play-Doh
and colored pipe cleaners (see Appendix B) available at a central table. They will use their
imagination to create bugs from the craft materials. Each student will take a sheet of large
scale (one inch or larger) graph paper and will design a movement pattern for his or her
bug. Remind the students that their bugs must remain within the grid. Students will give
their bugs a descriptive name that characterizes the bug’s unique movement style, and
they will share their creations with the class. Allow about 7 minutes for this activity.
Inform the students that, in this lesson, they will learn about the Actor class,
inheritance and code reuse. Actor is a superclass, and Bug is a subclass of Actor. Tell
the students that they will learn how to create their own subclass and implement that
class. In this lesson, they will discover some important design principles and then, in a
subsequent lesson, they will apply those principles in a group assignment. Students will
then design their own class.
Lesson Development
Start by having the students read the Actor and Extending Actor sections of Part 3
of the GridWorld Student Manual; examine the Actor, Rock and Flower API in the
GridWorld Testable API; and examine the Bug and BoxBug subclasses in the GridWorld
Testable Code for APCS A/AB. As they read, instruct the students to individually make
lists of the important things they learn about the Actor class, about extending Actor
and about the classes that extend Actor. Ask them to think about class design and what
a subclass inherits from the superclass. Tell them that when they finish the reading they
are to select the five ideas they think are the most important from each list and to make
new lists, which will be collected, putting those five ideas in order from most to least
important. Allow 15 minutes for this work, and then collect the lists.
Have the students return to the reading and complete the Actor and Extending
Actor Reading Worksheets. While they are doing that, compile the student lists into two
lists from the most frequent to the least frequent responses. You may need to combine
very similar responses into single statements. Arrange the compiled lists in order of most
to least important, using your educated opinion. (You may need to create the compiled
lists after class. You will be using these lists to introduce the lesson tomorrow.) Check the
students’ progress with the worksheets and provide help as needed.
30
Accommodations
For students who need extra help making the lists, you can offer suggestions as you
move about the room monitoring student progress. Students who need help with the
worksheets will be encouraged to discuss the questions with you during your open
period or after school..
Closure
At the end of class, ask the students what they learned about the Actor superclass and
the Rock, Flower, Bug and BoxBug subclasses from their investigation of the API and
code. Ask them to describe how they investigated the reading and code to find the main
ideas. Summarize the design principles found in this part of the case study.
Assignment
Complete the Actor and Extending Actor Reading worksheets for homework. These will
be collected and graded.
Assessment
• Diagnostic assessment concerning what students know about the classes will occur
as you listen to the students talk about their bug models.
• Formative assessment will be ongoing during the lesson as you observe students
making their lists, ask individual students questions, and respond to their
comments and questions.
• Summative assessment will occur through the lists and worksheets they complete
and hand in.
Evaluation
Formulate questions you will ask yourself after teaching this lesson:
• Did making the bug models, creating a movement pattern for them, and naming
the models to represent their pattern focus the students’ attention on the lesson
and activate prior knowledge?
• Did I give adequate instructions for the investigative part of the lesson?
• Did reading for the big ideas and then reading to complete the worksheets
accomplish my goal of having students learn about design principles?
• Did having the students investigate on their own achieve my goals? Did they find
the information I intended for them to find? Did they learn anything about how to
investigate?
• What would I do differently if I taught this lesson again?
31
• What did I do well and what would I repeat if I taught this lesson again?
Note: Here are a few possible ideas students might list.
About Actor:
• Use putSelfInGrid to insert an Actor into the grid.
• Use removeSelfFromGrid to remove an Actor from the grid.
• The act method defines an Actor’s behavior.
• An Actor has color, location and direction.
• The moveTo method allows the actor to move to any valid location.
About extended Actor (They probably will find many more ideas for this category):
• Bug, Rock and Flower extend Actor.
• Rock overrides act by doing nothing — empty method.
• Flower overrides act by darkening on each step.
• The canMove method in Bug determines if a Bug can move.
• The instanceOf method determines whether an object is a member of a class.
Learning Goals
• The students will learn how to design and implement a subclass. They will learn
to use inherited methods and how to override methods from the super or parent
class.
• The students will learn to work cooperatively to design and implement a subclass.
32
Lesson Objectives
• Given the Jumper assignment from Part 3 of the GridWorld Student Manual, the
student will work cooperatively in a small group to design and implement the
Jumper class with 100 percent accuracy.
• Given Part 3 and Appendixes B and C of the GridWorld Student Manual, the
student will successfully design and implement his or her own subclass of Actor,
using an appropriate reimplementation of the act method and following a model
similar to BoxBug and Jumper.
Materials
• GridWorld Part 3: GridWorld Classes and Interfaces (page 16)
(http://www.collegeboard.com/student/testing/ap/compsci_a/case.html)
• GridWorld Student Manual Testable API (http://www.collegeboard.com/prod_
downloads/student/testing/ap/compsci_a/compsci_a_exam_appendix.pdf)
• GridWorld Student Manual Testable Code for APCS A/AB (http://www.
collegeboard.com/prod_downloads/student/testing/ap/compsci_a/compsci_a_
exam_appendix.pdf)
• Results of the previous day’s lesson (five important ideas in two categories) set
up as hidden answers to a version of the Family Feud game. These can be on an
overhead transparency or covered on the board.
Anticipatory Set
Tell the students that they are going to play Family Feud. Inform them that you have taken their
“Top Five” important ideas in the two categories, Actor and Extending Actor, from their
previous lesson and tabulated the results. Divide the students into two “families” and play two
rounds based on those lists. Be sure that the teams are balanced in terms of overall academic
strength. The topics will be: The Five Most Important Ideas About the Actor Class and
The Five Most Important Ideas About Extending the Actor Class. Each team will choose a
captain. Play the Five Most Important Ideas About the Actor category first. Follow the game
rules for Family Feud; if you’re not sure how the game is played, see the Resources section for
links to rules and an online version, or ask your students.
Tell the class that, now that they have reviewed what they found out about Actor
and extending Actor, they are going to work in small groups to learn how to design and
develop a subclass of Actor: the Jumper class.
Lesson Development
Separate the class into small groups. Tell the students to follow directions found in Part
3 of the GridWorld Student Manual for the Jumper exercise, deciding within the group
how to answer the questions, design the class and implement the code. They are to
33
answer the questions in writing (using a word processor is preferred). Their answers will
be collected as well as their completed code. Urge them to use the GridWorld Testable
Code for APCS A/AB and Testable API as references. While they work, walk around the
classroom monitoring group progress and answering questions as needed. Be sure all
students are actively involved. Each student should take a turn entering code while the
others make suggestions and check for errors. For the coding part, you may decide to
have the students work in pairs with one student typing and the other navigating (making
suggestions and watching for errors). If you use this technique, insist that the pairs switch
roles at least once during coding. Tell the class their grade will be based on both the
success of the completed project and their level of participation. They will be evaluating
themselves and the other group members at the end of class. Collect their answers to the
Jumper exercise questions; code may be submitted electronically.
Accommodations
Students will be assigned to groups in such a way that a more able or knowledgeable
student can help a less able student. Groups will be reminded that they are to cooperate
and be sure all members understand every step of the assignment. The teacher should also
monitor the groups and provide help as needed.
Closure
Groups with working code will run their applications for the class to see. Ask the groups
to name one thing they learned through this exercise. Each group must contribute
something not already mentioned. Ask them to talk about how the groups answered the
questions, designed their Jumper class and implemented the code. What worked best
in this group situation? Was anything difficult? Did they overcome the difficulties? How?
Remind them that programmers usually work in teams in the workplace and that it’s
essential that they all cooperate and contribute. Give them a copy of the individual group
member evaluation form (see Materials list above) to complete.
Assignment
Each student will design and implement a subclass of his or her own choice. They may
work on this at home and in class the following day. Students should also write a journal
entry, describing what they have learned in Part 3 of the GridWorld case study. (See
Materials list above for a description.)
Assessment
• Diagnostic assessment occurs during the anticipatory set as students participate in
the game. Ensure that everyone is involved in deciding on a group response to the
game.
• Formative assessment occurs during the lesson as the teacher moves about the
room observing, listening and questioning the groups.
34
Evaluation
Formulate questions you will ask yourself after teaching this lesson:
• Did the Family Feud game grab the students’ attention, focus them on the lesson
and activate prior knowledge?
• Were my directions to the groups clear? Did they understand how to work together
to solve the problem?
• During closure did I ask appropriate questions to help the students summarize the
lesson? Did I help them understand the importance of working together? Did we
discuss techniques for success in cooperative groups?
• Is there anything I will change if I teach this lesson again?
• Is there anything that went very well and that I will repeat in future lessons?
35
Appendix A
36
Appendix B
Resources
37
Description_______________________________________________________________
Code:
Correct class structure
Descriptive identifiers
Well commented
Logically structured
Well-designed test class
Implementation:
Does the code run?
Test cases provided?
Output matches test cases?
Output readable?
Text output grammatically correct?
Comments:
38
Name______________________________Project_________________________________
Group Name________________________
My participation was:
39
Appendix C
40
21. Restart the BugRunner.java . Press on an empty cell. How many constructors are in
the drop-down menu?
22. How many of the constructors are for Actor?
23. Press the Step button.
24. What new constructors are now in the drop-down menu?
25. What determines the list of constructors in the drop-down menu?
26. Select the constructor info.gridworld.actor.Actor(). What image appears?
27. When a constructor requires a parameter what appears on screen?
28. Complete the Do You Know? Set 1.
41
42
18. How is the Run button different from the Step button? The Run button carries out
a series of steps.
19. What effect does the slider have? It changes the delay between steps.
20. Would the grid fill up with flowers if the GUI was left running indefinitely? Why?
No, the flowers only appear where the bug moved, and the bug will move in a
repeated path.
21. Restart the BugRunner.java . Press on an empty cell. How many constructors
are in the drop-down menu? Five
22. How many of the constructors are for Actor? One
23. Press the Step button.
24. What new constructors are now in the drop-down menu?
info.gridworld.actor.Flower(java.awt.Color)
info.gridworld.actor.Flower()
25. What determines the list of constructors in the drop-down menu? The objects that
have been placed in the grid.
26. Select the constructor info.gridworld.actor.Actor(). What image
appears? Theater Mask for comedy
27. When a constructor requires a parameter, what appears on screen? Dialogue
window
28. Complete the Do You Know? Set 1.
43
Appendix D
44
-270
-180
-45
-315
-360
-225
-135
-720
45
9. Explain the difference between what happens when you invoke the method
setDirection(45) and the turn method? setDirection(45) is
inherited from Actor and turns the bug northeast. The turn method rotates the
bug 45 degrees right.
10. Change the direction so that all the actors are facing the left edge of the grid. What
method did you use? setDirection(270)
11. Complete the Exercises on page 8.
12. How many Actors can be in a cell? One
46
47
Appendix E
Journal Descriptions
Submitting the journal electronically has the advantage of the teacher being able to use
track changes for comments.
Journal 1
Start your journal by describing your experience in class today. Write about three
things you learned in your investigation and one question you have that was not
answered so far. Discuss how today’s lesson relates to you and to what you expect to
learn in AP Computer Science.
Journal 2
Write about your role in the role play. What did you learn from playing the part?
What were your responsibilities in that role? With which other roles did your role
collaborate? How did you feel when you were playing the part? What value did the
role play have for you?
Journal 3
Write about what you learned from the readings, activities and assignments in Part
3 of the case study. What was especially interesting or motivating for you, and why?
What did you learn about working with others in the class? How has Part 3 increased
your understanding of the principles of computer science? How will you apply
concepts from Part 3 to classwork outside the case study? Is there anything you wish
would have been covered in more detail? What unanswered questions do you have?
Somewhere in your journal begin one sentence with the words “I wonder … ” and
another with the words “I believe … ”
48
Name_____________________________________
Self-
CRITERIA POINTS
Evaluation
1. Content of the Entries
• Substantive reactions to the reading material 4
• Thoughtful reflections about class discussions . 10
and activities 3
• Insightful applications of course content 3
3. Originality
• Appealing visual presentation of the text entries 2 4
• Mode of expressing the thought in writing 2
Total 20
Comments:
49
Appendix F
50
51
52
Appendix G
Runner Classes
1. Read page 12 of the Student Manual.
2. What is required to observe the behavior of one or more actors?
3. What is an ActorWorld object?
4. What method is used to place an object into the grid?
5. What two ActorWorld methods appear in the BoxBugRunner?
6. What does it mean to have an overloaded method?
7. What must you do to demonstrate your own classes extending Bug?
8. Explain how the two different add methods work.
9. Do the Exercises at the end of Part 2.
10. Write a runner class for a StudentBug class. The StudentBug has a
constructor that takes a color. Add a Bug, two StudentBugs and a Rock into
the world, and test your class.
53
54
Appendix H
55
56
38. What direction is an actor traveling if rows are increasing and columns are decreasing?
39. What is compared in the equals method of Location? _
40. What is compared in the compareTo method of Location?
41. Write a segment of code to output the name of Bug bugBoy or Bug bugGirl,
with the lowest Location.
42. When will the loc1.compareTo(loc2) method return a positive number?
Assume: loc1 = new Location(row1,col1) and loc2= new
Location(row2,col2) (Describe every situation.)
43. Do questions Do You Know? Set 3.
57
58
Question 18 refers to the following line of code from the Location class.
18. What does static final mean? It denotes a constant, so the value of North
cannot be changed.
19. Write an example of how to use the Location constant EAST in some Bug class.
Location.EAST
20. Write a segment of code to have Bug bugBoy change its color to blue if it is
facing north and change its color to red if it is not facing north.
if (bugBoy.getDirection() == Location.NORTH)
bugBoy.setColor(Color.BLUE);
else
bugBoy.setColor(Color.RED);
59
60
Appendix I
61
19. Create and initalize numCells to hold the number total number of cells in Grid
someGrid.
20. Do questions Do You Know? Set 4.
62
8. What must not be passed in as an argument in all case study methods? null
9. Write a segment of code to output if a Location loc is contained in grd.
if (grd.isValid(loc))
System.out.println(loc + “ is a valid location in grd”);
else
System.out.println(loc + “ is an invalid location in grd”);
10. List the three methods that add, remove and retrieve objects from a Grid. put,
remove, get
11. Why do all three of these methods return E? The Grid interface contains objects
of E type.
12. Declare Actor act1 to reference the Actor at Location loc1 in grd.
Actor act1 = grd.get(loc1);
63
64
Appendix J
65
18. After the code for problem 15 is executed, what is the location of the original actor
at otherLoc?
19. How many new modifier methods exist for the Actor class?
20. Write a statement to have Actor act1 be the color Color.BLUE.
21. Write a statement to check if Actor act1 and Actor act2 are different
colors. If they are, change act2 to act1’s color.
22. Write a statement to check if Actor act1 and Actor act2 face different
directions. If they do, have act2 face the same direction as act1.
23. Write code to check if grd contains an Actor at Location otherLoc. If
otherLoc is not empty, remove the Actor there.
24. Write code to change all the Actors in actr’s grid to be actr’s color.
25. How is the behavior of a class that extends Actor defined?
26. What is the behavior of the Actor class?
27. How can you extend the Actor class and keep the behavior of the Actor class?
28. What classes provide examples of overriding the act method?
29. Do questions Do You Know? Set 5.
66
11. Why does the removeSelfFromGrid method have no parameters? The actor
knows its location and grid, so it does not need any other information.
67
12. Write a segment of code to remove all Actors that are neighbors of actr.
ArrayList<Location> occNbr =
grd.getOccupiedAdjacentLocations(loc);
for (Location neighborLoc: occNbr)
{
Actor neighbor = grd.get(neighborLoc);
neighbor.removeSelfFromGrid();
}
13. Why not just put and remove actors directly from the grid? The put and
remove methods do not update the Actor object to reflect the change in state of
the object. This could leave an actor in an inconsistent state with the grid.
14. Write code to check if grd contains an Actor at Location mysteryLoc. If
mysteryLoc is empty, add an Actor there.
if (grd.isValid(mysteryLoc) && grd.get(mysteryLoc)==
null)
new Actor().putSelfInGrid(grd, mysteryLoc);
16. What happens when an actor calls the moveTo method using a location already
occupied by another actor? The other actor removes itself from the grid and the
current actor takes its location.
17. Write a statement to have Actor act1 move to the location of Actor act2.
act1.moveTo(act2.getLocation());
18. After the code for problem 15 is executed, what is the location of the original actor
at otherLoc? null
19. How many new modifier methods exist for the Actor class? Two (setColor,
setDirection)
20. Write a statement to have Actor act1 be the color Color.BLUE.
act1.setColor(Color.BLUE);
21. Write a statement to check if Actor act1 and Actor act2 are different
colors. If they are, change act2 to act1’s color.
if (! act1.getColor().equals(act2.getColor()))
act2.setColor(act1.getColor());
68
22. Write a statement to check if Actor act1 and Actor act2 face different
directions. If they do, have act2 face the same direction as act1.
if (act1.getDirection() != act2.getDirection())
act2.setDirection(act1.getDirection());
24. Write code to change all the Actors in actr’s grid to be actr’s color.
Grid<Actor> grd = actr.getGrid();
Color clr = actr.getColor();
ArrayList<Location> allActorLoc = grd.
getOccupiedLocations();
for (Location occupied: allActorLoc)
{
Actor temp = grd.get(occupied);
temp.setColor(clr);
}
25. How is the behavior of a class that extends Actor defined? By overriding act
26. What is the behavior of the Actor class? It reverses the direction of the actor.
27. How can you extend the Actor class and keep the behavior of the Actor class?
Do not override the act method.
28. What classes provide examples of overriding the act method? Bug, Flower and
Rock
29. Do questions Do You Know? Set 5.
69
Appendix K
70
71
11. Is instanceof Actor always true for any occupant in a Grid<E>? No,
because a Grid can contain objects that are not Actors.
12. Write a segment of code to remove all the Rocks in Grid<Actor> grd.
ArrayList<Location> allActorLoc = grd.getOccupiedLocations();
for (Location occupied : allActorLoc)
{
Actor temp = grd.get(occupied);
if (temp instanceOf Rock)
temp.removeSelfFromGrid();
}
72
13. If the adjacent location in front of Bug bg is a Flower, change the flower’s
color to bg’s color.
Grid<Actor> gr = bg.getGrid();
Location loc = bg.getLocation();
Location neighLoc =loc.getAdjacentLocation(bg.getDirection());
if (gr.isValid(neighLoc))
{
Actor actr = gr.get(neighLoc);
if (actr != null && actr instanceof Flower)
actr.setColor(bg.getColor());
}
14. If the adjacent location to a Bug is null, what does that mean about that grid
location? It is empty or invalid.
15. Why does the canMove method need to check if the neighbor is null first?
Short circuit evaluation
16. Why does the canMove method need to check if a bug is in the grid? It is possible
that an actor has been removed from the grid by another actor.
17. What does the turn method for bug do? Turns 45 degrees to the right
18. When is the turn method called by a bug method? When the location in front is
blocked
19. Do questions Do You Know? Set 6.
20. Read What Makes It Run? (page 27)
73
Introduction
Students are always curious about the application of what they learn in class to the “real
world.” In this project, students will model an ecosystem, a task that has been and is still
undertaken by many biologists and environmental scientists the world over. They will use
the GridWorld simulation to model an Amazon rainforest, although any ecosystem can be
simulated (desert, tundra, arctic, etc.).
Students will simulate one of three different types of symbiotic relationships and
a predator-prey relationship. The “hook” to this project is that students are able to design
their own creatures to place into the ecosystem along with creatures designed by other
students. The resulting interaction is one that students (and I) enjoy seeing and analyzing.
For this project, I assume that students are familiar with the basic operation of GridWorld
and have studied inheritance and polymorphism in addition to having a working
knowledge of class structure (data members and methods).
The project consists of four parts. In the first part, students will design and write
class definitions and implementations for two creatures that are involved in one of three
types of symbiotic relationships: mutualistic (both creatures benefit from each other),
commensalistic (one creature benefits, the other is unaffected) and parasitic (one creature
is harmed or weakened but not directly killed off). At least one of these creatures must
inherit from Critter or a subclass or Critter. Students may choose which symbiotic
relationship to model.
The second part requires students to design and write class definitions and
implementations for two creatures that exist in a predator-prey relationship (one creature
“eats” the other creature). Again, at least one of the two creatures must inherit from
Critter or a subclass of Critter.
The third part of the project requires students to design and write a class definition
and implementation for an “environmental feature” with which their creatures can interact
(trees, rivers, streams, holes, night/day, iceberg, cactus, etc.). Most of these features will
inherit from Actor instead of Critter, and students will define how their creatures
interact with the environmental feature. This part is geared toward students who are able
to implement such things as trees (tunnels for creatures to burrow into), queues (logs for
creatures to walk through) and stacks (places for creatures to store food). However, this
part can also accommodate students who can use ArrayLists to design simple features
such as nests. Again, any of these environmental features will inherit from Actor or
a subclass of Actor and include one or more of these data structures (tree, set, stack,
queue, etc.) in their private data member list.
74
Finally, in the fourth part, after all creatures and “environmental features” have
been written, the students will then integrate these objects into one working ecosystem,
where they will be able to see how their own creatures interact with other creatures and
“environmental features.” Here students can see that modifying the methods called in the
act method, but not the act method itself (e.g., by NOT removing or renaming the
methods called in the act method), is a powerful mechanism to create a related “family”
of creatures who behave or “act” in the same basic manner. In addition, students will also
see that overriding the act method of an Actor may be desirable and/or necessary
thing to do. In any case, all objects can and will be processed polymorphically because
they all possess an act method.
I have done a similar type of project with the Marine Biology Simulation. My
students were very excited to complete a project in which they were involved with the
design decisions of the “fish” and the “environmental features” of the “ocean.” In addition
to being the highlight of the year for my students, the final integration of all objects
into one working program illustrated the value of designing classes that could be used
without modification in a large-scale project and the issues that arise when certain design
decisions are made.
Learning Goals
• To understand that there are five methods which control the “acting” of a
Critter (getActors, processActors, getMoveLocations,
selectMoveLocation and makeMove).
• To understand that any or all of these five methods can be overridden to alter
creature behavior.
• To write a class definition that inherits from Critter and overrides one or more
of the five methods called in the act method.
• To understand why the act method should not be overridden.
• To understand the importance of clearly stated design specifications.
• To be able to integrate written class implementations into a larger project.
Instructional Considerations
This lesson assumes that the GridWorld simulation has been introduced and that students
are familiar with class definitions, inheritance and polymorphism. If students have not
been introduced to class design, this project may serve as their first experience with
designing a class and writing a class definition based on their own specifications. If this
is the case, it may be fruitful for each student to give a 4- to 5-minute oral presentation of
75
their ideas for the specifications of their class design. Allowing students to verbalize their
thoughts requires them to think through their thought processes (metacognition) and
justify their design decisions to themselves. Students may, and probably will, make design
changes based on feedback from the teacher and/or their peers. Allowing each student
to present their creature designs (and corresponding class names) will allow for other
students/groups to know what other creatures and features will be in the ecosystem in
Part 4.
Teaching Timeline (Each day described below is a
55-minute class period.)
Day 1: Introduce the project. Separate large classes into small groups (more
discussion on this below). Goal for students: (1) define class names for their
creatures, (2) define creature behavior, (3) define new instance variables for
their creatures, and (4) define which methods in act will be overridden for
their creatures.
Day 2: Students present ideas for creatures in Part I — Symbiotic relationships. Share
class names and creature behavior with other students/groups so that all know
what creatures will eventually exist in the “ecosystem.”
Day 3: Lab time — Write complete class definitions for the creatures presented on
Days 1–2 and create images for their new creatures. Test class implementation
in a test program. During this time, the teacher should move among
individuals or groups to check on student progress and address any problems.
Day 4: Students present ideas for creatures for Part II — Predator-prey relationships.
Share class names and creature behaviors as in Day 2.
Day 5: Lab time — Write complete class definitions for creatures presented on Day 4,
and create images for their new creatures. Test class implementation in a test
program. The teacher should again move about the class to check on student
progress.
Day 6: Students present ideas for Part III — Environmental features. Share class
names and environmental feature behavior as in Day 2.
Day 7: Lab time — Write complete class definitions for environmental feature
described on Day 6 and create images for their new feature. Test class
implementation in a test program.
Day 8: Integration of some or all of creatures and environmental features into one
working program.
76
77
the middle group of students, I will give more detailed instruction to the last group of
students who need help. I can have a small group discussion addressing their specific
questions while the others are at work. If needed, I will give ideas for creatures and walk
them through the design and coding process. I gauge their understanding to ensure that
I do not give them too much information, but instead constantly put them in a position
to think and proceed successfully.
I have found that allowing students to design their own objects, whether they are
fish, aliens or creatures, gives them a sense of ownership of their project. I only assign
the specifications for what needs to be done and how it will be assessed, but they have
the freedom to design something of their own. I have found this to be true for all types
of students: The ownership component of their project goes a long way in terms of their
intrinsic motivation level.
Learning Styles
Throughout the course, my delivery of the material includes auditory, kinesthetic and
visual components; this project is no different. When students present their ideas as
outlined in the “Teaching Timeline” above, I require them to speak, draw and act out
(mini role play) how their creatures will behave. Specifically, students describe verbally
how their creature will behave. They are given a 2-minute time limit to clearly and
succinctly describe their creatures. This 2-minute limit forces the students to “get to the
point” and remove any extraneous detail from their description. During their verbal
description, they are required to draw diagrams of their creature in a grid and show how
their creature will move and/or process other creatures in different situations. Diagrams
help the other students (and the teacher!) to understand the behavior of their creature.
Finally, as a mini “role play,” the students are required to perform an enactment of how
their creatures will behave using their peers as “creatures” in the grid. (I have the students
create a “grid” by moving their desks into a two-dimensional array arrangement.) In using
this three-pronged approach to teaching the material, I can anecdotally say that many
more students gain a deeper understanding of the material/problem at hand than when
I did not require all three learning modalities. For students who do not master these
concepts as quickly, I often find that addressing these three areas a second time and at a
slower pace helps these students grasp and internalize the material.
Student Assignments
Below are the formal assignments with design requirements for each of the four parts of
the project. These may be altered in any way to fit the dynamics of your class.
78
Student Directions
You have been hired to write a program that simulates the symbiotic (mutualistic,
commensalistic or parasitic) relationship between two kinds of creatures in an
ecosystem you choose. A mutualistic relationship is one where both creatures benefit
from each other’s existence; a commensalistic relationship is one where one creature
benefits from the relationship, but the other is unaffected; and a parasitic relationship
is one where one creature benefits from the relationship and the other is harmed
but not necessarily killed. You will write the class definitions for your creatures and
incorporate them into a working program that tests the functionality of the creatures.
Part I Requirements
1. At least one of the two creatures must inherit from Critter or a subclass of
Critter.
2. The two creatures must exhibit one of the three types of symbiotic behavior.
3. The creature(s) that inherits from Critter must NOT override the act
method.
4. The creature(s) that inherits from Critter should override one or more of the
“Big 5” methods called in the act method: getActors, processActors,
getMoveLocations, selectMoveLocation and makeMove.
5. All of the overridden “Big 5” methods must satisfy that method’s stated
postconditions.
6. Your new creature may add up to two new instance variables and two new
methods.
79
7. The two creatures should only interact with and/or kill off one creature outside
of its symbiotic relationship.
8. The new creatures (Java files and images) should be integrated into one
working GridWorld program.
80
81
Student Directions
You have been hired to write a program that simulates the predator-prey relationship
between creatures in an ecosystem. You will write the class definitions for the creature
descriptions that you were given and incorporate them into a working program that tests
the functionality of the creatures.
Part II Requirements
1. At least one of the two creatures must inherit from Critter or a subclass of
Critter.
2. The two creatures must exhibit a predator-prey relationship (i.e., one creature must
“eat” the other).
3. The creature(s) that inherits from Critter must NOT override the act method.
4. The creature(s) that inherits from Critter should override one or more of the
“Big 5” methods called in the act method: getActors, processActors,
getMoveLocations, selectMoveLocation and makeMove.
5. All of the overridden “Big 5” methods must satisfy that method’s stated
postconditions.
6. Each creature that inherits from Critter adds at most only two new instance
variables and at most two new methods.
7. The two creatures only interact with and/or kill off one creature outside of its
predator-prey relationship.
8. The new creatures (Java files and images) are integrated into one working
GridWorld program.
82
83
Student Directions
The company that has hired you wants to add an environmental feature found in the
ecosystem to be added to the simulation. This feature should interact with at least
one creature in the simulation. You will write the class definition for the feature and
incorporate it into a working program that tests its functionality.
Part III Requirements
1. The environmental feature should inherit from Actor or a subclass of
Actor.
2. At least one of the creatures written in Parts I and II should interact with
the environmental feature. This will require modification of the creature to
recognize the environmental feature.
3. An image for the environmental feature should be created.
4. The environmental feature should use one or more of the following containers:
ArrayList (AP Computer Science A only), stack, queue, tree, set or linked list
(for those students who have studied these more advanced data structures).
84
Part IV Requirements
You should give copies of your creatures and environmental feature Java files and
images to each class member and/or group in your class.
Your creatures and environmental features (Java files and images) should be directly
usable in a standard GridWorld project (i.e., each new class should have an act
method that can be called polymorphically).
Sample Project
In this sample project, I created a simple ecosystem in the Amazon rainforest with a
symbiotic relationship, a predator-prey relationship and an environmental feature. The
project consists of a Bird, Agouti (a nut-eating rodent), Nut, Seed, Fly, Larvae, Venus
Flytrap and Tree. An inheritance diagram is shown below.
85
Symbiotic Relationship
In my model, the agouti rodent and the bird exist in a commensalistic relationship. Here
the agouti feeds on nuts, leaving the seeds behind. The bird, which would otherwise
be unable to eat the seeds, benefits from the agouti breaking the nut apart, while the
agouti does not benefit from the bird. The Agouti and Bird classes both inherit from
Critter, while the Nut and Seed classes inherit from Actor.
Predator-Prey Relationships
These types of relationships are easy to think about and implement. Here the predator is
the VenusFlytrap and the fly is the prey. Flies can fly around as a Critter moves, as
mentioned above. However, if a fly moves into a location in front of a VenusFlytrap, it
will be eaten by the VenusFlytrap. The VenusFlytrap will then turn to the right or
left 45 degrees and wait for the next fly. If it does not eat within five steps, then it will turn
45 degrees again.
86
However, to keep the fly population alive and well, flies will leave larvae behind after
each move. The larvae will turn into a fly after a period of 10 iterations of its act method.
VenusFlytrap and Fly both inherit from Critter, while Larvae inherits from Actor.
(Note that I created a third creature in this example [i.e., the Larvae creature], whereas
the assignment calls for only two creatures. If students become enthusiastic about the project
and ask to create more creatures than are required, I encourage them to proceed as long as
the new creatures meet the requirements of their respective parts.)
Environmental Feature
In this project, a tree serving two purposes was implemented. First, it will drop nuts into
adjacent locations for the agouti to eat. Second, it serves as a resting place for flies. If a fly flies
into an adjacent location, the fly will “enter” the tree and be stored internally in the tree in an
ArrayList. When four flies have entered the tree, they will, one by one, fly away from the tree.
The following figure shows a complete Amazon Ecosystem, with each of the
objects described above.
87
The following figure shows the new data members and methods added to the class derived
from Critter.
Select methods from the Fly, Agouti and VenusFlytrap classes are shown below.
Fly placeLarvae method
void placeLarvae(Location loc)
{
if (moveCounter < 10)
{
moveCounter++;
}
else
{
moveCounter = 0;
int currentDir = getDirection();
Location currentLoc = getLocation();
// find the direction BEHIND the fly
// where the larvae will be left
int behindDir = currentDir + Location. HALF_CIRCLE;
// find the location behind the fly
Location locBehind =
currentLoc.getAdjacentLocation(behindDir);
if (isValidLarvaeLocation(locBehind))
{
// place larvae behind fly
Larvae newLarvae = new Larvae();
newLarvae.putSelfInGrid(getGrid(),locBehind);
}
}
} // end method placeLarvae
88
89
Conclusion
This sample Amazon project can be used to demonstrate possibilities for each of the
four parts of the project. After some discussion, students will undoubtedly think of even
more relevant and sophisticated ecosystems to simulate, especially if they have taken or
are taking AP Environmental Science. (Note that this project can be further modified to
model systems consisting of “nonliving creatures,” e.g., robots, traffic systems, air traffic
controller systems, etc.) Allowing students to design their own creatures and integrating
these creations into one project gives them ownership of the project and makes for a great
“Grand Finale,” both for the students and the teacher.
Sample Files for the Amazon Project can be downloaded from the GridWorld tag
at http://www.thecubscientist.com/APCS/indexAPCS.html.
Worksheets on Part 4 of GridWorld, written by Joe Coglianese, are in the
appendixes that follow.
90
Appendix A
91
92
13. Assign locList to be the locations that someCritter could move into.
locList = someCritter.getMoveLocations();
14. Write a segment of code to have someCritter move to a randomly selected
location from the locList.
int size = locList.size();
int ranNum = (int)(Math.random() * size);
someCritter.makeMove(locList.get(ranNum));
15. Which method should not be overridden in the subclasses of Critter? act
16. What was the design intention of the Critter class? Critters are actors that
process other actors and then move.
17. When the Critter class is unsuitable for extending, what class should be
extended? Actor
18. Do questions Do You Know? Set 7.
93
Appendix B
94
7. What does the processActors method in the Critter remove? All actors
that are not rocks or critters
8. What operator allows a Critter to tell if it is going to process another
Critter? instanceof
9. If a critter did not eat Actors, what would it eat? Nothing
10. What is the three-step process for a critter to move to a new location?
a. Determine which locations are candidates for the move.
b. Select one candidate
c. Make the move
11. Why are there three different methods implementing this single process? Allows
subclasses to change each behavior separately
95
12. What is returned by the getMoveLocations method for Critter? All the
empty adjacent locations
13. If a critter were at (4, 3) facing East, what could be in the list returned by
getMoveLocations? (3, 2), (3, 3), (3, 4), (4, 2), (4, 4), (5, 2), (5, 3) and (5, 4)
14. How does a Critter select which location to move to? Randomly
15. What does getMoveLocations return if a Critter is unable to move? Its
current location
16. What gets passed to the makeMove method by a critter? The selected location
17. What if null is passed in as an argument for the makeMove method? The critter
removes itself from the grid!
96
Appendix C
97
ChameleonCritter
1. Read pages 32–33 of the Student Manual.
2. Which actors does Critter class send its list of actors for processing? All the
neighboring actors (touching the critter)
3. Which actors does ChameleonCritter class send its list of actors for
processing? The same as Critter, all the neighboring actors
4. What are the neighbors of the ChameleonCritter at (6, 3)? (5, 2), (5, 3), (5, 4),
(6, 2), (6, 5), (7, 2), (7, 3) and (7, 5)
5. How does Critter process actors? Removes actors that are not rocks or critters
6. How does ChameleonCritter process actors? Randomly selects one and
changes its own color to the color of the selected actor
7. Which method(s) does the ChameleonCritter override? makeMove,
processActors
8. What are the neighbors of the ChameleonCritter at (6, 3)? (5, 2), (5, 3), (5, 4),
(6, 2), (6, 5), (7, 2), (7, 3) and (7, 5)
9. If the ChameleonCritter at (4, 4) move to (3, 4), what direction would it be
facing? Location.NORTH
98
Appendix D
Another Critter
CrabCritter
1. Read page 34 of the Student Manual.
2. Which actors does CrabCritter class send its list of actors for processing?
3. Actors at which locations would be sent for processing by a CrabCritter at (6,
3) facing Location.EAST?
4. How does CrabCritter process actors?
5. Where is CrabCritter process actors defined?
6. If a CrabCritter were at (4, 3) facing Location.EAST, what locations
would be returned by getMoveLocations?
7. What methods did the CrabCritter override?
8. From what location would a CrabCritter at (3, 4) facing Location.NORTH eat?
9. What will a CrabCritter not eat? Why?
10. How does a crab select which location to move to?
11. What does a crab do if it cannot move?
Suppose there is a new subclass of CrabCritter named SkinnyCrabCritter. It
processes actors like CrabCritter but it only randomly selects one actor to eat. The
SkinnyCrabCritter moves like CrabCritter, but if it has not eaten it dies.
12. Explain why SkinnyCrabCritter dying in processActors would violate
the method’s postconditions.
13. In what method could SkinnyCrabCritter die?
14. Propose a way to have SkinnyCrabCritter die based on not eating in any
given turn.
99
100
Another Critter
CrabCritter
1. Read page 34 of the Student Manual.
2. Which actors does CrabCritter class send its list of actors for processing?
Actors from the three cells in front of CrabCritter
3. Actors at which locations would be sent for processing by a CrabCritter at (6,
3) facing Location.EAST? (5, 4), (6, 4) and (7, 4)
4. How does CrabCritter process actors? Removes all actors from the three cells
in front that are not rocks or critters
5. Where is CrabCritter process actors defined? Critter
6. If a CrabCritter were at (4, 3) facing Location.EAST, what locations
would could be returned by getMoveLocations? [ (4, 2), (4, 4) ]
7. What methods did the CrabCritter override? getActor,
getMoveLocations and makeMove .
8. From what location would a CrabCritter at (3, 4) facing Location.NORTH
eat? (2, 3), (2, 4), (2, 5)
9. What will a CrabCritter not eat? Why? Rock or Critter because it was
inherited from Critter
10. How does a crab select the location to move to? Randomly
11. What does a crab do if it can not move? Turns 90 degrees
Suppose there is a new subclass of CrabCritter named SkinnyCrabCritter. It
processes actors like CrabCritter but it only randomly selects one actor to eat. The
SkinnyCrabCritter moves like CrabCritter, but if it has not eaten it dies.
12. Explain why SkinnyCrabCritter dying in processActors would
violate the method’s postconditions. Postcondition (2) the location of the critter is
unchanged.
13. In what method could SkinnyCrabCritter die? makeMove
101
14. Propose a way to have SkinnyCrabCritter die based on not eating in any
given turn. Add a Boolean instance variable to store if it has eaten. Then check
the value of the variable in the makeMove method and remove itself from the
grid if it has not eaten.
15. Write the processActors method for SkinnyCrabCritter.
public void processActors(ArrayList<Actor> actors)
{
int num = actors.size();
if( num == 0)
{
hasEasten = false;
return;
}
int ranNum = (int) (Math.random() * num);
Actor other = actors.get(ranNum);
other.removeSelfFromGrid();
}
102
Introduction
This project is designed to help students learn about extending the AbstractGrid class
as a part of the GridWorld case study (http://www.thecubscientist.com/APCS/indexAPCS.
html). Included in this project are a number of supporting materials to help students
become proficient at using the Grid class and also to become familiar with questions
regarding different implementations of a grid. The program assignment, Airplane
Scheduling, asks the students to extend the AbstractGrid class and then use the class
in a context to answer questions about seating priority in an airplane. In addition to the
program assignment, you will also find multiple-choice questions and a short-answer
assessment question involving Big-Oh for different implementations of a grid.
103
Passenger
The Passenger class should extend the Actor class and also provide functionality to
store the location of the passenger’s assigned seat on the airplane (separate from her or his
current location). It should also provide functionality for a counter to be used to “pause”
passengers as they are putting away their luggage upon reaching their rows, before leaving
the aisle to sit in their assigned seats.
The Passenger constructor should take two parameters: a row and seat
(column) value for the assigned seat of that passenger. It should assign values to the
private variables, including a wait time of 10 time steps for stowing luggage.
The Passenger class should also have an implementation for an act method.
The Passenger act method should deal with the following cases:
1. If the passenger is already in his or her seat, he or she should not do anything.
2. If the passenger is in the row where his or her seat is located and their luggage
counter is 0, then he or she should move into their seat.
3. If the passenger is in the row where his or her seat is located and their luggage
counter is greater than 0, he or she should continue storing their luggage (subtract
one from the luggage counter).
4. If the passenger is not yet to his or her row and the aisle is not blocked in front of
them, he or she should move one row closer to their assigned row.
104
Airplane
The Airplane class should extend the AbstractGrid class and provide data storage
for the grid. The Airplane, in addition to maintaining the ability to store rows and
columns of passengers, should also maintain a variable for the aisle row within the
airplane. The aisle is a column without seats and will be the means by which passengers
make their way to their seats.
The Airplane class needs a constructor that will take the number of rows, the
number of seats across and the location of the aisle.
Other methods the Airplane class needs to implement will be:
1. get(Location loc), which will retrieve a passenger stored at a particular
row/seat location
2. getNumCols(), which will return the number of seats across, plus one for the aisle
3. getNumRows(), which will return the number of rows of seats in the airplane
4. getOccupiedLocations(), which will return an ArrayList of
Locations for all of the seats that currently have passengers sitting in them, as
well as all of the locations in the aisle where passengers are either loading baggage
or waiting to continue on to their seats
5. isValid(Location loc), which will return true if the given location is a
valid seat or aisle location on the plane and false otherwise
6. remove(Location loc), which will remove the passenger from the grid (plane)
7. isAisleEmpty(), which will return a Boolean value if the aisle of the airplane
is empty (either the plane is completely empty or all passengers are seated)
8. getCenterAisle(), which will return the column number of the central aisle
9. put(Location loc, Passenger obj), which will insert the passenger
into the grid (Airplane) at the given location
10. put(Location loc, Object obj), which is used only to satisfy the
abstract class inheritance requirements
105
106
}
/**
* returns an ArrayList containing the occupied locations in the
* grid
*/
public ArrayList<Location> getOccupiedLocations() {
}
/**
* returns true if the given Location is valid, false otherwise
*/
public boolean isValid(Location loc) {
}
/**
* removes the passenger at the given location from the grid
*/
public Passenger remove(Location loc) {
}
/**
* Returns true if there are no passengers in the aisle
* waiting to be seated
*/
public boolean isAisleEmpty(){
}
/**
* returns the number corresponding to the column that serves
* as the center aisle on the airplane
*/
public int getCenterAisle(){
}
/**
* puts the passenger into the grid at the given location
*/
public Passenger put(Location loc, Passenger obj) {
}
107
/**
* puts the indicated object into the grid.
* This method exists only to satisfy inheritance requirements.
* only the overloaded put method with a passenger
* object should be called
*/
public Object put(Location loc, Object obj) {
}
}
AirplaneWorld
The AirplaneWorld class should extend the ActorWorld class. The
AirplaneWorld class does not need any new data stored other than what
ActorWorld provides for.
The AirplaneWorld constructor should take an Airplane parameter and
call the ActorWorld constructor with that parameter.
The Airplane world has one additional method, runSim(), that is used to run
the airplane simulation and watch how passengers seat themselves.
In a purely random seating arrangement, the runSim method will create a new
ArrayList of Passengers, with each passenger having a targeted seat location within
the aircraft. The easiest way to accomplish this is to write some loops to create a passenger
for every seat; be careful not to seat anyone in the aisle.
Until the ArrayList is empty, if the “door” to the airplane is empty (location 0,
aisle), randomly remove one passenger from the ArrayList and add him or her to the
airplane. Don’t forget to step and show the grid as you go. Also, make sure that all of your
passengers get seated before you finish the simulation (i.e., make sure the aisle is empty).
108
109
110
Appendix A
Discussion Questions
Preassignment Questions
These questions can be used before the assignment (after the description is read, but
before any code is written), for a discussion part way through the assignment as a way to
check for understanding, or after the assignment in a summary. Following the questions,
you will find possible discussion points to use with each question in your class discussion.
1. What similarities are there between an Airplane and a Grid? What are the
characteristics of each Location within an airplane as modeled by a Grid?
2. What information does an Airplane need to know that is separate from a
BoundedGrid? (For example, what is the difference between the information
you need to store for an Airplane and the information you store for a generic
BoundedGrid?)
3. Without extending any Grid class or interface, what would the challenges be for
implementation of the simulation?
4. Consider an Airplane implementation where the data structure used
specifically stores Passenger objects. For this particular program, why is it
feasible to store the objects in the grid in this manner, instead of using a data
structure that can store any type of object the way that BoundedGrid does?
5. What are some possible data structures that could be used for the Airplane?
What criteria would you use to choose one of these data structures? What
information would you like to know about the flights in order to choose the most
appropriate data structure?
6. Knowing that the planes are restricted to a relatively small size, but that the airline
wants to run the simulation a very large number of times repeatedly in order to
gather results, how does that affect your considerations?
111
2. An airplane needs to know the location of the aisle and any informational
methods that would be helpful in looking at seated pasengers versus standing
passengers.
3. Without extending a Grid class, the airplane could not know where the aisle was;
this information would have to be kept elsewhere, and it would make the code in
other places more difficult to write and less abstracted.
4. For this simulation, we are programming it specifically to hold passengers. With
the problem description given and the requirements of the client, it is not likely
that other types of objects would take up seats on the airplane.
5. Students may name any data structure covered in the course. Answers will vary
based on the material covered prior to this assignment. Knowledge about how full
the flights are would be helpful in selecting the most appropriate data structure.
6. This indicates that speed is a more important concern than space. It would be
acceptable to choose a data structure that required more memory in favor of a
faster implementation (i.e., a two-dimensional array would be preferable to a
linked list or even a sparse matrix).
Post-Assignment Questions
These questions can either be used for class discussion or as a part of an assessment.
1. For each of the following methods, specify the Big-Oh time for your
implementation:
getCenterAisle
aisleEmpty
getOccupiedLocations
get
put
2. Name a data structure, other than the one you used, that improves the time
efficiency of at least one of the above listed methods (even if the other methods
get slower). List the Big-Oh time for each of the above methods for the other data
structure that you chose. Defend your choice over this other data structure.
3. How would you change the program if we allowed for very large aircraft that had
two aisles (three seats to one side, an aisle, four seats in the middle, a second aisle
and three seats to the other side)?
4. How would you change the program if there were two doors to enter the airplane?
5. Based on your observations of seating time, what would you recommend to the
airline as a method of boarding passengers?
6. We only dealt with passengers as they entered the airplane. What other
possibilities in an airport exist for the study of data structures?
112
Appendix B
Multiple-Choice Questions
Use the following information to answer questions 1–4.
Consider the following two implementation of a Grid that stores Actors in an array.
You may assume that the average time for adding new items to the grid does not take
resizing into account.
Implementation I: The array is maintained in sorted order by inserting each new
actor into the array in order by location whenever an Actor is put into the Grid. The
Grid is also set up to maintain the list in sorted order with no gaps (null elements
between data) throughout the program. In order to find an Actor within the Grid, a
private getIndex method is implemented that uses a binary search in order to locate
either the index of the Actor itself or the index where the actor should be inserted.
Implementation II: The array is maintained in the order in which Actors were
added to the environment. A linear search is performed in order to get the index of an
Actor within the array any time it needs to be located.
1. What is the expected time for the Grid method get under Implementation I above?
a. O(1)
b. O(log n)
c. O(n)
d. O(n log n)
e. O(n2)
2. What is the expected time for the Grid method get under Implementation II above?
a. O(1)
b. O(log n)
c. O(n)
d. O(n log n)
e. O(n2)
113
3. Which of the following data structures would yield a comparable time for the get
method as Implementation I above?
a. LinkedList
b. HashMap
c. TreeMap
d. HashSet
e. None of the above
4. Which of the following methods would not need to be changed from their current
implementation in BoundedGrid in order to implement a Grid as defined
above (either Implementation I or II)?
a. put
b. isValid
c. remove
d. getNeighbors
e. All methods would need to be reimplemented
Use the following information to answer questions 5–7.
A group of scientists want to study how different plants attract different types of insects.
For this, they are going to write a computer simulation containing complex insect
behavior programmed into actors. When creating the simulation, they decided it would
be easier to divide the garden into sections based on the plants being grown and then
record all the different types of insects in each section to see what plants are favored. Their
current implementation of the Grid allows for only one Actor per location; however,
they would like to change the implementation of the Grid to allow the actors to move
freely throughout the grid, regardless of the number of actors already at that location.
Consider the following two implementations for the GardenGrid.
Implementation I: The GardenGrid implementation contains a HashMap
keyed by location. Each value stored in the HashMap is a HashSet of IDActors
representing the collection of actors in any one grid in the garden. The IDActor class is
an extension of Actor that contains a unique ID number for each actor that is used as
the key for the HashMap.
Implementation II: The GardenGrid implementation contains a HashMap of
IDActors. The unique ID number for each actor is used as the key for the HashMap.
5. With Implementation I above, if there are N locations inside the grid and S insects
in the simulation, what is the worst case time for retrieving information about a
single insect if we have its location and ID number?
a. O(1)
b. O(N)
c. O(S*N)
d. O(S)
114
e. O((log S)*N)
6. With Implementation II above, if there are N locations inside the grid and S
insects in the simulation, what is the worst case time for retrieving information
about a single insect if we have its location and ID number?
a. O(1)
b. O(N)
c. O(S*N)
d. O(S)
e. O((log S)*N)
7. The scientists in the study anticipate having a very large number of actors spread
relatively evenly over the different grids. They anticipate concentrations in
particular areas; however, they do not anticipate all of the insects being in only one
location on the grid. With this in mind, which of the above implementations will
be more efficient if the scientists plan on focusing on one location in the grid at a
time? This means that, during the simulation, at each time step they would retrieve
all the actors stored at a given location in order to process such information as
number of insects and variety of species.
a. Implementation I would be better.
b. Implementation II would be better.
c. Implementation I and II would be the same.
d. It is impossible to know the answer without more information about the
behavior of the insects.
e. It is impossible to know the information without more information about the
plants.
8. When creating an implementation of the Grid interface, which of the following
methods would most likely be affected by a change in data structure?
a. remove
b. getValidAdjacentNeighbors
c. getNeighbors
d. a and c only
e. a, b, and c
115
Appendix C
116
Fill in the following table with Big-Oh notation, representing the time it would
take for the applyWind method for each of the following implementations of the
GridWorld environment. Use r for the number of rows in the grid, c for the number of
columns in the grid and n for the width of the range to be blown. If another variable is
needed for the analysis, be sure to define it (i.e., b = number of bugs in environment).
North/South Wind
Implementation Big-Oh time for applyWind
2D Arrayarray
East/West Wind
Implementation Big-Oh time for applyWind
2D aArray
Solutions
Use r for the number of rows, c for the number of columns in the grid and n for the width
of the range to be blown. If another variable is needed for the analysis, be sure to define it
(i.e., b = number of bugs in environment).
117
North/South Wind
Implementation Big-Oh time for applyWind
2D Array O(n*r)
East/West Wind
Implementation Big-Oh time for applyWind
2D Array O(n*c)
Discussion Question
How do the values of n, r, c and b affect which implementations are more efficient?
(really large n, r and c with a really small b or vice versa)
118
Appendix D
119
120
Appendix E
121
16. What is the time complexity (Big-Oh) for the getNumCols method?
17. Write the constructor for BoundedArrayListGrid<E>. (Hint: use
BoundedGrid.java as a model.)
122
123
14. What is the time complexity (Big-Oh) for the getNumRows method? O(1)
15. Write the getNumCols method for BoundedArrayListGrid<E>.
public int getNumCols()
{
return occupantList.get(0).size();
}
16. What is the time complexity (Big-Oh) for the getNumCols method? O(1)
17. Write the constructor for BoundedArrayListGrid<E> . (Hint: use BoundedGrid.
java as a model.)
public BoundedArrayListGrid(int rows, int cols)
{
if (rows <= 0)
throw new IllegalArgumentException(“rows <= 0”);
if (cols <= 0)
throw new IllegalArgumentException(“cols <= 0”);
occupantList = new ArrayList<ArrayList<E>>();
for (int i = 0; i < rows; i++)
{
ArrayList<E> row = new ArrayList<E>();
occupantList.add(row);
for (int j = 0; j < cols; j++)
row.add(null);
}
124
Appendix F
125
126
{
if (node == null)
return null;
Location nodeLoc = node.getLocation();
if (loc.compareTo(nodeLoc) == 0)
return node.getOccupant();
else if (loc.compareTo(nodeLoc) < 0)
return getHelper (node.getLeft(), loc);
else
return getHelper (node.getRight(), loc);
}
127
128
Fran Trees taught AP Computer Science at Westfield High School in Westfield, N.J.,
from 1983 to 2001. She presently teaches computer science and mathematics at Drew
University in Madison, N.J. She has served as an AP Reader, Question Leader and
Exam Leader for the AP Computer Science Exam. She has also served as a member
of the AP Computer Science Test Development Committee and a member of various
ad hoc committees for AP Computer Science. Trees has served as a College Board
consultant in computer science since 1985 and is the primary author of the Teacher’s
Guide for AP Computer Science (C++) and the Advanced Placement® Computer Science
Study Guide to Accompany Java Concepts.
129