129
 GridWorld: A Curriculum Module for AP ®  Computer Science 2010 Curriculum Module

GridWorld AP CompScience

Embed Size (px)

Citation preview

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 1/129

GridWorld:

A Curriculum Modulefor AP® Computer

Science

2010Curriculum Module

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 2/129

The College Board

Te College Board is a not-or-proft membership association whose mission is toconnect students to college success and opportunity. Founded in 1900, the College Board

is composed o more than 5,700 schools, colleges, universities and other educationalorganizations. Each year, the College Board serves seven million students and theirparents, 23,000 high schools, and 3,800 colleges through major programs and services incollege readiness, college admission, guidance, assessment, fnancial aid and enrollment.Among its widely recognized programs are the SA®, the PSA/NMSQ®, the AdvancedPlacement Program® (AP®), SpringBoard® and ACCUPLACER®. Te College Board iscommitted to the principles o excellence and equity, and that commitment is embodiedin all o its programs, services, activities and concerns.

For urther inormation, visit www.collegeboard.com.

© 2010 Te College Board. College Board, ACCUPLACER, Advanced Placement,Advanced Placement Program, AP, SA, SpringBoard and the acorn logo are registeredtrademarks o the College Board, inspiring minds is a trademark owned by the CollegeBoard. PSA/NMSQ is a registered trademark o the College Board and National MeritScholarship Corporation. All other products and services may be trademarks o theirrespective owners.

Visit the College Board on the Web: www.collegeboard.com.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 3/129

Contents

Introduction........................................................................................ 4

Fran Trees

Overview............................................................................................ 5

Judy Hromcik

Unit Plan: Parts 1, 2 and 3................................................................11

Kathleen A. Larson, with worksheets by Joe Coglianese

Unit Plan: Part 4 — Critters..............................................................74

Mike Lew, with worksheets by Joe Coglianese

Unit Plan: Part 5 — Grid.................................................................103

Leigh Ann Sudol, with worksheets by Joe Coglianese

About the Editor and Authors.........................................................128

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 4/129© 2010 Te College Board.

4

AP Computer Science Curriculum Module: GridWorld

Introduction

FranTrees

“A case study describes a programming problem, the process used by an expert to solve theproblem, and one or more solutions to the problem. Case studies emphasize the decisionsencountered by the programmer and the criteria used to choose among alternatives.” 1 Case studies have been part o the AP® Computer Science curriculum since 1995. Tesestudies allow students the benefts o an apprenticeship by being able to work with largeprograms written by experts. Students can be guided through programming design issuesearly in your course rather than postponing the complexity o program design until thelanguage has been mastered. Case studies also provide an excellent vehicle or assessing astudent’s knowledge and are great tools or promoting teamwork and active learning.

Te teaching modules included here provide instructional strategies andpresentation suggestions related to the GridWorld case study (http://www.collegeboard.com/student/testing/ap/compsci_a/case.html). Te authorso the modules are experienced AP teachers and university proessors who have usedcase studies in an introductory Java course and are excited about sharing their avoriteactivities with you.

Aer an overview o the GridWorld case study, highlighting ways to incorporatethe case study into an AP Computer Science course, each o the fve parts o the casestudy are addressed by supplying you with a variety o ideas and tools. Te instructionalunits include teaching strategies, presentation suggestions and activities (including lab

assignments) that are designed to address the various ability levels and learning styleso the students in your class. Troughout the document there are student worksheetsthat can be printed and distributed to students at various times in your course, either asreviews o GridWorld concepts or as exercises and homework assignments while workingwith 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).

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 5/129© 2010 Te College Board.

5

AP Computer Science Curriculum Module: GridWorld

Overview

JudyHromcik

GridWorld is a great tool or teaching inheritance to computer science students. In thepast, many o us have taught the case study as an add-on at the end o the course, justbeore the AP Exam. In this article, I suggest ways to integrate the case study throughoutthe year by using it as a vehicle to teach students inheritance, to teach students how tocreate and use objects, and to acilitate the instruction o other non-OOP computerscience concepts. I will also discuss some o the technical issues with setting up andrunning the case study code.

The gridworld.jar le

