在生活游戏中分配迭代时间

assign iteration time in conways game of life

本文关键字:迭代 时间 分配 生活 游戏      更新时间:2023-10-16

大家好,我在写康威人生游戏的代码。我需要在这里分配0.5秒的迭代时间。矩阵应该每0.5秒更新一次。如何在这里分配0.5秒的迭代时间?我想用计时器。但是如何实现呢?我的代码如下:

/*
 * 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;
    }
}

在两次对life的调用之间,插入一个this_thread::sleep_for,时间间隔为500毫秒

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

如果你喜欢c风格,使用ussleep

不要忘记包含必要的标题。

类似:

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});
  } 
}