Grid World Case Studies n Case studies are

















![Bug. Runner public static void main(String[] args) { Actor. World world = new Actor. Bug. Runner public static void main(String[] args) { Actor. World world = new Actor.](https://slidetodoc.com/presentation_image_h/ba6a56899d7c5f622a0ddfcd5f37a80c/image-18.jpg)










































































- Slides: 92
Grid. World
Case Studies n 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 Grid. World 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 create actors. § Part 4: Defines classes that extend the Critter class. §
Chapter 1: Observing and Experimenting with Grid. World
The first look at Grid. World § Exploring Actor state and behavior § § § Exploring Bug state and behavior Exploring Flower state and behavior Exploring Rock state and behavior
Demo: Compile and run Bug. Runner. java. Grid. World 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? n 2. And not facing the edge? n 6. The color gets darker over time. It can act. It inherits other behavior from Actor (set. Color, set. Direction, etc) Does a rock move or have any other behavior? 1. n No What behavior does a flower have? 1. n It turns 45 degrees to the right. Does a flower move? 1. n 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 (set. Color, set. Direction, etc) Can more than one actor (bug, flower, rock) be in the same grid location at the same time? 1. No
Exercises page 8 n 1. Click on a bug, flower, or rock ¨ Invoke the set. Direction method n Fill in the following table for the set. Direction method Degrees 0 45 90 135 180 225 270 315 360 Direction North
Exercise Answers n Click on a bug, flower, or rock ¨ n n Invoke the set. Direction method Fill in the following table for the set. Direction method Can you set the direction to an angle that isn’t a multiple of 45? ¨ What happens? Degrees 0 45 90 Direction Northeast East 135 180 225 270 315 360 Southeast Southwest West Northwest North
Exercise n 2. Use the move. To 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 n Use the move. To method to move a bug ¨ Does it change direction? n ¨ How far can you move it? n ¨ You get an Illegal. Argument. Exception What is the top left location? n ¨ Anywhere in the grid What happens if you try to move it outside the grid? n ¨ No 0, 0 What is the bottom right location? n 9, 9
Exercise n 3. What method can you use to change the color of a bug, rock, or flower? n 4. Move a rock to a location with a bug in it. Move the rock again to another location. What happened to the bug? n What methods are defined in bug ¨Not just inherited from Actor?
Exercise Answers n What method can you use to change the color of a bug, rock, or flower? ¨ set. Color n Move a rock to a location with a bug in it. Move the rock again to another location. What happened to the bug? ¨ It n is removed from the world What methods are defined in bug ¨ Not n just inherited from Actor act, move, turn, can. Move
Bug. Runner public static void main(String[] args) { Actor. World world = new Actor. World(); world. add(new Bug()); world. add(new Rock()); world. show(); } not tested on AP exam
Bug. Runner n You can add a new Bug, Rock, Flower, or Actor ¨ An Actor can be added to the Grid if any Actor subclass has been added in the Bug. Runner class. ¨ Good time to introduce n a Bug IS-A Actor n n a Rock IS-A Actor a Flower IS-A Actor inheritance;
Bug. Runner n n Right click on a bug. Run a method that will move the bug off the grid. ¨ n n n 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 can. Move method to return false?
Bug. Runner n What can a flower do? n What situations cause a bug to turn? What happens if you move a bug to a cell that is occupied by n A flower? ¨ A rock? ¨ Another bug? ¨
Chapter 2 Bug Variations
Methods of the Bug class n The Bug class provides three methods that specify how bugs move and turn. public boolean can. Move() ¨ public void move() ¨ public void turn() ¨ n These methods are in the act method
public void act() { if (can. Move()) move(); else turn(); }
public boolean can. Move() { Grid <Actor> gr = get. Grid(); if (gr == null) return false; Location loc = get. Location(); Location next = loc. get. Adjacent. Location(get. Direction()); if (!gr. is. Valid(next)) return false; Actor neighbor = gr. get(next); return (neighbor == null) || (neighbor instance. Of Flower); // ok to move into empty location or onto flower // not ok to move onto any other actor }
public void move() { Grid <Actor> gr = get. Grid(); if (gr == null) return; Location loc = get. Location(); Location next = loc. get. Adjacent. Location(get. Direction()); if (gr. is. Valid(next)) move. To(next); else remove. Self. From. Grid(); Flower flower = new Flower(get. Color()); flower. put. Self. In. Grid(gr, loc); }
public void turn() { set. Direction(get. Direction() + Location. HALF_RIGHT); }
Extending the Bug Class n. A new type of bug with different behavior can be created by extending the Bug class and overriding the act method. n No new methods need to be added; the act method uses the three auxiliary methods from the Bug class.
Box. Bug Class n n A Box. Bug moves in a square pattern. In order to keep track of its movement, the Box. Bug class has two instance variables ¨ side. Length ¨ steps.
Exercise Set 2 1. 2. 3. 4. 5. 6. 7. What is the role of the instance variable side. Length? What is the role of the instance variable steps? Why is the turn method called twice when steps becomes equal to side. Length? Why can the move method be called in Box. Bug when there is no move method in the Box. Bug class? After a Box. Bug is constructed will the size of the square pattern always be the same? Can the path a Box. Bug travels ever change? When will the value of steps be zero?
Exercise Answers Set 2 1. What is the role of the instance variable side. Length? ¨ 2. What is the role of the instance variable steps? ¨ 3. Yes, there is no mutator (modifier) method in Box. Bug for side. Length Can the path a Box. Bug travels ever change? ¨ 7. It is inherited from Bug since the Bug. Bog class extends the Bug class After a Box. Bug 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 Box. Bug when there is no move method in the Box. Bug 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 side. Length? ¨ 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 n n n In order to observe the behavior of one or more actors, a “runner” class is required. That class constructs an Actor. World object, places actors into it, and shows the world. Bug. Runner Box. Bug. Runner When a new class is written that extends Bug, you also need to create a similar runner class.
Box. Bug. Runner import public { info. gridworld. actor. Actor. World; info. gridworld. grid. Location; java. awt. Color; class Box. Bug. Runner static void main(String[] args) Actor. World world = new Actor. World(); Box. Bug alice = new Box. Bug(6); alice. set. Color(Color. ORANGE); Box. Bug bob = new Box. Bug(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 n n Write a class Circle. Bug that is identical to Box. Bug, except that in the act method the turn method is called once instead of twice. How is its behavior different from a Box. Bug?
Box. Bug n n Students need to understand ¨ Bug constuctors ¨ act method Students will need to use can. Move ¨ turn ¨ move ¨ ¨ Students can create a new type of Bug by modifying Box. Bug code
Box. Bug Code public class Box. Bug extends Bug { private int steps; private int side. Length; public Box. Bug(int length) { steps = 0; side. Length = length; } public void act() { if (steps < side. Length && can. Move()) { move(); steps++; } else { turn(); steps = 0; } } }
Extending the Bug class n Override Bug's act method n Each call to the move method should be guarded by a call to the can. Move method n Add additional instance fields if needed n Add new methods to the subclass if needed n Constructors for the subclass call super() or super(some. Color)
Exercise 2 n n Write a class Spiral. Bug that drops flowers in a spiral pattern. Hint: Imitate Box. Bug, but adjust the side length when the bug turns. You may want to use an Unbounded. Grid to see the spiral pattern more clearly.
Exercise 3 n n 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 n n n Write a class Dancing. Bug that “dances” by making different turns before each move. The Dancing. Bug 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 n Study the code for Box. Bug. Runner class. Summarize the steps you would use to add another Box. Bug actor to the grid.
Chapter 3: Grid. World Classes and Interfaces
Main classes are: ¨ Location – Class ¨ Grid of Actors - Interface n n Bounded. Grid of Actors - Class Unbounded. Grid of Actors Class ¨ Actor n n n – Class Bug – Class Flower – Class Rock - Class
Location Class n Encapsulates the coordinates for an actor’s position in a grid ¨ Row and Column number n Rows increase going down n Columns increase going right ¨ Also has methods that determine relationships between locations and compass directions ¨ Every actor has a direction n 0 for north, 45 is northeast, … ¨ Location class also has eight constants that specify the constant direction n NORTH, NORTHEAST, …
Location Class public Location (int r, int c) constructs a location with row r and column c public int get. Row() returns the row of this location public int get. Col() returns the column of this location public Location get. Adjacent. Location (int direction) returns the adjacent location in the compass direction that is closest to direction public int get. Direction. Toward (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 hash. Code() returns a hash code for this location public int compare. To(Object other. Object) 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 to. String() 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 static static final final int int NORTH = 0; EAST = 90; SOUTH = 180; WEST = 270; NORTHEAST = 45; SOUTHEAST = 135; SOUTHWEST = 225; NORTHWEST = 315;
Location Class Turn angles: public public static static final final int int LEFT = -90; RIGHT = 90; HALF_LEFT = HALF_RIGHT= FULL_CIRCLE HALF_CIRCLE AHEAD = 0; -45; = 360; = 180 ;
Example Location loc 1 = new Location(5, 7); Location loc 2 = loc 1. get. Adjacent. Location(Location. WEST); Location loc 3 = loc 1. get. Adjacent. Locaton(Location. NORTHEAST); int dir = loc 1. direction. Toward(new Location(6, 8));
Example Location loc 1 = new Location(5, 7); Location loc 2 = loc 1. get. Adjacent. Location(Location. WEST); // (5, 6) Location loc 3 = loc 1. get. Adjacent. Locaton(Location. NORTHEAST); // (4, 8) int dir = loc 1. direction. Toward(new Location(6, 8)); // 135
Turning by an Amount n We have been using multiple calls to the turn method to turn an Actor ¨ We can use set. Direction and Location constants for this instead ¨ set. Direction(get. Direction + Location. HALF_RIGHT); // turn 45 degrees
Exercise Set 3 Given Location loc 1 = new Location (4, 3); Location loc 2 = new Location (3, 4); 1. How would you access the row value of loc 1? 2. What is the value of b after the following statement is executed? boolean b = loc 1. equals(loc 2); 3. What is the value of loc 3 after the following? Location loc 3 = loc 2. get. Adjacent. Location(Location. SOUTH); 4. What is the value of dir after the following? int dir = loc 1. get. Direction. Toward (new Location(6, 5)); 5. How does the get. Adjacent. Location method know which location to return?
Exercise Set 3 Answers Given Location loc 1 = new Location (4, 3); Location loc 2 = new Location (3, 4); 1. How would you access the row value of loc 1? loc 1. get. Row() 2. What is the value of b after the following statement is executed? boolean b = loc 1. equals(loc 2); false 3. What is the value of loc 3 after the following? Location loc 3 = (4, 4) loc 2. get. Adjacent. Location(Location. SOUTH); 4. What is the value of dir after the following? 135 int dir = loc 1. get. Direction. Toward (new Location(6, 5)); 5. How does the get. Adjacent. Location method know which location to return? The parameter indicates the direction
Grid Interface int get. Num. Rows() returns the number of rows, or -1 if this grid is unbounded int get. Num. Cols() returns the number of columns, or -1 if this grid is unbounded Boolean is. Valid(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 Array. List <Location> get. Occupied. Locations() returns all occupied locations in this grid Array. List<Location> get. Valid. Adjacent. Locations(Location loc) returns all valid locations adjacent to loc in this grid precondition: loc is valid in this grid
Grid Interface Array. List <Location> get. Empty. Adjacent. Locations(Location loc) returns all valid empty locations adjacent to loc in this grid precondition: loc is valid and in this grid Array. List <Location> get. Occupied. Adjacent. Locations(Location loc) returns all valid occupied locations adjacent to loc in this grid precondition: loc is valid in this grid Array. List <E> get. Neighbors(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 Array. List. 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. is. Valid(new Location(10, 10)); Grid contains method declarations but no code. Why? ¨ 5. get. Num. Rows() * get. Num. Cols() – get. Occupied. Locations. size() How can you check if location(10, 10) is in the grid? ¨ 4. get. Occupied. Locations(). size() In the classes that implement the interface: Bounded. Grid and Unbounded. Grid All methods that can return multiple objects return them in an Array. List. Would it have been a better design to return them in an array? Explain your answer. ¨ Array. Lists 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 get. Color() returns the color of this actor public void set. Color(Color new. Color) sets the color of this actor to new. Color public int get. Direction() returns the direction of this actor, an angle between 0 and 359 degrees public void set. Direction(int new. Direction) sets the direction of this actor to the angle between 0 a nd 359 degrees that is equivalent to new. Direction
Actor Class public Grid <Actor> get. Grid() returns the grid of this actor, or null if this actor is not contained in the grid public Location get. Location() returns the location of this actor precondition: this actor is contained in this grid public void put. Self. In. Grid(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 remove. Self. From. Grid() removes this actor from its grid precondition: this actor is contained in a grid
Actor Class public void move. To(Location new. Location) moves this actor to new. Location. If there is another actor at new. Location, it is removed. precondition: this actor is contained in a grid and new. Location 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 to. String() 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 Illegal. State. Exception 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 Illegal. State. Exception 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? ¨ set. Direction(get. Direction() + Location. RIGHT);
Rock and Flower Classes n Subclasses of Actor ¨ Override n Rocks don’t do anything in the act method ¨ Empty n act() body {} Flowers change the color ¨ Reduces the red, green, and blue by the same amount (0. 05) ¨ Gets darker
Bug Class n n Extends Actor In act() check if can move and if can move, and drop a flower in the old location, else turn (45 degrees) public void act() { if (can. Move()) move(); else turn(); }
Bug Class public class Bug extends Actor { public Bug() { set. Color(Color. RED); } /** * Constructs a bug of a given color. * @param bug. Color the color for this bug */ public Bug(Color bug. Color) { set. Color(bug. Color); }
Bug Class public void act() { if (can. Move()) move(); else turn(); } /** * Turns the bug 45 degrees to the right without changing its location. */ public void turn() { set. Direction(get. Direction() + Location. HALF_RIGHT); }
Bug Class /** * Moves the bug forward, putting a flower into the location it previously occupied. */ public void move() { Grid<Actor> gr = get. Grid(); if (gr == null) return; Location loc = get. Location(); Location next = loc. get. Adjacent. Location(get. Direction()); if (gr. is. Valid(next)) move. To(next); else remove. Self. From. Grid(); Flower flower = new Flower(get. Color()); flower. put. Self. In. Grid(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 can. Move() { Grid<Actor> gr = get. Grid(); if (gr == null) return false; Location loc = get. Location(); Location next =loc. get. Adjacent. Location(get. Direction()); if (!gr. is. Valid(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 can. Move method ensures that a bug doesn’t move out of the grid? Which statement in the can. Move method keeps a bug from walking into a rock? Which methods from the Grid interface are invoked in the can. Move method and why? Which method in the Location class is invoked in the can. Move method and why? Which methods inherited from the Actor class are invoked in the can. Move 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 get. Location() 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 can. Move method ensures that a bug doesn’t move out of the grid? • 2. Which statement in the can. Move method keeps a bug from walking into a rock? • 3. is. Valid 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 can. Move method and why? • 5. return (neighbor == null) || (neighbor instanceof Flower); Which methods from the Grid interface are invoked in the can. Move method and why? • 4. if (!gr. is. Valid(next)) get. Adjacent. Location to get the location in front of the bug Which methods inherited from the Actor class are invoked in the can. Move method and why? • get. Grid is used to check that the bug is in a grid, and get. Location 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 get. Location() 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. put. Self. In. Grid(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 n In groups of 3 -5 students ¨ Create a Jumper class. n 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: n What happens if the next location is empty but the one two in front contains a rock or flower? n What should happen if the location two in front is out of the grid? n What should a Jumper do if it is facing the edge of the grid? n What should a Jumper do if the location two in front has another Actor in it (not a Flower or Rock) n What will a Jumper do if it encounters another Jumper? n Are there any other tests a Jumper needs to make?
Jumper Activity Cont. n 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? n n Code the Jumper and Jumper. Runner classes Test the Jumper class ¨ Or give it to another group to test
The Graphical User Interface n 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 ¨ Actor. World is a subclass of World n n That has a step method that calls act() on each object in the Grid Has methods for adding objects ¨ ¨ n public void add(Location loc, Actor the. Actor) public void add(Actor the. Actor) § 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 n Critters are actors that have a common pattern for behavior ¨ n Use the same act() method When a critter acts it: ¨ gets a list of actors to process n ¨ processes the actors n ¨ Array. List<Location> get. Move. Locations() selects a location n ¨ void process. Actors(Array. List<Actor> actors); generates a list of locations it can move to n ¨ Array. List<Actor> get. Actors() Location select. Move. Location(Array. List<Location> loc. List) moves to the selected location n void make. Move(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 get. Actors() 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, get. Actors, process. Actors, get. Move. Locations, select. Move. Location, make. Move n n n 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 get. Actors() method? ¨ 4. Act checks that the Critter is in a grid and if so calls the other methods get. Actors gets the neighboring Actors process. Actors eats (removes) actors that are not Rocks or Critters get. Move. Locations returns valid empty neighboring locations (1 cell away) select. Move. Location returns current location if no empty neighbors or a random empty neighbor make. Move if the location is null remove self from grid otherwise move to the location get. Move. Locations, select. Move. Location, make. Move. 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 n Chameleon. Critter Overrides process. Actors to pick a random actor and change its current color to the actor’s color ¨ Overrides make. Move to also turn toward the new location ¨ n Crab. Critter Overrides get. Actors to get actors straight ahead, diagonal left, and diagonal right (from front) ¨ Overrides get. Move. Locations to only move to the left or right ¨ Overrides make. Move 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 Chameleon. Critter to act differently than a Critter even though act is not overriden? Why does the make. Move method of Chameleon. Critter call super. make. Move? How would you make a Chameleon. Critter drop a flower in the old location when it moves? Why doesn’t Chameleon. Critter override the get. Actors method? Which class contains the get. Location method? How can a Critter access its own grid?
Exercise Answers Set 8 Why does act cause a Chameleon. Critter 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 make. Move method of Chameleon. Critter call super. make. Move? 2. • Because it wants to do the same actions as the parent class How would you make a Chameleon. Critter 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 Chameleon. Critter override the get. Actors method? 4. • It wants the same behavior Which class contains the get. Location method? 5. • Actor How can a Critter access its own grid? 6. • The inherited get. Grid method (from Actor)
Exercise Set 9 1. 2. Why doesn’t Crab. Critter override the process. Actors method? Describe the process Crab. Critter uses to find and eat actors. 1. 2. 3. 4. 5. 6. 7. Does it always eat all neighboring actors? Explain. Why is the get. Locations. In. Directions method used in Crab. Critter? If a Crab. Critter has location (3, 4) and faces south what are the possible locations for actors returned by get. Actors? What are the similarities and differences between the movements of a Crab. Critter and a Critter? How does a Crab. Critter determine when it turns instead of moving? Why don’t the Crab. Citters objects eat each other?
Exercise Answers Set 9 1. Why doesn’t Crab. Critter override the process. Actors method? • 2. Because it wants to eat the actors which is what the method in Critter does Describe the process Crab. Critter uses to find and eat actors. 1. Does it always eat all neighboring actors? n 2. Explain. n 3. It overrides get. Actor to get only these and then calls process. Actors to eat them Why is the get. Locations. In. Directions method used in Crab. Critter? • 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 Crab. Critter has location (3, 4) and faces south what are the possible locations for actors returned by get. Actors? • (4, 4), (4, 3), (4, 5)
Exercise Answers Set 9 What are the similarities and differences between the movements of a Crab. Critter and a Critter? 5. • If a Crab. Critter can’t move it randomly turns left or right, if it can move it moves like a Critter How does a Crab. Critter determine when it turns instead of moving? 6. • It turns only if it can’t move Why don’t the Crab. Citters objects eat each other? 7. • Because process. Actors in Critter won’t eat other Critters and a Crab. Critter is a type of Critter
Overview of Grid. World Creatures n Actors ¨ Bugs n extending Bug: override Act ¨ Rocks ¨ Flowers ¨ Critters DO NOT OVERRIDE ACT!!! n extending Critter overrides one or more of the 5 methods n
Exercises n 1. Modify the process. Actors method in Chameleon. Critter so that if the list of actors to process is empty, the color of the Chameleon. Critter will darken (like a flower) n 2. Create a class called Chameleon. Kid that extends Chameleon. Critter as modified in exercise 1. A Chameleon. Kid 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 Chameleon. Kid darkens like the modified Chameleon. Critter.
Exercises n 3. Create a class called Rock. Hound that extends Critter. A Rock. Hound gets the actors to be processed in the same way as a Critter. It removes any rocks in that list from the grid. A Rock. Hound moves like a Critter. n 4. Create a class called Bluster. Critter that extends Critter. A Bluster. Critter looks at all of the neighbors within two steps of its current location. (For a Bluster. Critter 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 Bluster. Critter’s color gets brighter (color values increase). If there are c or more critters, the Bluster. Critter’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 n 5. Create a class Quick. Crab that extends Crab. Critter. A Quick. Crab processes actors the same way a Crab. Critter does. A Quick. Crab 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 Quick. Crab moves like a Crab. Critter. n 6. Create a class King. Crab that extends Crab. Critter. A King. Crab gets the actors to be processed in the same way a Crab. Critter does. A King. Crab causes each actor that it processes to move one location further away from the King. Crab. If the actor cannot move away, the King. Crab removes it from the grid. When the King. Crab has completed processing the actors, it moves like a Crab. Critter.
Group Activity n Specify ¨ Create n a new creature that extends Critter Design ¨ What variables are needed? What algorithms are needed? n Code ¨ Implement n the code Test ¨ Write test cases for the creature specified