用c语言编写细胞生命游戏
时间: 2024-01-18 17:01:11 浏览: 75
细胞生命游戏是一种模拟细胞繁衍与死亡的游戏,使用C语言可以很好地实现该游戏。下面是一个简短的示例代码:
```c
#include <stdio.h>
#define SIZE 10
#define ALIVE 'O'
#define DEAD ' '
// 检查指定位置的细胞状态
int checkCellStatus(int x, int y, char grid[][SIZE]) {
if (x < 0 || x >= SIZE || y < 0 || y >= SIZE) {
return 0;
}
return grid[x][y] == ALIVE ? 1 : 0;
}
// 计算周围活细胞数
int countAliveNeighbors(int x, int y, char grid[][SIZE]) {
int count = 0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (i == 0 && j == 0) {
continue;
}
count += checkCellStatus(x + i, y + j, grid);
}
}
return count;
}
// 更新细胞状态
void updateCellStatus(char grid[][SIZE]) {
char newGrid[SIZE][SIZE];
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
int aliveNeighbors = countAliveNeighbors(i, j, grid);
if (grid[i][j] == ALIVE) {
if (aliveNeighbors < 2 || aliveNeighbors > 3) { // 周围活细胞数小于2或大于3,细胞死亡
newGrid[i][j] = DEAD;
} else {
newGrid[i][j] = ALIVE;
}
} else {
if (aliveNeighbors == 3) { // 周围活细胞数为3,细胞复活
newGrid[i][j] = ALIVE;
} else {
newGrid[i][j] = DEAD;
}
}
}
}
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
grid[i][j] = newGrid[i][j];
}
}
}
// 输出当前细胞状态
void printGrid(char grid[][SIZE]) {
for (int i = 0; i < SIZE; i++) {
for (int j = 0; j < SIZE; j++) {
printf("%c ", grid[i][j]);
}
printf("\n");
}
printf("\n");
}
int main() {
char grid[SIZE][SIZE] = {
{ DEAD, DEAD, DEAD, DEAD, DEAD, DEAD, DEAD, DEAD, DEAD, DEAD },
{ DEAD, DEAD, DEAD, DEAD, ALIVE, DEAD, DEAD, DEAD, DEAD, DEAD },
{ DEAD, DEAD, DEAD, ALIVE, ALIVE, DEAD, DEAD, DEAD, DEAD, DEAD },
{ DEAD, DEAD, DEAD, DEAD, DEAD, ALIVE, DEAD, DEAD, DEAD, DEAD },
{ DEAD, DEAD, DEAD, ALIVE, DEAD, DEAD, DEAD, DEAD, DEAD, DEAD },
{ DEAD, DEAD, DEAD, DEAD, DEAD, DEAD, ALIVE, DEAD, DEAD, DEAD },
{ DEAD, DEAD, DEAD, DEAD, DEAD, DEAD, DEAD, DEAD, DEAD, DEAD },
{ DEAD, DEAD, DEAD, DEAD, ALIVE, DEAD, DEAD, DEAD, DEAD, DEAD },
{ DEAD, DEAD, DEAD, DEAD, DEAD, DEAD, ALIVE, DEAD, DEAD, DEAD },
{ DEAD, DEAD, DEAD, DEAD, DEAD, DEAD, DEAD, DEAD, DEAD, DEAD }
};
printf("初始状态:\n");
printGrid(grid);
for (int i = 0; i < 5; i++) { // 进行5次更新
updateCellStatus(grid);
printf("第%d次更新:\n", i+1);
printGrid(grid);
}
return 0;
}
```
以上代码定义了`SIZE`为细胞生命游戏的网格大小,使用`ALIVE`和`DEAD`表示细胞存活和死亡的状态。在`main`函数中,我们定义了一个初始状态的细胞网格,并进行了5次更新。更新使用`updateCellStatus`函数,该函数根据游戏规则计算新的细胞状态,并更新到原始网格。最后,我们使用`printGrid`函数打印当前的细胞状态。
这个示例代码只是一个简单的实现,你可以根据实际需求和规则,修改和优化代码。
阅读全文