Java Reference
In-Depth Information
10.2.5 The Simulator class: a simulation step
The central part of the Simulator class is the simulateOneStep method shown in
Code 10.4. It uses separate loops to let each type of animal move (and possibly breed or do
whatever it is programmed to do). Because each animal can give birth to new animals, lists
for these to be stored in are passed as parameters to the hunt and run methods of Fox and
Rabbit . The newly born animals are then added to the master lists at the end of the step.
Running longer simulations is trivial. To do this, the simulateOneStep method is called
repeatedly in a simple loop.
In order to let each animal act, the simulator holds separate lists of the different types of ani-
mals. Here, we make no use of inheritance, and the situation is reminiscent of the first version
of the network project introduced in Chapter 8.
Code 10.4
Inside the Simulator
class: simulating one
step
public void simulateOneStep()
{
step++;
// Provide space for newborn rabbits.
List<Rabbit> newRabbits = new ArrayList<Rabbit>();
// Let all rabbits act.
for (Iterator<Rabbit> it = rabbits.iterator(); it.hasNext(); ) {
Rabbit rabbit = it.next();
rabbit.run(newRabbits);
if (!rabbit.isAlive()) {
it.remove();
}
}
// Provide space for newborn foxes.
List<Fox> newFoxes = new ArrayList<Fox> ();
// Let all foxes act.
for (Iterator<Fox> it = foxes.iterator(); it.hasNext(); ) {
Fox fox = it.next();
fox.hunt(newFoxes);
if (!fox.isAlive()) {
it.remove();
}
}
// Add the newly born foxes and rabbits to the main lists.
rabbits.addAll(newRabbits);
foxes.addAll(newFoxes);
view.showStatus(step, field);
}
 
Search WWH ::




Custom Search