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
public void simulateOneStep()
// 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 =;;
if (!rabbit.isAlive()) {
// 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 =;
if (!fox.isAlive()) {
// Add the newly born foxes and rabbits to the main lists.
view.showStatus(step, field);
Search WWH ::

Custom Search