细胞生命游戏一维c语言,生命游戏 c语言实现

本世纪70年代,人们曾疯魔一种被称作“生命游戏”的小游戏,这种游戏相当简单。假设有一个像棋盘一样的方格网,每个方格中放置一个生命细胞,生命细胞只有两种状态:“生”或“死”。游戏规则如下:

1. 如果一个细胞周围有3个细胞为生(一个细胞周围共有8个细胞),则该细胞为生,即该细胞若原先为死,则转为生,若原先为生,则保持不变;

2. 如果一个细胞周围有2个细胞为生,则该细胞的生死状态保持不变;

3. 在其它情况下,该细胞为死,即该细胞若原先为生,则转为死,若原先为死,则保持不变设定图像中每个像素的初始状态后依据上述的游戏规则演绎生命的变化,由于初始状态和迭代次数不同,将会得到令人叹服的优美图案。

程序的算法:

设置两个二维数组,一个用于表示当前生命细胞的状态,另一个用于判断当前的细胞的下一个状态。

这个程序还能统计当前活着的细胞的个数:

程序如下:

/*lifegame.c*/

#include

#include

#include

#include

#define MAX 60

#define SIZE 5

void initG(); /*图形模式初始化*/

void closeG();/*关闭图形模式*/

void live(int col,int row);

void death(int col,int row);

void initG()

{

int gdriver=DETECT,gmode;

initgraph(&gdriver,&gmode,"d:\\tc");

cleardevice();

}

void closeG()

{

cleardevice();

settextstyle(1,0,5);

setcolor(BLUE);

outtextxy(80,50,"Programme Desiged:Y.Z.X");

outtextxy(80,160,"MAIL:yzx_xue@163.com");

outtextxy(200,330,"2006.5");

getch();

closegraph();

}

void live(int col,int row)

{

setcolor(WHITE);

setfillstyle(SOLID_FILL,WHITE);

bar(SIZE*(col+1)+1,SIZE*(row+1)+1,SIZE*(col+2)-1,SIZE*(row+2)-1);

}

void death(int col,int row)

{

setcolor(BLACK);

setfillstyle(SOLID_FILL,BLACK);

bar(SIZE*(col+1)+1,SIZE*(row+1)+1,SIZE*(col+2)-1,SIZE*(row+2)-1);

}

void table() {

int i;

setcolor(RED);

for(i=0;i<=MAX;i++)

{

line(SIZE*(i+1),SIZE,SIZE*(i+1),SIZE*(MAX+1));

line(SIZE,SIZE*(i+1),SIZE*(MAX+1),SIZE*(i+1));

}

}

void game()

{

int nrow,ncol,i,resData[MAX][MAX],ori[MAX][MAX];

int count;

char str[20];

/*if life is live color is balck*/

/*init the life*/

table();

for(nrow=0;nrow!=MAX;nrow++)

for(ncol=0;ncol!=MAX;ncol++)

{

ori[nrow][ncol]=1;

resData[nrow][ncol]=1;

}

for(i=0;i<=100;i++)

{

count=0;

for(nrow=1;nrow!=MAX;nrow++)

for(ncol=1;ncol!=MAX;ncol++)

{

if(resData[nrow][ncol]==1) live(nrow,ncol);

if(resData[nrow][ncol]==0) death(nrow,ncol);

count+=resData[nrow][ncol];

}

table();

delay(5000);

for(nrow=1;nrow

for(ncol=1;ncol

switch((ori[nrow-1][ncol-1]+ori[nrow-1][ncol]+ori[nrow-1][ncol+1]

+ori[nrow][ncol-1]+ori[nrow][ncol+1]

+ori[nrow+1][ncol-1]+ori[nrow+1][ncol]+ori[nrow+1][ncol+1]))

{

case 3: resData[nrow][ncol]=1;break;

case 2: resData[nrow][ncol]=ori[nrow][ncol]; break;

default: resData[nrow][ncol]=0;

}/*end switch*/

for(nrow=1;nrow!=MAX;nrow++)

for(ncol=1;ncol!=MAX;ncol++)

ori[nrow][ncol]=resData[nrow][ncol];

sprintf(str,"%d",count);

setcolor(RED);

rectangle(450,30,getmaxx(),200);

settextstyle(1,0,4);

outtextxy(455,40,"LIFE GAME");

outtextxy(455,100,"LIVE:");

setfillstyle(SOLID_FILL,BLACK);

bar(550,100,getmaxx()-5,140);

outtextxy(550,100,str);

}  /*end time for*/

}

void main()

{

initG();

game();

getch();

closeG();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值