GridWorld PowerPoint

advertisement
GridWorld
Case Studies

Case studies are a teaching tool used in many disciplines.
They have been a part of the AP Computer Science
curriculum since the 1995-96 academic year. Case studies
give students an opportunity to:
 Read source code written by someone else.
 Work with a program of significant length.
 Become familiar with good coding, design, and
documentation practice.
 Learn about testing in a non-trivial context.
 Think through design and implementation tradeoffs.
Overview
 The GridWorld case study provides
a graphical environment where
visual objects inhabit and interact
in a two-dimensional grid.
 In this case study, you will
 design and create “actor” objects,
 add them to the grid, and
 determine whether the actors
behave according to their
specifications.
Overview
 A graphical user interface (GUI)
is provided that displays the
grid and the actors.
 In addition, the GUI has a
facility for adding actors to the
grid and for invoking methods
on them.
Narrative
 Part 1: Provides experiments to
observe the attributes and behavior of
the actors.
 Part 2: Defines Bug variations.
 Part 3: Explores the code that is
needed to understand and create
actors.
 Part 4: Defines classes that extend the
Critter class.
Chapter 1:
Observing and
Experimenting with
GridWorld
The first look at GridWorld

Exploring Actor state and
behavior



Exploring Bug state and behavior
Exploring Flower state and behavior
Exploring Rock state and behavior
Demo:
Compile and run
BugRunner.java.
GridWorld GUI shows a grid
containing two actors, a “bug”
and a “rock”.
Clicking on the Step button runs
one step, making each actor
act once.
Clicking on the Run button carries
out a series of steps until the
Stop button is clicked.
The delay between steps during a
run can be adjusted with the
slider.
Demo
Clicking on an empty cell in the
grid displays a drop-down
menu that shows the
constructors for different actor
types.
The menu lists constructors for the
classes of all objects that have
ever been placed in the grid
Selecting one of these
constructors places an instance
of that type in the grid. If the
constructor has parameters, a
dialog window appears
requesting parameter values
Exercise Set 1
1.
2.
3.
4.
5.
Does the bug always move to a new location?
In what direction does the bug move?
What does the bug do if it can’t move?
What does the bug leave behind when it moves?
What happens when the bug is at the edge of the grid?
1.
2.
And facing the edge?
And not facting the edge?
What happens when a bug is facing a rock and you click
step?
7. Does a flower move?
8. What behavior does a flower have?
9. Does a rock move or have any other behavior?
10. Can more than one actor (bug, flower, rock) be in the
same grid location at the same time?
6.
Exercise Answers Set 1
1.
Does the bug always move to a new location?

2.
In what direction does the bug move?

3.
Turns right 45 degrees
What does the bug leave behind when it moves?

5.
The direction it is facing
What does the bug do if it can’t move?

4.
No
A flower
What happens when the bug is at the edge of the grid?
1.
And facing the edge?
2.
And not facing the edge?


6.
The color gets darker over time. It can act. It inherits other behavior from Actor (setColor, setDirection, etc)
Does a rock move or have any other behavior?

10.
No
What behavior does a flower have?

9.
It turns 45 degrees to the right.
Does a flower move?

8.
Continues to move if it can
What happens when a bug is facing a rock and you click step?

7.
Turns 45
It doesn’t change over time. It can act. It inherits other behavior from Actor (setColor, setDirection, etc)
Can more than one actor (bug, flower, rock) be in the same grid location at the same time?

No
Exercises page 8

1. Click on a bug,
flower, or rock
 Invoke
the setDirection
method

Fill in the following
table for the
setDirection method
Degrees
0
45
90
135
180
225
270
315
360
Direction
North
Exercise Answers

Click on a bug, flower, or
rock



Invoke the setDirection
method
Fill in the following table
for the setDirection
method
Can you set the direction
to an angle that isn’t a
multiple of 45?

What happens?
Degrees
0
45
Direction
North
Northeast
90
135
180
225
East
Southeast
South
Southwest
270
315
360
West
Northwest
North
Exercise

2. Use the moveTo
method to move a bug





Does it change direction?
How far can you move it?
What happens if you try to
move it outside the grid?
What is the top left
location?
What is the bottom right
location?
Exercise Answers

