Eco Simulation  «Prev  Next»
Lesson 5 Lifeform interaction rules
Objective Write a version of next() for empty squares that is based on the lifeform interactions defined in other versions of next().

Lifeform interaction rules

The rules in the different versions of next() determine a set of interactions between the lifeforms. In this example, we are keeping the interactions purposely simple. We use the array type world as a container for the lifeforms. We will look at how world is initialized and updated in the next lesson.

Grass

Grass can be eaten by rabbits. If there is more grass than rabbits in the neighborhood the grass remains; otherwise, the grass is eaten up:
living* grass::next(world w)
{
   int  sum[STATES];
    
   sums(w, sum);
   if (sum[GRASS] > sum[RABBIT]) //eat grass
      return (new grass(row, column));
   else
      return (new empty(row, column));
}

Rabbits


Rabbits die of old age if they exceed some defined limit DRAB. In addition, rabbits can be eaten if there is an appropriate number of foxes in the neighborhood:
living* rabbit::next(world w)
{
   int  sum[STATES];

   sums(w, sum);
   if (sum[FOX] >= sum[RABBIT] )  //eat rabbits
      return (new empty(row, column));
   else if (age > DRAB)           //rabbit too old
      return (new empty(row, column));
   else
      return (new rabbit(row, column, age + 1));
}

Behavior of Foxes

Foxes can die of overcrowding, or they die of old age if they exceed some defined limit DFOX:

living* fox::next(world w)
{
   int  sum[STATES];
    
   sums(w, sum);
   if (sum[FOX] > 5)           //too many foxes
      return (new empty(row, column));
   else if (age > DFOX)        //fox is too old
      return (new empty(row, column));
   else
      return (new fox(row, column, age + 1));
}
The rules in the different versions of next() determine a possibly complex set of interactions. Of course, to make the simulation more interesting, other behaviors, such as sexual reproduction, where the animals have gender and can mate, should be simulated.
There is another version of next() where we need one for empty squares.

next empty Squares - Exercise

Click the Exercise link below to write a version of next() that determines how to fill an empty square in the simulation.
next empty Squares - Exercise