生命游戏
问题描述:在一个环境中,有很多细胞,细胞的位置周围,上,下,左,右,左上,左下,右上,右下,八个方位
如果这个细胞周围存在一个及一个一下,则下一代会消失;
如果这个细胞周围存在四个及四个以上,则下一代会消失;
如果这个细胞周围存在两个或三个,则下一代保留;
如果这个位置,本来没用细胞,但是周围有三个细胞,则下一代满血复活;
----->>>请展示一代又一代的生存状况
附上代码;C++ 耶
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include<iostream>
using namespace std;
#define MAXROW 10
#define MAXCOL 25
#define DEAD 0
#define ALIVE 1
int map[MAXROW][MAXCOL], newmap[MAXROW][MAXCOL];
//初始生活环境
void init();
int neighbors(int, int);
//打印生活图
void outputMap();
void copyMap();
int main() {
int row, col;
char ans;
//初始生活状态,二维数组,存活细胞位置;
init();
while (1) {
outputMap();
for (row = 0; row < MAXROW; row++) {
for (col = 0; col < MAXCOL; col++) {
switch (neighbors(row, col)) {
case 0:
case 1:
case 4:
case 5:
case 6:
case 7:
case 8:
newmap[row][col] = DEAD;
break;
case 2:
newmap[row][col] = map[row][col];
break;
case 3:
newmap[row][col] = ALIVE;
break;
}
}
}
copyMap();
cout << "输入Y进入下一代,输入其他停止!";
cin >> ans;
if (ans != 'Y')
break;
}
return 0;
}
void init() {
int row, col;
//数组赋值
for (row = 0; row < MAXROW; row++)
for (col = 0; col < MAXCOL; col++)
map[row][col] = DEAD;
//输入存活细胞位置
cout << "欢迎来到生存游戏" << endl << "输入 x,y值确认初始生存的细胞位置" << endl;
printf("0 <= x <= %d, 0 <= y <= %d\n", MAXROW - 1, MAXCOL - 1);
cout << "输入-1 -1则停止输入" << endl;
while (1) {
cin >> row >> col;
if (0 <= row && row < MAXROW && 0 <= col && col < MAXCOL)
map[row][col] = ALIVE;
else if (row == -1 || col == -1)
break;
else
printf("(x, y) exceeds map ranage!");
}
}
int neighbors(int row, int col) {
int count = 0, c, r;
for (r = row - 1; r <= row + 1; r++)
for (c = col - 1; c <= col + 1; c++) {
if (r < 0 || r >= MAXROW || c < 0 || c >= MAXCOL)
continue;
if (map[r][c] == ALIVE)
count++;
}
if (map[row][col] == ALIVE)
count--;
return count;
}
void outputMap() {
int row, col;
printf("\n\n%20cGame of life cell status\n");
for (row = 0; row < MAXROW; row++) {
printf("\n%20c", ' ');
for (col = 0; col < MAXCOL; col++)
if (map[row][col] == ALIVE)
putchar('#');
else putchar('-');
}
}
void copyMap() {
int row, col;
for (row = 0; row < MAXROW; row++)
for (col = 0; col < MAXCOL; col++)
map[row][col] = newmap[row][col];
}