Note: GridWorld is no longer featured on the AP CS A Exam (since the 2015 Exam).
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
class
public class BlusterCritter extends Critter
{
private int courage;
public BlusterCritter(int c)
{
courage = c;
}
/**
* Returns a list of actors within 2 steps
*/
public ArrayList<Actor> getActors()
{
ArrayList<Actor> actors = new ArrayList<Actor>();
Location myLoc = 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 = 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)
setColor(getColor().darker());
else
setColor(getColor().brighter());
}
}