生命游戏就是最简单的元胞自动机之一——在二维平面上的方格子(细胞),每个细胞有两种状态:死或活,而下一回合的状态完全受它周围8个细胞的状态而定。按照以下三条规则进行演化:
- 活细胞周围的细胞数如果小于2个或多于3个则会死亡;(离群或过度竞争导致死亡)
- 活细胞周围如果有2或3个细胞可以继续存活;(正常生存)
- 死细胞(空格)周围如果恰好有3个细胞则会诞生新的活细胞。(繁殖)
#include <graphics.h>
#include <conio.h>
#include <iostream>
const int HEIGH = 120, WIDTH = 160, BLOCK_SIZE = 5;//高度、宽度和每个方格大小
int Blocks[HEIGH][WIDTH];//用1表示有细胞,0表示无细胞
int oldBlocks[HEIGH][WIDTH];
int dx[] = { -1,-1,-1,0,0,1,1,1 }, dy[] = { -1,0,1,-1,1,-1,0,1 };
void Start1() {
for (int i = 1; i < HEIGH; i++) {
for (int j = 1; j < WIDTH; j++) {
int t = rand();
if (t % i == 0 ||t % j == 0|| t%5==0 || t%7==0)
Blocks[i][j] = 1;
}
}
}
void Start2() {
Blocks[50][50] = Blocks[50][51] = Blocks[50][52] = 1;
}
void start() {//初始化函数
srand(time(NULL));
Start1();
initgraph(WIDTH * BLOCK_SIZE, HEIGH * BLOCK_SIZE);
setlinecolor(RGB(200,200,200));
BeginBatchDraw();
}
void show() {//刷新图画
if (_kbhit()&&_getch()==' ') {//按空格暂停
char a;
while (a = _getch()) {
if (a == ' ') break;
}
}
for (int j = 0; j < WIDTH; j++) for (int i = 0; i < HEIGH; i++) {
if (Blocks[i][j]) setfillcolor(GREEN);
else setfillcolor(WHITE);
fillrectangle(j * BLOCK_SIZE, i * BLOCK_SIZE, (j + 1) * BLOCK_SIZE, (i + 1) * BLOCK_SIZE);
}
FlushBatchDraw();
}
bool nextTime(int x,int y) {//返回(x,y)下一时刻状态
int sum = 0, tx, ty;
for (int i = 0; i < 8; i++) {
tx = x + dx[i];
ty = y + dy[i];
if (tx >= 0 && tx < HEIGH && ty >= 0 && ty < WIDTH && oldBlocks[tx][ty]) sum++;
}
if (sum == 3) return true;
else if (sum == 2 && oldBlocks[x][y]) return true;
else return false;
}
void update() {//间隔一段时间更新数组值
Sleep(10);
memcpy(oldBlocks, Blocks, sizeof(Blocks));
for (int i = 0; i < HEIGH; i++) {
for (int j = 0; j < WIDTH; j++) {
if (nextTime(i, j)) Blocks[i][j] = 1;
else Blocks[i][j] = 0;
}
}
}
int main()
{
start();
while (1) {
show();
update();
}
return 0;
}