Use the moveTo method
to move a bug

Does it change direction?


How far can you move it?


You get an
IllegalArgumentException
What is the top left
location?


Anywhere in the grid
What happens if you try to
move it outside the grid?


No
0,0
What is the bottom right
location?

9,9
Exercise
 3.
What method can you use to
change the color of a bug, rock, or
flower?
 4. Move a rock to a location with a
bug in it. Move the rock again to
another location. What happened
to the bug?
 What methods are defined in bug
Not
just inherited from Actor?
Exercise Answers

What method can you use to change the color of
a bug, rock, or flower?
 setColor

Move a rock to a location with a bug in it. Move
the rock again to another location. What
happened to the bug?
 It

is removed from the world
What methods are defined in bug
 Not

just inherited from Actor
act, move, turn, canMove
BugRunner
public static void main(String[] args)
{
ActorWorld world = new ActorWorld();
world.add(new Bug());
world.add(new Rock());
world.show();
}
not tested on AP exam
BugRunner

You can add a new Bug, Rock, Flower, or
Actor
Actor can be added to the Grid if any
Actor subclass has been added in the
BugRunner class.
 An
 Good



time to introduce inheritance;
a Bug IS-A Actor
a Rock IS-A Actor
a Flower IS-A Actor
BugRunner


Right click on a bug.
Run a method that will move the bug off the
grid.




Is there more than one way to do this?
After all bugs are removed from the grid, can
you add a new bug to the grid?
Add a few bugs.
What conditions cause the bug's canMove
method to return false?
BugRunner

What can a flower do?

What situations cause a bug to turn?
What happens if you move a bug to a cell
that is occupied by

A flower?
 A rock?
 Another bug?

Chapter 2
Bug Variations
Methods of the Bug class
 The
Bug class provides three
methods that specify how bugs move
and turn.
public boolean canMove()
 public void move()
 public void turn()

 These
methods are in the act method
public void act()
{ if (canMove())
move();
else
turn();
}
public boolean canMove()
{ Grid <Actor> gr = getGrid();
if (gr == null)
return false;
Location loc = getLocation();
Location next = loc.getAdjacentLocation(getDirection());
if (!gr.isValid(next))
return false;
Actor neighbor = gr.get(next);
return (neighbor == null) || (neighbor instanceOf Flower);
// ok to move into empty location or onto flower
// not ok to move onto any other actor
}
public void move()
{ Grid <Actor> gr = getGrid();
if (gr == null)
return;
Location loc = getLocation();
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
Flower flower = new Flower(getColor());
flower.putSelfInGrid(gr,loc);
}
public void turn()
{
setDirection(getDirection() +
Location.HALF_RIGHT);
}
Extending the Bug Class
A
new type of bug with different
behavior can be created by extending
the Bug class and overriding the act
method.
 No new methods need to be added;
the act method uses the three
auxiliary methods from the Bug
class.
BoxBug Class


A BoxBug moves in a
square pattern.
In order to keep track
of its movement, the
BoxBug class has two
instance variables
 sideLength
 steps.
Exercise Set 2
1.
2.
3.
4.
5.
6.
7.
What is the role of the instance variable sideLength?
What is the role of the instance variable steps?
Why is the turn method called twice when steps
becomes equal to sideLength?
Why can the move method be called in BoxBug when
there is no move method in the BoxBug class?
After a BoxBug is constructed will the size of the square
pattern always be the same?
Can the path a BoxBug travels ever change?
When will the value of steps be zero?
Exercise Answers Set 2
1.
What is the role of the instance variable sideLength?

2.
What is the role of the instance variable steps?

3.
Yes, there is no mutator (modifier) method in BoxBug for sideLength
Can the path a BoxBug travels ever change?

7.
It is inherited from Bug since the BugBog class extends the Bug class
After a BoxBug is constructed will the size of the square pattern always be
the same?

6.
To make a 90 degree turn (each turn is 45 degrees)
Why can the move method be called in BoxBug when there is no move
method in the BoxBug class?

5.
Keeps track of the current number of steps the bug has taken on the current
side.
Why is the turn method called twice when steps becomes equal to
sideLength?

