Part (a)
/** Looks ahead range locations in current direction
* @return the nearest fish in that direction within range (if any);
* null if no such fish is found
*/
private Fish findFish()
{
Environment env = environment();
Location loc = location();
for (int k = 0; k < range; k++)
{
loc = env.getNeighbor(loc, direction());
if (env.isValid(loc) && !env.isEmpty(loc))
return (Fish)env.objectAt(loc);
}
return null;
}
Part (b)
/** Acts for one step in the simulation
*/
public void act()
{
if (!isInEnv())
return;
Fish prey = findFish();
if (prey != null)
{
Location preyLoc = prey.location(); 1
prey.die();
changeLocation(preyLoc);
}
else
super.act();
}
Notes:
- Save prey's location before you kill the prey.
|