Java Reference
In-Depth Information
Code 10.2
continued
The
Fox
class
// See if it was possible to move.
if
(newLocation !=
null
) {
setLocation(newLocation);
}
else
{
// Overcrowding.
setDead();
}
}
}
/**
* Look for rabbits adjacent to the current location.
* Only the first live rabbit is eaten.
* @return Where food was found, or null if it wasn't.
*/
private
Location findFood()
{
List<Location> adjacent = field.adjacentLocations(location);
Iterator<Location> it = adjacent.iterator();
while
(it.hasNext()) {
Location where = it.next();
Object animal = field.getObjectAt(where);
if
(animal
instanceof
Rabbit) {
Rabbit rabbit = (Rabbit) animal;
if
(rabbit.isAlive()) {
rabbit.setDead();
foodLevel = RABBIT_FOOD_VALUE;
return
where;
}
}
}
return
null
;
}
//
other methods omitted
}
For foxes, the
hunt
method is invoked at each step and defines their behavior. In addition to aging
and possibly breeding at each step, a fox searches for food (using
findFood
). If it is able to find a
rabbit in an adjacent location, then the rabbit is killed and the fox's food level is increased. As with
rabbits, a fox that is unable to move is considered dead through overcrowding.
Exercise 10.13
As you did for rabbits, assess the degree to which we have simplified the model
of foxes and evaluate whether you feel the simplifications are likely to lead to an inaccurate simulation.
Search WWH ::
Custom Search