4.
The number of grid cells in one side of the box – 1.
Yes, if it can’t move it turns 90 degrees.
When will the value of steps be zero?

When it is constructed and after each 90 degree turn.
Runner Classes





In order to observe the behavior of one or more
actors, a “runner” class is required.
That class constructs an ActorWorld object,
places actors into it, and shows the world.
BugRunner
BoxBugRunner
When a new class is written that extends Bug,
you also need to create a similar runner class.
BoxBugRunner
import
import
import
public
{
public
{
info.gridworld.actor.ActorWorld;
info.gridworld.grid.Location;
java.awt.Color;
class BoxBugRunner
static void main(String[] args)
ActorWorld world = new ActorWorld();
BoxBug alice = new BoxBug(6);
alice.setColor(Color.ORANGE);
BoxBug bob = new BoxBug(3);
world.add(new Location(7, 8), alice);
world.add(new Location(5, 5), bob);
world.show();
}
}
not tested on the AP exam
Exercise 1


Write a class
CircleBug that is
identical to BoxBug,
except that in the act
method the turn
method is called once
instead of twice.
How is its behavior
different from a BoxBug?
BoxBug

Students need to understand



Bug constuctors
act method
Students will need to use




canMove
turn
move
Students can create a new type of Bug by modifying
BoxBug code
BoxBug Code
public class BoxBug extends
Bug
{
private int steps;
private int sideLength;
public BoxBug(int length)
{
steps = 0;
sideLength = length;
}
public void act()
{
if (steps < sideLength
&& canMove())
{
move();
steps++;
}
else
{
turn();
turn();
steps = 0;
}
}
}
Extending the Bug class

Override Bug's act method

Each call to the move method should be guarded by
a call to the canMove method

Add additional instance fields if needed

Add new methods to the subclass if needed

Constructors for the subclass call super() or
super(someColor)
Exercise 2


Write a class
SpiralBug that drops
flowers in a spiral
pattern.
Hint: Imitate BoxBug,
but adjust the side length
when the bug turns. You
may want to use an
UnboundedGrid to see
the spiral pattern more
clearly.
Exercise 3




Write a class ZBug to
implement bugs that move in a
“Z” pattern, starting at the top
left corner.
After completing one “Z”
pattern, a ZBug should stop
moving.
Supply the length of the “Z” as a
parameter in the constructor.
Hint: Notice that a ZBug needs
to be facing east before
beginning its “Z” pattern.
Exercise 4



Write a class DancingBug
that “dances” by making
different turns before each
move.
The DancingBug
constructor has an integer
array as a parameter.
The integer entries in the
array represent how many
times the bug turns before
it moves.
Exercise 5
 Study
the code for
BoxBugRunner class.
Summarize the steps you would
use to add another BoxBug actor
to the grid.
Chapter 3:
GridWorld Classes
and Interfaces
Main classes are:
– Class
 Grid of Actors - Interface
 Location


BoundedGrid of Actors - Class
UnboundedGrid of Actors Class
 Actor



– Class
Bug – Class
Flower – Class
Rock - Class
Location Class

Encapsulates the coordinates for an actor’s
position in a grid
 Row and Column number
 Rows increase going down
 Columns increase going right
 Also has methods that determine
relationships between locations and
compass directions
 Every actor has a direction
 0 for north, 45 is northeast, …
 Location class also has eight constants
that specify the constant direction
 NORTH, NORTHEAST, …
