生命游戏其实是一个零玩家游戏,英文名叫Game of Life,也称生命棋。它包括一个二维矩形世界,这个世界中的每个方格居住着一个活着的或死了的细胞。一个细胞在下一个时刻生死取决于相邻八个方格中活着的或死了的细胞的数量。如果相邻方格活着的细胞数量过多,这个细胞会因为资源匮乏而在下一个时刻死去;相反,如果周围活细胞过少,这个细胞会因太孤单而死去。
游戏的规则就是:当一个方格周围有2或3个活细胞时,方格中的活细胞在下一个时刻继续存活;即使这个时刻方格中没有活细胞,在下一个时刻也会“诞生”活细胞。在这个游戏中,还可以设定一些更加复杂的规则,例如当前方格的状况不仅由父一代决定,而且还考虑祖父一代的情况。你还可以作为这个世界的上帝,随意设定某个方格细胞的死活,以观察对世界的影响。
出于对称性考虑,矩阵最右边与最左边相邻,最上边与最下边相邻,这样整个矩阵就模拟了一个奇怪的“球体”。
代码如下
/*
* lifegame.cpp
* Copyright (C) 2014 - Jiang
*
* lifegame.cpp is free software; you can redistribute it and/or modify
* it under the terms of the Just-For-Fun Public License or How Casually License as published
*
* lifegame.cpp is distributed while I don't know whether it is useful.
*
* See the Just-For-Fun Public License for more details,
* BUT You may not receive a copy of the Just-For-Fun Public License
* along with lifegame.cpp. So, please see <http://www.ligelaige.com/just-for-fun/license/>.
*/
/*
* File Name: lifegame.cpp
* Operating Environment: ubuntu linux
* Author: Jiang
* Email: ligelaige@gmail.com
* Created Time: 2014-04-08 16:59:37.465070
*/
/*
* g++ lifegame.cpp -std=c++11 -o lifegame
*/
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cstdio>
using namespace std;
class Cell
{
public:
Cell (int row = 30, int col = 79, int num = 0) : RowLength(row), ColLength(col), count(num)//行 列 数据
{
cell = new int* [row];
cellSum = new int* [row];
for (int i = 0; i < RowLength; ++i)
{
cell[i] = new int[col];
cellSum[i] = new int [col];
for (int j = 0; j < ColLength; ++j)
{
cell[i][j] = 0;
cellSum[i][j] = 0;
}
}
int n = 0;
srand((int)time(0));
while (n < count)
{
int i = rand() % RowLength;
int j = rand() % ColLength;
n += ALIVE - cell[i][j];
cell[i][j] = ALIVE;
}
}
int OutCell()
{
cout << "the num of cell: " << count << endl;
char status[2][5] = {"○ ", "● "};
for (int i = 0; i < RowLength; ++i)
{
for (int j = 0; j < ColLength; ++j)
{
cout << status[cell[i][j]];
LinSum(i, j);
}
cout << "\n";
}
return count;
}
void CellFunc()
{
count = 0;
for(int row = 0; row < RowLength; ++row)
{
for(int col = 0; col < ColLength; ++col)
{
cell[row][col] = cellSum[row][col]==2 ? cell[row][col] :
cellSum[row][col]==3 ? ALIVE : DEAD;
count += cell[row][col];
}
}
}
private:
const int DEAD = 0;
const int ALIVE = 1;
int RowLength, ColLength, count;
int** cell;
int** cellSum;
void LinSum(int row, int col)
{
int count = 0;
for (int r = row-1; r < row+2; ++r)
{
for (int c = col-1; c < col+2; ++c)
{
count += cell[(r+RowLength) % RowLength][(c+ColLength) % ColLength];
}
}
cellSum[row][col] = count - cell[row][col];
}
};
int main (void)
{
int row = 30,col = 70;
int count = row * col / 4;
Cell cell = Cell(row, col, count);
do
{
count = cell.OutCell();
cell.CellFunc();
getchar();
}while (count > 3);
return 0;
}
补充
C#版完整代码下载 http://download.csdn.net/detail/huangjinqiang/7168363