Eco Simulation  «Prev  Next»
Lesson 6Initializing and displaying the simulation
ObjectiveWrite two functions for the main() function of the simulation--one to generate an initial world and one to display the world.

Initialize C++ Display Simulation

The array type world is a container for the lifeforms. The container will have the responsibility of creating its current pattern. It needs to have ownership of the living objects so as to allocate new ones and delete old ones.
Notice that in the update() function below, we are ignoring the complications caused by the borders of the world. In this simple simulation, we are keeping a 1-square border all around the world that is always empty.

//world is all empty
void init(world w)
{
 int  i, j;

 for (i = 0; i < N; ++i)
  for (j = 0; j < N; ++j)
   w[i][j] = new empty(i,j);
}

//new world w_new computed from old world w_old
void update(world w_new, world w_old)
{
 int  i, j;

 for (i = 1; i < N - 1; ++i)  //borders are taboo
  for (j = 1; j < N - 1; ++j)
   w_new[i][j] = w_old[i][j] -> next(w_old);
}

//clean world up
void dele(world w)
{
 int  i, j;

 for (i = 1; i < N - 1; ++i)
  for (j = 1; j < N - 1; ++j)
   delete(w[i][j]);
}

main() method

The simulation will have odd and even worlds, which alternate as the basis for the next cycle's calculations. Here is main() for our simple ecological simulation:
int main()
{
world  odd, even;
int    i;

init(odd);  init(even);

//initialize inside world to non-empty types
eden(even);         //generate initial world
pr_state(even);      //display garden of eden state

for (i = 0; i < CYCLES; ++i) {  //simulation
if (i % 2) {
update(even, odd);
pr_state(even);
dele(odd);
}
else {
update(odd, even);
pr_state(odd);
dele(even);
}
}
return 0;
}

Initialize Display Simulation - Exercise

Click the Exercise link below to write the eden() and the pr_state() functions.
Initialize Display Simulation - Exercise