8/11/2019 AP Sf Computer Science Gridworld
1/80
AP
ComputerScience20072008
Professional Development
Workshop Materials
Special Focus:
GridWorld Case Study
8/11/2019 AP Sf Computer Science Gridworld
2/80
The College Board: Connecting Students to College Success
Te College Board is a not-or-profit membership association whose mission is to connect students
to college success and opportunity. Founded in 1900, the association is composed o more than
5,000 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,500 collegesthrough major programs and services in college admissions, guidance, assessment, financial aid,
enrollment, and teaching and learning. Among its best-known programs are the SA, the PSA/
NMSQ, and the Advanced Placement Program (AP). Te College Board is committed to
the principles o excellence and equity, and that commitment is embodied in all o its programs,
services, activities, and concerns.
For urther inormation, visit www.collegeboard.com.
2007 Te College Board. All rights reserved. College Board, Advanced Placement Program, AP,
AP Central, AP Vertical eams, Pre-AP, SA, and the acorn logo are registered trademarks o the
College Board. AP Potential and connect to college success are trademarks owned by the College
Board. All other products and services may be trademarks o their respective owners. Visit the
College Board on the Web: www.collegeboard.com.
ii
8/11/2019 AP Sf Computer Science Gridworld
3/80
1
APComputer ScienceSpecial Focus Materials for 200708GridWorld Case Study
Table of Contents
I. Introduction ...........................................................................................................3
II. Content-Enrichment Articles
A. The Design of the GridWorld Case Study .....................................................5
B. Integrating GridWorld....................................................................................18
III. Instructional Units/Lessons
A. Early Exercises with GridWorld ...................................................................26
B. Board Game Projects .....................................................................................31
C. Ant Farm Project ............................................................................................44
D. Save My Heart................................................................................................56
IV. About the Authors ..............................................................................................75
Table of Contents
8/11/2019 AP Sf Computer Science Gridworld
4/80
8/11/2019 AP Sf Computer Science Gridworld
5/80
3
Introduction
Debbie Carter, editor
Lancaster Country Day School
Lancaster, Pennsylvania
Starting with the 200708 academic year, a new case study based on a gridcalled
GridWorldwill be a required part o the AP Computer Science A and AB curricula.
GridWorld provides a graphical environment in which students can experiment with
different types o objects, observing the ways in which programming changes affect the
objects behavior. Questions related to this case study will first appear on the 2008 AP
Computer Science Exams. (AP Computer Science Newsletter, No. 6, Nov. 15, 2006).
We have commissioned a group o articles and instructional materials to help you prepare to
use the GridWorld case study to teach computer science.
Tose o us who are amiliar with the Marine Biology Simulation (MBS), the previous
AP Computer Science case study, will find some amiliar eatures in GridWorld. As Cay
Horstmann explains in his article, Te Design o the GridWorld Case Study, GridWorlds
design grew rom what we learned rom our experiences with the MBS in the classroom.
We wanted more exibility in the types o objects that could populate the world, as well as in
the ways that they could be displayed. An object in the world can
be displayed using an external graphic or via a graphics display class;
examine a list o other objects in the world and respond to one or more o them;
behave independently o other objects (or not at all).
In Integrating GridWorld, Jill Kaminski gives us both an overview and some detailed
practical advice about how we might effectively weave the case study throughout our AP
Computer Science courses.
Four additional authors, all computer science educators, have contributed hands-on
instructional materials, with complete solutions, descriptions o teaching strategies, and
suggestions or differentiation or students o varying needs. I would like to thank the
contributors or their hard work and cooperation, as well as their continuing commitment to
the AP Computer Science community.
We know that youll find many treasures in the next several pages, ready to be used to excite
your AP Computer Science students!
Introduction
8/11/2019 AP Sf Computer Science Gridworld
6/80
4
Special Focus: GridWorld Case Study
References
College Board.AP Computer Science Course Description, May 2007, May 2008.
College Board.AP Computer Science A and AB Newsletter.No. 6 Nov. 15, 2006.http://www.collegeboard.com/email/ap_compsci_n8490.html
8/11/2019 AP Sf Computer Science Gridworld
7/80
5
The Design of the GridWorld Case Study
Cay S. Horstmann
San Jose State University
San Jose, Caliornia
Abstract
In this article, I describe the rationale behind decisions that were made in the design o
the GridWorld case study. Knowing about these decisions can be useul to address student
questions, or simply to satisy your own curiosity. I also give inormation about the inner
workings o the GUI that is helpul or designing your own worlds.
A Brief History of GridWorld
In 2004, the AP Computer Science Development Committee solicited proposals or a
new case study. Te committee received a number o interesting suggestions, but none o
them had the exibility o the Marine Biology Simulation (MBS) case study or producing
exam questions. Instead, we decided to make the MBS code more generic, to easily handle
creatures other than fish, and to remove inessential classes. Te redesign was governed by
our themes:
Continuity. eachers who are amiliar with MBS should eel right at home in
GridWorld.
Simplicity. Students who see GridWorld or the first time should not be
overwhelmed.
estability. Te ramework should give rise to many kinds o exam questions.
Extensibility. Enthusiasts should be able to design grid-based games, mazes, puzzles,
simulations, and so on, without GUI programming.
Te first prototype o GridWorld appeared in March 2005. It consisted o the MBS code, with
one important changethe ability to add GIF images instead o having to use Java graphics
or drawing occupants. It turns out that this ability was already present in the MBS GUI
code, but it was well hidden. Figure 1 shows the very first GridWorld screen capture; note
the cuddly critter and the rame title.
Te next months were the Cambrian explosion o GridWorld, with numerous exotic
lie orms appearing rapidly: rock hounds that search or rocks by recursively asking theirneighbors, robots that drop owers, potato-shaped cells, ocks o boids, and aliens. Tey
became extinct, to be replaced with the bugs and critters that we know today.
The Design of the GridWorld Case Study
8/11/2019 AP Sf Computer Science Gridworld
8/80
6
Special Focus: GridWorld Case Study
Figure 1First GridWorld screen capture.
Te other major innovation was the direct manipulation interace that allows students
to invoke constructors and methods. I had always admired this capability in BlueJand
experimented with controlling grid occupants rom the BlueJworkbench. Tat proved too
cumbersome, and I ended up implementing direct manipulation inside GridWorld. Figure 2
shows another historic firstthe first screen capture o the method menu. Note the method
names and parameters!
Figure 2First screen capture o the method menu.
8/11/2019 AP Sf Computer Science Gridworld
9/80
7
Chris Nevison and Barbara Cloud Wells joined in September 2005 to produce the narrative.
Tey invented the crab and chameleon critters that show off the template method pattern.
Shortly afer the narrative was released, we were delighted to receive a beautiul set o
icons rom Chris Renard, a student at the School or the alented and Gifed o the Dallas
Independent School District.
Te design o GridWorld has now been finalized, and the case study is ready or use in
the 200708 school year. In this article, I will discuss some o the design decisions behind
GridWorld and give tips or advanced users.
Design Decisions
In this section, I discuss some o the design decisions that were made during the
development o GridWorld. You may disagree with some decisions; some o your colleagues
have done so rather vocally. You may want to discuss the pros and cons o some decisions
with your class.
Actors Store Their Location
Te MBS case study used an Environmentthat holds Locatableobjects. Tis proved to berestrictive when writing exam questions. We decided that we wanted a grid that can hold objects
o anytype. Tat means that the grid cannot ensure that the grid location and the occupant
location are synchronizedthe grid doesnt know whether its occupants have locations.
We attempted to solve this problem in an ingenious way, by passing the current location to
the actmethod.
public void act(Location loc, Grid gr)
Te actors didnt have to remember their location; the world reminded them. Unortunately,
the location and grid ended up being passed into many other helper methods, leading to
tedious code. In the end, we settled or actors that store their location, and supplied the
putSelfInGridand removeSelfFromGridmethods or synchronizing the actorand grid locations. As your students will undoubtedly find out, the putand removemethods o the Gridinterace do not work or actors. Te actors will throw exceptionswhen they find that their locations are not properly set.
The Out-Of-Subset instanceofOperatorTe instanceofoperator is not in the AP Java subset, but it is used to sense the type oactors that are being processed. For example, a bug decides that it can move to a location by
testing
(neighbor == null) || (neighbor instanceof Flower)
The Design of the GridWorld Case Study
8/11/2019 AP Sf Computer Science Gridworld
10/80
8
Special Focus: GridWorld Case Study
Going beyond the AP Java subset or the case study has precedent. Te MBS case study used
the protectedmodifier that is not in the subset. Nevertheless, it is not an ideal situation,and we explored alternatives. Unortunately, all o the alternatives required students to write
code that was more cumbersome than the instanceoftest. Tere is no point in makingstudents learn cumbersome custom code when they could instead learn a Java eature.
Note that we use the instanceoftest in its most benign orm, without the dreaded cast.Tat is, we do not have code o the orm
if (myActor instanceof Critter){ Critter myCritter = (Critter) myActor; //we dont do in //GridWorld . . .}
Will other GridWorld users exhibit the same good taste and restraint? Only time will tell.
Grid Types are Generic
In the AB course, students look at the Gridinterace and theAbstractGrid,BoundedGrid, and UnboundedGridclasses. Tey will see implementations o generictypes, even though the implementation o generic types is not currently in the AP Java
subset. In the A course, o course, there is no problem. Students use Gridmuch likeArrayList. An old-style Gridthat stores Objectreerences requires unsightly
casts. We elt that this advantage outweighed the slight complexity o type variables in the
AB course.
No Directionclass
Te MBS case study had a Directionclass or compass directions such as Direction.NORTH. Te class had ew interesting methods, and we eliminated it to minimize thenumber o classes that students see when they encounter GridWorld or the first time. Now
the constants are placed in the Locationclass, which is admittedly not optimal.
Eight neighbors
A location in the grid has eight neighbors. In contrast, the MBS environment could be
configured so that a location had our or eight neighbors, and some people even produced
triangular or hexagonal grids. Tis led to cumbersome exam questions since we always had
to be explicit about the number o neighbors. We decided that hexagonal grids were cute but
not useul enough to pay or the added complexity.
8/11/2019 AP Sf Computer Science Gridworld
11/80
9
No Random Singleton
Naive users ofen try to generate random numbers like this:
int r = new Random().nextInt(n); // DONT DO THAT!
However, constructing many random number generators will lead to poorly distributed
random numbers.
Te MBS case study had its own provider or a singleton random generator. Tat is the right
design i you are serious about controlling random number generation. In the context o
the MBS narrative, it made sense to have repeatable sequences o pseudo-random numbers.
However, the subtleties o random number generation are clearly not a central part o the AP
Computer Science curriculum. In GridWorld, we simply generate random numbers with the call
int r = (int) (n * Math.random());
You Cant Save the World
Te MBS case study had a mechanism or saving and reloading simulation data, in files with
contents such as
bounded 7 5Fish 3 2 North
In GridWorld, thats a lot harder since grid occupants can be arbitrary objects. I solved the
problem by using the XML file ormat or a specialized Java eature called long-term beanspersistence. However, that led to a harder problem. A data file can reerence an exotic critter
whose implementation is not on the class path. Not to be deterred, I saved a world as a zip
file that contains all classes and the data. You could mail your avorite world to someone else,
and the recipients GridWorld program would read the classes directly rom that file, using a
nify class loader.
Tis was, i I may say so, a technical tour de orce. Unortunately, but perhaps not
surprisingly in hindsight, users did not send world files to each other. Tey were just
conused that there was one set o classes in their project directory and a separate set in the
world files. I ended up removing the eature. My heart still bleeds when I think about it.
Actors Are Concrete
Te actmethod o theActorclass ips the actor, so that you can easily see i you orgotto override that method. O course, there would be an even better way o ensuring that the
method has been overridden: to declare it abstract.
The Design of the GridWorld Case Study
8/11/2019 AP Sf Computer Science Gridworld
12/80
10
Special Focus: GridWorld Case Study
MakingActorinto an abstract class would clearly be the better design. However, abstractclasses are typically introduced at the end o the A course and reinorced in the AB course.
Te committee wanted to make it easy to use GridWorld throughout the A course. We
thereore decided to use the conceptually simpler concrete actor class. In the AB course, the
AbstractGridclass gives a good opportunity or studying abstract classes.
Critter Methods Have Restrictive Postconditions
Te actmethod o the Critterclass calls five other Crittermethods.
public void act()
{
if (getGrid() == null)
return;
ArrayList actors = getActors();
processActors(actors);
ArrayList moveLocs = getMoveLocations();
Location loc = selectMoveLocation(moveLocs);
makeMove(loc);
}
Critter subclasses override one or more o these methods, but not the actmethod. Ideally,we would have declared actas final. However, the finalmodifier is not in the APComputer Science subset, and we wanted to stay within the subset whenever possible.
When ormulating an initial set o potential exam questions, we noticed that we needed
a tool to enorce the spirit o the design. We wanted to ask questions about design
alternatives in which one choice is right and the others are wrong. We wanted to signal that
certain implementations are reprehensible, such as eating neighbors in the getActorsmethod. In order to make clear what is good and bad, we added restrictive postconditions to
the five methods that are called in the actmethod.
o ensure that the getActorsmethod has no side effects, we added a postconditionTe state o all actors is unchanged. Similarly, we wanted to make sure that the
processActorsmethod makes use o the list o actors passed as a parameterrather than looking or actors elsewhere. Tis explains the first postcondition o
processActors: Te state o all grid occupants other than this critter and the elementso actorsis unchanged. New occupants may be added to empty locations. Te secondpostcondition Te location o this critter is unchanged makes sure that the critter
movement is carried out by the getMoveLocations/ selectMoveLocation/makeMovemechanism.
8/11/2019 AP Sf Computer Science Gridworld
13/80
11
Under the Hood
GridWorld was designed to be extensible, so that you can easily go beyond bugs and critters.
In this section, you will see some o the inner workings o GridWorld and learn how to take
advantage o them when you produce your own worlds.
How a World Is Displayed
When the showmethod o a Worldis called or the first time, a WorldFrameisconstructed. (WorldFrameis a generic class to minimize unsightly warnings in the codeor the constructor and method menus.) In subsequent calls to show, the rame is repainted.You will want to call showi you update the grid outside the stepmethod, so that yourchanges are displayed.
Te rame shows a GridPanelthat draws the grid (or a portion o the grid i it is toolarge), the grid occupants, and the selection square that indicates the currently active cell.
Te selection square can be moved with the arrow keys or the mouse. Occasionally, you willwant to hide the selection square. Call
System.setProperty("info.gridworld.gui.selection", "hide");
Every GridWorld program in the case study constructs a world, populates it, and then calls
the showmethod. But you dont have to call show. When you write a test program, perhapsor automated grading o your students work, you can simply call the stepmethod andthen check whether the grid occupants have acted correctly. For example, to test whether
your students ZBugworks correctly, place an instance into the grid, call stepa number o
times, and then check the grid or a Z-pattern o owers.
How Grid Occupants Are Painted
As you know, you can supply GIF images or grid occupants. Simply give the image the
same name as the occupant class, such as MyCritter.gif. Te image is rotated to theoccupants direction and tinted to the occupants color. Te occupant need not be an actor.
Te info.gridworld.gui.ImageDisplayclass simply checks whether there aremethods getDirectionand getColor.
You can have multiple images or an occupant. Suppose you want hungry critters to look
different rom normal critters. Supply a method getImageSuffi xthat returns a string ""or"_hungry", and supply two images MyCritter.gifand MyCritter_hungry.gif.
Note:(1) One o the images musthave the same name as the class, even i you never use
it. (2) Te getImageSuffi xmethod must return any separators such as underscores.(3) Images look best i their size is 48 48 pixels. Images are always scaled to a size
The Design of the GridWorld Case Study
8/11/2019 AP Sf Computer Science Gridworld
14/80
12
Special Focus: GridWorld Case Study
122n 122n, where n0. When a grid is first displayed, nis chosen as the largest value
or which the grid cells fit in the rame, or 0 i 12 12 cells overow the rame. When you
zoom in or out, nis incremented or decremented. Menu icons are scaled to 16 16. You can
supply images o other sizes, but they may not look as good.
Sometimes, you may want to achieve more complex drawing effects. Supply a class thatextends info.gridworld.gui.AbstractDisplayand whose name is the nameo your occupant, ollowed by Display, such as MyCritterDisplay. Implement theollowing method:
/**
* Draw the given object. Subclasses should implement this
* method to draw the occupant facing North in a cell of size
* (1,1) centered around (0,0) on the drawing surface.
* (All scaling/rotating has been done beforehand).
* @param obj the occupant we want to draw* @param comp the component on which to draw
* @param g2 the graphics context
*/
abstract public void draw(Object obj, Component comp,
Graphics2D g2);
You can use any o the Java AW drawing calls in the drawmethod.
You may wonder why the drawmethod isnt simply part o the occupant class itsel.
However, the drawing code is usually quite complex. For example, the class to draw the MBSfish uses the GeneralPathand GradientPaintclasses. By placing the drawing codein a separate class, you can hide that complex code rom students.
8/11/2019 AP Sf Computer Science Gridworld
15/80
13
I there isnt a display class or a GIF image that matches an occupant class name, the
superclass names are used to find a match. (For that reason, the deault drawing o an
Actorsubclass is the actor mask.) I none o the superclasses has a display class or GIFimage, then the info.gridworld.gui.DefaultDisplayclass is used. Tat classsimply fills the cell with a background color and places centered text into the cell. Te
background color is the value returned by the getColormethod, or the value o the objectitsel i it is an instance o the Colorclass. Te text is the value o the getTextmethod,or, i there is no such method, the toStringmethod.
Te deault display does the right thing or a Worldor World.
The Design of the GridWorld Case Study
8/11/2019 AP Sf Computer Science Gridworld
16/80
14
Special Focus: GridWorld Case Study
You can also use the deault display or simple game tiles. Define a Tileclass withgetColorand getLabel.
Note that invalid grid locations are painted gray. Here is an unbounded triangular grid:
8/11/2019 AP Sf Computer Science Gridworld
17/80
15
How the Buttons Work
When the user clicks the Step button in the GridWorld program, the stepmethod o thecurrent world is invoked. When you click on the Run button, the stepmethod is invokedrepeatedly, until the Stop button is clicked. Te requency depends on the setting o the
Slow/Fast slider.
The Design of the GridWorld Case Study
8/11/2019 AP Sf Computer Science Gridworld
18/80
16
Special Focus: GridWorld Case Study
In theActorWorld, the stepmethod invokes acton each actor.
In your own programs, you can define the stepmethod differently. For example, you caneasily turn GridWorld into a GUI or Conways Game of Life. Define the stepmethod tocompute the next generation, then click the Runbutton to see the simulation unold.
I you leave the stepmethod undefined in your Worldsubclass, then the buttons wont doanything.
Note that you dont have to click the buttons in your own program. You can write a program
that creates a world, invokes stepmultiple times, and calls show. Te program simplydisplays the final state o the world. Tis is useul or speeding up gradingyou can visually
check whether the students answer is correct, without having to do any clicking.
How the Message Display Works
Te yellow area above the grid is the message display. By deault, it is blank or ordinaryworlds, and it shows the message Click on a grid location to construct or manipulate an
actor orActorWorld.
You can set your own message by calling the setMessagemethod. Tis is useul in manysituations. For example, in a game, you can display messages Player As turn or Game over.
Te message can be arbitrarily long; scroll bars will appear when needed.
Each call to setMessagereplaces the preceding message. I you call setMessage(null)
in anActorWorld, the deault message reappears.
How You Can Intercept Mouse Clicks and Keystrokes
Te Worldclass has student-riendly mechanisms or intercepting mouse clicks andkeystrokes. No knowledge o AW events is required.
When the user clicks on a grid location, the locationClickedmethod o the Worldis called. By deault, that method returns false, which tells the ramework to initiate thedeault action, namely to move the selection square and to show the constructor or method
menu.
o intercept the mouse click, override the locationClickedmethod. Carry out anydesired action and return true. Te grid location on which the user clicked is passed as aparameter. ypical actions include ipping tiles, populating empty locations, and so on.
Sometimes, you need to ask the user or additional inormation afer the mouse click. Te
easiest method is to use a JOptionPane.
8/11/2019 AP Sf Computer Science Gridworld
19/80
17
Lets consider a common situation. In a game, a user selects a piece. You want to ask where
the user wants to move the piece. You can wait or another mouse click. Tat means,
your locationClickedmethod needs to keep track o the click state (piece selectionvs. target selection). Or you can enumerate all legal targets and call JOptionPane.showOptionDialog.
When the user hits a key, the keyPressedmethod o the Worldis called. By deault,that method returns false, which tells the ramework to initiate the deault key action.I the user hit a cursor key, the selection square is moved. I the user hit the Enter key, the
constructor or method menu is shown. All other keys are ignored.
o intercept the keystroke, override the keyPressedmethod. Te method receives thecurrent location and the keystroke string, encoded in the same ormat that is used by the
java.awt.KeyStrokeclass. Example keystroke strings are "INSERT"or "altshift X". Your keyPressedmethod should check the keystroke string. I the string
matches a keystroke that you want to intercept, carry out any desired action and returntrue. Return falseor all other keystrokes. It is a good idea to return falseor thecursor keys and the Enter key. Otherwise, the standard actions are disabled or your world.
Conclusion
You now know the rationale behind some o the design decisions in GridWorld, and you
have had a peek under the hood o the GUI. I hope you find this inormation helpul as you
use the GridWorld case study or your Computer Science classes.
The Design of the GridWorld Case Study
8/11/2019 AP Sf Computer Science Gridworld
20/80
18
Special Focus: GridWorld Case Study
Integrating GridWorld
Jill Kaminski
Chaparral High School
Parker, Colorado
Integrating GridWorld
When I first began teaching AP Computer Science, I planned my course around a list o
the AP Java Subset and opic Outline: ifstatements, loops, methods, classes, searching,sorting, case study, etc., etc. I ound that using this approach, my students brains resembled
shif registers. Tey could store content during the current unit o study. But they seemed
to shif it out as the next unit began, so that they could store the new inormation. By
May, my average student had, shall we say, underwhelming retention. My less-than-average
students aired even worse. And this isnt the kind o test you can cram or.
Several years ago, I began to ollow the sage advice o ormer AP Chie Reader Chris Nevison:Dont teachthe case study! Usethe case study to teach computer science. Tis advice also
appears in the prior case studys teachers manual: Te case study and the accompanying
teachers manual were designed in such a way that you can use these materials throughout
the course. You may, in act, wish to teach many computer science concepts rom the AP CS
curriculum through the case study itsel. What a concept! I revised my course so that the
case study was no longer a unit to be taught, but a tool or teaching a variety o topics.
Te good news is: it worked!Once my students learned how the case study works, they were
able to learn and apply new concepts within that ramework. By May, they remembered the
concepts as well as the case study. Scores improved! Te people rejoiced!
And the best news o all: I think that GridWorld has even more potential to be used
throughout a course than the prior case studies (particularly an A course). My students
appreciate that this is more o a real program, and less like the programs we tend to
write in beginning computer science classes (e.g., Student or BankAccount classes).
Its well-designed, its particularly great or teaching inheritance and data structures, and
the possibilities or its enhancement by students are really exciting.
I usually begin my year-long AP Computer Science A classes by reviewing the basic Java
topics covered in the courses in the pre-AP years. Student activities involve reading, takingnotes, doing ree-response practice assignments, doing multiple-choice tests, and writing
programs. I try to save as much time as possible or the programming, because they enjoy
learning by doing, and I find that its effective. I usually preer two or so short multiple-choice
tests to one long test at the end o each one to three weeks or at the end o each unit.
I typically begin case study work by November. We go through each Part o the Student
Manual, and at the conclusion o each Part, we reinorce the concepts with extra labs. I
8/11/2019 AP Sf Computer Science Gridworld
21/80
19
present new concepts within the GridWorld context, and much o the subset is covered this
way. And best o all: its un!
Getting Started
Youll have to roll up your sleeves at some point and do some GridWorld programming.Youre definitely busy, and probably putting it off, but when you do begin, I think youll enjoy
it. Read Cay Horstmanns article about the design o GridWorld. It will help you understand
the behind-the-scenes design and rationale.
I possible, grow to love GridWorld beore you present it to your students. Tey wont love it
any more than you do. I this is not possible, then act like you love it. Tey wont love it any
more than you can act like you do. Do the exercises and labs in the Student Manual, and take
notes as you think o ways that you can enhance them.
Te case study Student Manual is well-written and engaging. ake advantage o this teachingtool! Its a very good textbook or you during these weeks. Troughout your work in the case
study, talk through the Do You Know? sets with the whole class, and have students do all
o the Exercises. Tese questions and exercises are well designed and valuable.
Part 1
Introduce the case study in a memorable way. As students walk in your room on Day 1 o
GridWorld, let them:
see GridWorld running on a projector.
see you dressed or the occasion in a estive bug-related t-shirt or tie. Or wear checks or
plaid, to represent the grid.
hear some kind o bug music. Here are a ew ideas that are available on iunes
(http://www.apple.com/itunes/):
There Aint No Bugs On Me (traditional)
Bugs. Mr. Heath
Bugs. Rosenshontz
Bugs. Renee Austen
Bugs! Funky Mama The Bug. (aka Sometimes Youre the Windshield) Mary Chapin Carpenter, and
also by Dire Straits
The Time of Your Life. Randy Newman (fromA Bugs Lifethe whole soundtrackis terrific)
Flight of the Bumblebee. Nikolai Rimsky-Korsakov
Antmusic or Ant Invasion Adam and the Ants
Integrating GridWorld
8/11/2019 AP Sf Computer Science Gridworld
22/80
20
Special Focus: GridWorld Case Study
You could integrate bug and/or ower decor in your room. Jazz up the computer lab with a
bug-related movie poster:A Bugs Life, Te Ant BullyorAntzor un, or Tem!,Eight-Legged
Freaks,Arachnophobia, or Te Flyor horror movie ans. You can find it on eBay! Consider
an ant arm, or a class pet hermit crab. Perhaps your science department has some creatures
that they can loan you. I these ideas dont match your personality or style, then think about
other ways to present GridWorld in a positive light.
Explain to your students what a case study is. Tey probably dont know. Explain to them
why the College Board wants them to analyze and modiy a complex program.
Explain to them that in the real world, theyll likely need to modiy code more ofen than
write it rom scratch. Explain to them that theyll be fired or modiying a class that already
works and didnt need to be changed!
Click-ability is a welcome addition! Have students experiment with GridWorld using the
table at the end o Part 1, so that they get accustomed to the user interace. Tis will paygreat dividends throughout the course. ake advantage o the BlueJ-like drop-down menus
to enorce the concepts o state and behavior o objects.
Incorporate ideas rom Judy Hromciks Early Exercises with GridWorld. Students interest
level skyrockets when they can do something to the code, early and ofen. I your students
havent studied inheritance at this point yet, GridWorld is a terrific tool to present the basic
concepts o Is-A and Has-A, even in Part 1.
Part 2
Afer students are amiliar with the basic behaviors o theActors, incorporate role playactivities in which students become Bugs, Flowers, and Rocks. Nonacting students cangive instructions to the actors. You can use a wister mat as a un way to represent the grid,
or make a grid on the oor with duct tape.
Im so grateul to Student Manual authors Chris Nevison and Barbara Cloud Wells or
presenting inheritance early! Inheritance allows infinite creativity in the case study.
Dont move on to Part 3 without letting students spend some time extending the Bugand/orBoxBugclasses in various ways. Make sure that students understand the good news about
inheritance: you dont have to start rom scratch! Most Bugbehaviors do not have to berewritten.
As inheritance is explored and new methods are added to subclasses, use the drop-down
menus to illustrate that an object o a subclass has its own unique methods, and also the
methods in the parent class. A classs methods are displayed in a distinct section o the menu.
8/11/2019 AP Sf Computer Science Gridworld
23/80
21
Tis visual cue is a great reminder that an object has methods rom its own class, and also
methods rom its parent classes.
In Part 2, show students that they can create any kind oActorthat theyd like. Show themhow easy it is to incorporate their own graphics. I youre a Marine Biology Simulation an,
run a demonstration o the Marine Biology Simulation, and have students implement basicMBS Fish movement in GridWorld. Your avorite MBS labs do not have to collect dust afer
the 2007 AP Exam! Or have students write GridWorld programs using other characters they
may know and love, like Karel J Robot, Sonic the Hedgehog, or Pac-Man.
Continue to use Judy Hromciks ideas as you begin Part 2. Explore Dave Wittrys Game O
Fifeen and WuZiQi projects rom his terrific Board Game Projects article as you continue
in Part 2. When students realize that GridWorld can be modified to implement a wide
variety o very different projects, theyll be excited about continuing to work with it, and
their understanding o program design will be greatly enhanced.
Part 3
In this important section o the Student Manual, the inner workings o the case study are
unwrapped or students. Tey have likely thought o many creative ideas or GridWorld projects.
Now they will learn the inormation necessary to implement those using solid design practices.
Incorporate some discussion about the GridWorld design into your classes. Review Cay
Horstmanns rationale, and share some o this with your students. Tey will appreciate that
the GridWorld designer made the decisions he elt were best, but that he wrestled with some
pros and cons along the way. It will really help them solidiy their understanding beore they
begin making major changes to the code.
Afer completing the Jumper project in the Student Manual, let your students design their
own labs! Teyll likely need some guidance in the process, but theyll have un while
learning valuable lessons about modiying an existing design. Youll be amazed at what they
come up with, and theyll buy in to the assignments.
Part 4
Te introduction o the Critterclass allows the case study to remain resh. You and yourstudents will think o even more ideas to implement. Te skys the limit! At this point, I think
that your problem will no longer be What will I do? but rather We dont have enough timeto do all the un stuff Id like to!
Afer completing the un activities in the Student Manual, use Robert Glen Martins Ant
Farm. Ten, proceed to Reg Hahnes Save My Heart labs. Ten try your own ideas, or again,
those o your students.
Integrating GridWorld
8/11/2019 AP Sf Computer Science Gridworld
24/80
22
Special Focus: GridWorld Case Study
Part 5
It is so much un to teach data structures using a case study like this! Te pros and cons o
the various structures come to lie as students repeatedly extend theAbstractGridclassin various ways.
In Exercise 1, have students use Javas LinkedListclass first. Ten, make a copy o thatproject, and have them create their own LinkedListclass using the ListNodeclass.None o the client code rom their first LinkedListproject needs to change afer theimport o java.util.LinkedListis removed, and when there are problems (mostofen NullPointerExceptions!), students have to admit that the problem lies in theirLinkedListclass. Similarly, students can use the case study as the platorm or creating abinary search tree to represent the grid.
Download and use Dave Wittrys Generic Data Structures Viewer tool. Tis terrific
application, written by Daves students, provides students with a visual representation o the
data structures that they create. Tis makes debugging much easier.
And speaking o Dave, definitely consider his AB data structure labs (also rom Board
Game Projects.) Students love writing games, and Daves ideas give very interesting and un
contexts or the study o data structures.
Beyond the Narrative
Continue to use GridWorld as May approaches to reinorce various topics like inheritance,
ArrayLists, recursion, and design. In the process, students will solidiy their knowledge
o the topics and the case study itsel.
I you didnt get to all o Dave Wittrys more advanced A and AB game projects while
studying Parts 35, then consider using them afer youre finished going through the Student
Manual. Daves ideas provide a launching pad or many other grid-based game ideas.
Consider ic-ac-oe, Pac-Man, Minesweeper, Hunt the Wumpus, role-playing games, and
games commonly downloaded to programmable calculators. And have un! Te best o these
will become project staples or years to come.
Different Strokes for Different Folks
All students are created equal. But not all students are able to perorm equally in our classes.
I usually have a high percentage o AP Computer Science students or whom mine is their
only AP course. I encourage their enrollment, and I do my best to help them achieve their
best on the exam (even i that means I help them earn a 2). Tey will still be better off in
college or the experience o taking an AP course and exam, according to the 2007Advanced
Placement Report to the Nation.
8/11/2019 AP Sf Computer Science Gridworld
25/80
23
Te key is successul differentiation in our classes. Here are a ew ideas pertaining to
GridWorld in particular:
Differentiate by various orms o assessments. Multiple-choice quizzes on GridWorld
will help prepare students or the AP Exam, and will help improve scores or those who
struggle with multiple-choice questions by giving them more practice.
Differentiate by presenting their assignments in various orms. Students should not
only read about a programming project but also see it run (on a projector) prior to
attempting it. Tis will help ESL students and those with poor reading skills.
Differentiate the amount o work within a programming project. Break down the
assignment, and allow credit or the subparts completed. For example, when working
on Robert Glen Martins Ant Farm lab, give credit or implementing the QueenAnt
class, and then the WorkerAnt class, and then the Cookie class. Tis way, even i a
student doesnt complete the entire lab, he or she can still gain learning and grades
along the way. You can also add additional parts to labs or the advanced students.
Differentiate the number o programming projects. I usually list multiple assignmentswithin a unit rom easiest to hardest. Te projects at the bottom are not a punishment
or my overachievers, but are designed to provide more un and challenge to the
advanced students. Tey generally want to get there! Tis keeps them motivated and
gives me time to work on less-challenging labs with students who need more o my
help. When grading, I assess whether students did their best to complete the highest
number o labs possible, with excellent quality, in the given amount o time.
Closing Thoughts and Ideas (on GridWorld and AP Computer Sciencein general)
Ive ound that my students will work or ood! Tis is an especially effective strategy
when I need to give an extended lecture, since theyre happy and they ofen talk less
when their mouths are ull. From time to time, try one o the ollowing as a treat:
Look or ruit snacks in bug shapes.
Get a large container o Chex Party Mix. Te Chex can represent a grid. Or, add fish
objects to the grid, and serve Pepperidge Farm Goldfish crackers. Reuse plastic cups
to serve the snacks, and have students write their names on the cups.
Get one o the bug-shaped Pez dispensers (Pez Bugz), and reward a kid or two each
day with a little Pez candy. Teyll be much more likely to answer your questionsenthusiastically!
Read them On Beyond Bugs! All About Insectsby ish Rabe.
Play motivating snippets rom movies likeA Bugs Life, Cars, Finding Nemo, Rudy, and
Invincible. Look or the inspiring scenes in which our hero is discouraged and a riend
picks him up, or when he prevails in the end even though the odds were against him.
My avorite is Dorys Just keep swimming speech in Finding Nemo. I tell my students
Integrating GridWorld
8/11/2019 AP Sf Computer Science Gridworld
26/80
24
Special Focus: GridWorld Case Study
to remember this line in the middle o any diffi cult test, when they might be ready to
give up.
Change gears i things arent working in your class. Abandon your plans, and meet the
kids needs. Be exible. Hold them accountable, but be realistic in your expectations.
Have a donut party or them on the morning o the exam. Let them anxiously ask
you those last-minute questions. Give them your sage advice, like never leave a
ree-response question blank. ell them that youre proud o them. Read them some
inspirational quotes, stories, or poems. ell them to Just keep swimming. Afer the
exam, tell them that i they want to, they can still be sofware engineers when they grow
up, no matter what their test score was! Te experience will have been worthwhile, and
when they take those first college programming courses, theyll be ahead o the class.
Smile. Have un. You shouldnt be teaching unless you love it . . . at least, most o the
time!
Please consider sharing your GridWorld ideas and successes on the AP Computer
Science Electronic Discussion group and the CSA Web Repository.
References
Bergin, Joseph, et al. 2005. Karel J Robot: A Gentle Introduction to the Art of Object-OrientedProgramming in Java.Dream Songs Press.
BlueJ. http://www.bluej.org
College Board. 2007.Advanced Placement Report to the Nation.
College Board.AP Computer Science Electronic Discussion Groups. http://apcentral.collegeboard.com
Computer Science eachers Association. CSA Source: a Web Repository of K-12 eaching andLearning Materials for Computer Science.http://csta.acm.org/Resources/sub/WebRepository.html
Disney/Pixar. 1998.A Bugs Life. DVD or VHS.
Disney. 2003.Finding Nemo.DVD or VHS. Walt Disney Video.
Disney. 2006. Invincible. DVD. Walt Disney Home Video.
Hunt the Wumpus. Wikipedia. http://en.wikipedia.org/wiki/Hunt_the_Wumpus
iunes. http://www.apple.com/itunes/
Levine, David, and Steven Andriano. 2003. Role Playing In an Object-Oriented World.St. Bonaventure, New York: St. Bonaventure University, Department o Computer Science.http://www.cs.sbu.edu/dlevine/RolePlay/roleplay.html
Minesweeper (computer game). Wikipedia.http://en.wikipedia.org/wiki/Minesweeper_%28game%29
8/11/2019 AP Sf Computer Science Gridworld
27/80
25
Pac-Man. Wikipedia. http://en.wikipedia.org/wiki/Pac-Man
Rabe, ish. 1999. On Beyond Bugs!: All About Insects.New York: Random House.
Sonic the Hedgehog. Wikipedia. http://en.wikipedia.org/wiki/Sonic_the_Hedgehog
Sony. 1993. Rudy. DVD or VHS.
ic-ac-oe. Wikipedia. http://en.wikipedia.org/wiki/ic-tac-toe
wister. Board game. Hasbro.
Wittry, Dave. Generic Data Structures Viewer (GDSV).AP Computer Science.aipei AmericanSchool. http://www.apcomputerscience.com/gdsv.index.html
Integrating GridWorld
8/11/2019 AP Sf Computer Science Gridworld
28/80
26
Special Focus: GridWorld Case Study
Early Exercises with GridWorld
Judith Hromcik
Arlington High School
Arlington, exas
Chapter 1: Observing and Experimenting with GridWorld
Te GridWorld GUI is an interactive GUI. For each actor that has been placed in the
grid, students can observe the actors behavior, test its methods, and learn how it acts by
right-clicking on the actor in the grid and running its methods. Tis unit is designed to
let students explore and discover what unctionality the actors possess and how the actors
behave in the grid.
Modifying BugRunner.java
Te BugRunnerclass contains a main method that when compiled and executed, runsthe GridWorld GUI. Te grid is an interactive part o the GUI. Right-clicking on an emptycell in the grid will allow the user to add a new actor in the grid during the simulation.
Right-clicking on an occupied cell in the grid will allow the user to run methods or that
occupant.
Afer compiling and running the BugRunner.java, make small changes to the file. Teoriginal main is shown below:
import info.gridworld.actor.ActorWorld;import info.gridworld.actor.Bug;import info.gridworld.actor.Rock;
/*** This class runs a world that contains a bug and a rock,* added at random locations. Click on empty locations to add* additional actors. Click on populated locations to invoke* methods on their occupants. To build your own worlds,* defi ne your own actors and a runner class. See the* BoxBugRunner (in the boxBug folder) for an example. This* class is not tested on the AP Computer Science A and AB* exams.*/1. public class BugRunner2. {3. public static void main(String[] args)4. {5. ActorWorld world = new ActorWorld();
8/11/2019 AP Sf Computer Science Gridworld
29/80
27
6. world.add(new Bug());7. world.add(new Rock());8. world.show();9. }10. }
Suggested changes:
1. Comment out line 7, recompile the ile and execute.
a. Beore stepping or running the simulation, right-click on an empty cell in the grid.
What types o actors can be added to the grid at this point?
b. Step or run the simulation. Right-click on an empty cell in the grid. What types o
actors can be added to the grid at this point?
2. Uncomment line 7, recompile the ile and execute.
a. Beore stepping or running the simulation, right-click on an empty cell in the grid.
What types o actors can be added to the grid at this point? b. Step or run the simulation. Right-click on an empty cell in the grid. What types o
actors can be added to the grid at this point?
Afer making these changes, students should realize that they can only add the same types o
objects that currently exist in the grid.
Questions
1. he original BugRunnerclass adds a Bugand a Rockto the grid. Beore thesimulation runs one step, you can add a new Bug, Rock, orActor. Why can anActorobject be added to the grid when the BugRunnerdid not add anActor(i.e. world.add(new Actor()); )?
2. Right-click on every Bugin the grid and run a method that will allow you to move thebugs out o the grid without a runtime exception. What method(s) did you run? Right-
click on an empty spot in the grid. Can a Bugbe added to the grid?
AnActorcan be added to the grid i anyActorsubclass has been added in the BugRunnerclass. Tis is a good time to introduce the idea o inheritance and the idea o IS-A.
A BugIS-AActor A FlowerIS-AActor A RockIS-AActor
When all Bugobjects are removed rom the grid by using the moveorremoveSelfFromGridmethods, new Bugobjects can still be added to the grid. Note:Using the moveTomethod to remove anyActorrom the grid will cause a runtimeexception to occur.
Early Exercises with GridWorld
8/11/2019 AP Sf Computer Science Gridworld
30/80
28
Special Focus: GridWorld Case Study
Afer the idea o inheritance has been introduced, right-clicking on a Bugobject in thegrid visually shows the students which methods are defined by the Bugclass (a Bugimageappears by these methods) and which methods the Bugclass inherits rom theActorclass(anActorimage appears by these methods).
Exercises
1. Run BugRunner.java. Right click on one o the Bugobjects in the grid and do theollowing:
a. list all o the methods that the Bugclass deines
b. list all o the inherited methods rom theActorclass that can be called rom a Bugobject
c. draw an inheritance hierarchy diagram or the Bugclass, Flowerclass, and Rockclass
2. List all the cases that will cause the canMovemethod o a Bugobject to return false.
Run the simulation to test your cases.3. List all the methods that will cause a Bugobject to turn.
4. Right-click on a bug in the grid and orce it to move to a location that is occupied by a
lower, a rock, an actor, and another bug. What happens i a bug moves into a location
that is occupied by a lower? an actor? a rock? another bug?
Chapter 2: Bug Variations
Chapter 2 o the case study is teaching simple inheritance. Te code or the Bugclassconstructors and the actmethod is the only code that the students need to really
understand at this point. Students need to only use the canMove, turnand movemethods. In such a constrained space, students can ocus on creating a subclass o the Bugclass by modiying the BoxBugclass.
General notes or creating Bugsubclasses:When students extend the Bugclass
they should only override the actmethod;
each call to the movemethod should be guarded by a call to the canMovemethod;
private instance variables should be added to the subclasses as necessary;
new methods or the actmethod to call can be added to the subclass; constructors or the subclasses should be written to initialize any private instance
variables declared in the subclass;
super(); or super(someColor);can be introduced at this time i studentsare ready.
8/11/2019 AP Sf Computer Science Gridworld
31/80
29
Additional Beginning Labs for Chapter 2
JumpingBug:
A JumpingBugis a Bugthat tries to move two spaces ahead each step. I a JumpingBugcan move, it will move one space ahead and then try to move again. It is possible that it will
only move one space i the second move is not possible. I a JumpingBugdoes not move atall, it will turn 90 degrees and change its color to a random color.
Create the JumpingBugclass. In writing this class, create a new method, randomColor,that will return a random color when called.
Te key to writing the actmethod or this class is to guard both calls to movewith calls tocanMove:
public void act(){ if (canMove()) { move(); if (canMove()) move(); } else { turn();
turn(); setColor(randomColor()); }}
A common mistake or beginning students is to omit the second call to canMove.
Tis lab emphasizes the need to guard all calls to move. It also provides students theopportunity to create additional methods or the actmethod to call.
DiagonalBug
A DiagonalBugis a Bugthat initially aces northeast, northwest, southeast, orsouthwest. When a DiagonalBugcannot move, it turns 180 degrees. Create theDiagonalBugclass.
Early Exercises with GridWorld
8/11/2019 AP Sf Computer Science Gridworld
32/80
30
Special Focus: GridWorld Case Study
In order to solve this problem, students must realize that they will need to write a
constructor or the DiagonalBugand set the initial direction in the constructor. Arandom number should be used to determine which one o the our possible directions each
DiagonalBugwill ace.
Once a correct constructor is written, the actmethod should be overridden to a makeDiagonalBugturn 180 degrees when it cannot move instead o 90 degrees.
Tis lab emphasizes the need to create a constructor or the subclass and set the proper
initial conditions.
Solutions and student handouts can be ound athttp://www.apluscompsci.com/material.htm.
Pedagogical Rationale
Prerequisite knowledge or students:
compiling and running a Java project
creating objects
calling an objects methods
making small modifications to an existing program
Pedagogical approach: Discovery learning and ormative assessment
Discovery learning is an approach to instruction through which students interact with
their environmentby exploring and manipulating objects, wrestling with questions and
controversies, or perorming experiments (Ormrod, 1995, p. 442).
Te case study offers instructors a natural vehicle to employ this pedagogical approach.
Tese lessons will allow a teacher to actively engage students in the learning process
and ascertain what the students know and understand. Tese lessons involve classroom
discussion, active questioning, and solving small problems. Tese are all ormative
assessment strategies.
Reference
Ormrod, J. 1995. Educational Psychology: Principles and Applications.Englewood Cliffs,
NJ: Prentice-Hall.
8/11/2019 AP Sf Computer Science Gridworld
33/80
31
Board Game Projects
Dave Wittry
aipei American School
aiwan
General Comments and Some Tips for Differentiation
Te word game here is being used, in some cases, liberally. While three o the games are
clearly games, two o them are clearly not. I use the term as it will appear to the students.
Tose games that are not actually games are deemed un by studentsso I list them as
games as well. You will see what I mean i you use them; theyre un!
Tese projects have more to do with learning about the individual classes within GridWorld
(e.g., Grid, World, Location) than with inheritance. Tese were chosen so that youcould see how one might use GridWorld or things other than Bugs,Actors, Rocks,
and Critters. We all have our avorite labs weve used over the years (e.g., NQueens,Lie)maybe you can start to see how you can still use those ideas but do so within the
context o the case study. One side benefit o doing so is that youll keep your students within
a common metaphor (that o the GridWorld) over the course o many different types o
projects, thereby helping them ocus on the specific computer science topic at hand and
not distracting them with a context change each time you want to move in a new curricular
direction.
Te nice thing about all o these projects is that you can use each one in many different ways
depending on what you want to have your students ocus on, how much time you have to
dedicate to the individual project, and the current knowledge o your students. Te labs canbe used in AP Computer Science at either the A or AB level; some can even be used twice
when either revisiting topics or when demonstrating alternate algorithms/data structures at
another point in the course(s). Some tips or how to do so are given and Im sure youll have
a ew more ideas along the way. Each o the projects comes complete with a solution as well
as a suggested starting point or students. (See .java files within the student version o each
projectsee Materials section at the end o this document.) You can simply, or example,
delete the body o one method, leaving the students to write it. You pick and choose what
parts o the project you want them to write. Students who need more help might be given
an initial lab setup that has more code filled in, or example, than those who need or desire
less assistance. Also, i you have gifed/talented students in your course, the labs are easilyextensible to help push them and keep interest. Consider working with such students by
giving them some options and asking or their ideas or extension, then let them run with
the ball; youll get much more out o them when they get to choose.
Whether or not we have both A and AB level students in one classroom, we ofen need to
differentiate, not only among levels but within. Some possible extension ideas that would
Board Game Projects
8/11/2019 AP Sf Computer Science Gridworld
34/80
32
Special Focus: GridWorld Case Study
give the games a more real eel and that apply to all labs below would be to save game state
and reinstate at a later time. Or one could keep game statistics. A very advanced extension
could be to make the game playable over the network while students sit at different
computers. Tese extensions would teach students, among other things, some o the
ollowing:
to use the Scannerclass to read/save.
to serialize an object so as to simpliy saving and reinstating the state o an object, as
well as sending objects over the network connection.
to add menu items and buttons, or example, in order to add unctionality. Tis would
constitute either inspecting and editing the GridWorlds GUI files and/or creating your
own rame with additional controls. Te latter option is modeled or you in the raffi c
Jam lab below.
Te games chosen in this discussion were chosen or several reasons. First and maybe
oremost, they were chosen because they are a un way to learn about computer science.Tere may be no better way to engage someone than through gaming. Another reason these
projects were chosen is that they demonstrate some o the more captivating eatures o the
GridWorld package. What color something is or which custom, student-created graphic
is being displayed may not be computer science, but incorporating those simple-to-do
eatures in your projects will sure go a long way toward keeping your students engaged and
wanting more. Within the context o these five games youll see how to accomplish just about
everything you need to know about displaying custom colors, graphics, and text. In addition,
youll expose students to the event-driven paradigm with easy-to-handle keyboard/mouse
user-driven events. Along the way they will also learn other typical game constructs such as
how to take turns, pause play, read/save game data, and more. Tese will open the door to
many other projects. Let the gaming begin!
8/11/2019 AP Sf Computer Science Gridworld
35/80
33
Game of Fifteen
You may have played this game beore. Te game o Fifeen is usually played with thenumbers 1 to 15. Here, letters o the alphabet are being used. Te object o the game is to
rearrange the scrambled letters so that they are in alphabetical, row-major order with the
hole located at the bottom right. Te only pieces you can slide in any turn are those located
horizontally/vertically rom the open slot.
Tis is a antastic lab to use early in the case study in the AP Computer Science A course.
Your students will get lots o practice with the Grid, Location, and Worldclasses.In addition, they get some good practice with algorithms as they try to figure out how to
determine a winner and how to set up a random starting board.
Relevant GridWorld classes and interfaces
World, Grid, BoundedGrid, Location
Relevant topics
tested on AP Exam: nested loops,ArrayList, or each loop, Math.random()not tested on AP Exam: Collectionsclass
Board Game Projects
8/11/2019 AP Sf Computer Science Gridworld
36/80
34
Special Focus: GridWorld Case Study
Code Example
private boolean determineWinner(){ Grid grid = getGrid(); ArrayList list = newArrayList(); for (int row=0; row
8/11/2019 AP Sf Computer Science Gridworld
37/80
35
Game of WuZiQi ( )
WuZiQi, also known as Gomoku or Gobang, is an ancient, abstract strategy game. An
abstract strategy game is one that has no random elements or hidden inormation. Other
examples o abstract strategy games include Chess and Checkers. Te object o WuZiQi is
to get 5 o your pieces in a row either horizontally, vertically, or diagonally. Black moves first
and then play alternates.
Relevant GridWorld classes and interfacesWorld, Grid, BoundedGrid, Location
Relevant topics
tested on AP Exam: ArrayList, 2D arrays, writing equals()not tested on AP Exam: displaying and switching between custom images, taking
turns mechanism (boolean), event-handling, determining a winner
Board Game Projects
8/11/2019 AP Sf Computer Science Gridworld
38/80
36
Special Focus: GridWorld Case Study
Graphics
For notes on how to dynamically use/swap custom graphics, colors, and text within
GridWorld projects, see the GamePiececlass. Te explanations come with specific codeexamples and are generalized or any project.
Code Example
public boolean determineWinner(Location loc){ // only need to check 5 in a row from the current loc // (last move made) int dir = Location.AHEAD, consecutive = 0; Location nextLoc; Grid gr = getGrid(); // There are 4 main diagonals to check for 5-in-a-row.
GamePiece piecePlayed = gr.get(loc); for (int numDiagonals=1; numDiagonals
8/11/2019 AP Sf Computer Science Gridworld
39/80
37
Escape from a Maze
Tis is your typical escape-rom-a-maze lab. You click in an empty cell and then the
algorithm takes over, finding its way out (to the edge o the grid).
In addition, i youre looking to teach I/O, this is a great place to do it. Tis lab shows
you how to create a text file with maze data, read it, and use it to build the initial starting
world/grid.
Relevant GridWorld classes and interfaces
World, Grid, Location
Board Game Projects
8/11/2019 AP Sf Computer Science Gridworld
40/80
38
Special Focus: GridWorld Case Study
Relevant topics
tested on AP Exam: nested loops, recursion, Stack,ArrayList, or each loopnot tested on AP Exam : Scannerclass (file i/o)
Code Example
private boolean escape(Location loc){ Grid gr = getGrid(); ArrayList nbrs = gr.getEmptyAdjacentLocations(loc); if ( nbrs.size() == 0 ) return false; Stack stk = new Stack(); Location aLoc; for (Location tmpLoc: nbrs) stk.push(tmpLoc);
while ( !stk.isEmpty() ){ aLoc = stk.pop(); if ( onBorder(aLoc, gr.getNumRows(), gr.getNumCols()) ) { add(aLoc, new Tile(Color.RED, "escaped"));
return true; // found a way out, were done } else
{ add(aLoc, new Tile(Color.RED)); nbrs = gr.getEmptyAdjacentLocations(aLoc); for (Location tmpLoc: nbrs) stk.push(tmpLoc); } pause("searching..."); } return false;}
While this might more elegantly be written using recursion (sample recursive solution in the
project files), this would be a good lab to use early on when teaching stacks. Students will be
able to watch the cells being visited (a pause is built in). You can have discussions about how
subtle changes in the code will lead to certain pathways being attempted beore others. You
can have students try to predict what will happen. Tis lab could be used at the A level when
teaching recursion; then you can revisit it in your AB course. Another suggestion might be
to have the teacher use this lab as a demo in class and then assign MagicWandWorld.
8/11/2019 AP Sf Computer Science Gridworld
41/80
39
MagicWandWorld
MagicWandWorld is based on the paint can tool ound in many graphic editing programs.
You first select a cell (color) with the eye dropper and rom then on, anything you click
will turn that color, along with all adjoining cells o the same color. So, or example, i youtouch a light gray cell when you begin and then you go and touch the dark gray cell in the
upper-lef corner, the dark gray cell and its our blue neighbors will all turn light gray. Its a
simple ideaand the kids love it. When things go wrong with their recursive solutions, they
immediately knowand ofen laugh. On their first attempt, or example, students might end
up turning the whole grid light gray with one clickthat always gets a good laugh rom a
neighbor.
Board Game Projects
8/11/2019 AP Sf Computer Science Gridworld
42/80
40
Special Focus: GridWorld Case Study
Relevant GridWorld classes and interfaces
World, Grid, Location
Relevant topics
tested on AP Exam: recursion, Stack, array, nested loops, or each loop,Math.random()
not tested on AP Exam: event-handling
Code Example
/** This is the recursive method that does the changing of the
colors.*/
public void changeColors(Location loc, Color col){ Grid gr = getGrid(); if ( ! gr.get(loc).getColor().equals(col) )
return; gr.put(loc, new Tile(startingColor)); ArrayList nbrs =
gr.getOccupiedAdjacentLocations(loc); for (Location aLoc: nbrs) changeColors(aLoc, col);}
Tis is a real good lab to use early on when teaching recursion. Te solution is short and
manageable, not to mention un (and it doesnt have anything to do with actorials or
Fibonacci numbers!J). You might then choose to revisit the lab when you are teaching the
AB level, having students, instead, write the solution using a stack. Tis is a nice way to give
application to your discussion o the relationship between recursion and a stack.
8/11/2019 AP Sf Computer Science Gridworld
43/80
41
Traffic Jam
raffi c Jam is a game based on Rush Hour by Nob Yoshigahara. Te goal o the game is
simple. Move the arrows around until you can get the red arrow over to the right wall.
Tis lab is nice or the AB level because one possible way to implement the arrows
needing to be stored in the grid is to extend the BoundedGridclass. Te new class(MultiCellBoundedGrid) contains a private Mapthat holds objects o typeArrow.Each arrow then knows about itsel and how many cells it takes up. When adding objects
to MultiCellBoundedGrid, the new implementation takes advantage o inheritance,storing all individual pieces o the arrows in the BoundedGrid.
Tis working version provides you with 40 game situations. Students learn to read rom a
text file to load the games. Tey use the keyboard to choose between games and then the
mouse to start moving arrows. As soon as they start, a JFramepops open and starts timing
Board Game Projects
8/11/2019 AP Sf Computer Science Gridworld
44/80
42
Special Focus: GridWorld Case Study
them, introducing them to threads, one simple GUI component, and some basic Graphicsmethods. I you dont like to spend a lot o time teaching GUI, this model works as a nice
teaser or those students who need differentiation and desire more depth.
Relevant GridWorld classes and interfaces
World, Grid, BoundedGrid, Location
Relevant topics
tested on AP Exam: inheritance (extending BoundedGrid), nested loops,ArrayList, Map, or each loop
not tested on AP Exam: Scanner, StringTokenizer, JFrame, Thread
Code Example
public class MultiCellBoundedGrid extends BoundedGrid
{ //Map holds arrows that take up multiple BoundedGrid//locations
private Map blocks;public Blockable putBlock(Location loc, Blockable blk){
Blockable oldBlk = blocks.remove(loc); blocks.put(loc, blk); // now put individual parts/pieces of Block into
// BoundedGrid
for (Piece p: blk.getCells()) if ( isValid(p.getLocation()) ) put(p.getLocation(), p); else throw new IllegalArgumentException( illegal Block location being put); return oldBlk; }
public void clearGrid()
{ for (Location loc: getOccupiedLocations()) remove(loc); blocks = new HashMap(); } // other methods and constructors not shown}
8/11/2019 AP Sf Computer Science Gridworld
45/80
43
Tis project is very involved. It is suggested as a final project. Just as with the other labs,
however, you can give students a working version with just a ew methods needing to be
finished. I you want to have students design their own Arrows, this lab shows you how the
GridWorld GUI works with images, rotating, and coloring.
Te code example above gives you a small idea o how the MultiCellBoundedGridworks by extending BoundedGrid. Te MultiCellBoundedGridhas a private Mapwhich holds the arrows (Blockable). BoundedGridwas extended so that it couldhold the individual pieces o each arrow.
Reference
Yoshigahara, Nob. Rush Hour (board game.)
http://www.thinkun.com/RUSHHOUR.ASPX?PageNo=RUSHHOUR.
Materials
Te annotated code solutions and suggestions or these projects and more related to
GridWorld may be ound at: www.apcomputerscience.com/gridworld
user: apteacher
password: specialocus
Board Game Projects
8/11/2019 AP Sf Computer Science Gridworld
46/80
44
Special Focus: GridWorld Case Study
Ant Farm Project
Robert Glen Martin
School or the alented and Gifed
Dallas, exas
Introduction
Tis is a detailed overview o Ant Farm, a GridWorld programming project that is
appropriate or students taking AP Computer Science A or AB. eachers can download the
student assignment, starter files, and a written ollow-up assignment. Te completed project
and ollow-up assignment key are included or teachers. More details about the download
are included at the end o this document.
As students complete the Ant Farm project, they write an interace and both concrete and
abstract classes. Tey demonstrate inheritance, encapsulation, and polymorphism. Prior to
beginning the Ant Farm project, students must read and understand the first our chapters othe GridWorld narrative.
Overview
Figure 1Ant Farm (Initial State)Worker ants hunt for food.
8/11/2019 AP Sf Computer Science Gridworld
47/80
45
Ant Farm Project
Te project utilizes our new types o objects (see Figure 1), two kinds o ood
(A- Cookieand B- Cake) and two kinds o ants (C- WorkerAntand D- QueenAnt).Originally, the worker ants walk around in search o ood. When they find ood, they take a
bite. Ants with ood turn red. Ten the worker ants go in search o a queen ant to give ood.
Once they give their ood to a queen, they turn black and go back to get more ood.
Food and queens remain stationary. Worker ants remember the locations o ood and the
queen. Additionally, they share those locations with other worker ants they meet.
When the Ant Farm program starts, the worker ants are spread around the grid in random
locations. Initially, they are disorganized as they search or ood. As the worker ants start to
find ood and the queen, they get more organized (see Figure 2). Afer all the ants learn the
locations, they exhibit an emergent behavior that is very organized (see Figure 3).
Figure 2Intermediate Stateworker ants start learning
locations of food & queen.
Figure 3Final Stateworker ants know locations of
food & queen.
8/11/2019 AP Sf Computer Science Gridworld
48/80
46
Special Focus: GridWorld Case Study
Program Organization
Figure 4Ant Farm Classes
Figure 4 shows the organization o the Ant Farm classes and interace.
GridWorld has a built-inActorclass or objects that live in the grid. Actors that haveminimal interaction with other objects in the grid normally inherit rom Actor. Tis is
appropriate or QueenAnt and Food.Cake, and Cookiealso inherit indirectly romActor.
Te other built-in actor is Critter,which inherits romActor. Crittershaveadditional methods that are useul or interacting with other actors. WorkerAnts need tocommunicate with the QueenAnt, Cake, Cookie, and other WorkerAntobjects, soinheriting romAntFarmCritteris appropriate or them.
Ant Farm also has a new Processableinterace. Tis interace has a single processmethod that is the key to communication between worker ants and the other actors.
Now well discuss each o the new classes and interace.
8/11/2019 AP Sf Computer Science Gridworld
49/80
47
Ant Farm Project
Processable Interface
Figure 5Processable Interface
Figure 5shows the complete Processableinterace. It contains a single public abstractprocessmethod. Note that all interace methods are automatically public and abstract.
When implemented in QueenAnt, Food, and WorkerAnt, this method processes(communicates with) a single WorkerAntobject (the one passed as a parameter). Tisinterace allows worker ants to invoke the other actors processmethods polymorphically.
Te individual processmethods will do the ollowing:
QueenAnt
Get ood rom the worker ant.
Give the queens location to the worker ant.
Food
Give ood to the worker ant.
Give the oods location to the worker ant.
WorkerAnt Give the saved ood location to the other worker ant.
Give the save queen location to the other worker ant.
Note that Ant Farm uses the Processableinterace to implement an interace variant othe emplate Design Pattern. Te emplate Design Pattern normally uses an abstract class to
contain the abstract method(s). Ten concrete classes (which inherit rom the abstract class)
implement the method(s) as appropriate. In Ant Farm, we use the Processableinteraceto hold the abstract processmethod. processmethods are written in the QueenAnt,Food, and WorkerAntclasses, each o which implement Processable.
8/11/2019 AP Sf Computer Science Gridworld
50/80
48
Special Focus: GridWorld Case Study
QueenAnt Class
Figure 6Queen Ant class
Figure 6 shows the QueenAntclass. Queen ants are the simplest o the new Ant Farmobjects.
Te QueenAntclass has one new instance variable (foodQuantity) that is used tocontain the total amount o ood that has been given to the queen by the worker ants. Note
that instance variables in Ant Farm, are made privateto preserve encapsulation.
Te QueenAntclass has a constructor that initializes foodQuantityto 0and uses theinheritedsetColormethod to set the queens color to Color.MAGENTA.
QueenAntimplements the processmethod (rom Processable) to get ood romthe passed worker ant and to provide it the queens location. It overrides theActoractmethod with an empty do nothing method (QueenAnts dont act).
8/11/2019 AP Sf Computer Science Gridworld
51/80
49
Ant Farm Project
It also overrides theActortoStringmethod to add additional inormation to thereturned string.
Tis provides a good example o using superto call a super class method:
return
super.toString() + ", FQty=" + foodQuantity;
Food, Cake, and Cookie Classes
Figure 7Food,Cake, and Cookie Classes
8/11/2019 AP Sf Computer Science Gridworld
52/80
50
Special Focus: GridWorld Case Study
Figure 7 shows the Food, Cake, and Cookie classes. Cake and cookie objects actsimilarly to queens. However, instead o getting ood, they give ood.
Different kinds o ood are very similar. Tey differ only by the size o a bite and the
displayed image. o take advantage o this similarity, the common instance data and
methods are placed in a Food super class. Tis class contains no abstract methods, but it isdeclared abstract so that it can not be instantiated. Food contains two instance variables:
BITE_SIZEa constant that determines how much ood is given to a worker antwhen it gets ood.
foodEatenkeeps track o the total amount o ood given to worker ants.
Te constructor initializes BITE_SIZEto the bitevalue passed in the parameter,initializesfoodEatento 0, and calls setColor(null)so that the Cake.gi and Cookie.gi images display with their original coloring.
Foodimplements the processmethod (rom Processable) to give ood to the passedworker ant and to provide it the oods location. It overrides theActoractmethod with anempty do nothing method (Foods dont act).
It also overrides the toStringmethod to include the BITE_SIZEand foodEateninormation.
Because o the Foodclass, the Cakeand Cookieclasses are very simple. Tey contain asingle class constant BITEwhich contains the size o a bite. Tey each have a one statementconstructor which passes the value o BITEto the Foodconstructorsuper(BITE);
8/11/2019 AP Sf Computer Science Gridworld
53/80
51
Ant Farm Project
WorkerAnt Class
Figure 8WorkerAnt class
8/11/2019 AP Sf Computer Science Gridworld
54/80
52
Special Focus: GridWorld Case Study
WorkerAnt(Figure 8) is the most complex Ant Farm class. Tis is to be expected, since itis aCritterthat interacts with the other objects in the grid.
Worker ants have instance variables to keep track o the amount o ood they currently have
as well as the locations o the ood and the queen.
Te constructor initializes these instance variables, makes the ant black, and uses Math.randomto randomly point the ant in one o the eight valid compass directions.
WorkerAntimplements the processmethod to share queen and ood locations withother worker ants. WorkerAnthas our methods that do the processing. Tey aretakeFood, giveFood, shareFoodLocation, and shareQueenLocation.Tese methods are called rom the processmethods o the QueenAnt, Food, andWorkerAntclasses.
Te Critteractmethod calls the ollowing methods in order:1. getActorsgets a list o actors or interaction.
2. processActorsinteracts with the list o actors.
3. getMoveLocationsgets a list o possible locations or moving.
4. selectMoveLocationchooses one o the possible move locations.
5. makeMovemoves.
Worker ants inherit theCritteractmethod, which does the ollowing:
1. Uses the inherited getActorsto get all the adjacent neighboring actors.
2. processActorsprocesses each o the neighboring ant arm actors. his method is amodel o elegance and conciseness. he entire method is
for (Actor actor : actors) { Processable processor = (Processable)actor; processor.process(this); }
An actorcould be a QueenAnt, aCake, aCookie, or aWorkerAnt. Without
theProcessableinterace, processActorswould need to determine the type oactor and then downcast the actorreerence beore making the call to process.But, since each o these classes implements Processable, processActorsonly needs to cast theactortoProcessablebeore the call. Tis polymorphicprocessing is allowed because Processablecontains the processmethod. Te JavaRun ime Environment (JRE) determines the actual type o object at runtime and calls
the appropriate processmethod.
8/11/2019 AP Sf Computer Science Gridworld
55/80
53
Ant Farm Project
Also note the use o the thisreerence. thisis a reerence to the worker ant executing theprocessActorsmethod, which is exactly the ant that needs to be passed toprocess.
3. getMoveLocationsdoes the ollowing:
a. Calls the private getDesiredDirectonmethod to get the general direction theant wants to move. This is determined as follows. If
i. the ant wants food and knows where the food is, then the direction is towards the
food.
ii. the ant has food and knows where the queen is, then the direction is towards the
queen.
iii. neither of the above, then the direction is the ants current direction.
b. Creates a list with up to three of the adjacent locations that are in the general direction
of the one returned by getDesiredDirection. Locations are included if theymeet all of the following criteria. They must be:
i. Adjacent to the current location. ii. In the desired direction or 45 degrees to the left and right of the desired
direction.
iii. Valid.
iv. Empty.
c. Returns the list of locations.
4. Uses the inherited selectMoveLocationto randomly select one o the possiblelocations. I the list o possible locations is empty, it returns the current location.
5. I the selected move location is dierent rom the current location, makeMovemovesto the selected location. Otherwise it stays put and changes its direction by randomlychoosing between the two directions 45 degrees to the let and right. hen, in either
case, it sets its color based on whether it has ood (red) or not (black).
WorkerAntalso overrides toStringto include the values o its instance variables.
AntFarmRunner
Like all GridWorld projects, Ant Farm has a runner application that is used to set up the
initial configuration and show the GUI.AntFarmRunnerdiffers rom the introductory
examples in that it creates its own grid and uses the one parameterActorWorldconstructor so that the world will use it.
Modifications
Te Ant Farm project is complete. But it can be modified in several ways. Here are a ew
ideas:
8/11/2019 AP Sf Computer Science Gridworld
56/80
54
Special Focus: GridWorld Case Study
Split Assignment
Since this assignment contains new classes that inherit rom bothActorandAntFarmCritter, it can be split into two assignments. Afer students read chapter 3
o the GridWorld Narrative, they could be given a revised starter project that includes a
working WorkerAnt.classfile (but no WorkerAnt.java). Tis revised assignmentwould have students implementingAntFarmRunner, Processable, QueenAnt,Food, Cake, and Cookie.
Later, afer completing chapter 4 o the GridWorld Narrative, students could write
WorkerAntto complete the project.
A-level Enhancements:
1. Add additional oods. Each o them would extend Food.
2. Currently the worker ants and the queen ants dont need the ood to survive. he project
could be changed so that they use up the ood over time and die i they dont receiveenough.
3. Currently the ood is never totally consumed. Each ood could start with an initial
number o bites and could go away when totally consumed.
4. Additional ood objects could be created as the simulation progresses. his would require
creating a new world which extendsActorWorldand overrides the stepmethod.
AB-level Enhancements
1. Currently worker ants vary their directions a little and can navigate around other ants
and small obstacles such as rocks. However, they are unable to get around a wall oobstacles that would require them taking a longer path.
Worker ants could be extended to do a breadth-irst search or the shortest possible path
to the ood or queen.
2. Another method o navigating around obstacles would be to use maps which would
indicate the number o steps required to get to ood or a queen. hese maps could be
created by breadth-irst searches initiated inAntFarmRunner.
Summary
Ant Farm is a GridWorld project that is appropriate or both A and AB students. As studentscomplete the project, they demonstrate their understanding o the first our chapters o the
GridWorld Narrative.
Tis project utilizes both types o actors. Students inherit romActoror FoodandQueenAnt. Students inherit rom Critteror WorkerAnt, an actor that interacts withthe other actors.
8/11/2019 AP Sf Computer Science Gridworld
57/80
55
Ant Farm Project
As students complete the Ant Farm project, they write an interace, an abstract class, and
several concrete classes. Tey demonstrate inheritance, encapsulation, and polymorphism.
Te polymorphism is acilitated by the is-arelationships created by both class inheritance
and interace implementation.
DownloadTe assignment and starter project can be obtained rom http://www.martin.
apluscomputerscience.com/gridworld.html. Since this download contains the teacher
solution and key, its access is restricted to teachers only(Passwordabbott). Please do not
share the URL or password with students.Te ollowing files are included:
Student Files
AntFarm Assignment.docthe assignment
AntFarm Student.zipthe starter files (JCreator project)
AntFarm Follow-up Questionsquestions about the important OOP and GridWorld
concepts demonstrated in the Ant Farm project.
eacher Files
AntFarm eacher.zipthe completed project
AntFarm Follow-up Questions KEY
Reference
As students execute the Ant Farm project, they see an emergent behavior exhibited by the
worker ants. eachers and students may want to explore emergence urther at the ollowing
URL:
Emergence. Wikipedia. http://en.wikipedia.org/wiki/Emergence
Ant Farm uses an Interace variant o the emplate Design Pattern. Tis can be explored at:
http://en.wikipedia.org/wiki/emplate_method_pattern
Special Thanks
I would like to thank
Cay Horstmann or his helpul design suggestions.
Chris Renard, one o my