生命游戏

生命游戏又称为元胞自动机,模拟自然界里的生物进化,在自然界中,一个孢子需要一定的生活资源,如果周围的孢子为2个,则维持原状,如果为3个则孢子复活,为他情况则改孢子死亡。元胞自动机在GIS行业中应用很广泛,可以模拟自然界中的进化现象。
#include <math.h>
#include <ctype.h>
int Cell[10][10];int Temp[10][10]; //定义原细胞与临时细胞

void Init()
{
	for(int Row=0;Row<10;Row++)
	{
		for(int Col=0;Col<10;Col++)
		{
			Cell[Row][Col]=0;   //初始化原细胞存活状态,开始为0,为死亡状态
			Temp[Row][Col]=0;   //  初始化临时细胞存活状态,开始为0,为死亡状态

		}
	}
}

void OutPut()                                   //打印输出
{
	for(int Row=0;Row<10;Row++)
	{
		for(int Col=0;Col<10;Col++)
		{
			if(Cell[Row][Col]==1)
				printf("A");
			else
				printf(" ");
		}
		printf("\n");
	}
	
}

void InPut()            //输入
{
    while(1)
	{
		int Row,Col;
		scanf_s("%d %d",&Row,&Col);
		if(0<=Row&&Row<10&&0<=Col&&Col<10)
			Cell[Row][Col]=1;			
		else if(Row==-1&&Col==-1)
			break;
		else		
			printf("请输入正确的坐标");			
	}
}

int CalcNum(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>=10||j<0||j>=10)
				continue;
			if(Cell[i][j]==1)
				Count++;
		}
	}
	if(Cell[Row][Col]==1)
		Count--;               //如果原来本身存活,则需要减一,因为是判断该细胞周围的细胞数量
	return Count;
}

void CopyCell()                        //输出一次就需要保存一次状态,为下一次变化做准备
{
	int row, col;
	for (row = 0; row < 10; row++)
		for (col = 0; col < 10; col++)
			Cell[row][col]=Temp[row][col];
}

int main()
{
	Init();
	InPut();
	while(1)
	{
		OutPut();
		for(int Row=0;Row<10;Row++)
		{
			for(int Col=0;Col<10;Col++)
			{
				switch(CalcNum(Row,Col))      //计算周围细胞数量
				{
					case 0:
					case 1:
					case 4:
					case 5:
					case 6:
					case 7:
					case 8:
						Cell[Row][Col]=0;
						break;
					case 2:
						Cell[Row][Col]=Temp[Row][Col];
						break;
					case 3:
						Cell[Row][Col]=1;
						break;								
				}
			}
		}	
		CopyCell();
		getchar();
		int ans = toupper(getchar());
		if (ans != 'y')
			break;
	}
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值