c++ - 在康威的人生游戏中分配迭代时间

标签 c++ conways-game-of-life

您好,我正在编写康威生命游戏的代码。我需要在这里分配 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 风格,请使用 usleep

不要忘记包含必要的 header 。

类似于:

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

关于c++ - 在康威的人生游戏中分配迭代时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39611539/

相关文章:

C++。 valgrind 输出 : Syscall param open(filename) points to unaddressable byte(s)

java - 生命游戏,方法行不通

c - 为什么将一个变量设置为它自己的地址会在不同的程序运行时产生不同的结果?

java - 为什么我返回的计数值错误?

c++ - 在编译时评估 strlen?

c++ - 错误 LNK2005 : "void __cdecl operator delete(void *)" (? ?3@YAXPAX@Z) 已在 LIBCMTD.lib(delete_scalar.obj) 中定义

c++ - 非标准语法,使用 & 创建指向成员的指针

c++ - DirectX 9 字体库?

c++ - 生命游戏 (C++) 的逻辑错误

c - 从函数返回一个二维数组到主函数