C語言版生命遊戲

/**********************************************************************************************
** C語言模擬生命遊戲(原細胞自動機)
**
** 每個細胞有兩種狀態-存活或死亡,每個細胞與以自身爲中心的周圍八格細胞產生互動。
** 當前細胞爲存活狀態時,當週圍低於2個(不包含2個)存活細胞時, 該細胞變成死亡狀態。(模擬生命數量稀少)
** 當前細胞爲存活狀態時,當週圍有2個或3個存活細胞時, 該細胞保持原樣。
** 當前細胞爲存活狀態時,當週圍有3個以上的存活細胞時,該細胞變成死亡狀態。(模擬生命數量過多)
** 當前細胞爲死亡狀態時,當週圍有3個存活細胞時,該細胞變成存活狀態。 (模擬繁殖)
**
************************************************************************************************/


#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

#define SIZE	16							//地圖數組的長度
#define Death	printf("%c%c",0xA1,0xF5)	//死亡方塊
#define Live	printf("%c%c",0xA1,0xF6)	//存活方塊

boolean map_b[SIZE+2][SIZE+2] = {0};
void display(const int map[SIZE + 2][SIZE + 2]);
void transform(const int map[SIZE + 2][SIZE + 2]);


int main(int argc, char** argv) {

	int map[SIZE + 2][SIZE + 2] = { 0 };
	int *map_p = map;
	int count = 0;
	map[4][4] = map[4][5] = map[4][6] = map[3][6] = map[2][5] = 1;

	while (1)
	{
		printf("            第%d代\n", count++);
		display(map_p);
		Sleep(200);		//休眠 
		transform(map_p);	//爲什麼這裏不能填數組,而是填數組名
		system("cls");		//清屏 
	}
	system("pause");		//暫停
	return 0;
}


/*改變狀態*/
void transform(int map[SIZE + 2][SIZE + 2])
{
	int w, h, sum;
	sum = 0;
	int map_t[SIZE + 2][SIZE + 2] = {0};

	for (w = 1; w <= SIZE; w++)
		for (h = 1; h <= SIZE; h++)
			map_t[w][h] = map[w][h];

	for (w = 1; w <= SIZE; w++){

		for (h = 1; h <= SIZE; h++){

			sum = map_t[w - 1][h - 1] + map_t[w - 1][h] + map_t[w - 1][h + 1]
				+ map_t[w][h - 1] + map_t[w][h + 1]
				+ map_t[w + 1][h - 1] + map_t[w + 1][h] + map_t[w + 1][h + 1];

			switch (sum)
			{
			case 2:
				break;
			case 3:
				if (map_t[w][h] == 0)
					map[w][h] = 1;
				break;
			default:
				map[w][h] = 0;
				break;

			}
		}
	}
}


/*顯示*/
void display(const int map[SIZE + 2][SIZE + 2]){

	int w, h;
	
	for (w = 1; w <= SIZE; w++){
		for (h = 1; h <= SIZE; h++){
			if (map[w][h] == 1)
				Live;
			else
				Death;
		}
		printf("\n");
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章