Location Class
public Location (int r, int c)
constructs a location with row r and column c
public int getRow()
returns the row of this location
public int getCol()
returns the column of this location
public Location getAdjacentLocation
(int direction)
returns the adjacent location in the compass direction
that is closest to direction
public int getDirectionToward
(Location target)
returns the closest compass direction from this location
toward target
Testable API
Location Class
public boolean equals(Object other)
returns true if other is a Location object with the same
row and column values as this location, and false
otherwise
public int hashCode()
returns a hash code for this location
public int compareTo(Object otherObject)
returns a negative integer if this location is less than
other, zero if the two locations are equal, or a positive
integer if this location is greater than other. Locations
are ordered in row-major order
public String toString()
returns a string with the row and the column of this
location, in the format (row, col)
Testable API
Location Class
Compass directions:
public
public
public
public
public
public
public
public
static
static
static
static
static
static
static
static
final
final
final
final
final
final
final
final
int
int
int
int
int
int
int
int
NORTH = 0;
EAST = 90;
SOUTH = 180;
WEST = 270;
NORTHEAST = 45;
SOUTHEAST = 135;
SOUTHWEST = 225;
NORTHWEST = 315;
Location Class
Turn angles:
public
public
public
public
public
public
public
static
static
static
static
static
static
static
final
final
final
final
final
final
final
int
int
int
int
int
int
int
LEFT = -90;
RIGHT = 90;
HALF_LEFT =
HALF_RIGHT=
FULL_CIRCLE
HALF_CIRCLE
AHEAD = 0;
-45;
45;
= 360;
= 180 ;
Example
Location loc1 = new Location(5,7);
Location loc2 = loc1.getAdjacentLocation(Location.WEST);
Location loc3 =
loc1.getAdjacentLocaton(Location.NORTHEAST);
int dir = loc1.directionToward(new Location(6,8));
Example
Location loc1 = new Location(5,7);
Location loc2 = loc1.getAdjacentLocation(Location.WEST);
//
(5,6)
Location loc3 =
loc1.getAdjacentLocaton(Location.NORTHEAST);
//
(4,8)
int dir = loc1.directionToward(new Location(6,8));
//
135
Turning by an Amount

We have been using multiple calls to the
turn method to turn an Actor
 We
can use setDirection and Location
constants for this instead
 setDirection(getDirection +
Location.HALF_RIGHT); // turn 45 degrees
Exercise Set 3
Given
Location loc1 = new Location (4, 3);
Location loc2 = new Location (3, 4);
1.
How would you access the row value of loc1?
2.
What is the value of b after the following statement is
executed?
boolean b = loc1.equals(loc2);
3.
What is the value of loc3 after the following?
Location loc3 =
loc2.getAdjacentLocation(Location.SOUTH);
4.
What is the value of dir after the following?
int dir = loc1.getDirectionToward
(new Location(6,5));
5.
How does the getAdjacentLocation method know which
location to return?
Exercise Set 3 Answers
Given
Location loc1 = new Location (4, 3);
Location loc2 = new Location (3, 4);
1.
How would you access the row value of loc1?
loc1.getRow()
2.
What is the value of b after the following statement is
executed?
boolean b = loc1.equals(loc2);
false
3.
What is the value of loc3 after the following?
Location loc3 =
(4,4)
loc2.getAdjacentLocation(Location.SOUTH);
4.
What is the value of dir after the following?
135
int dir = loc1.getDirectionToward
(new Location(6,5));
5.
How does the getAdjacentLocation method know which
location to return? The parameter indicates the direction
Grid Interface
int getNumRows()
returns the number of rows, or -1 if this grid is unbounded
int getNumCols()
returns the number of columns, or -1 if this grid is unbounded
Boolean isValid(Location loc)
returns true if loc is valid in this grid, false otherwise
precondition: loc is not null
E put(Location loc, E obj)
puts obj at location loc in this grid and returns the object
previously at that location (or null if the location was previously
empty)
precondition: loc is valid in this grid and obj is not null
Grid Interface
E remove(Location loc)
removes the object at location loc and returns it (or null if the location is
unoccupied)
precondition: loc is valid in this grid
E get(Location loc)
returns the object at location loc (or null if the location is unoccupied)
precondition: loc is valid in this grid
ArrayList <Location> getOccupiedLocations()
returns all occupied locations in this grid
ArrayList<Location> getValidAdjacentLocations(Location
loc)
returns all valid locations adjacent to loc in this grid
precondition: loc is valid in this grid
Grid Interface
ArrayList <Location> getEmptyAdjacentLocations(Location
loc)
returns all valid empty locations adjacent to loc in this grid
precondition: loc is valid and in this grid
ArrayList <Location> getOccupiedAdjacentLocations(Location
loc)
returns all valid occupied locations adjacent to loc in this grid
precondition: loc is valid in this grid
ArrayList <E> getNeighbors(Location loc)
returns all objects in the occupied locations adjacent to loc in this grid
precondition: loc is valid in this grid
Exercise Set 4
1.
2.
3.
4.
5.
6.
How can you get a count of the objects in the grid?
How can you get a count of the empty locations in the
grid?
How can you check if location(10,10) is in the grid?
Grid contains method declarations but no code. Why?
Where can you find the code for the methods?
All methods that can return multiple objects return them
in an ArrayList. Would it have been a better design
to return them in an array? Explain your answer.
Exercise Answers Set 4
1.
How can you get a count of the objects in the grid?

