Note: GridWorld will not be featured on the 2015 and subsequent AP CS Exams.
BlusterCritter gets and processes actors differently than Critter; therefore, it must override getActors and processActors. Getting each location (or Actor, Critter, Rock, etc) within a specific number of spaces is commonly required on the AP Computer Science Free Response. The solution is always the same and is illustrated below. Each location is constructed using row and column values not known to be valid in the grid. As a result, the location must be checked for validity before the Actor at the location, if any, can be obtained from the grid.
Review the BlusterCritter solution with AP CS Tutor Brandon Horn.
BlusterCritter
public class BlusterCritter extends Critter { private int courage; public BlusterCritter(int c) { this.courage = c; } /** * Returns a list of actors within 2 steps */ public ArrayList<Actor> getActors() { ArrayList<Actor> actors = new ArrayList<Actor>(); Location myLoc = this.getLocation(); for (int row = myLoc.getRow() - 2; row <= myLoc.getRow() + 2; row++) { for (int col = myLoc.getCol() - 2; col <= myLoc.getCol() + 2; col++) { Location loc = new Location(row, col); if (this.getGrid().isValid(loc)) { Actor actorAtLoc = this.getGrid().get(loc); if (actorAtLoc != null && actorAtLoc instanceof Critter) actors.add(actorAtLoc); } } } actors.remove(this); return actors; } /** * Darkens if at least c actors in actors; otherwise, lightens */ public void processActors(ArrayList<Actor> actors) { if (actors.size() >= this.courage) this.setColor(this.getColor().darker()); else this.setColor(this.getColor().brighter()); } }
AP CS GridWorld Case Study Solutions |
Recommended Practice Problems |
I am sooo confused!! What does the this refer to after the constructor??
The keyword
this
always refers to the current object. In the BlusterCritter constructorthis.courage
refers to the instance fieldcourage
. In thegetActors()
method,this.getLocation()
runs thegetLocation()
method on the same BlusterCritter on whichgetActors()
was run. In both cases,this
could be omitted and the result would be the same.this
is often used to make the implicit parameter for a method clear; however, it is only required in a few cases.Thanks for this but I am still confused, every time I try to run this it never changes the color unless courage is 0? Why is this?
The color change is slight and can be difficult to see. Run getColor() before and after act() and check the return value. Setting the BlusterCritter’s color to black can also help since the lighter color is grey.