经过了之前的学习,我们接下来进行的是对数组的学习应用——生命游戏。
简介
假设有 int Cells[50][50] 即划分出50 * 50的空间,
每个小格里有生命存活(1)或死亡(0),
通过把所有生命的状态(0或1)输出得到图案。
初始化
我们首先利用游戏框架将游戏初始化,输出静态的生命状态,其中定义二维数组int Cells[High][Width] 用于记录所有位置的生命状态。值为1时表示存活,值为0时表示死亡。
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <time.h>
// 界面尺寸
#define High 25
#define Width 50
//全局变量
int Cells[High][Width];
void gotoxy(int x, int y) //移动光标便于清屏重画
{
HANDLE handle = GetStdHandle(STD_UOTPUT_HANDLE);
CROOD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(handle, pos);
}
void startup() //数据初始化
{
int i,j;
for(i=0; i<High; i++) //首先随机为各小格赋值
{
for(j=0; j<Width; j++)
{
Cells[i][j] = rand() % 2;
}
}
}
void show() //显示画面
{
gotoxy(0, 0);
int i,j;
for(i=0; i<High; i++)
{
for(j=0; j<Width; j++)
{
if(Cells[i][j] == 1)
printf("*"); //存活
else
printf(" "); //死亡则不输出
}
printf("\n");
}
sleep(50); //适当休眠时间
}
void updateWithoutInput() //无输入更新部分
{}
void updateWithInput()
{}
int main()
{
startup();
while(1)
{
show();
updateWithoutInput();
updateWithInput();
}
return 0;
}
生死规则
游戏中生命目标存活或死亡的规则如下:
- 若其周围有3个存活细胞,则该细胞为生(死亡转为存活,存活本身不变)。
- 若其周围有2个存活细胞,生命状态不变。
- 除去前两种情况,该细胞死亡(存活转为死亡,死亡本身不变)。
生死更新
根据生命游戏的规则,我们做出相关更新:
void updateWithoutInput()
{
// 因为难以直接对原数组操作,所以我们使用中间变量。
int NewCells[High][Width]; //记录下一帧里生命状态
int NeibourNumber; //记录目标生命相邻存活生命数量
int i,j;
// 记录相邻生命时,不能从边界开始或在边界结束
for(i=1; i<=High-1; i++)
{
for(j=1; j<=Width-1; j++)
{
// 首先记录相邻8个细胞生命状态
NeibourNumber = Cells[i-1][j-1] +
Cells[i][j-1] + Cells[i+1][j-1] +
Cells[i-1][j] + Cells[i+1][j] +
Cells[i-1][j+1] + Cells[i][j+1] +
Cells[i+1][j+1]
if(NeibourNumber == 3)
NewCells[i][j] = 1;
else if(NeibourNumber == 2)
NewCells[i][j] = Cells[i][j];
else
NewCells[i][j] = 0;
}
}
//完成下一帧记录后,更新原数组
for(i=1; i<=High-1; i++)
{
for(j=1; j<=Width-1; j++)
Cells[i][j] = NewCells[i][j];
}
}
小结
以上我们实现了生命游戏的自动更新,当然我们也可以加入更多的规则,从而丰富游戏效果,以下内容供改进者参考:
- 规定特地区域,在这些区域内有特殊规则(如加速生长,暴毙等)。
- 使用键盘控制游戏,例如加速、暂停等。
- 增加生命目标,用不同字符表示等。
感谢浏览,点个赞再走吧