2.
How can you get a count of the empty locations in the grid?

3.
It is an interface
Where can you find the code for the methods?

6.
isValid(new Location(10,10));
Grid contains method declarations but no code. Why?

5.
getNumRows() * getNumCols() – getOccupiedLocations.size()
How can you check if location(10,10) is in the grid?

4.
getOccupiedLocations().size()
In the classes that implement the interface: BoundedGrid and
UnboundedGrid
All methods that can return multiple objects return them in an
ArrayList. Would it have been a better design to return them in an
array? Explain your answer.

ArrayLists are arrays that can grow or shrink. They are better than
arrays when you don’t know how many items you will have.
Actor Class
public Actor()
constructs a blue actor that is facing north
public Color getColor()
returns the color of this actor
public void setColor(Color newColor)
sets the color of this actor to newColor
public int getDirection()
returns the direction of this actor, an angle between 0 and 359 degrees
public void setDirection(int newDirection)
sets the direction of this actor to the angle between 0 a nd 359 degrees
that is equivalent to newDirection
Actor Class
public Grid <Actor> getGrid()
returns the grid of this actor, or null if this actor is not contained in the grid
public Location getLocation()
returns the location of this actor
precondition: this actor is contained in this grid
public void putSelfInGrid(Grid<Actor> gr, Location loc)
puts this actor into the location loc of the grid gr. If there is another actor
at loc, it is removed.
precondition: this actor is not contained in a grid and loc is valid in gr
public void removeSelfFromGrid()
removes this actor from its grid
precondition: this actor is contained in a grid
Actor Class
public void moveTo(Location newLocation)
moves this actor to newLocation. If there is another actor at
newLocation, it is removed.
precondition: this actor is contained in a grid and newLocation is
valid in the grid of this actor
public void act()
reverses the direction of this actor. Override this method in
subclasses of Actor to define types of actors with different
behavior
public String toString()
returns a string with the location, direction, and color of this actor
Exercise Set 5
1.
2.
3.
4.
5.
6.
7.
Name three properties of every actor.
When an actor is constructed what is its direction and
color?
Why was the Actor class created as a class and not an
interface?
Can an Actor put itself in the grid twice without
removing itself?
Can an Actor remove itself from the grid twice?
Can an actor place itself in the grid and then remove
itself and then add itself to the grid? Try it. What
happens?
How can an actor turn 90 degrees to the right?
Exercise Answers Set 5
1.
Name 3 properties that every Actor has.

2.
When an actor is constructed what is its direction and color?

3.
No, you will get an IllegalStateException
Can an actor place itself in the grid and then remove itself and then add
itself to the grid? Try it. What happens?

7.
No, you will get an IllegalStateException
Can an Actor remove itself from the grid twice?

6.
Use classes or abstract classes when we want to provide fields and methods.
Interfaces can only define constants and abstract methods.
Can an Actor put itself in the grid twice without removing itself?

5.
Blue and North
Why was the Actor class created as a class and not an interface?

4.
Color, direction, location
Should work.
How can an actor turn 90 degrees to the right?

setDirection(getDirection() + Location.RIGHT);
Rock and Flower Classes

Subclasses of Actor
 Override

Rocks don’t do anything in the act method
 Empty

act()
body {}
Flowers change the color
 Reduces
the red, green, and blue by the
same amount (0.05)
 Gets darker
Bug Class


