Search code examples
c++conways-game-of-life

assign iteration time in conways game of life


Hi I am writing a code of Conway's game of Life. I need to assign 0.5 seconds iteration time here. The matrix should be updated in every 0.5 seconds. How to assign 0.5 second iteration time here? I thought of using a timer. But how to implement this? My code is as follows:

/*
 * pp1.cpp
 *
 *  Created on: 21.09.2016
 *      Author: fislam
 */
#include <iostream>
#include <string>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

using namespace std;

void copy(int array1[10][10],int array2[10][10])
{ for(int j=0;j<10;j++)
              {for(int i=0;i<10;i++)
                  array2[j][i]=array1[j][i];
              }
              }
void life(int array[10][10])
{ int temp[10][10];
copy (array,temp);
for (int j=0;j<10;j++)
  {      for (int i=0;i<1;i++)
      { int count=0;
      count=array[j-1][i]+
            array[j-1][i-1]+
            array[j][i-1]+
            array[j+1][i-1]+
            array[j+1][i]+
            array[j+1][i+1]+
            array[j][i+1]+
            array[j-1][i+1];
      if(count<2||count>3)
          temp[j][i]=0;
      if (count==2)
          temp[j][i]=array[j][i];
      if (count==3)
          temp[j][i]=1;



}
}copy (temp,array);
}
void print(int array[10][10])
{
    for(int j = 0; j < 10; j++)
    {
        for(int i = 0; i < 10; i++)
        {
            if(array[j][i] == 1)
                cout << '*';
            else
                cout << ' ';
        }
        cout << endl;
    }
}

Solution

  • Between two calls into life, insert a this_thread::sleep_for with a 500 miliseconds

    std::this_thread::sleep_for(std::chrono::milliseconds{500});
    

    If you prefer C-style, use usleep

    Don't forget to include the necessary headers.

    Something like:

    int main() {
      // how may iteration of 'life'
      const int MAX_ITER=100;
      int world[10][10];
    
      // set your world to the initial configuration
      // ....
    
      for(int i-0; i<MAX_ITER; i++) {
        life(world);
        print(world);
        // wait for half a second
        std::this_thread::sleep_for(std::chrono::milliseconds{500});
      } 
    }