Note: GridWorld is no longer featured on the AP CS A Exam (since the 2015 Exam).

KingCrab processes actors differently than CrabCritter; therefore, it must override processActors. Overriding the correct methods and adhering to the postconditions of the superclass methods is commonly required on the AP Computer Science Free Response. KingCrab must push actors farther away from itself if possible. This can be accomplished by checking whether the distance between the KingCrab and each possible new location, surrounding empty locations, is greater than one. This works because the getActors method in CrabCritter returns only neighboring actors.

Review the KingCrab solution with AP CS Tutor Brandon Horn.

KingCrab class

public class KingCrab extends CrabCritter
{
    /**
     * Moves each actor farther away. Eats actor if can't be moved
     */
    public void processActors(ArrayList<Actor> actors)
    {
        for (Actor actor : actors)
            if ( ! scare(actor) )
                actor.removeSelfFromGrid();
    }

    /**
     * Moves actor one location farther away if possible.
     * 
     * @return true if actor was moved, false otherwise
     */
    private boolean scare(Actor actor)
    {
        for (Location loc : getGrid().getEmptyAdjacentLocations(actor.getLocation()))
        {
            if (distance(loc) > 1)
            {
                actor.moveTo(loc);
                return true;
            }
        }

        return false;
    }

    /**
     * Returns the distance from this KingCrab to loc.
     */
    private double distance(Location loc)
    {
        return Point2D.distance(
                getLocation().getRow(), getLocation().getCol(),
                loc.getRow(), loc.getCol());
    }
}