⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 life.c

📁 生命游戏
💻 C
字号:
#include "base.h"


typedef struct{
	int b;
	int n;
}Life;
Life lifenode[MAXSIZE+2][MAXSIZE_Y+2];

void InitLife();
void ShowLife(Life [][MAXSIZE_Y+2]);
void ShowEndMenu();
int Count(Life [][MAXSIZE_Y+2],int,int);

void main()
{
	int q=0;
	int gener=1;
	char ch[MAXSIZE];

	InitLife();	
	do{
	
		printf("Generation: %3d\n",gener);
		ShowLife(lifenode);
		printf("Do you want to see the next generation?(Y/N)?");
		scanf("%s",&ch);
		if (ch[0]=='N'||ch[0]=='n')
			q=1;
		gener++;
		system("cls");	
	}while(!q);
	ShowEndMenu();
}

void InitLife()
{
	FILE *fp;
	char filename[MAXSIZE];
	int x=1,y=1;
	char ch;

	printf("Please input the file name:");
	scanf("%s",filename);
	if ((fp=fopen(filename,"r"))==NULL){
		printf("read file error!\n");
		exit(OVERFLOW);
	}
	
	for (x=0;x<MAXSIZE+2;x++){
		lifenode[x][0].b=lifenode[x][0].n=0;
		lifenode[x][21].b=lifenode[x][21].n=0;
	}
	for (y=0;y<MAXSIZE_Y;y++){
		lifenode[0][y].b=lifenode[0][y].n=0;
		lifenode[MAXSIZE+1][y].b=lifenode[MAXSIZE+1][y].n=0;
	}
	for (x=1;x<=MAXSIZE;x++)
		for (y=1;y<=MAXSIZE_Y;y++)
			lifenode[x][y].n=0;
	
		x=1,y=1;
	while ((ch=fgetc(fp))!=EOF){
		switch (ch){
		case 'x':
			lifenode[x][y].n=1;
			x++;
			break;
		case 10:
			lifenode[x][y].n=0;
			x=1;
			y++;
			break;
		default:
			x++;
		}
	}

	fclose(fp);
}

void ShowLife(Life [][MAXSIZE_Y+2])
{
	int x,y;
	int n;

	for (y=1;y<=MAXSIZE_Y;y++){
		for (x=1;x<=MAXSIZE;x++){
			if (lifenode[x][y].n)
				putchar('x');
			else 
				putchar(' ');
			lifenode[x][y].b = lifenode[x][y].n;
			n=Count(lifenode,x,y);
			switch (n){
			case 3:
				lifenode[x][y].n = 1;
				break;
			case 2:
				lifenode[x][y].n = lifenode[x][y].b;
				break;
			default:
				lifenode[x][y].n = 0;
			}	
		}
		printf("\n");
	}

}

void ShowEndMenu()
{
	printf("\t\t*********************************\n");
	printf("\t\t*Thanks you to use my program!  *\n");
	printf("\t\t*All Copyright Reserved  2004--4*\n");
	printf("\t\t*********************************\n");
}

int Count(Life [][MAXSIZE_Y+2],int x,int y)
{
	int n;
	n = lifenode[x-1][y-1].b+lifenode[x][y-1].b+lifenode[x+1][y-1].b
	   +lifenode[x-1][y].b+lifenode[x+1][y].n 
	   +lifenode[x-1][y+1].n+lifenode[x][y+1].n+lifenode[x+1][y+1].n;
	return n;	
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -