C语言版生命游戏

xiaoxiao2021-02-27  176

/********************************************************************************************** ** 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"); } }
转载请注明原文地址: https://www.6miu.com/read-12173.html

最新回复(0)