生命游戏

来源:互联网 发布:得力考勤机上传数据 编辑:程序博客网 时间:2024/06/08 06:23

说明:生命游戏为1970年英国数学家J.H.Conway所提出,某一细胞的邻居包括上、下、左、右、左上、左下、右上、右下,游戏规则如下:

孤单细胞死亡:如果细胞邻居小于一个,则该细胞在下一状态将死亡。

拥挤死亡:如果细胞的邻居在4个以上,则该细胞在下一状态将死亡。

稳定:如果细胞的邻居为二个或三个,则下一状态为稳定存活:

复活:如果某位置原无细胞存活,而该位置的邻居为3个,则该位置将复活一细胞。

 具体规则:

邻居为0、1、4、5、6、7、8时,则该细胞下次状态为死亡。

邻居个数为2时,则该细胞下次状态为复活。

邻居个数为3时,该细胞下次状态为稳定。

每次输出都是对称的图形

Ss 生命游戏(类似数字电路中的状态机)(读者看完tips之后请试着自己编写程序)

1.    设置两个二维数组map,newmap,分别代表上一状态和当前状态,newmap的值根据map(上一状态)来设置

2.    每当newmap完成并且输出之后,调用copy,将newmap复制到map中(状态机)

3.    注意考虑边界条件,不能超出边界访问。

4.    Case 语句实现更加便捷

#include<iostream>#include<string>#include<sstream>#include<fstream>using namespace std;const int live = 1;const int dead = 0;int cnt;int map[20][20];int newmap[20][20];void init();int neighbor(int row, int col);void print();void copy();int main(int argv,char**argc){cout << "set the initial state" << endl;cout << "ps:0<=row<=19,0<=col<=19,1 represents live,0 represents death" << endl;init();print();while (true){for (int i = 0; i < 20;i++)for (int j = 0; j < 20;j++)switch (neighbor(i, j)){case 0:case 1:case 4:case 5:case 6:case 7:case 8:newmap[i][j] = dead;break;case 2:newmap[i][j] = map[i][j];break;case 3:newmap[i][j] = live;break;}copy();print();char ch;cout << "continue or not" << endl;cin >> ch;if (ch == '#')break;}system("pause");return 0;}void init(){ifstream in("input.txt");for (int j = 0; j < 20; j++){string temp;getline(in, temp);stringstream str(temp);for (int i = 0; i < 20; i++)str >> map[j][i];}}int neighbor(int row, int col){int count = 0;for (int i = row - 1; i <= row + 1;i++)for (int j = col - 1; j <= col + 1; j++){if (i < 0 || i >= 20 || j < 0 || j >= 20)continue;if (map[i][j] == 1)count++;}if (map[row][col] == 1)count--;//if the(row,col)one is alive, total number will be minus//one,else the count is rightreturn count;}void print(){printf("No.%d time is:\n",++cnt);for (int i = 0; i < 20; i++){for (int j = 0; j < 20; j++)printf("%d ", map[i][j]);printf("\n");}}void copy(){for (int i = 0; i < 20;i++)for (int j = 0; j < 20; j++)map[i][j] = newmap[i][j];}


0 0
原创粉丝点击