As with any case study, there are always obstacles to overcome beore you and yourstudents will be able to compile and run the case study code. Te case study requiresstudents to examine a large body o code and add to that body o code. Te classes that arealready written have been compiled into .class fles and are contained in the gridworld.jar fle ound in your distribution fles rom the College Board(http://www.collegeboard.com/student/testing/ap/compsci_a/case.html). A classpath mustbe set to this jar fle or students will not be able to compile and run the case study code.I you are unamiliar with this process, the GridWorld case study fles rom the CollegeBoard include a document, “GridWorld Installation Guide,” that should be read beore

setting up projects or your students.

I use JCreator and BlueJ in my classroom. In BlueJ, you can set the classpath to the jar fle by adding it as a library in the preerences; you only need one copy o the jar fle.In a controlled lab setting, this is very painless, and any case study project will run romthat point on without worrying about the jar fle. I have ound this to be convenient whenteaching workshops with teachers and students in a lab.

Using just one copy o the jar fle in JCreator poses more problems than it does inBlueJ, because there are so many ways to set the classpath to the jar fle. Each project mustset a classpath to the jar fle or you must confgure the JCreator environment to add the jarfle. For many reasons, this has not worked well or my students when they work at home

on GridWorld projects. When transporting project olders between school and home, theclasspath must be reset in the project or you must count on the students confguring theJCreator environment correctly at home. In order to make case study projects completely portable, I have my students copy the jar fle into each project’s older and add the jar fleto the project. Once the project is saved, students can transport the project older betweencomputers with Java and JCreator installed and the project will always fnd the jar fle.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 6/129© 2010 Te College Board.

6

AP Computer Science Curriculum Module: GridWorld

Import statements

Te GridWorld case study uses packages. Tis requires the programmer to use importstatements or use a very long class name when declaring and instantiating actors, bugs,

critters, etc. For example, the Bug class is a part o the info.gridworld.actor package. Te ully qualifed name o the Bug class is actually info.gridworld.actor.Bug. o be able to just type Bug when declaring and instantiating a bug, theprogrammer must write the ollowing import statement:

import info.gridworld.actor.Bug;

Te ollowing chart lists the classes and interaces in each package:

Package Classes and Interfaces

info.gridworld.actor ActorWorld, Actor, Bug, Critter, Rock, Flower

info.gridworld.grid Grid, AbstractGrid, BoundedGrid, UnboundedGrid,Location

info.gridworld.world World

In addition to these classes, students must remember to include import statementsor the standard Java classes that they use. A common one needed is the java.awt.Color class. While import statements are not tested on the AP Exam, students need tounderstand when to include them when necessary.

Integrating GridWorld in the AP® Computer

Science curriculum

Te purpose o a case study is to allow students to study, modiy and add to a largebody o code. In an Object Oriented language, it also requires students to understandand use interacting classes. Te GridWorld case study was designed to allow teachers tointroduce the material to students early in the AP Computer Science course and then useit throughout the school year. AP Computer Science teachers have the task o fguring outhow and when to teach the case study material.

I you compare GridWorld to the Marine Biology Simulation (MBS), you will

notice that there are ewer interacting classes in GridWorld than there are in MBS. Tismay lull you into the alse sense o security that you can teach GridWorld aster thanyou could MBS; I have not ound that to be true. Te complexity is still there, and Part 4requires solid knowledge o the interacting classes. Some teachers introduce GridWorldearly and throughout the year come back to the case study as the topics covered inGridWorld come up in the curriculum. Some teachers plan to teach the case study as areview o the AP Computer Science course right beore the exam. Initially, I was goingto ollow the materials and cover them in order as I got to those topics in the curriculum,

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 7/129© 2010 Te College Board.

7

AP Computer Science Curriculum Module: GridWorld

but I have since changed my mind; I am now using GridWorld to help reinorce the useo objects and inheritance. I am also using GridWorld to help teach loops and conditionalstatements, ArrayList, classes, and anything else I can think o as I teach thecurriculum throughout the year.

I introduce my students to OOP using Jeroo (Jeroo:http://home.cc.gatech.edu/dorn/jeroo), a wonderul book and program by Dean Sandersand Brian Dorn rom the University o Missouri. In Jeroo, students make one kind o object, a Jeroo, and then send messages to the Jeroos to make them act. Tey also modiy the Jeroo class by adding new methods. Once this unit is fnished, I introduce the studentsto Java. Early in the Java introduction, it is dicult to keep students in the OO rame o mind. Java does not have a lot o simple classes that students can easily use as they areintroduced to the language basics. It is dicult to leverage what the students learnedabout creating and using objects in Jeroo as they move into Java.

Stacey Armstrong (http://apluscompsci.com) rom Cypress Woods High School inHouston, exas, has solved this problem by using GridWorld as a key curriculum componentin AP Computer Science, developing GridWorld lessons and labs or students to use rom the

 very beginning o the course and throughout the year. Tese labs allowed me to seamlessly move rom Jeroo to Java and keep OO alive. Aer students fnish Part 1 o the case study, the

 Actor, Location and ActorWorldclasses can be introduced. Introductory labs havestudents 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();

}}

Te frst labs only require that students know how to call the constructors or the

 Actor and Location classes and the constructor, add, and show methods or the ActorWorld class. Students are essentially doing the same tasks in these programs as

they did at the beginning o the Jeroo unit.

Aer the GridWorld introduction, the Java language basics can be taught:primitive variables, reerences, 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.

Aer the Java language basics have been covered, you could begin teachingsimple inheritance by making new types o actors. One such actor rom Armstrong’s

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 8/129© 2010 Te College Board.

8

AP Computer Science Curriculum Module: GridWorld

materials is the MoveLeftActor. Only the Actor actmethod is overridden and the

getDirection and moveTomethods o  Actor are used. Te Location classmethods getAdjacentLocation, getRow, getCol and the Location constantsare also introduced. Students learn how to get the adjacent location to the le o the actorand then move to that location. No checks are added to keep the actor rom going out o thegrid. Te ocus o this lab and others like it is to introduce inheritance and to learn how to usesome o the methods ound in the Actor andLocation classes. Later on, aer conditionalstatements have been taught, this lab is redone to check or boundaries. Te Actor’s 

getGridmethod is introduced along with the Grid interace’sisValid, getNumRows andgetNumCols methods. Beore Part 2 is taught, students are introduced to a substantialnumber o methods ound in the case study’s interacting classes. Many o these methodsare not introduced in the narrative until Part 3. Tis simplifes teaching Part 3 and gives theteacher 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() andsuper.method() can be taught using the Bug class as a

base class. Essentially, Part 2 can be taught as is in the narrative. Te 2007–2008 AP Computer Science Special Focus Edition: GridWorld Case Study has additional Bug labs as well that canalso be added to the exercises ound in the narrative. Parts 3 and 4 can be taught aer loopsand ArrayList. Part 4 is a great unit to help you teach the intricacies o inheritance.

GridWorld can be used to enhance your teaching o other programming conceptssuch as conditionals and loops. Cay Horstmann has a Web page(http://www.horstmann.com/gridworld/extending-gridworld.html) that shows how to usethe GridWorld environment to teach other concepts in AP Computer Science. My avoriteis LoopWorld. Using this project, students can place Actor objects in the grid with aloop 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. Te graphical nature o thiscode can assist your visual learners. Additional extensions o the GridWorld case study can also be ound at the above-reerenced website. I you and your students visit this page,you will fnd that you can also use the GridWorld ramework to create games.

As I work with GridWorld, I see more ways to integrate worlds, locations, gridsand actors to help reinorce object instantiation and object use, and to help teach classes,inheritance, conditionals, loops, input, etc. Te GridWorld classes help me to teachobjects frst and to teach them oen.

Part 4 of the GridWorld Case Studyhe Critter class was designed with an act method that always perorms ivebasic behaviors:

1. Get a list o actors or the critter to process in some way.

2. Process those actors.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 9/129© 2010 Te College Board.

9

AP Computer Science Curriculum Module: GridWorld

3. Get a list o possible move locations or the critter.

4. Select one o those locations.

5. Make the move.

Tis is what all critters do when they act. New types o critters should do this as well.Tereore new Critter subclasses override one or more o the fve methods ound inthe act method. Te act method should not be overridden. Students should rememberthat a Critter is defned to be an actor that perorms the fve basic behaviors in theact method. I a new actor is being defned and needs to perorm other behaviors,consider overriding the Actor class.

A word of caution about Part 4: Read all o the descriptions and postconditionsor these fve methods ound in act. Tey must be ollowed when your students createnew Critter subclasses. Te postconditions and additional comments about thepostconditions or each o these fve methods are listed below:

Critter Method Postconditions and Comments

getActors

Postcondition:Thestateofallactorsisunchanged.

Nochangescanbemadetoanyactorsanywhere,inoroutofthe

grid.Thismeansyoucannotmoveactorsinthegridoraddactorsto

thegridorchangeanyactor’sattributes.

processActors

Postcondition:

(1)Thestateofallactorsinthegridotherthanthiscritterandthe

elementsof<code>actors</code>isunchanged.

(2)Thelocationofthiscritterisunchanged.

Foractorscurrentlyinthegrid,onlythiscritterandtheactorsinthegetActors()ArrayListcanchange.Newactorscanbeaddedto

unoccupiedlocations.

getMoveLocations

Postcondition:Thestateofallactorsisunchanged.

Nochangescanbemadetoanyactorsanywhere,inoroutofthe

grid.Thismeansyoucannotmoveactorsinthegridoraddactorsto

thegridorchangeanyactor’sattributes.

selectMoveLocation

Postcondition:(1)Thereturnedlocationisanelementoflocs,this

critter’scurrentlocation,ornull.

(2)Thestateofallactorsisunchanged.

Nochangescanbemadetoanyactorsanywhere,inoroutofthegrid.Thismeansyoucannotmoveactorsinthegridoraddactorsto

thegridorchangeanyactor’sattributes

makeMove

Postcondition:(1)getLocation()==loc.

(2)Thestateofallactorsotherthanthoseattheoldandnew

locationsisunchanged.

Onlytheactorandtheactoratthemovelocationcanchange.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 10/129© 2010 Te College Board.

10

AP Computer Science Curriculum Module: GridWorld

Suppose you have a new type o critter that keeps a log o all o the places that it visits. It contains an ArrayList private instance variable to store these locations. Whichmethod should update the ArrayList? You might choose selectMoveLocation.Tis is a reasonable place to update the list, but the postconditions do not allow any changesto be made to the critter. Te ArrayList should be updated in makeMove. Be sure toteach these postconditions to your students. Students who violate the postconditions whenwriting ree-response answers may not receive ull credit or their solutions.

Te GridWorld case study can and should be used throughout the year tointroduce and enhance numerous topics, such as OOP undamentals, decision making,looping and inheritance. GridWorld can be used to help students better understandand grasp any o the AP Computer Science A topics. Te graphical nature o GridWorldmakes it very attractive to visual learners, and it also serves as a game creation platorm,thus making it an incredible recruiting tool. GridWorld is robust and has a rich source o materials to help us teach AP Computer Science.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 11/129© 2010 Te College Board.

11

AP Computer Science Curriculum Module: GridWorld

Unit Plan: Parts 1, 2 and 3

KathleenA.Larson

Parts 1, 2 and 3 o the GridWorld case study (http://www.collegeboard.com/student/testing/ap/compsci_a/case.html) can be taughtduring a contiguous time period or may be spread over many weeks interspersed withother AP Computer Science course material. Tis instructional unit is designed tobe implemented either way, at the teacher’s discretion, and provides a variety o waysto introduce the case study parts. It includes activities and lesson plans or each part;diagnostic, ormative and summative assessment tools; accommodations or dierenttypes o learners; a teacher sel-evaluation; and resources.

GridWorld topics covered in this unit are:

• Part 1: Observing and Experimenting with GridWorld

• Part 2: Bug Variations

• Part 3: GridWorld Classes and Interaces

Te GridWorld case study is a required element o the AP Computer Sciencecurriculum and constitutes a signifcant part o the AP Computer Science Examination.It is incumbent upon the teacher to provide ample experience with the case study orstudents to learn the important concepts illustrated in it and or them to achieve successon the exam.

Worksheets or Parts 1–3 o GridWorld, written by Joe Coglianese, are ound inthe appendixes o this article.

Introducing GridWorld

Te purposes o a careully planned introduction are as ollows:

• Motivate students to want to learn the new material

• Focus their attention on this topic

• Activate prior knowledge by connecting the new learning to what each studentalready knows, in order to create brain synapses that will enable real learning to occur

• Diagnostic assessment, to fnd out what students already know in order to build ontheir prior knowledge

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 12/129© 2010 Te College Board.

12

AP Computer Science Curriculum Module: GridWorld

Te ollowing are fve possible GridWorld introductory activities:

1. One simple way to introduce any new material is a KWL (Know, Want to knowand Learned) chart (see Appendix A). Give each student a paper divided intothree columns labeled “Know,” “Want to Know” and “Learned.” At the beginning

o study, the students are asked to fll out the frst two columns with a list o what they already know about the topic (case studies, grids and GridWorld inparticular) and what they want to know. At the end o a module (all three partsor each part individually), students will complete the third column with whatthey have learned. Give the students two or three minutes to fll out the frst twocolumns. On a transparency or on the whiteboard, create a similar chart. Allowfve minutes or students to tell you what they know and what they want to know,and to student’s list many o their answers on the master chart. Aer completingthe module, you and the students can fll in what they have learned. Tis activity satisfes the required parts o an introduction, especially by giving you eedback ordiagnostic assessment; you will build on this inormation.

2. When the students enter the classroom, have a “Gummy Bug” (see Appendix B)on each student’s desk. ell them they have one minute to write down three waystheir bug might interact with its environment. Aer one minute, tell the studentsto share their ideas in small groups and decide on the best three ideas; allow twominutes or this activity. Each group should choose one spokesperson to report thegroup’s three ideas to the class. Students may eat their bugs.

3. As students enter the classroom, have them take a olded piece o paper rom apaper bag (basket, hat …); the papers will say either “bug,” “ower” or “rock.” Inone corner o the room have a large picture o a bug; in another corner, a picture

o a ower; and in a third corner, a picture o a rock. ell the students they havetwo minutes to fnd their corners and discuss how their selected character behaves.You might provide props or costumes to enhance the role-playing aspect o thisactivity. At the end o two minutes, ask each group to act out the behaviors o theirselected character. Have the rest o the class try to guess what the “acting” group isdoing.

4. Make up tic-tac-toe game boards on sheets o paper, and distribute them to pairso students. Make game pieces that are either bugs or rocks (see Appendix B). Giveone player o each pair three bug pieces, and give three rock pieces to the otherplayer in the pair. Have them play tic-tac-toe with the pieces fve times and report

the number o wins. (Alternatively the players could draw a bug or a rock in theposition on the paper game board.) Ask the class to name other games that areplayed on a grid and suggest extra credit or any o the pairs who, by the time themodule is completed, come up with rules or a new game that is played on a gridand that uses bugs, rocks and, possibly, owers.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 13/129© 2010 Te College Board.

13

AP Computer Science Curriculum Module: GridWorld

An alternative to traditional tic-tac-toe is a version played in reverse. Pairs o students start with a 4 x 4 (or N x N) grid and take squares using bugs and rocks.Te object is to avoid getting three o the same marker in a row. Ask students todiscuss their choice o moves and describe a winning strategy.

5. Ask each student to recall an incident that happened to him or her in theirchildhood involving a bug, a ower or a rock. Have them draw a depiction o thestory. Ten have the students orm small groups to share their stories and createone single story out o their individual stories. Tey may use the pictures they already have or create a single picture that combines the stories. Each group thenhas two minutes to tell their combined story to the class.

Each o these activities is intended to introduce GridWorld on the frst day you use thecase study. Each in some way uses social interaction (cooperative learning) and activeinvolvement. Parts o the activities are geared toward dierent types o learners (i.e.,

 visual, auditory or kinesthetic), and each activity allows the teacher to grab the students’

attention and to attach new learning rom GridWorld to students’ prior knowledge.At the end o any o these introductory activities, inorm the class that you are

introducing them to the GridWorld case study. Explain to the students the duration o the class work with the case study (typically three weeks) and that the class will revisit thecase study periodically throughout the rest o the school year. Also explain that the casestudy will help them learn several o the primary concepts o this course; that they will seemodel code that will help them learn how to organize and write their own programs; thatthey will work with graphic characters, developing special abilities or them, and make thecharacters move around a special world on the screen; and that the case study is part o their preparation or the AP Computer Science Exam.

Note: Each o the ollowing lesson plans is intended or one 45- to 50- minuteclass period.

Part 1: Activity/Lesson Plan 1 — GridWorld Part 1

Students will experiment with GridWorld to learn how the environment and actors behave.

Learning Goals

• Students will learn the capabilities o bugs, rocks, owers and the Graphic User

Interace (GUI).

• Students will develop investigative techniques to be used in understandingGridWorld.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 14/129© 2010 Te College Board.

14

AP Computer Science Curriculum Module: GridWorld

Lesson Objectives

• Given a working version o GridWorld and an investigative worksheet, thestudent will be able to activate the GUI in Step and Run modes and determinethe characteristics and capabilities o the GUI, a bug, a ower and a rock with 100percent accuracy.

• Given a working version o GridWorld and a set o questions to be explored, thestudent will be able to work cooperatively with another student to investigateadding actors to the grid and to determine what those actors can and cannot doand 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 frst day o the unit, one o the introductory activities listed above may serve as the anticipatory set or this lesson. I, however, thislesson is not taught on the frst day, the ollowing introduction may be used.

Play the game, Find the Route, ound at http://math2.eku.edu/Greenwell/MA303.

In this game, an individual player must fnd a route rom the upper le-hand corner tothe lower right-hand corner o a grid according to prescribed rules. Tis activity ocusesthe students’ attention on the grid. Ask them to contrast the grid in this game with theCartesian coordinate system.

Lesson Development

Project the instructor’s computer screen and demonstrate how to open and run theGridWorld demo program. Instruct the students to ollow the steps with you, makingsure they are able to open and run GridWorld. Hand out Part 1 o the case study and theabove-reerenced worksheets. Instruct the students to complete the Running the Demoworksheet independently, ollowing the instructions and answering the questions, then

compare answers with another student. Te pairs o students should then work on theExploring Actor worksheet activities and questions. Students may reer to Part 1 o thecase study as needed. Circulate about the classroom, answering students’ questions andhelping as needed, but allowing the students to do their own investigation. Monitor thestudents to be sure that they are fnding the worksheet answers through their investigation.Tis is your ormative assessment, the time during which you determine to what extenteach student is mastering the material.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 15/129© 2010 Te College Board.

15

AP Computer Science Curriculum Module: GridWorld

Accommodations

Students who need extra help may receive it by working with a partner and by the teachercirculating about the room to provide eedback and guidance regarding their work. Tosewho fnish early can investigate eatures o the case study urther.

Closure

At the close o class, take a ew minutes to ask the students to summarize what they learned. Ask them not only or the acts that they learned about the GUI and the actors,but also ask them to discuss the investigative strategies they used to fnd answers to theworksheet questions.

Assignment

Read Part I and answer o the GridWorld Student Manual and complete “Do You Know? Set1.” For homework and as a summative assessment, tell the students to write a short letter to

their best riend describing fve things they learned about the GUI, fve things they learnedabout a bug, two things they learned about a rock and three things they learned about a ower.

Rubric for a Letter to a Friend

Topic Evaluation Point ValuePoints

Earned

Content:

FivevalidthingslearnedaboutaBug 5

TwovalidthingslearnedaboutaRock 2

ThreevalidthingslearnedaboutaFlower 3

10

Style:

Correctfriendlyletterstyle 5

Freeofspellingandgrammarerrors 5

10

Instruct the students to begin keeping a GridWorld journal. Te frst entry is to describewhat they learned in this lesson and what it means to them in terms o the AP ComputerScience course. (See Appendix E.)

Assessment

• Diagnostic assessment occurs by asking questions during the anticipatory set inorder to fnd out what the students already know about a grid.

• Formative assessment occurs through questioning and observation during lessondevelopment.

• Summative assessment occurs with the letter written to a riend. Give the studentsa rubric or the letter and grade according to the rubric.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 16/129© 2010 Te College Board.

16

AP Computer Science Curriculum Module: GridWorld

Evaluation

Formulate questions you will ask yoursel aer teaching this lesson, such as the ollowing:

• Was my anticipatory set eective in activating prior knowledge and motivating the

lesson?• Do the students understand how to use the eatures o 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 dierence between accessor and modifer methodcalls?

• In teaching this lesson, what did I do well?

• What could I have done dierently?

Part 1: Activity/Lesson Plan 2 — GridWorld Part 1

(continued)

Aer introducing the students to GridWorld in Part 1, use the GridWorld Role Play totransition into Part 2. Te role play provides complete directions and a complete scriptor implementation.

Role Play for Activity 2A Role and Name sign is helpul in identiying the players. Print each roleindividually using a very large ont size, centered on a sheet o 8 x 11 inch paper,landscape style. Print the script using regular ont size and landscape style, and printany supplementary pages that accompany the role. Insert the role type and script/supplementary orms into a transparent sheet protector. ie a string or ribbon tothe holes in the sheet protector so it can be hung around the player’s neck. Using anerasable marker, write the player’s frst name on the outside o the sheet protector.(Sheet protectors can be reused or any role play, provided names are not written withpermanent markers.)

Costume pieces may be used to enhance the role play. Don’t go or elaborate,expensive items. Find bug antennae, baseball caps in the shape o bugs, ower headpiecesand crumpled material to look like rocks. Homemade headpieces work equally well. Tepoint is simply to give the impression o the role, not to dress up. Hats or headpieces work best. Te addition o hats isn’t necessary to the role play; it adds a sense o identity withthe role and the silliness o wearing bug antennae or a ower or rock hat adds to the un.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 17/129© 2010 Te College Board.

17

AP Computer Science Curriculum Module: GridWorld

Do not expect to complete one iteration o the Role Play in a single class period,unless your school is on block scheduling. Tis lesson typically takes two class periods.o do justice to the lessons learned rom this activity, it can’t be rushed. aking time nowpays big dividends in students’ subsequent understanding o 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 thebest o his or her ability.

Notes for the GridWorld Role Play

Early in the school year and prior to teaching the case study, take time to use the First Day Role Play (see Appendix B). Students oen have little or no previous experience doing arole play. (Perhaps the teacher has little experience directing a role play as well.) Te FirstDay Role Play is a series o short scripts in which everyone can take part. Not only do thescripts allow the teacher and students to see how a role play works but each script actually illustrates an object-oriented programming (OOP) concept.

Have the students sit in a circle and make sure each one has a role or at least oneo the scripts. Most important, take time or debriefng aer role playing a script. Ask the students how it elt to play a role and what they learned both in terms o the actiono playing a part and in terms o the OOP concept illustrated. Te teacher as well as the

students should examine the role play rom both perspectives. Tese role plays are un;they usually provide a real break rom normal classroom routine. Kinesthetic learnerstypically understand the concepts better by using this approach, and the whole experiencecreates enthusiasm and motivation or learning.

Experience with the First Day Role Play is crucial to the success o the subsequentGridWorld Role Play.

Materials

• GridWorld Role Play scripts

• Copies o GridWorld Role Play accompanying notes pages or the roles

• Ball o yarn or string

• Hats or other props to signiy roles

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 18/129© 2010 Te College Board.

18

AP Computer Science Curriculum Module: GridWorld

• Large grid drawn on erasable plastic sheet or the Display to use

• Erasable markers or stick-on bugs, owers and rocks or the Display to use

Anticipatory Set

Minimally, one iteration o the role play requires approximately 90 minutes. For many teachers this means allowing at least two class days. Te role play includes many tips orsuccess, not the least o which is the teacher’s considered decision about which studentsshould take on the most active roles. o maximize the use o classroom time, hand outthe roles the day beore the role play is to be done and tell the students to become amiliarwith their scripts prior to class.

Students have observed GridWorld in action rom Part 1, but they haven’t lookedat any code up to this point. Tey soon will do so, but by experiencing the role play frstthey will understand the code better when they examine it. Some teachers believe that theopposite is true — that students should study the code and then role play it. Tis has not

been my experience.

When students come into the classroom, tell them to get into character andreview their scripts.

Lesson Development

Once again have the students sit in a circle or the role play. I there are more studentsthan roles, have the “extra” students act as a “buddy” or each role, helping the player tofnd his or her part when told to take an action. I the class is small, a student could takeon more than one o the smaller roles. In that case, there should be a way or the student

to identiy himsel or hersel in the current role. Signs hung around the students’ necks(see Materials list above) help to identiy their roles. You might fnd hats that signiy thepart being played as well (again, see Materials).

An eective method or keeping track o the hierarchy o method calls is tossinga ball o yarn. Te frst student to begin the role play holds an end o the yarn. As eachobject 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 o method calls is completed and the ball goes back tothe player who started the whole chain o event calls. Tis dynamic illustration o how the

objects interact is eective in helping students understand GridWorld code. Later, whenstudying the code, students are reminded o who did what and in what order during therole play.

Te GridWorld Role Play includes ime-or-a-Commercial-Break intervals, duringwhich the teacher and students review what has occurred up to that point. Tis is anopportunity to check on student understanding.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 19/129© 2010 Te College Board.

19

AP Computer Science Curriculum Module: GridWorld

Closure

Debriefng is a critical part o any role play. Activate the students’ higher learning skills o analysis, synthesis and evaluation by asking questions and initiating a discussion o whatoccurred 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 learnabout object instantiation? What did they observe about object interaction? From theirobservations, what can they say about parameters and return values? More questions willcome to mind as you watch the role play in action.

Accommodations

Te role play involves students in the Social Interaction and Inormation Processingmodels o education. Students are actively involved in their education. Visual, auditory and kinesthetic learners are all engaged during the role play. Repetition o steps providesreinorcement or those who need extra practice to understand concepts, while discussion

and debriefng questions challenge those who are ready or enrichment.

Assessment

• Diagnostic assessment occurs as the students recall what they learned romGridWorld Part 1.

• Formative assessment takes place during the “commercial breaks” in the role play.

• Summative assessment consists o each student writing a journal entry commenting on his or her role, what he or she learned rom participation, fveelements o 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 yoursel aer teaching this lesson, such as the ollowing:

• Did my anticipatory set actually activate prior knowledge in the students?

• Did I implement the role play eectively?

• Did the students understand what a Bug, Rock and Flower can do?

• Did the students understand responsibilities and the hierarchy o method calls?

• Was the debriefng eective?

• Is there anything I could have done better or anything I would change the nexttime I teach this lesson?

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 20/129© 2010 Te College Board.

20

AP Computer Science Curriculum Module: GridWorld

• Is there anything I did particularly well and would repeat the next time I teach thislesson?

Part 2: Activity/Lesson Plan 3 — GridWorld Part 2Students study the BoxBug and BoxBugRunner classes. Using BoxBug as a template,they create variations o the Bug class that have dierent characteristics; this acilitateslearning about inheritance. Tis is a Direct Instruction lesson because studying theGridWorld code and learning how to modiy it is new material to the students.

Learning Goal

• Te students will learn how to create and run their own variations on a class.

Lesson Objective• Given the BoxBug and BoxBugRunner classes as templates, the student will

design and implement a variation o a subclass o 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 estable Code or APCS A/AB(http://www.collegeboard.com/prod_downloads/student/testing/ap/compsci_a/

compsci_a_exam_appendix.pd)

• “Bug Class” Reading Worksheet (see Appendix F)

• “Runner Class” Reading Worksheet (see Appendix G)

Anticipatory Set

ell the students they have one minute to jot down one thing they have in common witheveryone else in the class and one thing they can do that is unique about them, somethingthat sets each one apart rom everyone else in the class. Aer one minute the students willfnd a partner and share what they wrote. Aer another minute ask the pairs to share their

ideas o what is common to the students in the class. Write their ideas on the board. Ten ask each one to share what their partner’s unique ability is. ell the students that while we havecommon characteristics, in some way we are all unique variations o the Student class, andthat in this lesson they will learn about a variation o theBug class called a BoxBug. Inormthe students that they will work in pairs to design and implement another variation (that youassign), and then they will use their experience and creativity to design a Bug variation o their own. Inorm the students that this code is testable on the AP Computer Science Exam.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 21/129© 2010 Te College Board.

21

AP Computer Science Curriculum Module: GridWorld

Lesson Development

Demonstrate the BoxBugRunner class that instantiates a BoxBug. Students willimitate the teacher’s steps, observing how a BoxBug behaves. Tey will be given copieso Part 2 and Appendix C. Introduce the BoxBug class and discuss the code line by line,

explaining that BoxBug is a subclass o (extends) the Bug class, to be studied in Part 3.Te constructor, private instance variables and act method will be careully discussed. Inaddition, a runner class must be created or each Bug variation. Te BoxBugRunner class provides a template. Tere should be continuous didactic questioning o the studentsto assess how well they understand the new material. Tese questions are short andactual, aimed at the lowest level o learning. Tink o this as the “I do” part o the lesson,in which the teacher does most o the talking and demonstrates what is to be learned.

Aer 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 o the lesson), the instructor and the students

work together. In this instance, the model has been modifed to involve the studentsin pair programming. Students will take turns being the “programmer,” the person atthe keyboard actually typing the code, and the “navigator,” the person studying themodifcations or errors and making suggestions about additional modifcations tobe made. It is important that students swap roles midstream; insist that each personexperiences both roles. During this part o the lesson, walk around the room observingstudent interaction and progress, oering suggestions, and keeping the pairs on task.

When a pair has successully completed CircleBug, they will separate andwork independently during the third part o the lesson. In this, the “you do” part, eachstudent will again adapt the BoxBug code to create his or her own variation. I 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.

Te resulting BoxBug variation constitutes the summative assessment or eachstudent. Te instructor’s usual grading rubric or programs will be applied. (See Materialslist above or an example.)

Accommodations

For students who need extra help, the instructor will be available to discuss programmingconcepts and techniques. Students who are ready or a greater challenge may work onmore complex variations or instantiate two objects o the same or dierent types to see

how they interact on the grid.Closure

Review with the students what they learned rom studying the BoxBug andBoxBugRunner code. Ask them to think about how these concepts apply toprogramming aside rom the case study.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 22/129© 2010 Te College Board.

22

AP Computer Science Curriculum Module: GridWorld

Assignment

Students will complete the Bug class “Bug Reading Worksheet” and the “Runner ClassReading Worksheet ” on concepts rom Part 2. Te worksheets will be collected andgraded as a summative assessment.

Assessment

• Diagnostic assessment occurs during the anticipatory set when the instructordetermines i students understand the concept o variation.

• Formative assessment will be ongoing with questioning and observation duringthe “I do” and “we do” parts o the lesson.

• Summative assessment will be based on the students’ individual variations basedon BoxBug and the Part 2 worksheets.

EvaluationFormulate questions you will ask yoursel aer teaching this lesson, such as the ollowing:

• Did my anticipatory set grab the students’ attention and help me to diagnose priorknowledge?

• Was my demonstration and explanation clear?

• Were the students able to work together successully 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?

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 23/129© 2010 Te College Board.

23

AP Computer Science Curriculum Module: GridWorld

Part 3: Activity/Lesson Plan 4 — GridWorld Part 3

Tis lesson examines the Location class and applies the Location class in a programseparate rom GridWorld. Te model or this lesson is Inormation Processing because the

topic acilitates the students’ research about the class and fnding an application other thanthe case study.

Learning Goals

• Students will understand the Location class.

• Students will work together to develop an alternate application or the Location class.

Lesson Objectives

• Given Part 3 and the GridWorld Student Manual Appendix B, the student willcomplete a worksheet on the Location class with 90 percent accuracy.

• Given the Location class, the student will work with a small group to design anapplication or Location in a situation dierent rom the case study.

Materials

• GridWorld Part 3: GridWorld Classes and Interaces (page 16)

• GridWorld Student Manual estable Application Programming Interace (API)(http://www.collegeboard.com/prod_downloads/student/testing/ap/compsci_a/compsci_a_exam_appendix.pd)

• Location Reading Worksheet (see Appendix H)

Anticipatory Set

Give each student a compass (see Appendix B). ell them to use the compass to ace in various directions, then pick one direction and turn a hal-circle rom there. Ask them todescribe in degrees the direction they are acing upon each turn. Ask them to tell you howmany degrees they have turned with each new move.

Inorm the students that in this lesson they will investigate the Location class in

GridWorld. ell them that they will complete a worksheet based on the Location classand then design an application or the Location class dierent rom GridWorld.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 24/129© 2010 Te College Board.

24

AP Computer Science Curriculum Module: GridWorld

Lesson Development

Arrange students into pairs and give each pair a compass. Have them ollow a set o directionsto fnd an object hidden in the classroom. Each pair will have a unique set o directions and

object to fnd (toy or edible rock, ower, or bug). Te directions given in terms o objects,constants and methods o the Location class instruct the pairs to ace dierent compassdirections, turn through dierent compass angles and move a specifed number o steps tofnd their hidden object. Tis part o the activity should take 5 to 7 minutes.

When students have ound their hidden objects, discuss the meaning o theinstructions and the constant values rom Location. Give the students a copy o Part3 and the GridWorld estable Application Programming Interace (API) containingthe Location class. Tey will continue working in pairs to understand Location.Ask them to write down any questions they have and submit them to you. Address thequestions one at a time during a class discussion.

Student pairs will then design an application o the Location class other thanthe case study. Te design phase is the ocus in this exercise. Student pairs will presenttheir application designs to the class, speciying the problem being solved and howLocation is used in the design. Te class will question the presenters, who are expectedto deend and justiy their applications.

Te design process does not require actual coding and implementation. Extra creditcould be awarded to pairs that develop a running program within the ollowing 10 days.

Accommodations

Pairs will be ormed in such a way that students who need extra help are paired with studentswho are likely to help them without taking over. Students who are more capable may beselected 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 fnd their hidden object. Discusshow the pairs investigated the Location class. Review the Location class methodsand constants.

Assignment

Students will complete the “Location Reading Worksheet” and turn it in at the beginningo the next class.

Assessment

• Diagnostic assessment occurs through the anticipatory set activity, which allowsthe instructor to assess the students’ prior knowledge o compass locations.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 25/129© 2010 Te College Board.

25

AP Computer Science Curriculum Module: GridWorld

• Formative assessment takes place during the lesson as the instructor observes andquestions the students’ progress in completing the assignment.

• Summative assessment is achieved through the worksheet.

EvaluationFormulate questions you will ask yoursel aer teaching this lesson, such as the ollowing:

• Did the compass activity at the beginning o class activate students’ priorknowledge o compass directions and angles?

• Did the search or the hidden objects cause the students to use and understandLocation class objects, constants and methods?

• Did I perorm my role as acilitator in a way that was helpul but not interering?

• What worked well with this lesson?

• Is there anything I would change when I present this lesson again?

Part 3: Activity/Lesson Plan 5 — GridWorld Part 3

(continued)

A surprising number o undamental concepts can be introduced to students in a highly motivating way through the case study. Tis lesson examines the Grid interace andintroduces preconditions. It is taught using the direct instruction, due to the act that

most o the material is new to the students. In the latter part o the lesson, students work cooperatively to understand method signatures.

Tis lesson could (and perhaps should) be divided into two separate lessons. Tefrst would be direct instruction about interaces and preconditions. Te second would besocial interaction (cooperative learning) in which the students develop skills in readingand interpreting an API, in particular those listed in the GridWorld estable API.

Learning Goals

• Students will understand the purpose and appreciate the design advantages o 

creating Grid as an interace.

• Students will understand the implications o preconditions.

• Students will work together to develop skills or reading an API and analyzingmethod signatures.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 26/129© 2010 Te College Board.

26

AP Computer Science Curriculum Module: GridWorld

Lesson Objectives

• Given the “Grid Reading Worksheet,” the student will complete the worksheet with90 percent accuracy.

• Given the GridWorld estable API, the student will be able to describe what mustbe true when a method is invoked rom examining the precondition with 100percent accuracy.

• Given the GridWorld estable API, the student will work with a small group tolist the methods, preconditions, parameters, parameter types and return typeso the Grid interace and the Location class, describing the dierences betweenmethods whose names are nearly the same with 100 percent accuracy.

Materials

• First Day Role Play • GridWorld Classes and Interaces Grid Reading Worksheet (see Appendix I)

• GridWorld Student Manual estable API (http://www.collegeboard.com/prod_downloads/student/testing/ap/compsci_a/compsci_a_exam_appendix.pd)

Anticipatory Set

Begin the class by recalling one aspect o the First Day Role Play. Have one student be aCalculator and another, a Lazy Calculator with a Helper. (Both o these are classes in the FirstDay 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 dierent ways. Remind the class that thecommand and the parameters were the same in both cases, so you didn’t have to change theway the request was made, and in both cases the result was predictable and consistent.

Now ask the students i they recall the choices they have or a grid when they runany o the bug runner classes. Tey should reply “a bounded grid and an unbounded grid.”Ask them i Bug behavior is predictable and consistent in either grid, and how the twogrids are alike and dierent; then have them list their responses on the board. Tey may run BugRunner or some other runner class with each grid and test out their answers.Inorm the students that the grid in GridWorld is an interace, not a class, and that thebounded grid and the unbounded grid are classes that are said to “implement” the Grid 

interace. Inorm them that in this lesson they will learn about interaces in Java and study the Grid interace as an example o how to design and use an interace.

Lesson Development

Explain that interace types are used to express operations which are common torelated classes. Te interace specifes a set o methods and their signatures but doesnot provide implementation. Each class that implements the interace must includethe common methods and their signatures, but each class most likely implements the

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 27/129© 2010 Te College Board.

27

AP Computer Science Curriculum Module: GridWorld

methods dierently. Continue along these lines, discussing how an interace works andemphasizing the design advantages o creating an interace. ell the students that aninterace is not a class because there is no constructor and there are no instance variables,only method signatures. An interace doesn’t have “state” and the behavior isn’t completely specifed. alk about the ease with which a student can select the bounded or unboundedgrid and how the Grid interace allows this to happen. Te methods in the interace areinvoked the same way or either type o grid, and the result is consistent and predictable.All o this is direct instruction, but you should continually ask questions to check orstudent understanding. Encourage your students to express in their own words the pointsyou have made, and use any misunderstandings you hear as an opportunity to activatetheir higher-level thinking skills and help them synthesize the concepts.

With the students, draw a high-level diagram o the interace and the classes thatimplement it. Show the method signatures but no code. Tis is “we do” component o direct instruction.

Introduce the students to the purpose o a precondition. Tink o a preconditionas a promise made to the method, a guarantee that a given condition will be true whenthe method is invoked. Ask the class how that guarantee can be made. Ask them about theresponsibility o the code that calls the method. Only i the precondition is met does themethod guarantee a correct result.

In terms o the AP Exam (or good programming, or that matter), remind studentsthat when they write code that invokes a method having a precondition, they must makesure their code assures that the precondition is met beore making the method call.

Discuss method signatures in the Grid interace. (Tis is more o the “we do” parto the lesson.) Look only at the signatures, the part they need to know how to use romthe GridWorld estable API.

For the “you do” part o the lesson, have the students complete the Grid worksheet.Move about the room, checking to see how they are doing, oering suggestions oranswering questions as needed.

Form small cooperative-learning groups o three or our students. Te groupswill analyze the Grid interace method signatures and, or each signature, list the name,number o parameters, type and name o each parameter, and return type. For similarsignatures, have the groups write down exactly what each method does and how thereturn values dier. I groups complete their analysis o 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 willhave the support o a more knowledgeable peer. All students will be responsible orunderstanding the interace. Tose who catch on quickly will be expected to help anyonein the group who struggles with the concepts. Monitor groups to be sure this is happening.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 28/129© 2010 Te College Board.

28

AP Computer Science Curriculum Module: GridWorld

Closure

Ask students to summarize what they learned about interaces in today’s lesson. Randomly select a spokesperson rom each cooperative learning group to list the group’s fndingsabout one o the method signatures. Check or agreement between groups. Remind the

students to always be aware o the properties o a method signature, especially whenreading or writing code on the AP Exam.

Assignment

For homework, students will complete a similar analysis o the Comparable interace.Te homework will be collected and graded.

Assessment

• Diagnostic assessment occurs during the anticipatory set when students are askedto recall their observations about the role play and the grid.

• Formative assessment is ongoing during the lesson. Didactic questioning duringthe direct instruction segment, ollowed by teacher observation as the groupsanalyze the Grid interace, provides continuous eedback to the teacher.

• Summative assessment is met through the Grid worksheet, group reports andindividual homework assignments.

Evaluation

Formulate questions that you will ask yoursel aer 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 dierences between an interace and a class thatimplements the interace?

• Were the students able to analyze the Grid interace and understand the methodsignatures? Do they understand the signifcance o the preconditions? Will they beable to use the methods correctly?

• Is there anything I would change about this lesson in the uture?

• What did I do right that I would like to remember and repeat?

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 29/129© 2010 Te College Board.

29

AP Computer Science Curriculum Module: GridWorld

Part 3: Activity/Lesson Plan 6 — GridWorld Part

3 (continued)

In this lesson the students will investigate the Actor class and classes that extend Actor.Tey will discover the important ideas in creating new subclasses and the key idea o overriding the act method. Tis lesson uses the Inormation Processing Model becausestudents will investigate reading material on their own to answer the question o fndingtwo sets o fve important ideas in the reading assignment.

Tis is the frst o a two-part lesson. Tis plan and Activity/Lesson Plan 7 should bepresented on consecutive days. Tey can be combined i the school is on block scheduling.

Learning Goals

• Te students will understand the Actor class and design principles associated

with Actor.• Te students understand inheritance and will learn how to extend a superclass to

create a subclass.

Lesson Objectives

• Given Part 3 o the Student Manual and Student Manual Appendixes B and C, thestudent will be able to investigate inheritance and class design and make two lists,each containing fve important ideas they have ound.

• 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 theworksheet with 90 percent accuracy.

Materials

• GridWorld Part 3: GridWorld Classes and Interaces (page 16)(http://www.collegeboard.com/student/testing/ap/compsci_a/case.html)

• GridWorld Student Manual estable API (http://www.collegeboard.com/prod_downloads/student/testing/ap/compsci_a/compsci_a_exam_appendix.pd)

• GridWorld Student Manual estable Code or APCS A/AB (http://www.collegeboard.com/prod_downloads/student/testing/ap/compsci_a/compsci_a_exam_appendix.pd)

• Actor Reading Worksheet (see Appendix J)

• Extending Actor Reading Worksheet (see Appendix K)

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 30/129© 2010 Te College Board.

30

AP Computer Science Curriculum Module: GridWorld

• Play-Doh in several colors

• Colored pipe cleaners

• Large square grid paper (1-inch or more)

Anticipatory Set

When the students arrive in the classroom, they will fnd small containers o Play-Dohand colored pipe cleaners (see Appendix B) available at a central table. Tey will use theirimagination to create bugs rom the cra materials. Each student will take a sheet o largescale (one inch or larger) graph paper and will design a movement pattern or his or herbug. Remind the students that their bugs must remain within the grid. Students will givetheir bugs a descriptive name that characterizes the bug’s unique movement style, andthey will share their creations with the class. Allow about 7 minutes or this activity.

Inorm 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 o  Actor. ellthe students that they will learn how to create their own subclass and implement thatclass. In this lesson, they will discover some important design principles and then, in asubsequent lesson, they will apply those principles in a group assignment. Students willthen design their own class.

Lesson Development

Start by having the students read the Actor and Extending Actor sections o Part 3o the GridWorld Student Manual; examine the Actor, Rock and Flower API in theGridWorld estable API; and examine the Bug and BoxBug subclasses in the GridWorldestable Code or APCS A/AB. As they read, instruct the students to individually makelists o the important things they learn about the Actor class, about extending Actorand about the classes that extend Actor. Ask them to think about class design and whata subclass inherits rom the superclass. ell them that when they fnish the reading they are to select the fve ideas they think are the most important rom each list and to makenew lists, which will be collected, putting those fve ideas in order rom most to leastimportant. Allow 15 minutes or this work, and then collect the lists.

Have the students return to the reading and complete the Actor and ExtendingActor Reading Worksheets. While they are doing that, compile the student lists into twolists rom the most requent to the least requent responses. You may need to combine

 very similar responses into single statements. Arrange the compiled lists in order o most

to least important, using your educated opinion. (You may need to create the compiledlists aer class. You will be using these lists to introduce the lesson tomorrow.) Check thestudents’ progress with the worksheets and provide help as needed.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 31/129© 2010 Te College Board.

31

AP Computer Science Curriculum Module: GridWorld

Accommodations

For students who need extra help making the lists, you can oer suggestions as youmove about the room monitoring student progress. Students who need help with theworksheets will be encouraged to discuss the questions with you during your open

period or aer school..

Closure

At the end o class, ask the students what they learned about the Actor superclass andthe Rock, Flower, Bug and BoxBug subclasses rom their investigation o the API andcode. Ask them to describe how they investigated the reading and code to fnd the mainideas. Summarize the design principles ound in this part o the case study.

Assignment

Complete the Actor and Extending Actor Reading worksheets or homework. Tese will

be collected and graded.

Assessment

• Diagnostic assessment concerning what students know about the classes will occuras you listen to the students talk about their bug models.

• Formative assessment will be ongoing during the lesson as you observe studentsmaking their lists, ask individual students questions, and respond to theircomments and questions.

• Summative assessment will occur through the lists and worksheets they complete

and hand in.

Evaluation

Formulate questions you will ask yoursel aer teaching this lesson:

• Did making the bug models, creating a movement pattern or them, and namingthe models to represent their pattern ocus the students’ attention on the lessonand activate prior knowledge?

• Did I give adequate instructions or the investigative part o the lesson?

• Did reading or the big ideas and then reading to complete the worksheetsaccomplish my goal o having students learn about design principles?

• Did having the students investigate on their own achieve my goals? Did they fndthe inormation I intended or them to fnd? Did they learn anything about how toinvestigate?

• What would I do dierently i I taught this lesson again?

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 32/129© 2010 Te College Board.

32

AP Computer Science Curriculum Module: GridWorld

• What did I do well and what would I repeat i I taught this lesson again?

Note: Here are a ew possible ideas students might list.

About Actor:

• Use putSelfInGrid to insert an Actor into the grid.

• Use removeSelfFromGrid to remove an Actor rom the grid.

• Te act method defnes an Actor’s behavior.

• An Actor has color, location and direction.

• Te moveTo method allows the actor to move to any valid location.

About extended Actor (Tey probably will fnd many more ideas or this category):

• Bug, Rock and Flower extend Actor.

• Rock overrides act by doing nothing — empty method.

• Flower overrides act by darkening on each step.

• Te canMove method in Bug determines i a Bug can move.

• Te instanceOf method determines whether an object is a member o a class.

Part 3: Activity/Lesson Plan 7 — GridWorld Part 3

(continued)

Tis is a continuation o Activity/Lesson Plan 6 and should be implemented on the day ollowing Plan 6. Students will work in small groups to design and implement the Jumperexercise ound in Part 3 o the Student Manual. Tey will then design their own subclasses,determining which class they should extend, and making design decisions about themethods to override or to create. Tis lesson uses the Social Interaction (CooperativeLearning) Model.

Learning Goals

• Te students will learn how to design and implement a subclass. Tey will learnto use inherited methods and how to override methods rom the super or parent

class.

• Te students will learn to work cooperatively to design and implement a subclass.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 33/129© 2010 Te College Board.

33

AP Computer Science Curriculum Module: GridWorld

Lesson Objectives

• Given the Jumper assignment rom Part 3 o the GridWorld Student Manual, thestudent will work cooperatively in a small group to design and implement theJumper class with 100 percent accuracy.

• Given Part 3 and Appendixes B and C o the GridWorld Student Manual, thestudent will successully design and implement his or her own subclass o  Actor,using an appropriate reimplementation o the act method and ollowing a modelsimilar to BoxBug and Jumper.

Materials

• GridWorld Part 3: GridWorld Classes and Interaces (page 16)(http://www.collegeboard.com/student/testing/ap/compsci_a/case.html)

• GridWorld Student Manual estable API (http://www.collegeboard.com/prod_downloads/student/testing/ap/compsci_a/compsci_a_exam_appendix.pd)

• GridWorld Student Manual estable Code or APCS A/AB (http://www.collegeboard.com/prod_downloads/student/testing/ap/compsci_a/compsci_a_exam_appendix.pd)

• Results o the previous day’s lesson (fve important ideas in two categories) setup as hidden answers to a version o the Family Feud game. Tese can be on anoverhead transparency or covered on the board.

Anticipatory Set

ell the students that they are going to play Family Feud. Inorm them that you have taken their“op Five” important ideas in the two categories, Actor and Extending Actor, rom theirprevious lesson and tabulated the results. Divide the students into two “amilies” and play tworounds based on those lists. Be sure that the teams are balanced in terms o overall academicstrength. Te topics will be: Te Five Most Important Ideas About the ActorClass andTe Five Most Important Ideas About Extending the ActorClass. Each team will choose acaptain. Play the Five Most Important Ideas About the Actor category frst. Follow the gamerules or Family Feud ; i you’re not sure how the game is played, see the Resources section orlinks to rules and an online version, or ask your students.

ell the class that, now that they have reviewed what they ound out about Actor and extending Actor, they are going to work in small groups to learn how to design anddevelop a subclass o  Actor: the Jumper class.

Lesson Development

Separate the class into small groups. ell the students to ollow directions ound in Part3 o the GridWorld Student Manual or the Jumper exercise, deciding within the grouphow to answer the questions, design the class and implement the code. Tey are to

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 34/129© 2010 Te College Board.

34

AP Computer Science Curriculum Module: GridWorld

answer the questions in writing (using a word processor is preerred). Teir answers willbe collected as well as their completed code. Urge them to use the GridWorld estableCode or APCS A/AB and estable API as reerences. While they work, walk around theclassroom monitoring group progress and answering questions as needed. Be sure allstudents are actively involved. Each student should take a turn entering code while theothers make suggestions and check or errors. For the coding part, you may decide tohave the students work in pairs with one student typing and the other navigating (makingsuggestions and watching or errors). I you use this technique, insist that the pairs switchroles at least once during coding. ell the class their grade will be based on both thesuccess o the completed project and their level o participation. Tey will be evaluatingthemselves and the other group members at the end o class. Collect their answers to theJumper 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 cooperateand be sure all members understand every step o the assignment. Te teacher should alsomonitor the groups and provide help as needed.

Closure

Groups with working code will run their applications or the class to see. Ask the groupsto name one thing they learned through this exercise. Each group must contributesomething not already mentioned. Ask them to talk about how the groups answered thequestions, designed their Jumper class and implemented the code. What worked bestin this group situation? Was anything dicult? Did they overcome the diculties? How?

Remind them that programmers usually work in teams in the workplace and that it’sessential that they all cooperate and contribute. Give them a copy o the individual groupmember evaluation orm (see Materials list above) to complete.

Assignment

Each student will design and implement a subclass o his or her own choice. Tey may work on this at home and in class the ollowing day. Students should also write a journalentry, describing what they have learned in Part 3 o the GridWorld case study. (SeeMaterials list above or a description.)

Assessment

• Diagnostic assessment occurs during the anticipatory set as students participate inthe game. Ensure that everyone is involved in deciding on a group response to thegame.

• Formative assessment occurs during the lesson as the teacher moves about theroom observing, listening and questioning the groups.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 35/129© 2010 Te College Board.

35

AP Computer Science Curriculum Module: GridWorld

• Summative assessment is through the answers to the questions turned in by eachgroup, the successul design and implementation o the Jumper class (examiningthe code as well as the run), and through the group evaluation orms.

Evaluation

Formulate questions you will ask yoursel aer teaching this lesson:

• Did the Family Feud game grab the students’ attention, ocus them on the lessonand activate prior knowledge?

• Were my directions to the groups clear? Did they understand how to work togetherto solve the problem?

• During closure did I ask appropriate questions to help the students summarize thelesson? Did I help them understand the importance o working together? Did wediscuss techniques or success in cooperative groups?

• Is there anything I will change i I teach this lesson again?

• Is there anything that went very well and that I will repeat in uture lessons?

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 36/129© 2010 Te College Board.

36

AP Computer Science Curriculum Module: GridWorld

Appendix A

KWL Chart for Introducing GridWorld Activities

We are about to begin a study involving bugs, critters and other objects situated in a worldcomposed o a two-dimensional grid. Tinking about this scenario, list in the le-handcolumn o the chart below what you already know about this topic. In the middle column,list what you want to know about this topic. Te right-hand column is where you will listwhat you have learned upon completing this module. You have three minutes to fll in thefrst two columns beore we share what each o you has written with the class.

KNOW WANT to know LEARNED

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 37/129© 2010 Te College Board.

37

AP Computer Science Curriculum Module: GridWorld

Appendix B

Resources

• GridWorld Student Manual

• GridWorld Installation Guide

• Oriental rading Company (http://www.orientaltrading.com) — an excellentsource o many items at very reasonable prices

 - gummy bugs

 - costume pieces or bug or critter items, antennae, hats, etc.

 - compasses

• Games or the classroom played on a grid(http://math2.eku.edu/Greenwell/MA303/)

• First Day Role Play and GridWorld Role Play (http://www.cs.sbu.edu/dlevine/RolePlay/roleplay.html)

• Sheet protectors (which can be purchased at stores such as Staples and Oce Max)

• Costume pieces (which can be purchased rom costume shops, cra stores and dollarstores, and at online sites, such as Oriental rading Company, or very little money)

• Small, very inexpensive containers o Play-Doh or similar brands (which can beound at “dollar” stores; you can also make your own using recipes ound online)

• Bags o multicolored pipe cleaners (which can be ound at crat stores suchas Michaels)

• Rules or playing Family Feud can be ound at:http://en.wikipedia.org/wiki/Family_Feud#Basics

• An online version o Family Feud is available at:http://www.gameools.com/onlinegames/ree/FamilyFeud2.html

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 38/129© 2010 Te College Board.

38

AP Computer Science Curriculum Module: GridWorld

Lab Grading Rubric

Name ___________________________

Lab # __________________________ Grade ________________________/10

Description ______________________________________________________________

Each item has a value o one point. Hal-points may be given.

Code:

Correct class structureDescriptive identifersWell commentedLogically structured

Well-designed test class

Implementation:

Does the code run?est cases provided?Output matches test cases?Output readable?ext output grammatically correct?

Comments:

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 39/129© 2010 Te College Board.

39

AP Computer Science Curriculum Module: GridWorld

Individual Feedback on Cooperative

Learning Group Work

Name _____________________________Project ________________________________

Group Name _______________________

What I did to help my group’s success today:

 My participation was:

__________ 5 __________4 __________3 __________2 __________1great good OK poor not acceptable

What I will do the same next time we work together:

What I will do dierently:

Te rate of my group members’ participation:

Name

___________________________________ _____5 ____4 ____ 3 ____ 2 ____1

___________________________________ _____5 ____4 ____ 3 ____ 2 ____1

___________________________________ _____5 ____4 ____ 3 ____ 2 ____1

___________________________________ _____5 ____4 ____ 3 ____ 2 ____1

___________________________________ _____5 ____4 ____ 3 ____ 2 ____1(5 = the highest, 1 = the lowest)

My suggestions, ideas on how to improve CL group work, comments on the project:

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 40/129© 2010 Te College Board.

40

AP Computer Science Curriculum Module: GridWorld

Appendix C

GridWorld Case Study Part 1 — Running the DemoObserving and Experimenting in GridWorld

1. Set up GridWorld on your computer.

Running the Demo

2. Read pages 4–6 o the Student Manual.

3. Run the BugRunner.java. I the bug is acing the bounding wall or a rock,

close the GUI and repeat Step 3.4. What two actors appear in the GridWorld GUI?

5. How many cells are in the Grid?

6. Press the Step button.

7. What actor(s) appears in the Grid?

8. Where is the new actor relative to where the bug was?

9. Where did the bug move?

10. How has the rock changed?

11. Press the Step button again.

12. How many actors are in the world?

13. How has the actor in the bug’s original location changed?

14. How has the bug changed?

15. How has the rock changed?

16. How many actors will be in the grid i you press the Step button again?

17. Press the Run button.

18. How is the Run button dierent rom the Step button?

19. What eect does the slider have?

20. Would the grid fll up with owers i the GUI was le running indefnitely? Why?

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 41/129© 2010 Te College Board.

41

AP Computer Science Curriculum Module: GridWorld

21. Restart the BugRunner.java . Press on an empty cell. How many constructors are inthe drop-down menu?

22. How many o the constructors are or Actor?

23. Press the Step button.

24. What new constructors are now in the drop-down menu?

25. What determines the list o constructors in the drop-down menu?

26. Select the constructor ino.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.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 42/129© 2010 Te College Board.

42

AP Computer Science Curriculum Module: GridWorld

GridWorld Case Study Part 1 — Running the Demo

Observing and Experimenting in GridWorld

Reading Worksheet (Solutions)

1. Set up GridWorld on your computer.

Running the Demo

2. Read pages 4–6 o the Student Manual.

3. Run the BugRunner.java . I the bug is acing the bounding wall or a rock,close the GUI and repeat Step 3.

4. What two actors appear in the GridWorld GUI?Bug and Rock

5. How many cells are in the grid? 100 cells

6. Press the Step button.

7. What actor(s) appears in the grid? A Flower 

8. Where is the new actor relative to where the bug was? Te ower is at the Bug’s ormer location.

9. Where did the bug move? Forward one cell

10. How has the rock changed? Te rock has not changed.

11. Press the Step button again.

12. How many actors are in the world? In most cases, our (Bug, Rock and twoFlowers). However, i the Bug is at an edge or acing an adjacent rock, therewould only be three actors aer Step.

13. How has the actor in the bug’s original location changed? Te ower’s color hasdarkened.

14. How has the bug changed? It moved orward one cell i it wasn’t at an edge or

acing an adjacent rock.

15. How has the rock changed? Te rock has not changed.

16. How many actors will be in the grid i you press the Step button again? Five(another ower), unless the bug is at an edge or acing an adjacent rock.

17. Press the Run button.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 43/129© 2010 Te College Board.

43

AP Computer Science Curriculum Module: GridWorld

18. How is the Run button dierent rom the Step button? Te Run button carries outa series o steps.

19. What eect does the slider have? It changes the delay between steps.

20. Would the grid fll up with owers i the GUI was le running indefnitely? Why?No, the owers only appear where the bug moved, and the bug will move in arepeated path.

21. Restart the BugRunner.java . Press on an empty cell. How many constructorsare in the drop-down menu? Five

22. How many o the constructors are or 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 o constructors in the drop-down menu? Te objects thathave been placed in the grid.

26. Select the constructor info.gridworld.actor.Actor(). What imageappears? Teater Mask or comedy 

27. When a constructor requires a parameter, what appears on screen? Dialoguewindow

28. Complete the Do You Know? Set 1.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 44/129© 2010 Te College Board.

44

AP Computer Science Curriculum Module: GridWorld

Appendix D

GridWorld Case Study Part 1 — Exploring ActorObserving and Experimenting in GridWorld

Reading Worksheet

Exploring Actor State and Behavior

1. Read pages 7–8 o the Student Manual.

2. What is in the drop-down menu when you click on a cell containing an Actor?

3. Click on the bug. Explore the methods.

4. How many methods are in the drop-down menu when you click on the cellcontaining the bug?

5. Which our methods are not inherited rom the Actor class?

6. Which methods are accessor methods?

7. What is the prefx o all modifer methods?

8. Which accessor methods do not have a companion modifer method?

9. Explain the dierence between what happens when you invoke the method setDirection(45) and the turn method?

10. Change the direction so that all the actors are acing the le edge o the grid. Whatmethod did you use?

11. Complete the Exercises on page 8.

12. How many  Actors can be in a cell?

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 45/129© 2010 Te College Board.

45

AP Computer Science Curriculum Module: GridWorld

13. ry a negative number as an argument in setDirection.

Degrees Compass Directions

-90

-270

-180

-45

-315

-360

-225

-135

-720

14. How many dierent directions can a bug appear to ace?

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 46/129© 2010 Te College Board.

46

AP Computer Science Curriculum Module: GridWorld

GridWorld Case Study Part 1 — Exploring Actor

Observing and Experimenting in GridWorld

Reading Worksheet (Solutions)

Exploring Actor State and Behavior

1. Read pages 7–8 o the Student Manual.

2. What is in the drop-down menu when you click on a cell containing an Actor?Te methods that you can invoke on this Actor object.

3. Click on the bug. Explore the methods.

4. How many methods are in the drop-down menu when you click on the cellcontaining the bug? 14

5. Which our methods are not inherited rom the Actor class? act, canMove, 

move and turn

6. Which methods are accessor methods? getColor, getDirection, 

getGrid and getLocation . toString are oen considered to be accessormethods because they return inormation about the object and do not change thestate o the object.

7. What is the prefx o the modifer methods? Set

8. Which accessor methods do not have a companion modifer method?getGrid

and getLocation9. Explain the dierence between what happens when you invoke the method

setDirection(45) and the turn method? setDirection(45) isinherited rom Actor and turns the bug northeast. Te turn method rotates thebug 45 degrees right.

10. Change the direction so that all the actors are acing the le edge o the grid. Whatmethod did you use? setDirection(270)

11. Complete the Exercises on page 8.

12. How many  Actors can be in a cell? One

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 47/129© 2010 Te College Board.

47

AP Computer Science Curriculum Module: GridWorld

13. ry a negative number as an argument in setDirection.

Degrees Compass Directions

-90 West

-270 East

-180 South

-45 Northwest

-315 Northeast

-360 North

-225 Southeast

-135 Southwest

-720 North

14. How many dierent directions can a bug ace? Eight

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 48/129© 2010 Te College Board.

48

AP Computer Science Curriculum Module: GridWorld

Appendix E

Journal Descriptions

Submitting the journal electronically has the advantage o the teacher being able to usetrack changes or comments.

Journal 1

Start your journal by describing your experience in class today. Write about threethings you learned in your investigation and one question you have that was notanswered so ar. 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 rom playing the part?What were your responsibilities in that role? With which other roles did your rolecollaborate? How did you eel when you were playing the part? What value did therole play have or you?

Journal 3

Write about what you learned rom the readings, activities and assignments in Part3 o the case study. What was especially interesting or motivating or you, and why?What did you learn about working with others in the class? How has Part 3 increasedyour understanding o the principles o computer science? How will you apply concepts rom Part 3 to classwork outside the case study? Is there anything you wishwould have been covered in more detail? What unanswered questions do you have?Somewhere in your journal begin one sentence with the words “I wonder … ” andanother with the words “I believe … ”

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 49/129© 2010 Te College Board.

49

AP Computer Science Curriculum Module: GridWorld

Rubric for Reective Journal

Name ____________________________________

CRITERIA POINTSSelf-

Evaluation

1. Content of the Entries

• Substantivereactionstothereadingmaterial 4

• Thoughtfulreectionsaboutclassdiscussions

andactivities 3

• Insightfulapplicationsofcoursecontent 3

10

2. Structure of the Journal and Each Entry

• Hasareectivetitle 1

• Theentryreectsthemajorconceptsdiscussed

duringtheperiodofreection 2

• Evaluateswhathasbeenlearnedintrospectively 3

6

3. Originality

• Appealingvisualpresentationofthetextentries 2

• Modeofexpressingthethoughtinwriting 2

4

Total20

Comments:

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 50/129© 2010 Te College Board.

50

AP Computer Science Curriculum Module: GridWorld

Appendix F

GridWorld Case Study Part 2 — Bug ClassBug Variations

Reading Worksheet

Methods of the Bug Class

1. Read page 10 o the Student Manual.

2. What three methods speciy how the bugs move and turn?

3. What methods are invoked in theact method?

4. Why does the bug’s act method invoke the canMove method?

5. When does a bug turn?

6. Draw a grid where a bug can never move. Explain how the bug would act in this grid.

7. What happens to a ower when a bug moves orward onto it?

8. When a bug moves, what does it leave in its previous location?

9. How the bug moves is determined by which method?

Extending the Bug Class

10. Read page 11 o the Student Manual.

11. When creating new types o bugs, which method is most likely to be overridden?

12. What does it mean to have an overridden method?

13. How many new methods need to be added to a new Bug class?

14. What are the new instance variables or the BoxBug class?

15. What are the values o the sideLengths or the two BoxBugs in the picture?

16. Write a turnAround method or BackAndForthBug. turnAround thatmakes a BackAndForthBug ace the opposite direction.

17. Write an act method or BackAndForthBug. When a BackAndForthBug‘spath is blocked, it should turn around. Otherwise it acts like a Bug.

18. Do questions Do You Know? Set 2.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 51/129© 2010 Te College Board.

51

AP Computer Science Curriculum Module: GridWorld

GridWorld Case Study Part 2 — Bug Class

Bug Variations

Reading Worksheet (Solutions)

Methods of the Bug Class

1. Read page 10 o the Student Manual.

2. What three methods speciy how the bugs move and turn?canMove, moveand turn

3. What methods are invoked in theact method? canMove, move and turn

4. Why does the bug’s act method invoke the canMove method? o test i the bugcan move orward into an empty cell or a cell containing a ower

5. When does a bug turn? When canMove returns alse

6. Draw a grid where a bug can never move. Explain how the bug would act in this grid.Possible solution: 1 x 1 grid. A bug would turn every time the act was invoked.

7. What happens to a ower when a bug moves orward onto it? Te ower isremoved rom the grid.

8. When a bug moves, what does it leave in its previous location? A ower

9. How the bug moves is determined by which method? act (move, canMove 

and turn play roles, too!)

Extending the Bug Class

10. Read page 11 o the Student Manual.

11. When creating new types o bugs, which method is most likely to be overridden?act

12. What does it mean to have an overridden method? A subclass’s method has the samename and parameters as the superclass, but gives its own defnition o the method.

13. How many new methods need to be added to a new Bug class? 0 

14. What are the new instance variables or the BoxBug class? sideLength andsteps 

15. What are the values o the sideLengths or the two BoxBugs in the picture? 6and 3

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 52/129© 2010 Te College Board.

52

AP Computer Science Curriculum Module: GridWorld

16. Write a turnAround method or BackAndForthBug. turnAround thatmakes a BackAndForthBug ace the opposite direction.

public void turnAround(){

setDirection(180 + getDirection());}

17. Write an act method or BackAndForthBug. When a BackAndForthBug‘spath is blocked, it should turn around. Otherwise it acts like a Bug.

public void act(){

if (canMove())move();

elseturnAround();

}

18. Do questions Do You Know? Set 2.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 53/129© 2010 Te College Board.

53

AP Computer Science Curriculum Module: GridWorld

Appendix G

GridWorld Case Study Part 2 — Runner ClassBug Variations

Reading Worksheet

Runner Classes

 1. Read page 12 o the Student Manual.

2. What is required to observe the behavior o 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 extendingBug?

8. Explain how the two dierentadd methods work.

9. Do the Exercises at the end o Part 2.

10. Write a runner class or a StudentBug class. Te StudentBug has aconstructor that takes a color. Add a Bug, two StudentBugs and a Rock intothe world, and test your class.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 54/129© 2010 Te College Board.

54

AP Computer Science Curriculum Module: GridWorld

GridWorld Case Study Part 2 — Runner Class

Bug Variations

Reading Worksheet (Solutions)

Runner Classes

1. Read page 12 o the Student Manual.

2. What is required to observe the behavior o one or more actors? A “runner” class

3. What is an ActorWorldobject? Te object that keeps track o everything in the grid

4. What method is used to place an object into the grid? Add 

5. What two ActorWorld methods appear in the BoxBugRunner? Add and show

6. What does it mean to have an overloaded method? Methods have the same namebut dier rom each other in terms o the type, number and/or order o parameters.

7. What must you do to demonstrate your own classes extendingBug?You must write a “runner” class. 

8. Explain how the two dierentadd methods work. Te add method with Actor and Location parameters places an actor at a specifc location. Te add methodwith only an Actor parameter places an actor at a random empty location.

9. Do the Exercises at the end o Part 2.

10. Write a runner class or a StudentBug class. Te StudentBug has aconstructor that takes a color as a parameter. Add a Bug, two StudentBugs anda Rock into the world, and test your class.

public class StudentBugRunner{

public static void main(String[] args){

 ActorWorld world = new ActorWorld();Bug ann = new Bug();StudentBug bob = new StudentBug(Color.BLUE);

StudentBug claire = new StudentBug(Color.YELLOW);Rock darrel = new Rock();world.add(new Location(2, 5), ann);world.add(new Location(3, 5), bob);world.add(new Location(4, 6), claire);world.add(new Location(2, 1), darrel);world.show();

}

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 55/129© 2010 Te College Board.

55

AP Computer Science Curriculum Module: GridWorld

Appendix H

GridWorld Case Study Part 3 — LocationGridWorld Classes and Interfaces

Reading Worksheet

1. Read page 16 o the Student Manual.

2. What does a grid contain?

3. Any instances o a class that extends the Actor class must is-a

4. How many classes implement the Grid interace?5. What does an Actor know?

6. Answer the ollowing is-a questions:

a. Bug is-a ______________________ .

b. Flower is-a __________________ .

c. BoundedGrid is-a ____________ .

d. Actor is-a ___________________ .

7. Answer the ollowing has-a questions:

a. Actor has-a ___________________ .

b. Bug has-a _____________________ .

The Location Class

8. Read pages 16–19 o the Student Manual.

9. Every  Actor that appears in the grid must have a _________________________ .

10. Instances o what class represent locations in the grid? 

11. What does encapsulate mean?

12. Te Location class encapsulates what aspect o the grid?

13. What relationship does Location provide methods or?

14. Cells that run vertically up and down the grid are called what (rows or columns)?

15. What is the smallest row number?

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 56/129© 2010 Te College Board.

56

AP Computer Science Curriculum Module: GridWorld

16. What unit o measure is used to represent compass directions?

17. How many constants based on compass directions are provided in theLocation class?

Question 18 reers to the ollowing line o code rom the Location class.

 public static final int NORTH = 0;

18. What does static final mean?

19. Write an example o how to use theLocation constant EAST in some bug class.

20. Write a segment o code to haveBug bugBoy change its color to blue i it isacing NORTH and to change its color to red i it is not acing north.

21. What is the data type o Location.SOUTHWEST?

22. What is the 0 direction or the Location class?23. What is the 450 direction or theLocation class?

24. What is the value o Location.NORTHWEST?

25. What is the numerical value o Location.EAST + Location.SOUTH?

26. How many constants based on the turn angle are provided in theLocation class?

27. What is the data type o Location.LEFT?

28. What is the constant or a 0 degree turn angle or the Location class?

29. What is the value o Location.HALF_LEFT?

30. What is the value o Location.FULL_CIRCLE + Location.HALF_LEFT?

31. Write a segment o code to get an actor to turn around.

32. What two parameters are required o the Location constructor?

33. Create a reerenceLocation named loc1. Instantiate the Location objectwith a row number o 3 and a column number o 2.

34. How many new accessor methods exist or theLocation class?

35. Write the code to output the row or loc1.

36. Write the code to output the column orloc1.

37. List the Location methods that give inormation about the relationship betweenlocations and directions.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 57/129© 2010 Te College Board.

57

AP Computer Science Curriculum Module: GridWorld

38. What direction is an actor traveling i rows are increasing and columns are decreasing?

39. What is compared in the equals method o Location?

40. What is compared in the compareTo method o Location?

41. Write a segment o code to output the name o 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= newLocation(row2,col2) (Describe every situation.)

43. Do questions Do You Know? Set 3.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 58/129© 2010 Te College Board.

58

AP Computer Science Curriculum Module: GridWorld

GridWorld Case Study Part 3 — Location

GridWorld Classes and Interfaces

Reading Worksheet (Solutions)

1. Read page 16 o the Student Manual.

2. From your reading, what does a grid contain? Instances o the Actor class

3. Any instances o a class that extends the Actor class must is-a. Actor

4. How many classes implement the Grid interace? wo

5. What does an Actor know? Teir Grid, their current location, their directionand their color

6. Answer the ollowing is-a questions:

a. Bug is-a Actor.

b. Flower is-a Actor.

c. BoundedGrid is-a Grid.

d. Actor is-a Object.

7. Answer the ollowing has-a questions:

a.  Actor has-a Location or Grid (or Color or int (direction)).

b. Bug has-a Location or Grid (or Color or int (direction)).

The Location Class

8. Read pages 16–19 o the Student Manual.

9. Every  Actor that appears in the grid must have a Location.

10. Instances o what class represent locations in the grid?Location

11. What does encapsulate mean? Te way to interact with a class is visible, but howit’s implemented is hidden. “Don’t tell me how you do it; just do it.”

12. Te Location class encapsulates what aspect o the grid? Coordinates

13. What relationship does Location provide methods or? Relationship betweenlocations and compass directions

14. Cells that run vertically up and down the grid are called what (rows or columns)?Columns

15. What is the smallest row number? 0

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 59/129© 2010 Te College Board.

59

AP Computer Science Curriculum Module: GridWorld

16. What unit o measure is used to represent compass directions? Degrees 

17. How many constants based on compass directions are provided in theLocation class? Eight

Question 18 reers to the ollowing line o code rom the Location class.

public static final int NORTH = 0;

18. What does static final mean? It denotes a constant, so the value o Northcannot be changed.

19. Write an example o how to use theLocation constant EAST in some Bug class.Location.EAST

20. Write a segment o code to have Bug bugBoy change its color to blue i it isacing north and change its color to red i it is not acing north.

if (bugBoy.getDirection() == Location.NORTH)bugBoy.setColor(Color.BLUE);

elsebugBoy.setColor(Color.RED);

21. What is the data type o Location.SOUTHWEST? int 

22. What is the 0 direction or the Location class? NORTH

23. What is the 450 direction or theLocation class? EAST 

24. What is the value o Location.NORTHWEST? 315

25. What is the numerical value o Location.EAST + Location.SOUTH? 270

26. How many constants based on the turn angle are provided in theLocation class? Seven

27. What is the data type o Location.LEFT? int 

28. What is the constant or a 0 degree turn angle or theLocation class? AHEAD 

29. What is the value o Location.HALF_LEFT? -45

30. What is the value o Location.FULL_CIRCLE + Location.HALF_LEFT? 31531. Write a segment o code to get an actor to turn around.

setDirection(getDirection() + Location.HALF_CIRCLE);

32. What two parameters are required o the Location constructor? row, column

33. Create a reerenceLocation named loc1. Instantiate the Location objectwith a row number o 3 and a column number o 2.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 60/129© 2010 Te College Board.

60

AP Computer Science Curriculum Module: GridWorld

Location loc1 = new Location(3, 2);

34. How many new accessor methods exist or theLocation class? wo

35. Write the code to output the row or loc1. System.out.println(“loc1is at row: “ + loc1.getRow());

36. Write the code to output the column orloc1. System.out.println(“loc1 is at col: “ + loc1.getCol());

37. List the Location methods that give inormation about the relationshipbetween locations and directions. getAdjacentLocation,getDirectionToward

38. What direction is an actor traveling i rows are increasing and columns aredecreasing? Southwest

39. What is compared in the equals method o Location? row, and column

40. What is compared in the compareTo method o Location? row, then column

41. Write a segment o code to output the name o Bug bugBoy or Bug bugGirl,with the lowest Location.

If(bugBoy.getLocation().compareTo(bugGirl.getLocation()) < 0)

System.out.println(“bugBoy comes first”);else

System.out.println(“bugGirl comes first”);

42. When will loc1.compareTo(loc2) return a positive number?

Assume: loc1 = new Location(row1,col1) and loc2= newLocation(row2,col2) (Describe every situation.) I row1 is greater thanrow2 or i row1 equals row2 and col1 is greater than col2

43. Do questions Do You Know? Set 3.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 61/129© 2010 Te College Board.

61

AP Computer Science Curriculum Module: GridWorld

Appendix I

GridWorld Case Study Part 3 — GridGridWorld Classes and Interfaces

Reading Worksheet

The Grid Interfaces

1. Read pages 20–21 o the Student Manual.

2. Te Grid in BugRunner.java contains what type o objects?

3. Why can you not construct aGrid object?

4. Declare a Grid<Actor> reerence named grd.

5. Assign grd a new BoundedGrid o  Actor objects that is 25 x 25.

6. What method checks to see i aLocation is contained in the Grid?

7. Write a segment o code to output i a location (25, 25) is contained ingrd. Whatis the output o executing this code?

8. What must not be passed in as an argument in all case study methods?

9. Write a segment o code to output i a Location loc is contained in grd.

10. List the three methods that add, remove and retrieve objects rom aGrid.

11. Why do all three o these methods return E?

12. Declare Actor act1 to reerence the Actor at Location loc1 in grd.

13. What type is returned by the getOccupiedLocations method?

14. Write a segment o code to output the total number o occupants ingrd.

15. What is returned by grd.getValidAdjacentLocations(new

Location(0,0)) ? 16. What is returned by grd.getValidAdjacentLocations(new

Location(25, 25)) ? 

17. What methods allow the user to determine the size o theGrid?

18. What is returned by these methods or anUnboundedGrid?

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 62/129© 2010 Te College Board.

62

AP Computer Science Curriculum Module: GridWorld

19. Create and initalize numCells to hold the number total number o cells in GridsomeGrid.

20. Do questions Do You Know? Set 4.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 63/129© 2010 Te College Board.

63

AP Computer Science Curriculum Module: GridWorld

GridWorld Case Study Part 3 — Grid

GridWorld Classes and Interfaces

Reading Worksheet (Solutions)

The Grid Interfaces

1. Read pages 20–21 o the Student Manual.

2. Te Grid in BugRunner.java contains what type o objects? Actor

3. Why can you not construct aGrid object? Grid is an interace.

4. Declare a Grid<Actor> reerence named grd. Grid<Actor> grd;

5. Assign grd a new BoundedGrid o  Actor objects that is 25 x 25.

grd = new BoundedGrid<Actor>(25, 25);6. What method checks to see i aLocation is contained in the Grid? isValid

7. Write a segment o code to output i the location (25, 25) is contained ingrd. What is the output o executing this code?

if (grd.isValid(new Location(25, 25)))System.out.println(“(25, 25) is a valid location in grd”);

elseSystem.out.println(“(25, 25) is an invalid location

in grd”);Output:

(25, 25) is an invalid location in grd

8. What must not be passed in as an argument in all case study methods? null

9. Write a segment o code to output i a Location loc is contained in grd.

if (grd.isValid(loc))System.out.println(loc + “ is a valid location in grd”);

elseSystem.out.println(loc + “ is an invalid location in grd”);

10. List the three methods that add, remove and retrieve objects rom aGrid. put,

remove, get

11. Why do all three o these methods returnE? Te Grid interace contains objectso E type.

12. Declare Actor act1 to reerence the Actor at Location loc1 in grd. Actor act1 = grd.get(loc1);

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 64/129© 2010 Te College Board.

64

AP Computer Science Curriculum Module: GridWorld

13. What type is returned by the getOccupiedLocations method? ArrayList<Location> 

14. Write a segment o code to output the total number o occupants ingrd. ArrayList<Location> all = grd.getOccupiedLocations();

System.out.println(“The number of objects in the gridis: “

+ all.size());

15. What is returned by grd.getValidAdjacentLocations(newLocation(0,0)) ?[(0, 1), (1, 0), (1, 1)]

16. What is returned by grd.getValidAdjacentLocations(newLocation(25, 25)) ? [(24, 24)]

17. What methods allow the user to determine the size o the Grid? getNumRows,

getNumCols

18. What is returned by these methods or anUnboundedGrid? –1

19. Create and initalize numCells to hold the number total number o cells in GridsomeGrid.int numCells = someGrid.getNumRows() * someGrid.getNumCols();

20. Do questions Do You Know? Set 4.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 65/129© 2010 Te College Board.

65

AP Computer Science Curriculum Module: GridWorld

Appendix J

GridWorld Case Study Part 3 — ActorGridWorld Classes and Interfaces

Reading Worksheet

The Actor Class

1. Read pages 22–23 o the Student Manual.

2. How many assessor methods exist or the Actor class?

3. Declare a Color variable named clr to store the color o  Actor actr. 

4. Declare an int variable named dir to store the direction o actr.

5. Declare a Grid<Actor> variable named grd to store the grid o actr.

6. Declare a Location variable named loc to store the location o actr.

7. Declare a Location variable named nextLoc to store the adjacent locationdirectly in ront o actr. (You may use the variables rom previous questions inthe ollowing questions.)

8. Declare an ArrayList<Location> variable named emptyNbr to store the

empty neighboring locations o actr.

9. How does an Actor add itsel to the grid?

10. Write a segment o code to add an Actor into all the empty neighbors o actr.

11. Why does the removeSelfFromGrid method have no parameters?

12. Write a segment o code to remove all Actors that are neighbors o actr.

13. Why not just put and remove actors directly rom the grid?

14. Write code to check i grd contains an Actor at Location mysteryLoc. I 

mysteryLoc is empty, add an Actor there.

15. Write code to check i grd contains an Actor at Location otherLoc. I itdoes, remove it rom the grid.

16. What happens when an actor calls themoveTo method using a location already occupied by another actor?

17. Write a statement to have Actor act1 move to the location o  Actor act2.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 66/129© 2010 Te College Board.

66

AP Computer Science Curriculum Module: GridWorld

18. Aer the code or problem 15 is executed, what is the location o the original actorat otherLoc?

19. How many new modifer methods exist or the Actor class?

20. Write a statement to have Actor act1 be the color Color.BLUE.

21. Write a statement to check i  Actor act1 and Actor act2 are dierentcolors. I they are, change act2 to act1’s color.

22. Write a statement to check i  Actor act1 and Actor act2 ace dierentdirections. I they do, have act2 ace the same direction as act1.

23. Write code to check i grd contains an Actor at Location otherLoc. I 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 o a class that extends Actor defned?26. What is the behavior o the Actor class?

27. How can you extend the Actor class and keep the behavior o the Actor class?

28. What classes provide examples o overriding the act method?

29. Do questions Do You Know? Set 5.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 67/129© 2010 Te College Board.

67

AP Computer Science Curriculum Module: GridWorld

GridWorld Case Study Part 3 — Actor

GridWorld Classes and Interfaces

Reading Worksheet (Solutions)

The Actor Class

1. Read pages 22–23 o the Student Manual.

2. How many assessor methods exist or the Actor class? Four

3. Declare a Color variable named clr to store the color o  Actor actr.Color clr = actr.getColor();

4. Declare an int variable named dir to store the direction o actr.int dir = actr.getDirection();

5. Declare a Grid<Actor> variable named grd to store the grid o actr.Grid<Actor> grd = actr.getGrid();

6. Declare a Location variable named loc to store the location o actr.Location loc = actr.getLocation();

7. Declare a Location variable named nextLoc to store the adjacent locationdirectly in ront o actr. (You may use the variables rom previous questions inthe ollowing questions.)Location nextLoc = loc.getAdjacentLocation(dir);

8. Declare an ArrayList<Location> variable named emptyNbr to store theempty neighboring locations o actr.

 ArrayList<Location> emptyNbr =grd.getEmptyAdjacentLocations(loc);

9. How does an Actor add itsel to the grid? putSelfInGrid

10. Write a segment o code to add an Actor into all the empty neighbors o actr.

for (Location emptyLoc : emptyNbr)new Actor().putSelfInGrid(grd, emptyLoc);

11. Why does the removeSelfFromGrid method have no parameters? Te actorknows its location and grid, so it does not need any other inormation.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 68/129© 2010 Te College Board.

68

AP Computer Science Curriculum Module: GridWorld

12. Write a segment o code to remove all Actors that are neighbors o 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 rom the grid? Te put andremove methods do not update the Actor object to reect the change in state o the object. Tis could leave an actor in an inconsistent state with the grid.

14. Write code to check i grd contains an Actor at Location mysteryLoc. I mysteryLoc is empty, add an Actor there.

if (grd.isValid(mysteryLoc) && grd.get(mysteryLoc)==null)new Actor().putSelfInGrid(grd, mysteryLoc);

15. Write a segment o code to check i grd contains an Actor at LocationotherLoc. I it does, remove it rom the grid.

 Actor someActor = grd.get(otherLoc);If (someActor != null)someActor.removeSelfFromGrid();

16. What happens when an actor calls the moveTo method using a location already occupied by another actor? Te other actor removes itsel rom the grid and thecurrent actor takes its location.

17. Write a statement to have Actor act1 move to the location o  Actor act2.

act1.moveTo(act2.getLocation());

18. Aer the code or problem 15 is executed, what is the location o the original actorat otherLoc? null

19. How many new modifer methods exist or the Actor class? wo (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 i  Actor act1 and Actor act2 are dierentcolors. I they are, change act2 to act1’s color.

if (! act1.getColor().equals(act2.getColor()))act2.setColor(act1.getColor());

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 69/129© 2010 Te College Board.

69

AP Computer Science Curriculum Module: GridWorld

22. Write a statement to check i  Actor act1 and Actor act2 ace dierentdirections. I they do, have act2 ace the same direction as act1.

if (act1.getDirection() != act2.getDirection())act2.setDirection(act1.getDirection());

23. Write a segment o code to check i grd contains an Actor at LocationotherLoc. I otherLoc is not empty, remove the Actor there.

 Actor someActor = grd.get(otherLoc);if( someActor != null)someActor.removeSelfFromGrid();

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 o a class that extends Actor defned? By  overriding act 

26. What is the behavior o the Actor class? It reverses the direction o the actor.

27. How can you extend the Actor class and keep the behavior o the Actor class?Do not override the act method.

28. What classes provide examples o overriding theact method? Bug, Flower andRock

29. Do questions Do You Know? Set 5.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 70/129© 2010 Te College Board.

70

AP Computer Science Curriculum Module: GridWorld

Appendix K

GridWorld Case Study Part 3 — Extending ActorGridWorld Classes and Interfaces

Reading Worksheet

Extending the Actor Class

1. Read pages 24–25 o the Student Manual.

2. How many classes are given as subclasses o the Actor class?

3. How are the behaviors o the subclasses specifed to be dierent than Actor?

4. Describe the behavior o the Actor class.

5. Describe the behavior o the Rock class.

6. Describe the behavior o the Flower class.

7. What does a bug do when the location in ront is occupied by a rock? 

8. What does a bug do when the location in ront is occupied by a ower?

9. List the auxiliary methods o the Bug class.

10. Write two Boolean expressions (one resulting in true and one resulting in false)demonstrating the use o the instanceof operator and using the Rock reerencerck (you may not use the word Rock or this solution).

11. Is instanceof Actor always true or any occupant in a Grid<E>?

12. Write a segment o code to remove all theRocks in Grid<Actor> grd.

13. I the adjacent location in ront o Bug bg is a Flower, change the ower’scolor to bg’s color.

14. I the adjacent location to aBug is null, what does that mean about that grid

location? 

15. Why does the canMove method need to check i the neighbor is null frst?

16. Why does the canMove method need to check i a bug is in the grid?

17. What does the turn method or bug do?

18. When is the turn method called by a bug method?

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 71/129© 2010 Te College Board.

71

AP Computer Science Curriculum Module: GridWorld

19. Do questions Do You Know? Set 6.

20. Read What Makes It Run? (page 27)

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 72/129© 2010 Te College Board.

72

AP Computer Science Curriculum Module: GridWorld

GridWorld Case Study Part 3 — Extending Actor

GridWorld Classes and Interfaces

Reading Worksheet (Solutions)

Extending the Actor Class

1. Read pages 24–25 o the Student Manual.

2. How many classes are given as subclasses o the Actor class? Tree

3. How are the behaviors o the subclasses specifed to be dierent than Actor? By overriding the act method

4. Describe the behavior o the Actor class. Flips (turns) back and orth

5. Describe the behavior o the Rock class. Does nothing6. Describe the behavior o the Flower class. Darkens the color o the ower,

without moving

7. What does a bug do when the location in ront is occupied by a rock? urns right45 degrees

8. What does a bug do when the location in ront is occupied by a ower?Te ower removes itsel rom the grid and the bug moves into the location in ront.

9. List the auxiliary methods o the Bug class. canMove, move, turn

10. Write two Boolean expressions (one resulting in true and one resulting in false)demonstrating the use o the instanceof operator and using the Rock reerencerck (you may not use the word Rock or this solution).

rck instanceof Actor (true)rck instanceof Location (false) 

11. Is instanceof Actor always true or any occupant in a Grid<E>? No,because a Grid can contain objects that are not Actors.

12. Write a segment o code to remove all theRocks in Grid<Actor> grd.

 ArrayList<Location> allActorLoc = grd.getOccupiedLocations();

for (Location occupied : allActorLoc){

 Actor temp = grd.get(occupied);if (temp instanceOf Rock)temp.removeSelfFromGrid();

}

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 73/129© 2010 Te College Board.

73

AP Computer Science Curriculum Module: GridWorld

13. I the adjacent location in ront o Bug bg is a Flower, change the ower’scolor 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. I the adjacent location to aBug is null, what does that mean about that gridlocation? It is empty or invalid.

15. Why does the canMove method need to check i the neighbor is null frst?Short circuit evaluation

16. Why does the canMove method need to check i a bug is in the grid? It is possiblethat an actor has been removed rom the grid by another actor.

17. What does the turn method or bug do? urns 45 degrees to the right

18. When is the turn method called by a bug method? When the location in ront isblocked

19. Do questions Do You Know? Set 6.

20. Read What Makes It Run? (page 27)

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 74/129© 2010 Te College Board.

74

AP Computer Science Curriculum Module: GridWorld

Unit Plan: Part 4 — Critters

MikeLew

Introduction

Students are always curious about the application o what they learn in class to the “realworld.” In this project, students will model an ecosystem, a task that has been and is stillundertaken by many biologists and environmental scientists the world over. Tey will usethe GridWorld simulation to model an Amazon rainorest, although any ecosystem can besimulated (desert, tundra, arctic, etc.).

Students will simulate one o three dierent types o symbiotic relationships anda predator-prey relationship. Te “hook” to this project is that students are able to design

their own creatures to place into the ecosystem along with creatures designed by otherstudents. Te resulting interaction is one that students (and I) enjoy seeing and analyzing.For this project, I assume that students are amiliar with the basic operation o GridWorldand have studied inheritance and polymorphism in addition to having a workingknowledge o class structure (data members and methods).

Te project consists o our parts. In the frst part, students will design and writeclass defnitions and implementations or two creatures that are involved in one o threetypes o symbiotic relationships: mutualistic (both creatures beneft rom each other),commensalistic (one creature benefts, the other is unaected) and parasitic (one creatureis harmed or weakened but not directly killed o). At least one o these creatures must

inherit rom Critter or a subclass or Critter. Students may choose which symbioticrelationship to model.

Te second part requires students to design and write class defnitions andimplementations or two creatures that exist in a predator-prey relationship (one creature

“eats” the other creature). Again, at least one o the two creatures must inherit rom

Critter or a subclass o Critter.

Te third part o the project requires students to design and write a class defnitionand implementation or an “environmental eature” with which their creatures can interact(trees, rivers, streams, holes, night/day, iceberg, cactus, etc.). Most o these eatures willinherit rom Actor instead o Critter, and students will defne how their creatures

interact with the environmental eature. Tis part is geared toward students who are ableto implement such things as trees (tunnels or creatures to burrow into), queues (logs orcreatures to walk through) and stacks (places or creatures to store ood). However, thispart can also accommodate students who can use ArrayLists to design simple eaturessuch as nests. Again, any o these environmental eatures will inherit rom Actor ora subclass o  Actor and include one or more o these data structures (tree, set, stack,queue, etc.) in their private data member list.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 75/129© 2010 Te College Board.

75

AP Computer Science Curriculum Module: GridWorld

Finally, in the ourth part, aer all creatures and “environmental eatures” havebeen 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 eatures.” Here students can see that modiying the methods called in the

act method, but not the act method itsel (e.g., by NO removing or renaming themethods called in the act method), is a powerul mechanism to create a related “amily”o creatures who behave or “act” in the same basic manner. In addition, students will alsosee that overriding the act method o an Actor may be desirable and/or necessary thing to do. In any case, all objects can and will be processed polymorphically becausethey all possess an act method.

I have done a similar type o project with the Marine Biology Simulation. My students were very excited to complete a project in which they were involved with thedesign decisions o the “fsh” and the “environmental eatures” o the “ocean.” In additionto being the highlight o the year or my students, the fnal integration o all objectsinto one working program illustrated the value o designing classes that could be used

without modifcation in a large-scale project and the issues that arise when certain designdecisions are made.

Learning Goals

• o understand that there are fve methods which control the “acting” o aCritter (getActors, processActors, getMoveLocations,selectMoveLocation and makeMove).

• o understand that any or all o these fve methods can be overridden to altercreature behavior.

• o write a class defnition that inherits rom Critter and overrides one or moreo the fve methods called in the act method.

• o understand why the act method should not be overridden.

• o understand the importance o clearly stated design specifcations.

• o be able to integrate written class implementations into a larger project.

Instructional Considerations

Tis lesson assumes that the GridWorld simulation has been introduced and that studentsare amiliar with class defnitions, inheritance and polymorphism. I students have notbeen introduced to class design, this project may serve as their frst experience withdesigning a class and writing a class defnition based on their own specifcations. I thisis the case, it may be ruitul or each student to give a 4- to 5-minute oral presentation o 

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 76/129© 2010 Te College Board.

76

AP Computer Science Curriculum Module: GridWorld

their ideas or the specifcations o their class design. Allowing students to verbalize theirthoughts requires them to think through their thought processes (metacognition) and

 justiy their design decisions to themselves. Students may, and probably will, make designchanges based on eedback rom the teacher and/or their peers. Allowing each studentto present their creature designs (and corresponding class names) will allow or otherstudents/groups to know what other creatures and eatures will be in the ecosystem inPart 4.

Teaching Timeline (Each day described below is a

55-minute class period.)

Day 1: Introduce the project. Separate large classes into small groups (morediscussion on this below). Goal or students: (1) defne class names or theircreatures, (2) defne creature behavior, (3) defne new instance variables ortheir creatures, and (4) defne which methods in act will be overridden ortheir creatures.

Day 2: Students present ideas or creatures in Part I — Symbiotic relationships. Shareclass names and creature behavior with other students/groups so that all knowwhat creatures will eventually exist in the “ecosystem.”

Day 3: Lab time — Write complete class defnitions or the creatures presented onDays 1–2 and create images or their new creatures. est class implementationin a test program. During this time, the teacher should move amongindividuals or groups to check on student progress and address any problems.

Day 4: Students present ideas or creatures or Part II — Predator-prey relationships.Share class names and creature behaviors as in Day 2.

Day 5: Lab time — Write complete class defnitions or creatures presented on Day 4,and create images or their new creatures. est class implementation in a testprogram. Te teacher should again move about the class to check on studentprogress.

Day 6: Students present ideas or Part III — Environmental eatures. Share classnames and environmental eature behavior as in Day 2.

Day 7: Lab time — Write complete class defnitions or environmental eaturedescribed on Day 6 and create images or their new eature. est classimplementation in a test program.

Day 8: Integration o some or all o creatures and environmental eatures into oneworking program.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 77/129© 2010 Te College Board.

77

AP Computer Science Curriculum Module: GridWorld

Instructional Delivery Ideas

Tree dierent ways this project can be introduced to address class size, student abilities(dierentiation) and learning styles are provided below.

Class SizeWith class sizes that are relatively small (less than 16 students), this project could beindividually assigned to each student to be completed independently. With class sizessuch as these, individual students are responsible or their own assignments, but I assign

“buddy” partners with whom they can discuss problems they encounter. Most o thesimple (coding) problems are usually resolved by the students helping one another viatheir preassigned partners. In addition, the process o students assisting each other isa valuable learning experience or the “helper,” because he or she gains experience indebugging code other than his or her own. I there is a problem that cannot be solved by the students, I assist in the debugging process. However, when students come to me or

help, I also require them to describe the problem in detail. It is interesting to hear studentssolve their own problem through the process o verbalizing it!

A strategy that could be used with larger class sizes is to break the class into pairs.In my experience, the dynamics o two students works the best. A third student cansometimes be good in the case o debates about design decisions, but I have ound that theprogramming work is too diluted with three or more students. Grouping helps classroommanagement and allows the teacher more time to meet with the students. In a class o 30,it is much easier to meet and discuss issues with 15 pairs than with 30 individual students.

Student Abilities

Each year I have students with very diverse experience and aptitudes. I always have many students who have never programmed beore, and I usually have one or two studentswho have been programming or three or more years. In addition, I also have a spread o aptitudes. Each year, approximately a third o the class catches on very quickly and needs

 very little assistance. Another third o the class needs a key example or two to catch on,and the last third usually needs individualized help to one degree or another.

Tis project can be conducted with these dierent aptitude levels, as well. Aerintroducing the project and talking about the possibilities or dierent creatures, Iwill allow the students to begin to work on the design o their creature. Te studentswith a high aptitude or programming will quickly begin to work and will enjoy the

challenge o designing a class o their own. I one or more o these students fnishesearly, they can then begin work on the next part o the project. Tis prevents boredomand the question, “What do I do next?” Te “middle” group o students will also beginwork and usually do not have problems until they actually get into the coding o theirclasses. When problems arise during the coding phase, I will oer suggestions tohelp guide them through their problems and toward possible solutions. I believe thatgreater understanding (and satisaction) arises when they “fgure it out or themselves”using this guided inquiry-based instructional technique. During this work time or

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 78/129© 2010 Te College Board.

78

AP Computer Science Curriculum Module: GridWorld

the middle group o students, I will give more detailed instruction to the last group o students who need help. I can have a small group discussion addressing their specifcquestions while the others are at work. I needed, I will give ideas or creatures and walk them through the design and coding process. I gauge their understanding to ensure thatI do not give them too much inormation, but instead constantly put them in a positionto think and proceed successully.

I have ound that allowing students to design their own objects, whether they arefsh, aliens or creatures, gives them a sense o ownership o their project. I only assignthe specifcations or what needs to be done and how it will be assessed, but they havethe reedom to design something o their own. I have ound this to be true or all typeso students: Te ownership component o their project goes a long way in terms o theirintrinsic motivation level.

Learning Styles

Troughout the course, my delivery o the material includes auditory, kinesthetic and

 visual components; this project is no dierent. When students present their ideas asoutlined in the “eaching imeline” above, I require them to speak, draw and act out(mini role play) how their creatures will behave. Specifcally, students describe verbally how their creature will behave. Tey are given a 2-minute time limit to clearly andsuccinctly describe their creatures. Tis 2-minute limit orces the students to “get to thepoint” and remove any extraneous detail rom their description. During their verbaldescription, they are required to draw diagrams o their creature in a grid and show howtheir creature will move and/or process other creatures in dierent situations. Diagramshelp the other students (and the teacher!) to understand the behavior o their creature.Finally, as a mini “role play,” the students are required to perorm an enactment o how

their creatures will behave using their peers as “creatures” in the grid. (I have the studentscreate a “grid” by moving their desks into a two-dimensional array arrangement.) In usingthis three-pronged approach to teaching the material, I can anecdotally say that many more students gain a deeper understanding o the material/problem at hand than whenI did not require all three learning modalities. For students who do not master theseconcepts as quickly, I oen fnd that addressing these three areas a second time and at aslower pace helps these students grasp and internalize the material.

Student Assignments

Below are the ormal assignments with design requirements or each o the our parts o the project. Tese may be altered in any way to ft the dynamics o your class.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 79/129© 2010 Te College Board.

79

AP Computer Science Curriculum Module: GridWorld

Description for Teacher: Part I — Symbiotic

Relationships

Each student (or group) writes class defnitions or two “critter-like” creatures. At leastone o the creatures must be derived rom Critter. Tese new creatures will have asymbiotic relationship (students will have to do some research on the animals they wish tomodel). Te emphasis o this part o the project is to reinorce the idea that the actmethodcalls fve other methods (getActors, processActors,getMoveLocations,selectMoveLocation andmakeMove) and that it is these methods that should beoverridden to create new behaviors. Te actmethod itsel should not be overridden andi actneeds to be overridden, then what the student is attempting to create should not bederived rom Critter.

Part I — Symbiotic Relationships

Student Directions

You have been hired to write a program that simulates the symbiotic (mutualistic,commensalistic or parasitic) relationship between two kinds o creatures in anecosystem you choose. A mutualistic relationship is one where both creatures beneftrom each other’s existence; a commensalistic relationship is one where one creaturebenefts rom the relationship, but the other is unaected; and a parasitic relationshipis one where one creature benefts rom the relationship and the other is harmedbut not necessarily killed. You will write the class defnitions or your creatures and

incorporate them into a working program that tests the unctionality o the creatures.

Part I Requirements

1. At least one o the two creatures must inherit rom Critter or a subclass o Critter.

2. Te two creatures must exhibit one o the three types o symbiotic behavior.

3. Te creature(s) that inherits rom Critter must NO override the act method.

4. Te creature(s) that inherits rom Critter should override one or more o the“Big 5” methods called in the actmethod:getActors, processActors,getMoveLocations, selectMoveLocation andmakeMove.

5. All o the overridden “Big 5” methods must satisy that method’s statedpostconditions.

6. Your new creature may add up to two new instance variables and two newmethods.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 80/129© 2010 Te College Board.

80

AP Computer Science Curriculum Module: GridWorld

7. Te two creatures should only interact with and/or kill o one creature outsideo its symbiotic relationship.

8. Te new creatures (Java fles and images) should be integrated into one

working GridWorld program.

Part I Formative Assessments/Grading Rubrics

With a creative design project such as this, I have ound it very useul to have a gradingcriterion (rubric) in place that illustrates how the project will be evaluated. In short, my grading rubric is a one-or-one match with the project requirements. I show the studentsat the beginning o the project what the grading criteria are. Tis helps the studentsunderstand how their work will be evaluated. eachers can determine the point value oreach criterion to ft their grading scales.

Part I Project Criteria

1. Does at least one creature inherit rom Critter or a subclass o Critter?

2. Do the two creatures exhibit some orm o symbiotic behavior?

3. Does the creature(s) that inherits rom Critter NO override the act method?

4. Does the creature(s) that inherits rom Critter override one or more o the“Big 5” methods called in the act method: getActors, processActors,getMoveLocations, selectMoveLocation and makeMove?

5. Do all o the overridden “Big 5” methods satisy that method’s statedpostconditions?

6. Does the creature(s) that inherits rom Critter add at most only two newinstance variables and at most only two new methods?

7. Do the two creatures interact with and/or kill o only one creature outside o its symbiotic relationship?

8. Are the new creatures (Java fles and images) correctly integrated into aworking GridWorld program?

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 81/129© 2010 Te College Board.

81

AP Computer Science Curriculum Module: GridWorld

Description for Teacher: Part II — Predator-Prey

Relationships

Each student (or group) writes a detailed description or two creatures, at least one o whichmust be derived rom the original Critter class. Tese new creatures will have a predator-prey relationship. However, instead o writing the class defnitions and implementationsthemselves, the students (or groups) will exchange the program specifcations with otherstudents/groups and attempt to write the class defnitions or the program specifcations they were given. Tis will require the students to (1) write program descriptions clearly or othersto read and implement, and (2) understand the conceptual ramework or the Critter classand GridWorld as a whole in order to write a coherent program description.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 82/129© 2010 Te College Board.

82

AP Computer Science Curriculum Module: GridWorld

Part II — Predator-Prey Relationships

Student Directions

You have been hired to write a program that simulates the predator-prey relationshipbetween creatures in an ecosystem. You will write the class defnitions or the creaturedescriptions that you were given and incorporate them into a working program that teststhe unctionality o the creatures.

Part II Requirements

1. At least one o the two creatures must inherit romCritter or a subclass o Critter.

2. Te two creatures must exhibit a predator-prey relationship (i.e., one creature must

“eat” the other).

3. Te creature(s) that inherits romCrittermust NO override the actmethod.

4. Te creature(s) that inherits romCritter should override one or more o the“Big 5” methods called in the actmethod: getActors, processActors,getMoveLocations, selectMoveLocation andmakeMove.

5. All o the overridden “Big 5” methods must satisy that method’s statedpostconditions.

6. Each creature that inherits romCritter adds at most only two new instance

 variables and at most two new methods.7. Te two creatures only interact with and/or kill o one creature outside o its

predator-prey relationship.

8. Te new creatures (Java fles and images) are integrated into one workingGridWorld program.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 83/129© 2010 Te College Board.

83

AP Computer Science Curriculum Module: GridWorld

Part II Formative Assessments/Grading Rubrics

1. Does at least one creature inherit rom Critter or a subclass o Critter?

2. Do the two creatures exhibit a predator-prey relationship?3. Does the creature(s) that inherits rom Critter NO override the “act”

method?

4. Does the creature(s) that inherits rom Critter override one or more o the“Big 5” methods?

5. Do all o the overridden “Big 5” methods satisy that method’s statedpostconditions?

6. Does the creature(s) that inherits rom Critter add at most only two newinstance variables and at most two new methods?

7. Do the two creatures interact with and/or kill o only one creature outside o its predator-prey relationship?

8. Are the new creatures (Java fles and images) correctly integrated into aworking GridWorld program?

Description for Teacher: Part III — Environmental

Features

Although outside the scope o creating a creature that inherits rom Critter, the“Environmental Features” component o this project allows or creatures implemented inParts I and II to interact with other objects.

Each student/group will write a class description or an environmental change and/or an environmental eature with which the Critter will interact. Examples includestreams or mountains, logs that creatures walk through (queues), creature hills (stacks),underground creature dwellings (trees), eggs laid in nests ( ArrayLists), nocturnalbehavior, etc.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 84/129© 2010 Te College Board.

84

AP Computer Science Curriculum Module: GridWorld

Part III — Environmental Features

Student Directions

Te company that has hired you wants to add an environmental eature ound in theecosystem to be added to the simulation. Tis eature should interact with at leastone creature in the simulation. You will write the class defnition or the eature andincorporate it into a working program that tests its unctionality.

Part III Requirements

1. Te environmental eature should inherit rom Actor or a subclass o  Actor.

2. At least one o the creatures written in Parts I and II should interact with

the environmental eature. Tis will require modifcation o the creature torecognize the environmental eature.

3. An image or the environmental eature should be created.

4. Te environmental eature should use one or more o the ollowing containers: ArrayList (AP Computer Science A only), stack, queue, tree, set or linked list

(or those students who have studied these more advanced data structures).

Part III Formative Assessments / Grading Rubrics

1. Does the environmental eature inherit rom Actor or a subclass o  Actor?

2. Do one or more o the creatures written in Parts I and II interact with theenvironmental eature?

3. Does the new environmental eature have its own image?

4. Does the environmental eature use one or more o the ollowing containers: ArrayList (AP Computer Science A only), stack, queue, tree, set, or linked

list (or those students who have studied these more advanced data structures)?

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 85/129© 2010 Te College Board.

85

AP Computer Science Curriculum Module: GridWorld

Description for Teacher: Part IV — The Complete

Ecosystem

Te fnal part o the project is to have the entire class incorporate all o the creatures andenvironmental eatures into one working program (ecosystem). I all o the creatureshave kept their respective act methods intact, this should be a relatively short and easy component o the project. I have done this with the Marine Biology Simulation and thestudents were excited to see what happened with their creations!!

Part IV — The Complete Ecosystem

Student Directions

In this fnal part o the project, you will integrate all o the creatures designed by youand your classmates into one working “ecosystem.” You will compile and run theproject to see the interaction o all the objects in this ecosystem. I all goes well, youwill see some very interesting behavior!

Part IV Requirements

You should give copies o your creatures and environmental eature Java fles andimages to each class member and/or group in your class.

Your creatures and environmental eatures (Java fles 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).

Part IV Formative Assessments/Grading Rubrics

Student give copies o their Java fles and images or creature(s) and environmentaleatures to all other class members/groups.

Te creature(s) and environmental eature are directly usable in a standardGridWorld project.

Sample Project

In this sample project, I created a simple ecosystem in the Amazon rainorest with asymbiotic relationship, a predator-prey relationship and an environmental eature. Teproject consists o a Bird, Agouti (a nut-eating rodent), Nut, Seed, Fly, Larvae, VenusFlytrap and ree. An inheritance diagram is shown below.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 86/129© 2010 Te College Board.

86

AP Computer Science Curriculum Module: GridWorld

InheritanceHierarchyofAmazonProject

Symbiotic Relationship

In my model, the agouti rodent and the bird exist in a commensalistic relationship. Herethe agouti eeds on nuts, leaving the seeds behind. Te bird, which would otherwisebe unable to eat the seeds, benefts rom the agouti breaking the nut apart, while theagouti does not beneft rom the bird. Te Agouti and Bird classes both inherit romCritter, while the Nut and Seed classes inherit rom Actor.

Predator-Prey Relationships

Tese types o relationships are easy to think about and implement. Here the predator isthe VenusFlytrap and the y is the prey. Flies can y around as a Critter moves, asmentioned above. However, i a y moves into a location in ront o a VenusFlytrap, itwill be eaten by the VenusFlytrap. Te VenusFlytrap will then turn to the right orle 45 degrees and wait or the next y. I it does not eat within fve steps, then it will turn45 degrees again.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 87/129© 2010 Te College Board.

87

AP Computer Science Curriculum Module: GridWorld

However, to keep the y population alive and well, ies will leave larvae behind aereach move. Te larvae will turn into a y aer a period of 10 iterations of its actmethod.VenusFlytrap andFlyboth 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 or only two creatures. I students become enthusiastic about the projectand ask to create more creatures than are required, I encourage them to proceed as long asthe new creatures meet the requirements o their respective parts.)

Environmental Feature

In this project, a tree serving two purposes was implemented. First, it will drop nuts intoadjacent locations for the agouti to eat. Second, it serves as a resting place for ies. If a y iesinto an adjacent location, the y will “enter” the tree and be stored internally in the tree in an

 ArrayList. When four ies have entered the tree, they will, one by one, y away from the tree.

Te ollowing fgure shows a complete Amazon Ecosystem, with each o the

objects described above.

CompleteAmazonEcosystem

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 88/129© 2010 Te College Board.

88

AP Computer Science Curriculum Module: GridWorld

Te ollowing fgure shows the new data members and methods added to the class derivedrom Critter.

ClassDiagramsforObjectsDerivedfromCritter

Select methods rom 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 leftint behindDir = currentDir + Location. HALF_CIRCLE;

// find the location behind the flyLocation locBehind =

currentLoc.getAdjacentLocation(behindDir);

if (isValidLarvaeLocation(locBehind)){

// place larvae behind flyLarvae newLarvae = new Larvae();newLarvae.putSelfInGrid(getGrid(),locBehind);

}}

} // end method placeLarvae

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 89/129© 2010 Te College Board.

89

AP Computer Science Curriculum Module: GridWorld

Agouti dropSeeds method

public void dropSeeds(){

int currentDir = getDirection();

Location currentLoc = getLocation();// finding the direction to the left and right// of the Aguoutiint dirLeft = currentDir + Location.LEFT;int dirRight = currentDir + Location.RIGHT;

// these are the locations left and right of the birdLocation locLeft =

currentLoc.getAdjacentLocation(dirLeft);Location locRight =

currentLoc.getAdjacentLocation(dirRight);if( isValidSeedLocation(locLeft) ){

Seed s = new Seed();s.putSelfInGrid(getGrid(), locLeft);

}if( isValidSeedLocation(locRight) ){

Seed s = new Seed();s.putSelfInGrid(getGrid(), locRight);

}} // end method dropSeeds

 VenusFlytrap processActors method

public void processActors(ArrayList<Actor> creatures){

int currentDirection = getDirection();Location inFront =

getLocation().getAdjacentLocation(currentDirection);for (Actor thisCreature : creatures){

if (thisCreature.getLocation().equals(inFront)&& thisCreature instanceof Fly)

{thisCreature.removeSelfFromGrid();

changeDirection();timeSinceEaten = 0;}

} // end for

} // end processActors

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 90/129© 2010 Te College Board.

90

AP Computer Science Curriculum Module: GridWorld

Conclusion

Tis sample Amazon project can be used to demonstrate possibilities or each o theour parts o the project. Aer some discussion, students will undoubtedly think o even

more relevant and sophisticated ecosystems to simulate, especially i they have taken orare taking AP Environmental Science. (Note that this project can be urther modifed tomodel systems consisting o “nonliving creatures,” e.g., robots, trac systems, air traccontroller systems, etc.) Allowing students to design their own creatures and integratingthese creations into one project gives them ownership o the project and makes or a great

“Grand Finale,” both or the students and the teacher.

Sample Files or the Amazon Project can be downloaded rom the GridWorld tagat http://www.thecubscientist.com/APCS/indexAPCS.html.

Worksheets on Part 4 o GridWorld, written by Joe Coglianese, are in theappendixes that ollow.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 91/129© 2010 Te College Board.

91

AP Computer Science Curriculum Module: GridWorld

Appendix A

GridWorld Case Study Part 4 — CritterInteracting Objects

Reading Worksheet

The Critter Class

1. Read page 29 o the Student Manual.

2. What do all Critters share?

3. What does a Critter do frst when it acts?

4. What are the next our things a Critter does? 

5. How can dierent types o Critters move dierently than Critter?

6. Which method identifes the behavior o aCritter ?

7. How many methods are invoked by theact method?

8. Which method(s) could be overridden in the subclasses o Critter to producedierent behaviors?

9. Declare an ArrayList<Actor> variable named actorList.

10. Assign actorList to be the actors or Critter someCritter to process.

11. Write code to have someCritter process all the actors in actorList that arenot a Critter. (Leave the contents o actorList unchanged.)

12. Declare an ArrayList<Location> variable named locList.

13. Assign locList to be the locations that someCritter could move into.

14. Write a segment o code to have someCritter move to a randomly selectedlocation rom the locList.

15. Which method should not be overridden in the subclasses o Critter?

16. What was the design intention o the Critter class? 

17. When the Critter class is unsuitable or extending, what class should beextended?

18. Do questions Do You Know? Set 7.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 92/129© 2010 Te College Board.

92

AP Computer Science Curriculum Module: GridWorld

GridWorld Case Study Part 4 — Critter

Interacting Objects

Reading Worksheet (Solutions)

The Critter Class

1. Read page 29 o the Student Manual.

2. What do all Critters share? A common pattern o behavior

3. What does a Critter do frst when it acts? Gets a list o actors to process

4. What are the next our things a Critter does? Processes those actors, and thengenerates a set o possible move locations, selects one o them and moves tothat location

5. How can dierent types o Critters move dierently than Critter? Tey may get possible move locations dierently, and they may select the actual movelocation dierently.

6.  Which method identifes the behavior o a Critter ? act method

7. How many methods are invoked by theact method? Five

8. Which method(s) could be overridden in the subclasses o Critter toproduce dierent behaviors? getActors, processActors,getMoveLocations, selectMoveLocation, makeMove

9. Declare an ArrayList<Actor> variable named actorList. ArrayList<Actor> actorList;

10. Assign actorList to be the actors or Critter someCritter to process.

actorList = someCritter.getActors();

11. Write a segment o code to have someCritter store all the actors inactorList that are not Critters in a dierent ArrayList. (Leave thecontents o actorList unchanged.)

 ArrayList<Actor> nonCritters = new ArrayList<Actor>();

for (Actor actr : actorList)if (!(actr instanceof Critter))nonCritters.add(actr);

12. Declare an ArrayList<Location> variable named locList. ArrayList<Location> locList;

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 93/129© 2010 Te College Board.

93

AP Computer Science Curriculum Module: GridWorld

13. Assign locList to be the locations that someCritter could move into.locList = someCritter.getMoveLocations();

14. Write a segment o code to havesomeCritter move to a randomly selectedlocation rom 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 o Critter? act

16. What was the design intention o theCritter class? Critters are actors thatprocess other actors and then move.

17. When the Critter class is unsuitable or extending, what class should beextended? Actor

18. Do questions Do You Know? Set 7.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 94/129© 2010 Te College Board.

94

AP Computer Science Curriculum Module: GridWorld

Appendix B

GridWorld Case Study Part 4 — Critter BehaviorsInteracting Objects

Reading Worksheet

Default Critter Behavior

1. Read pages 30–31 o the Student Manual.

2. What does a critter do beore moving?

3. What two steps are involved in processing other actors?

4. How does the processActors method in the Critter class know whichactors to process?

5. Why would a subclass o Crittter override the getActors method?

6. Write code to have a Critter variable named someCritter process all theactors in the grid.

7. What does the processActors method in the Critter remove?

8. What operator allows a Critter to tell i it is going to process another

Critter?

9. I a critter did not eat Actors, what would it eat?

10. What is the three-step process or a critter to move to a new location?

11. Why are there three dierent methods implementing this single process?

12. What is returned by the getMoveLocations method or Critter?

13. I a critter were at (4, 3) acing East, what could be in the list returned by getMoveLocations?

14. How does a critter select which location to move to?

15. What does getMoveLocations return i a critter is unable to move?

16. What gets passed to the makeMove method by a critter?

17. What i null is passed in as an argument or the makeMove method?

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 95/129© 2010 Te College Board.

95

AP Computer Science Curriculum Module: GridWorld

GridWorld Case Study Part 4 — Critter Behaviors

Interacting Objects

Reading Worksheet (Solutions)

Default Critter Behavior

1. Read pages 30–31 o the Student Manual.

2. What does a critter do beore moving? Process other actors in some way 

3. What two steps are involved in processing other actors?

a. Select which actors to process

b. Process each selected actor

4. How does the processActors method in the Critter class know whichactors to process? An ArrayList<Actor> containing all neighboring actorsis passed in as an argument.

5. Why would a subclass o Critter override the getActors method? o choosea dierent set o actors that it will process

6. Write a segment o code to have aCritter variable named someCritter process all the actors in the grid.

Grid<Actor> grd = someCritter.getGrid(); ArrayList<Location> allOccpLoc = grd.getOccupiedLocations();

 ArrayList<Actor> allActors = new ArrayList<Actor>();for (Locations loc : allOccpLoc)allActors.add(grd.get(loc));

someCritter.processActors(allActors);

7. What does the processActors method in the Critter remove? All actorsthat are not rocks or critters

8. What operator allows a Critter to tell i it is going to process anotherCritter? instanceof

9. I a critter did not eat Actors, what would it eat? Nothing

10. What is the three-step process or a critter to move to a new location?

a. Determine which locations are candidates or the move.

b. Select one candidate

c. Make the move

11. Why are there three dierent methods implementing this single process? Allowssubclasses to change each behavior separately 

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 96/129© 2010 Te College Board.

96

AP Computer Science Curriculum Module: GridWorld

12. What is returned by the getMoveLocations method or Critter? All theempty adjacent locations

13. I a critter were at (4, 3) acing 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 i a Critter is unable to move? Itscurrent location

16. What gets passed to the makeMove method by a critter? Te selected location

17. What i null is passed in as an argument or the makeMove method? Te critterremoves itsel rom the grid!

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 97/129© 2010 Te College Board.

97

AP Computer Science Curriculum Module: GridWorld

Appendix C

GridWorld Case Study Part 4 — ChameleonCritterInteracting Objects

Reading Worksheet

Extending the Critter Class 

ChameleonCritter

1. Read pages 32–33 o the Student Manual.

2. Which actors does Critter class send its list o actors or processing?

3. Which actors does ChameleonCritter class send its list o actors orprocessing?

4. What are the neighbors o the ChameleonCritter at (6, 3)?

5. How does Critter process actors?

6. How does ChameleonCritter process actors?

7. Which method(s) does the ChameleonCritter override?

8. What are the neighbors o the ChameleonCritter at (6, 3)?

9. I the ChameleonCritter at (4, 4) move to (3, 4), what direction would itbe acing?

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 98/129© 2010 Te College Board.

98

AP Computer Science Curriculum Module: GridWorld

GridWorld Case Study Part 4 — ChameleonCritter

Interacting Objects

Reading Worksheet (Solutions)

Extending the Critter Class

ChameleonCritter

1. Read pages 32–33 o the Student Manual.

2. Which actors does Critter class send its list o actors or processing? All theneighboring actors (touching the critter)

3. Which actors does ChameleonCritter class send its list o actors orprocessing? Te same as Critter, all the neighboring actors

4. What are the neighbors o 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 andchanges its own color to the color o the selected actor

7. Which method(s) does the ChameleonCritter override? makeMove,

processActors

8. What are the neighbors o the ChameleonCritter at (6, 3)? (5, 2), (5, 3), (5, 4),(6, 2), (6, 5), (7, 2), (7, 3) and (7, 5)

9. I the ChameleonCritter at (4, 4) move to (3, 4), what direction would it beacing? Location.NORTH

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 99/129© 2010 Te College Board.

99

AP Computer Science Curriculum Module: GridWorld

Appendix D

GridWorld Case Study Part 4 — CrabCritterInteracting Objects

Reading Worksheet

Another Critter

CrabCritter

1. Read page 34 o the Student Manual.

2. Which actors does CrabCritter class send its list o actors or processing?

3. Actors at which locations would be sent or processing by aCrabCritter at (6,3) acing Location.EAST?

4. How does CrabCritter process actors?

5. Where is CrabCritter process actors defned?

6. I a CrabCritter were at (4, 3) acing Location.EAST, what locationswould be returned by getMoveLocations?

7. What methods did the CrabCritter override? 8. From what location would aCrabCritter at (3, 4) acingLocation.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 i 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. eSkinnyCrabCritter  moves like CrabCritter  , but if it has not eaten it dies.

12. Explain why SkinnyCrabCritter dying in processActors would violatethe method’s postconditions. 

13. In what method could SkinnyCrabCritter die?

14. Propose a way to haveSkinnyCrabCritter die based on not eating in any given turn.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 100/129© 2010 Te College Board.

100

AP Computer Science Curriculum Module: GridWorld

15. Write the processActors method or SkinnyCrabCritter.

16. Complete the Do You Know? Set 9.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 101/129© 2010 Te College Board.

101

AP Computer Science Curriculum Module: GridWorld

GridWorld Case Study Part 4 — CrabCritter

Interacting Objects

Reading Worksheet (Solutions)

Another Critter

CrabCritter

1. Read page 34 o the Student Manual.

2. Which actors does CrabCritter class send its list o actors or processing?Actors rom the three cells in ront o CrabCritter

3. Actors at which locations would be sent or processing by aCrabCritter at (6,

3) acing Location.EAST? (5, 4), (6, 4) and (7, 4)4. How does CrabCritter process actors? Removes all actors rom the three cells

in ront that are not rocks or critters

5. Where is CrabCritter process actors defned? Critter

6. I a CrabCritter were at (4, 3) acing Location.EAST, what locationswould 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) acing Location.NORTH eat? (2, 3), (2, 4), (2, 5)

9. What will a CrabCritter not eat? Why? Rock or Critter because it wasinherited rom Critter

10. How does a crab select the location to move to? Randomly 

11. What does a crab do i it can not move? urns 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. eSkinnyCrabCritter  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 o the critter isunchanged.

13. In what method could SkinnyCrabCritter die? makeMove

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 102/129© 2010 Te College Board.

102

AP Computer Science Curriculum Module: GridWorld

14. Propose a way to haveSkinnyCrabCritter die based on not eating in any given turn. Add a Boolean instance variable to store i it has eaten. Ten check the value o the variable in the makeMove method and remove itsel rom thegrid i it has not eaten.

15. Write the processActors method or 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();}

16. Complete the Do You Know? Set 9.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 103/129© 2010 Te College Board.

103

AP Computer Science Curriculum Module: GridWorld

Unit Plan: Part 5 — Grid

LeighAnnSudol

Introduction

Tis project is designed to help students learn about extending the AbstractGrid classas a part o the GridWorld case study (http://www.thecubscientist.com/APCS/indexAPCS.html). Included in this project are a number o supporting materials to help studentsbecome profcient at using the Grid class and also to become amiliar with questionsregarding dierent implementations o a grid. Te program assignment, AirplaneScheduling, asks the students to extend the AbstractGrid class and then use the classin a context to answer questions about seating priority in an airplane. In addition to the

program assignment, you will also fnd multiple-choice questions and a short-answerassessment question involving Big-Oh or dierent implementations o a grid.

Student Programming Assignment: Airplane

Scheduling

Airlines ace interesting problems every day. One common problem is to determine the bestway to seat passengers to ensure that it takes the least possible time or them to board theairplane. Since there is only one door to the airplane, only one passenger can enter the plane

at a time. Te passenger then walks to the row that contains his or her assigned seat, stores hisor her carry-on luggage, and then moves into his or her seat.

Te question becomes whether it is better to board the passengers who haveassigned seats in the rear o the plane frst, board them in random order or board themin some combination o the two. Tis question is a perect use or a computer simulation,because we can adjust variables and run a large number o tests without inconveniencingthe consumers.

In order to create the simulation you will need to write the ollowing classes:

 AirplaneTester: Tis class will contain a main method or testing your simulation.

 AirplaneWorld: Tis class will extend the ActorWorld class and handle theorder in which the passengers board the plane.

Passenger: Tis class will extend the Actor class and handle inormationthat passengers need, such as what seat they will sit in during theight.

 Airplane: Tis class will extend AbstractWorld and will be used torepresent the seats in the airplane.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 104/129© 2010 Te College Board.

104

AP Computer Science Curriculum Module: GridWorld

Passenger

Te Passenger class should extend the Actor class and also provide unctionality tostore the location o the passenger’s assigned seat on the airplane (separate rom her or hiscurrent location). It should also provide unctionality or a counter to be used to “pause”

passengers as they are putting away their luggage upon reaching their rows, beore leavingthe aisle to sit in their assigned seats.

Te Passenger constructor should take two parameters: a row and seat(column) value or the assigned seat o that passenger. It should assign values to theprivate variables, including a wait time o 10 time steps or stowing luggage.

Te Passenger class should also have an implementation or an act method.Te Passenger act method should deal with the ollowing cases:

1. I the passenger is already in his or her seat, he or she should not do anything.

2. I 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. I the passenger is in the row where his or her seat is located and their luggagecounter is greater than 0, he or she should continue storing their luggage (subtractone rom the luggage counter).

4. I the passenger is not yet to his or her row and the aisle is not blocked in ront o them, he or she should move one row closer to their assigned row.

Passenger class starter code

import info.gridworld.actor.Actor;

import info.gridworld.grid.Location;

public class Passenger extends Actor {//declare instance variables herepublic Passenger(int row, int seat){

}

public void act(){

}

}

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 105/129© 2010 Te College Board.

105

AP Computer Science Curriculum Module: GridWorld

Airplane

Te Airplane class should extend the AbstractGrid class and provide data storageor the grid. Te Airplane, in addition to maintaining the ability to store rows andcolumns o passengers, should also maintain a variable or the aisle row within the

airplane. Te aisle is a column without seats and will be the means by which passengersmake their way to their seats.

Te Airplane class needs a constructor that will take the number o rows, thenumber o seats across and the location o the aisle.

Other methods the Airplane class needs to implement will be:

1. get(Location loc), which will retrieve a passenger stored at a particularrow/seat location

2. getNumCols(), which will return the number o seats across, plus one or the aisle

3. getNumRows(), which will return the number o rows o seats in the airplane

4. getOccupiedLocations(), which will return an ArrayList ofLocations or all o the seats that currently have passengers sitting in them, aswell as all o the locations in the aisle where passengers are either loading baggageor waiting to continue on to their seats

5. isValid(Location loc), which will return true i the given location is a valid seat or aisle location on the plane and alse otherwise

6. remove(Location loc), which will remove the passenger rom the grid (plane)

7. isAisleEmpty(), which will return a Boolean value i the aisle o the airplaneis empty (either the plane is completely empty or all passengers are seated)

8. getCenterAisle(), which will return the column number o the central aisle

9. put(Location loc, Passenger obj), which will insert the passengerinto the grid (Airplane) at the given location

10. put(Location loc, Object obj), which is used only to satisy theabstract class inheritance requirements

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 106/129© 2010 Te College Board.

106

AP Computer Science Curriculum Module: GridWorld

Airplane class starter code

import java.util.ArrayList;import info.gridworld.actor.Actor;import info.gridworld.grid.Grid;

import info.gridworld.grid.AbstractGrid;import info.gridworld.grid.Location;

public class Airplane extends AbstractGrid{//declare instance variables here/*** Constructor for an Airplane* Creates a simulated airplane with seatsAcross-1 seats (leaving* an empty aisle in the middle for passengers to walk down)* @param numR the number of rows of seats in the airplane* @param seatsAcross the number of seats across plus the aisle

* @param centerRow the location of the aisle in the airplane*/public Airplane(int numR, int seatsAcross, int centerRow){

}

/*** returns the passenger at the given location, null if there is* no one there*/public Passenger get(Location loc) {

}

/*** returns the number of columns in the grid - this is the* number of seats in any given row plus the aisle*/public int getNumCols() {

}

/**

* returns the number of rows in the grid/Airplane*/public int getNumRows() {

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 107/129© 2010 Te College Board.

107

AP Computer Science Curriculum Module: GridWorld

}

/*** 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) {

}

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 108/129© 2010 Te College Board.

108

AP Computer Science Curriculum Module: GridWorld

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

Te AirplaneWorld class should extend the ActorWorld class. Te AirplaneWorld class does not need any new data stored other than what

 ActorWorld provides or.Te AirplaneWorld constructor should take an Airplane parameter and

call the ActorWorld constructor with that parameter.

Te Airplane world has one additional method, runSim(), that is used to runthe airplane simulation and watch how passengers seat themselves.

In a purely random seating arrangement, the runSim method will create a new

 ArrayList o Passengers, with each passenger having a targeted seat location withinthe aircra. Te easiest way to accomplish this is to write some loops to create a passengeror every seat; be careul not to seat anyone in the aisle.

Until the ArrayList is empty, i the “door” to the airplane is empty (location 0,

aisle), randomly remove one passenger rom the ArrayList and add him or her to theairplane. Don’t orget to step and show the grid as you go. Also, make sure that all o yourpassengers get seated beore you fnish the simulation (i.e., make sure the aisle is empty).

AirplaneWorld class starter code

import info.gridworld.actor.ActorWorld;import info.gridworld.grid.Location;import java.util.ArrayList;

public class AirplaneWorld extends ActorWorld {

public AirplaneWorld(Airplane grid) {

}

public void runSim(){

}

}

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 109/129© 2010 Te College Board.

109

AP Computer Science Curriculum Module: GridWorld

AirplaneTester class starter code

import info.gridworld.actor.ActorWorld;import info.gridworld.grid.Location;

public class AirplaneTester {public static void main(String args[]){

 Airplane toLoad = new Airplane(30, 7, 3); AirplaneWorld simulation = new AirplaneWorld(toLoad);simulation.runSim();

}

}

Notes to the Instructor for the Airplane

Scheduler Assignment

Use and ordering of activities

It is assumed that students have already covered a number o data structures and Parts 1–4o the GridWorld case study. I students have not addressed a number o data structures,the materials should be edited to cover only the data structures that have been coveredin class. Tese materials can be revisited once the additional data structures have beenstudied. Te suggested ordering and use o these materials within an AP ComputerScience class are listed below.

1. Introduce the Grid classes.

• Introduction to the Grid Classes (PowerPoint presentation) is available athttp://www.virtualcompsci.net/gridworld/Gridworld.ppt.

• Students should also read Part 5 o the case study narrative (http://apcentral.collegeboard.com/apc/members/repository/ap07_gridworld_casestudy_5.pd).

2. Use the Airplane Scheduling program assignment with students.

• Have students read the description o the assignment and complete thepreassignment questions (see Appendix A). Te discussion points can be usedto help students construct answers to the preassignment questions that will givethem insight into the program assignment.

• Students should then complete the program assignment. Links to thestarter code are available at http://www.virtualcompsci.net/gridworld/AirplaneStarterCode/Airplane.java, http://www.virtualcompsci.net/gridworld/AirplaneStarterCode/Airplaneester.java, http://www.virtualcompsci.net/gridworld/AirplaneStarterCode/AirplaneWorld.java, which includes the starter

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 110/129© 2010 Te College Board.

110

AP Computer Science Curriculum Module: GridWorld

fles Airplane.java, AirplaneTester.java, AirplaneWorld.java and Passenger.java.

• Students complete the post-assignment questions (see Appendix A).

3. Use the multiple-choice questions (see Appendix B) as assessments (as a part o aquiz or test) or as homework.

4. Use the short-answer assessment questions (see Appendix C) as a part o a ormalassessment or as homework or the students.

General Description

Tis assignment was designed to not only amiliarize students with writing code in orderto implement a special type o Grid (an Airplane), but to also use that grid in contextand to draw conclusions based upon what is observed in the simulation.

Te Airplane class itsel can be implemented by a wide variety o data

structures. Te solution is shown with a 2D matrix; however, since this is theimplementation provided to students in the narrative (along with a HashMap), youcan choose to either speciy another data structure or the students or require them toselect their own data structure and reect upon their choice. Questions or discussionare provided in the appendixes that ollow. Tese questions can either be used or groupdiscussion; or individual reection by each student; or, in the case where students selecttheir own data structure, as prompts or a class presentation o the data structure thatthey used and an explanation o why they chose that structure. Te Airplane classwas chosen to extend AbstractGrid to allow you the reedom to implement any datastructure you choose with your students and this assignment.

Also included in this module is starter code or the our classes o the assignment.It is le to the discretion o the instructor whether he or she chooses to provide the startercode to the students.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 111/129© 2010 Te College Board.

111

AP Computer Science Curriculum Module: GridWorld

Appendix A

Discussion Questions

Preassignment Questions

Tese questions can be used beore the assignment (aer the description is read, butbeore any code is written), or a discussion part way through the assignment as a way tocheck or understanding, or aer the assignment in a summary. Following the questions,you will fnd 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 thecharacteristics o each Location within an airplane as modeled by a Grid?

2. What inormation does an Airplane need to know that is separate rom aBoundedGrid? (For example, what is the dierence between the inormationyou need to store or an Airplane and the inormation you store or a genericBoundedGrid?)

3. Without extending any Grid class or interace, what would the challenges be orimplementation o the simulation?

4. Consider an Airplane implementation where the data structure usedspecifcally stores Passenger objects. For this particular program, why is iteasible to store the objects in the grid in this manner, instead o using a datastructure that can store any type o object the way that BoundedGrid does?

5. What are some possible data structures that could be used or the Airplane?What criteria would you use to choose one o these data structures? Whatinormation would you like to know about the ights in order to choose the mostappropriate data structure?

6. Knowing that the planes are restricted to a relatively small size, but that the airlinewants to run the simulation a very large number o times repeatedly in order togather results, how does that aect your considerations?

Possible Discussion Points1. Both an Airplane seat and a Grid cell can be occupied by only one actor/

person at a time. You can divide an airplane into the places where people are ableto stand and sit, just like you can divide a grid into locations. Each location in theairplane can be defned by a row number and a seat assignment (or classifed as anaisle — a passenger standing between seats).

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 112/129© 2010 Te College Board.

112

AP Computer Science Curriculum Module: GridWorld

2. An airplane needs to know the location o the aisle and any inormationalmethods that would be helpul in looking at seated pasengers versus standingpassengers.

3. Without extending a Grid class, the airplane could not know where the aisle was;

this inormation would have to be kept elsewhere, and it would make the code inother places more dicult to write and less abstracted.

4. For this simulation, we are programming it specifcally to hold passengers. Withthe problem description given and the requirements o the client, it is not likely that other types o 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 ullthe ights are would be helpul in selecting the most appropriate data structure.

6. Tis indicates that speed is a more important concern than space. It would be

acceptable to choose a data structure that required more memory in avor o aaster implementation (i.e., a two-dimensional array would be preerable to alinked list or even a sparse matrix).

Post-Assignment Questions

Tese questions can either be used or class discussion or as a part o an assessment.

1. For each o the ollowing methods, speciy the Big-Oh time or yourimplementation:getCenterAisleaisleEmptygetOccupiedLocationsgetput

2. Name a data structure, other than the one you used, that improves the timeeciency o at least one o the above listed methods (even i the other methodsget slower). List the Big-Oh time or each o the above methods or the other datastructure that you chose. Deend your choice over this other data structure.

3. How would you change the program i we allowed or very large aircra that hadtwo aisles (three seats to one side, an aisle, our seats in the middle, a second aisle

and three seats to the other side)?

4. How would you change the program i there were two doors to enter the airplane?

5. Based on your observations o seating time, what would you recommend to theairline as a method o boarding passengers?

6. We only dealt with passengers as they entered the airplane. What otherpossibilities in an airport exist or the study o data structures?

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 113/129© 2010 Te College Board.

113

AP Computer Science Curriculum Module: GridWorld

Appendix B

Multiple-Choice Questions for AssessmentGridWorld Module 5

Multiple-Choice Questions

Use the following information to answer questions 1–4.

Consider the ollowing two implementation o a Grid that stores Actors in an array.You may assume that the average time or adding new items to the grid does not takeresizing into account.

Implementation I: Te array is maintained in sorted order by inserting each newactor into the array in order by location whenever an Actor is put into the Grid. Te

Grid is also set up to maintain the list in sorted order with no gaps (null elementsbetween data) throughout the program. In order to fnd an Actor within the Grid, aprivate getIndex method is implemented that uses a binary search in order to locateeither the index o the Actor itsel or the index where the actor should be inserted.

Implementation II: Te array is maintained in the order in which Actors wereadded to the environment. A linear search is perormed in order to get the index o an

 Actor within the array any time it needs to be located.

1. What is the expected time or the Gridmethod 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 or the Gridmethodgetunder Implementation II above?

a. O(1)

b. O(log n)

c. O(n)

d. O(n log n)

e. O(n2)

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 114/129© 2010 Te College Board.

114

AP Computer Science Curriculum Module: GridWorld

3. Which o the ollowing data structures would yield a comparable time or the get method as Implementation I above?

a. LinkedList

b. HashMap

c. TreeMapd. HashSet

e. None o the above

4. Which o the ollowing methods would not need to be changed rom their currentimplementation in BoundedGrid in order to implement a Grid as defnedabove (either Implementation I or II)?

a. put

b. isValid

c. remove

d. getNeighborse. All methods would need to be reimplemented

Use the following information to answer questions 5–7.

A group o scientists want to study how dierent plants attract dierent types o insects.For this, they are going to write a computer simulation containing complex insectbehavior programmed into actors. When creating the simulation, they decided it wouldbe easier to divide the garden into sections based on the plants being grown and thenrecord all the dierent types o insects in each section to see what plants are avored. Teircurrent implementation o the Grid allows or only one Actor per location; however,they would like to change the implementation o the Grid to allow the actors to move

reely throughout the grid, regardless o the number o actors already at that location.Consider the ollowing two implementations or the GardenGrid.

Implementation I: Te GardenGrid implementation contains a HashMap keyed by location. Each value stored in the HashMap is a HashSet o IDActorsrepresenting the collection o actors in any one grid in the garden. Te IDActor class isan extension o  Actor that contains a unique ID number or each actor that is used asthe key or the HashMap.

Implementation II: Te GardenGrid implementation contains a HashMap o 

IDActors. Te unique ID number or each actor is used as the key or the HashMap.

5. With Implementation I above, i there are N locations inside the grid and S insectsin the simulation, what is the worst case time or retrieving inormation about asingle insect i we have its location and ID number?

a. O(1)

b. O(N)

c. O(S*N)

d. O(S)

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 115/129© 2010 Te College Board.

115

AP Computer Science Curriculum Module: GridWorld

e. O((log S)*N)

6. With Implementation II above, i there are N locations inside the grid and Sinsects in the simulation, what is the worst case time or retrieving inormationabout a single insect i 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. Te scientists in the study anticipate having a very large number o actors spreadrelatively evenly over the dierent grids. Tey anticipate concentrations inparticular areas; however, they do not anticipate all o the insects being in only onelocation on the grid. With this in mind, which o the above implementations will

be more ecient i the scientists plan on ocusing on one location in the grid at atime? Tis means that, during the simulation, at each time step they would retrieveall the actors stored at a given location in order to process such inormation asnumber o insects and variety o 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 inormation about thebehavior o the insects.

e. It is impossible to know the inormation without more inormation about the

plants.

8. When creating an implementation o the Grid interace, which o the ollowingmethods would most likely be aected by a change in data structure?

a. remove

b. getValidAdjacentNeighbors

c. getNeighbors

d. a and c only 

e. a, b, and c

Answers to Multiple-Choice Questions

1. b 2. c

3. c 4. b

5. d 6. a

7. a 8. d

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 116/129© 2010 Te College Board.

116

AP Computer Science Curriculum Module: GridWorld

Appendix C

Short-Answer Assessment QuestionsInvolving Big-Oh

GridWorld Case Study

Module 5

Consider a GridWorld environment used to study migration patterns o bugs. hemigration o bugs is done in a very large bounded grid (think o a locust cloud 20meters wide that is represented in a grid large enough to be comparable to the stateo exas). In addition to migrating based on their own internal control, the bugs

are also migrating based upon wind patterns. he BoundedGrid is modiied toinclude a method applyWind. he applyWind method takes a Direction (N,S, E or W) and also a start and end index or the wind. In this simpliied model, thewind “pushes” each object within the start and end indices one space in the directionthe wind is blowing. he indices are used opposite to the direction, so i the wind isblowing either north or south then the index is a row value; i the wind is blowingeast or west, then the index is a column value.

Consider the ollowing images o worlds aer the call to applyWind:

Starting Locations Aer applyWind(Direction.NORH, 2,3)

 

Starting Locations Aer applyWind(Direction.EAS, 1, 1)

 

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 117/129© 2010 Te College Board.

117

AP Computer Science Curriculum Module: GridWorld

Fill in the ollowing table with Big-Oh notation, representing the time it wouldtake or the applyWind method or each o the ollowing implementations o the

GridWorld environment. Use r or the number o rows in the grid, c or the number o columns in the grid and n or the width o the range to be blown. I another variable isneeded or the analysis, be sure to defne it (i.e., b = number o bugs in environment).

North/SouthWind

Implementation Big-Oh time for applyWind

2D Arrayarray

HashMapkeyedbyLocation

TreeMapkeyedbyLocation

Linked List ofallBugs

(noorderingtohowtheyarestored)

HashSetofall

Bugs

East/WestWind

Implementation Big-Oh time for applyWind

2DaArray

HashMapkeyedbyLocation

TreeMapkeyedbyLocation

Linked List ofallBugs

(noorderingtohowtheyarestored)

HashSetofallBugs

Solutions

Use r or the number o rows, c or the number o columns in the grid and n or the widtho the range to be blown. I another variable is needed or the analysis, be sure to defne it(i.e., b = number o bugs in environment).

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 118/129© 2010 Te College Board.

118

AP Computer Science Curriculum Module: GridWorld

North/SouthWind

Implementation Big-Oh time for applyWind

2DArray O(n*r)

HashMapkeyedbyLocation O(n*r)

TreeMapkeyedbyLocation O(n*r*logb)

LinkedListofallBugBugs

(noorderingtohowtheyarestored)O(b)

HashSetofallBugBugs O(b)

East/WestWind

Implementation Big-Oh time for applyWind

2DArray O(n*c)

HashMapkeyedbyLocation O(n*c)

TreeMapkeyedbyLocation O(n*c*logb)

LinkedListofallBugBugs

(noorderingtohowtheyarestored)O(b)

HashSetofallBugBugs O(b)

Discussion Question

How do the values o n, r , c and b aect which implementations are more ecient?

(really large n, r and c with a really small b or vice versa)

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 119/129© 2010 Te College Board.

119

AP Computer Science Curriculum Module: GridWorld

Appendix D

GridWorld Case Study Part 5 — AbstractGridGrid Data Structures

Reading Worksheet

The AbstractGrid Class

1. Read pages 39–40 o the Student Manual.

2. What two concrete implementations o the Grid interace are provided?

3. What is the dierence between bounded and unbounded grids?

4. Why was the AbstractGrid class defned?

5. How many methods o the Grid interace are defned by the AbstractGrid class?

6. How are methods in AbstractGrid dierent rom methods in Grid?

7. What are the subclasses o  AbstractGrid?

8. Why is AbstractGrid an abstract class?

9. What does the toString method return?

10. Te concrete subclasses o the AbstractGrid must defne which methods? 

11. Does a concrete implementation o a Grid need to extend AbstractGrid?Why/Why not?

12. Complete Do You Know? Set 10.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 120/129© 2010 Te College Board.

120

AP Computer Science Curriculum Module: GridWorld

GridWorld Case Study Part 5 — AbstractGrid

Grid Data Structures

Reading Worksheet (Solutions)

The AbstractGrid Class

1. Read pages 39–40 o the Student Manual.

2. What two concrete implementations o the Grid interace are provided? Boundedgrid (BoundedGrid<E>) and unbounded grid (UnboundedGrid<E>)

3. What is the dierence between bounded and unbounded grids? Bounded gridshave a fxed number o rows and columns. Unbounded grids allow any row andcolumn location to be a valid location in the grid.

4. Why was the AbstractGrid class defned? Te AbstractGrid providescode that two concrete grid classes share.

5. How many methods o the Grid interace are defned by the AbstractGrid class? Five

6. How are methods in AbstractGrid dierent rom methods in Grid? Allmethods in an interace(Grid) are undefned; some o the methods in anabstract class (AbstractGrid) can be defned. 

7. What are the subclasses o  AbstractGrid? BoundedGrid andUnboundedGrid

8. Why is AbstractGrid an abstract class? AbstractGrid does not defne allthe methods in Grid and it’s not intended to be instantiated.

9. What does the toString method return? A String containing the locations o all the occupants

10. Te concrete subclasses o the AbstractGrid must defne which methods?getNumRows, getNumCols, isValid, getOccupiedLocations,get, put, remove

11. Does a concrete class that implements the Grid interace need to extend

 AbstractGrid? Why/Why not? No, but a concrete class that does not extend AbstractGrid needs to implement all Grid methods.

12. Complete Do You Know? Set 10.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 121/129© 2010 Te College Board.

121

AP Computer Science Curriculum Module: GridWorld

Appendix E

GridWorld Case Study Part 5 — BoundedGridGrid Data Structures

Reading Worksheet

The BoundedGrid Class 

1. Read page 41 o the Student Manual.

2. What does a BoundedGrid have a fxed number o ? 

3. What arguments does the constructor or BoundedGrid require?

4. I a method attempts to access a location outside o aBoundedGrid, whatresults?

5. How does the BoundedGrid class store grid occupants?

6. What type o data is the occupantArray declared to hold? 

7. When the array is constructed, what is contained in the array elements? 

8. Why not declare: private E[][] occupantArray?

9. Why not just have the Grid<Actor> and avoid generics?

10. What advantage would it be to hold the occupants in an instance variable  ArrayList<ArrayList<E>> occupantList instead o Object[][]occupantArray?

11. How does the BoundedGrid make sure that only type E objects are added tothe array?

12. Complete Do You Know? Set 11.

Suppose a new class BoundedArrayListGrid<E> is created, which is a subclass o  AbstractGrid<E>. Te class stores the grid occupants in a two-dimensional list.

private ArrayList<ArrayList<E>> occupantList;

13. Write the getNumRows method or BoundedArrayListGrid<E>.

14. What is the time complexity (Big-Oh) or thegetNumRows method?

15. Write the getNumCols method or BoundedArrayListGrid<E>.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 122/129© 2010 Te College Board.

122

AP Computer Science Curriculum Module: GridWorld

16. What is the time complexity (Big-Oh) or thegetNumCols method?

17. Write the constructor or BoundedArrayListGrid<E>. (Hint: useBoundedGrid.java as a model.)

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 123/129© 2010 Te College Board.

123

AP Computer Science Curriculum Module: GridWorld

GridWorld Case Study Part 5 — BoundedGrid

Grid Data Structures

Reading Worksheet (Solutions)

The BoundedGrid Class 

1. Read page 41 o the Student Manual.

2. What does a BoundedGrid have a fxed number o ? rows and columns

3. What arguments does the constructor or BoundedGrid require? int rows,int cols

4. I a method attempts to access a location outside o aBoundedGrid, whatresults? A run-time exception is thrown.

5. How does the BoundedGrid class store grid occupants? 2-D array.

6. What type o data is the occupantArray declared to hold? Object 

7. When the array is constructed, what is contained in the array elements?null

8. Why not declare: private E[][] occupantArray? Java does not allowgeneric arrays.

9. Why not just have the Grid<Actor> and avoid generics? Te Grid<E> isdesigned to work with any type o objects, not just actors. Limiting Grid to actorswould prevent it rom being used or making games, maps or other non Actor uses.

10. What advantage would it be to hold the occupants in an instance variable  ArrayList<ArrayList<E>> occupantList instead o Object[][]occupantArray? Java allows generic ArrayLists.

11. How does the BoundedGrid make sure that only type E objects are added tothe array? Te put method requires elements to be o type E.

12. Complete Do You Know? Set 11.

Suppose a new class BoundedArrayListGrid<E> is created that is a subclass o  AbstractGrid<E>. Te class stores the grid occupants in a two-dimensional list.

private ArrayList<ArrayList<E>> occupantList;

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 124/129© 2010 Te College Board.

124

AP Computer Science Curriculum Module: GridWorld

13. Write the getNumRows method or BoundedArrayListGrid<E>.

public int getNumRows(){

return occupantList.size();

}

14. What is the time complexity (Big-Oh) or thegetNumRows method? O(1)

15. Write the getNumCols method or BoundedArrayListGrid<E>.

public int getNumCols(){

return occupantList.get(0).size();}

16. What is the time complexity (Big-Oh) or the getNumCols method? O(1)

17. Write the constructor or 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);

}

}

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 125/129© 2010 Te College Board.

125

AP Computer Science Curriculum Module: GridWorld

Appendix F

GridWorld Case Study Part 5 — UnboundedGridGrid Data Structures

Reading Worksheet

The UnboundedGrid Class

1. Read page 42 o the Student Manual.

2. What arguments does the constructor or BoundedGrid require?

3. What locations are valid in an UnboundedGrid? 

4. How are locations stored in an UnboundedGrid?

5. What is the key type or the map?

6. What is the value type or the map?

7. What is returned by the getNumRows and getNumCols methods orUnboundedGrid?

8. What is returned by the isValid method or UnboundedGrid?

9. What map method does getOccupiedLocations use to determine occupiedlocation in the grid?

10. Complete Do You Know? Set 12.

Suppose a new class was constructed UnboundedBinarySearchTreeGrid<E>, which is a subclass o  AbstractGrid<E>. Te class stores the occupants in a binary search tree based on their Location. (Need to guarantee a getLocation methodor this to work, so the constructor throws an exception i E is not an Actor.)

private TreeNode occupantBST;

11. What is returned by the getNumRows and getNumCols methods orUnboundedGrid?

12. Write the get method or UnboundedBinarySearchTreeGrid<E>.

13. What is the time complexity (Big-Oh) or get method?

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 126/129© 2010 Te College Board.

126

AP Computer Science Curriculum Module: GridWorld

GridWorld Case Study Part 5 — UnboundedGrid

Grid Data Structures

Reading Worksheet (Solutions)

The UnboundedGrid Class

1. Read page 42 o the Student Manual.

2. What arguments does the constructor or BoundedGrid require? None

3. What locations are valid in an UnboundedGrid? Any 

4. How are locations stored in an UnboundedGrid? Map<Location, E>

5. What is the key type or the map?Location

6. What is the value type or the map? E — same type as grid occupants

7. What is returned by the getNumRows and getNumCols methods orUnboundedGrid? -1

8. What is returned by the isValid method or UnboundedGrid? true

9. What map method does getOccupiedLocations use to determine occupiedlocation in the grid? keyset()

10. Complete Do You Know? Set 12.

Suppose a new class was constructed UnboundedBinarySearchTreeGrid<E>, which is a subclass o  AbstractGrid<E>. Te class stores the occupants in a binary search tree based on their Location. (Need to guarantee a getLocation methodor this to work, so the constructor throws an exception i E is not an Actor.)

private TreeNode occupantBST;

11. What is returned by the getNumRows and getNumCols methods orUnboundedGrid? -1

12. Write the get method or UnboundedBinarySearchTreeGrid<E>.

public E get(Location loc){

if (loc == null)throw new NullPointerException(“loc == null”);

return getHelper(root, loc);}

private E getHelper(TreeNode node, Location loc)

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 127/129© 2010 Te College Board.

127

AP Computer Science Curriculum Module: GridWorld

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

13. What is the time complexity (Big-Oh) orget method?

O(n) //Unbalanced ree

O(Log n) //Balanced ree

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 128/129© 2010 Te College Board.

128

AP Computer Science Curriculum Module: GridWorld

About the Editor and Authors

Joe Coglianese is an AP Computer Science teacher at roy High School in Fullerton,Cali., and has been teaching since 2000. He has been an AP Reader or the AP Computer

Science Exam since 2006. He has worked to develop programs to interest historically underrepresented students in technology.

Judy Hromcik is an AP Computer Science teacher at Arlington High School in Arlington,exas. She was a member o the AP Computer Science Development Committee rom2001 to 2005, has been an AP reader and is currently a Question Leader or the APComputer Science Exam. She has been a College Board consultant since 1997 and hasconducted many AP Computer Science Summer Institutes. Hromcik wrote the solutionsor the new case study GridWorld and has pilot tested GridWorld in her classes.

Kathleen A. Larson taught AP Computer Science at Kingston High School, Kingston, N.Y.,

rom 1984 through 2005. She currently teaches Introduction to Java Programming at UlsterCounty Community College, part o the State University o New York System. She has servedas an AP Reader, able Leader and Question Leader or the AP Computer Science Exam;is a past member o the AP Computer Science Development Committee; and has taughtnumerous one-day, two-day and weeklong College Board–sponsored workshops or APComputer Science teachers. Her publications include AP Computer Science syllabi and theTeacher’s Guide for the Marine Biology Simulation Case Study.

Mike Lew is an AP Computer Science and AP Physics teacher at Loyola High School inLos Angeles, Cali., where he has taught since 1991. He has been teaching AP ComputerScience since 1995. Lew was an AP Computer Science Exam Reader rom 2001 to 2004

and has been presenting one-day AP workshops and weeklong AP Summer Institutessince 2004. He has also authored a teacher’s guide or the textbook Head First Java.

Leigh Ann Sudol has been teaching computer science since 1996. During that time shehas taught in public high schools, community colleges and universities. Her courses havebeen delivered online, in person and also in mixed settings. She is currently a visitinglecturer in the School o Computer Science at Carnegie Mellon University and a membero the board o directors o the Computer Science eachers Association, where she servesas chair o the publications committee. Sudol has served as the high school liaison or theSpecial Interest Group on Computer Science Education (SIGCSE) 2007. She coauthored

 Java Soware Structures for AP Computer Science AB and also the most recent edition o 

 Addison Wesley’s Review for the AP Computer Science Exam in Java. She has been a CollegeBoard consultant and an AP Computer Science Exam Reader since 2002 and a QuestionLeader or the AP Exam since 2005.

5/13/2018 GridWorld AP CompScience - slidepdf.com

http://slidepdf.com/reader/full/gridworld-ap-compscience 129/129

129

AP Computer Science Curriculum Module: GridWorld

Fran Trees taught AP Computer Science at Westield High School in Westield, N.J.,rom 1983 to 2001. She presently teaches computer science and mathematics at DrewUniversity in Madison, N.J. She has served as an AP Reader, Question Leader andExam Leader or the AP Computer Science Exam. She has also served as a membero the AP Computer Science est Development Committee and a member o variousad hoc committees or AP Computer Science. rees has served as a College Boardconsultant in computer science since 1985 and is the primary author o the Teacher’sGuide for AP Computer Science (C++) and the Advanced Placement® Computer ScienceStudy Guide to Accompany Java Concepts.