Extends Actor
In act() check if can move and if can move,
move, and drop a flower in the old location, else
turn (45 degrees)
public void act()
{
if (canMove())
move();
else
turn();
}
Bug Class
public class Bug extends Actor
{
public Bug()
{
setColor(Color.RED);
}
/**
* Constructs a bug of a given color.
* @param bugColor the color for this bug
*/
public Bug(Color bugColor)
{
setColor(bugColor);
}
Bug Class
public void act()
{
if (canMove())
move();
else
turn();
}
/**
* Turns the bug 45 degrees to the right without
changing its location.
*/
public void turn()
{
setDirection(getDirection() +
Location.HALF_RIGHT);
}
Bug Class
/**
* Moves the bug forward, putting a flower into the location it
previously occupied.
*/
public void move()
{
Grid<Actor> gr = getGrid();
if (gr == null)
return;
Location loc = getLocation();
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
Flower flower = new Flower(getColor());
flower.putSelfInGrid(gr, loc);
}
Bug Class
/**
* Tests whether this bug can move forward into a location that is empty or
* contains a flower.
* @return true if this bug can move.
*/
public boolean canMove()
{
Grid<Actor> gr = getGrid();
if (gr == null)
return false;
Location loc = getLocation();
Location next =loc.getAdjacentLocation(getDirection());
if (!gr.isValid(next))
return false;
Actor neighbor = gr.get(next);
return (neighbor == null)||(neighbor instanceof Flower);
// ok to move into empty location or onto flower
// not ok to move onto any other actor
}
Exercise Set 6
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
Which statement in the canMove method ensures that a bug doesn’t move out of the
grid?
Which statement in the canMove method keeps a bug from walking into a rock?
Which methods from the Grid interface are invoked in the canMove method and why?
Which method in the Location class is invoked in the canMove method and why?
Which methods inherited from the Actor class are invoked in the canMove method
and why?
What happens in the move method when the location in front of the bug is out of the
grid?
Is the variable loc needed in the move method or could it be avoided by calling
getLocation() multiple times?
Why do you think that the flowers that are dropped by the bug have the same color
as the bug?
When a bug removes itself from the grid will it, will it place a flower in its previous
location?
Which statement in the move method places a flower in the grid at the previous
location?
If a bug needs to turn 180 degrees how many times should it call the turn method?
Exercise Answers Set 6
1.
Which statement in the canMove method ensures that a bug doesn’t move
out of the grid?
•
2.
Which statement in the canMove method keeps a bug from walking into a
rock?
•
3.
isValid is used to check if the location in front of the bug is value and get is used
to get the object in the grid in front of the bug
Which method in the Location class is invoked in the canMove method and
why?
•
5.
return (neighbor == null) || (neighbor instanceof Flower);
Which methods from the Grid interface are invoked in the canMove method
and why?
•
4.
if (!gr.isValid(next))
getAdjacentLocation to get the location in front of the bug
Which methods inherited from the Actor class are invoked in the canMove
method and why?
•
getGrid is used to check that the bug is in a grid, and getLocation is used to get
the current location
Exercise Answers Set 6
What happens in the move method when the location in front of the bug
is out of the grid?
6.
•
The bug removes itself from the grid
Is the variable loc needed in the move method or could it be avoided by
calling getLocation() multiple times?
7.
•
It is needed to store the previous location so that a flower can be put there
Why do you think that the flowers that are dropped by the bug have the
same color as the bug?
8.
•
To make it clear which bug they come from
When a bug removes itself from the grid will it, will it place a flower in its
previous location?
9.
•
Yes
Which statement in the move method places a flower in the grid at the
previous location?
10.
•
flower.putSelfInGrid(gr, loc);
If a bug needs to turn 180 degrees how many times should it call the turn
method?
11.
•
180 / 45 = 4
Jumper Activity

In groups of 3-5 students
 Create a Jumper class.
 Objects of this class can move forward 2 cells and can jump
over rocks or flowers. They don’t leave anything behind
 Discuss the following:
 What happens if the next location is empty but the one two in
front contains a rock or flower?
 What should happen if the location two in front is out of the
grid?
 What should a Jumper do if it is facing the edge of the grid?
 What should a Jumper do if the location two in front has
another Actor in it (not a Flower or Rock)
 What will a Jumper do if it encounters another Jumper?
 Are there any other tests a Jumper needs to make?
Jumper Activity Cont.

Consider the following design issues:
 Which class should Jumper extend?
 Is there an existing class that is similar to Jumper?
 Should you create a constructor? What parameters
should it have?
 Which methods should be overriden?
 What new methods should be added?
 How will you test the class?


Code the Jumper and JumperRunner classes
Test the Jumper class
 Or
give it to another group to test
The Graphical User Interface

The World class connects the described classes
and the GUI
 The
GUI asks the World for the grid, gets the objects
in the grid, and draws them at their locations
 ActorWorld is a subclass of World


That has a step method that calls act() on each object in the
Grid
Has methods for adding objects



public void add(Location loc, Actor theActor)
public void add(Actor theActor)
 Adds the actor to a random location
Has a method for removing objects

Public Actor remove(Location loc)
optional
Class Diagram
Role Play Exercise
Chapter 4:
Interacting Objects
The Critter Class

Critters are actors that have a common pattern for
behavior


Use the same act() method
When a critter acts it:

gets a list of actors to process


processes the actors


ArrayList<Location> getMoveLocations()
selects a location


void processActors(ArrayList<Actor> actors);
generates a list of locations it can move to


ArrayList<Actor> getActors()
Location selectMoveLocation(ArrayList<Location> locList)
moves to the selected location

void makeMove(Location loc)
Exercise Set 7
1.
2.
3.
4.
5.
6.
What methods are implemented in Critter?
What does each do?
What are the 5 basic actions common to all
Critters when they act?
Should subclasses of Critter override the
getActors() method?
Describe 3 ways a Critter could process
actors?
What 3 methods must be invoked to make a
Critter move? Explain each method.
Why is there no Critter constructor?
Exercise Answers Set 7
1.
What methods are implemented in Critter? What does each do?

act, getActors, processActors, getMoveLocations, selectMoveLocation, makeMove






2.
What are the 5 basic actions common to all Critters when they act?

3.
Change their color, Change their direction, remove them from the grid, etc
What 3 methods must be invoked to make a Critter move?

6.
Yes, if they want to control the type of actors to interact with or to get more than just the
neighboring Actors (one cell away)
Describe 3 ways a Critter could process actors?

5.
Get actors to process, process the actors, get a list of locations, select a location, move
Should subclasses of Critter override the getActors() method?

4.
Act checks that the Critter is in a grid and if so calls the other methods
getActors gets the neighboring Actors
processActors eats (removes) actors that are not Rocks or Critters
getMoveLocations returns valid empty neighboring locations (1 cell away)
selectMoveLocation returns current location if no empty neighbors or a random empty neighbor
makeMove if the location is null remove self from grid otherwise move to the location
getMoveLocations, selectMoveLocation, makeMove.
Why is there no Critter constructor?

Because it inherits from Actor and Actor has a no-arg constructor so by not providing any
constructors the compiler will add a no-arg constructor that calls super()
Extending the Critter Class

ChameleonCritter

Overrides processActors to
pick a random actor and
change its current color to the
actor’s color
 Overrides makeMove to also
turn toward the new location

CrabCritter

Overrides getActors to get
actors straight ahead,
diagonal left, and diagonal
right (from front)
 Overrides getMoveLocations
to only move to the left or right
 Overrides makeMove so that if
it doesn’t move it randomly
turns left or right
Exercise Set 8
1.
2.
3.
4.
5.
6.
Why does act cause a ChameleonCritter to act
differently than a Critter even though act is not
overriden?
Why does the makeMove method of
ChameleonCritter call super.makeMove?
How would you make a ChameleonCritter drop
a flower in the old location when it moves?
Why doesn’t ChameleonCritter override the
getActors method?
Which class contains the getLocation method?
How can a Critter access its own grid?
Exercise Answers Set 8
Why does act cause a ChameleonCritter to act differently than a
Critter even though act is not overriden?
1.
•
Because some of the methods act calls are overriden
Why does the makeMove method of ChameleonCritter call
super.makeMove?
2.
•
Because it wants to do the same actions as the parent class
How would you make a ChameleonCritter drop a flower in the old
location when it moves?
3.
•
Save the current location before you move and then create a flower
and add it to this saved location just like in Bug
Why doesn’t ChameleonCritter override the getActors method?
4.
•
It wants the same behavior
Which class contains the getLocation method?
5.
•
Actor
How can a Critter access its own grid?
6.
•
The inherited getGrid method (from Actor)
Exercise Set 9
1.
2.
Why doesn’t CrabCritter override the processActors method?
Describe the process CrabCritter uses to find and eat actors.
Does it always eat all neighboring actors?
2. Explain.
1.
3.
4.
5.
6.
7.
Why is the getLocationsInDirections method used in CrabCritter?
If a CrabCritter has location (3,4) and faces south what are the
possible locations for actors returned by getActors?
What are the similarities and differences between the movements of
a CrabCritter and a Critter?
How does a CrabCritter determine when it turns instead of moving?
Why don’t the CrabCitters objects eat each other?
Exercise Answers Set 9
1.
Why doesn’t CrabCritter override the processActors method?
•
2.
Because it wants to eat the actors which is what the method in Critter
does
Describe the process CrabCritter uses to find and eat actors.
1.
Does it always eat all neighboring actors?

2.
Explain.

3.
It overrides getActor to get only these and then calls processActors to eat
them
Why is the getLocationsInDirections method used in CrabCritter?
•
4.
No only the ones in front, or diagonally left or right
To get the locations in front, diagonally left and right to get Actors in
these locations
If a CrabCritter has location (3,4) and faces south what are the
possible locations for actors returned by getActors?
•
(4,4), (4, 3), (4,5)
Exercise Answers Set 9
What are the similarities and differences
between the movements of a CrabCritter and a
Critter?
5.
•
If a CrabCritter can’t move it randomly turns left or
right, if it can move it moves like a Critter
How does a CrabCritter determine when it
turns instead of moving?
6.
•
It turns only if it can’t move
Why don’t the CrabCitters objects eat each
other?
7.
•
Because processActors in Critter won’t eat other
Critters and a CrabCritter is a type of Critter
Overview of GridWorld
Creatures

Actors
 Bugs

extending Bug: override Act
 Rocks
 Flowers
 Critters
DO NOT OVERRIDE ACT!!!
 extending Critter overrides one or more of the 5
methods

Exercises

1. Modify the processActors method in
ChameleonCritter so that if the list of
actors to process is empty, the color of the
ChameleonCritter will darken (like a flower)

2. Create a class called ChameleonKid that
extends ChameleonCritter as modified in
exercise 1. A ChameleonKid changes its
color to the color of one of the actors
immediately in front or behind. If there is no
actor in either of these locations, then the
ChameleonKid darkens like the modified
ChameleonCritter.
Exercises

3. Create a class called RockHound that extends
Critter. A RockHound gets the actors to be
processed in the same way as a Critter. It removes
any rocks in that list from the grid. A RockHound moves
like a Critter.

4. Create a class called BlusterCritter that
extends Critter. A BlusterCritter looks at all of
the neighbors within two steps of its current location.
(For a BlusterCritter not near an edge, this
includes 24 locations). It counts the number of critters in
those locations. If there are fewer than c critters, the
BlusterCritter’s color gets brighter (color values
increase). If there are c or more critters, the
BlusterCritter’s color darkens (color values
decrease). Here c is a value that indicates the courage
of the critter. It should be set in the constructor.
Exercises

5. Create a class QuickCrab that extends
CrabCritter. A QuickCrab processes actors the
same way a CrabCritter does. A QuickCrab moves
to one of the two locations, randomly selected, that are
two spaces to its right or left, if that location and the
intervening location are both empty. Otherwise a
QuickCrab moves like a CrabCritter.

6. Create a class KingCrab that extends
CrabCritter. A KingCrab gets the actors to be
processed in the same way a CrabCritter does. A
KingCrab causes each actor that it processes to move
one location further away from the KingCrab. If the
actor cannot move away, the KingCrab removes it from
the grid. When the KingCrab has completed
processing the actors, it moves like a CrabCritter.
Group Activity

Specify
 Create

a new creature that extends Critter
Design
 What
variables are needed? What algorithms
are needed?

Code
 Implement

the code
Test
 Write
test cases for the creature specified
Download