//生命游戏
2026-09-13 12:52:50
发布于:广东
//生命游戏,可在DEV C上运行
#include <bits/stdc.h>
#include <windows.h>
using namespace std;
const int WIDTH = 39;
const int HEIGHT = 39;
bool grid[HEIGHT][WIDTH];
bool nextGrid[HEIGHT][WIDTH];
// 设置光标位置
void gotoxy(int x, int y)
{
COORD pos;
pos.X = x;
pos.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
// 统计周围活着的邻居数量
int countNeighbor(int y, int x)
{
int cnt = 0;
for(int dy = -1; dy <= 1; dy++)
{
for(int dx = -1; dx <= 1; dx++)
{
if(dx == 0 && dy == 0) continue;
int ny = y + dy;
int nx = x + dx;
if(ny >= 0 && ny < HEIGHT && nx >=0 && nx < WIDTH)
{
if(grid[ny][nx]) cnt++;
}
}
}
return cnt;
}
// 生命游戏规则生成下一代
void computeNext()
{
for(int y = 0; y < HEIGHT; y++)
{
for(int x = 0; x < WIDTH; x++)
{
int n = countNeighbor(y,x);
if(grid[y][x])
{
// 活着:2?3邻居存活,否则死亡
nextGrid[y][x] = (n == 2 || n ==3);
}
else
{
// 死亡:恰好3个邻居复活
nextGrid[y][x] = (n == 3);
}
}
}
// 复制回grid
for(int y = 0; y < HEIGHT; y++)
{
for(int x = 0; x < WIDTH; x++)
{
grid[y][x] = nextGrid[y][x];
}
}
}
// 绘制画面
void draw()
{
gotoxy(0,0);
for(int y = 0; y < HEIGHT; y++)
{
for(int x = 0; x < WIDTH; x++)
{
if(grid[y][x])
cout << "●";
else
cout << "○";
}
cout << endl;
}
}
int main()
{
srand((unsigned)time(NULL));
// 随机初始化生命格子
for(int y = 1; y < HEIGHT; y++)
{
for(int x = 1; x < WIDTH; x++)
{
grid[y][x] = rand() % 2 == 0;
}
}
/*grid[2][1]=true;
grid[3][2]=true;
grid[1][3]=true;
grid[2][3]=true;
grid[3][3]=true;*/
// 隐藏控制台光标,看着更干净
CONSOLE_CURSOR_INFO cursorInfo;
cursorInfo.dwSize = 1;
cursorInfo.bVisible = FALSE;
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursorInfo);
while(true)
{
draw();
computeNext();
Sleep(0); // 停顿150毫秒,调大更慢,调小更快
}
return 0;
}
这里空空如也















有帮助,赞一个