C++用类和对象实现生命游戏 运行时可以暂停 在终端页面修改细胞状态
时间: 2024-03-21 12:43:01 浏览: 18
好的,让我来解答你的问题。
生命游戏是一种由英国数学家约翰·何顿·康威发明的细胞自动机。在这个游戏中,每个细胞都有两种状态:生或死。游戏的规则是:如果一个细胞周围有三个活细胞,则该细胞变成活细胞,如果一个细胞周围有两个或三个活细胞,则该细胞维持原样,否则该细胞死亡。这个游戏的规则简单,但是它能够产生出复杂的模式,甚至能够模拟生命的进化。
下面是一个用 C++ 类和对象实现生命游戏的例子。这个例子可以在运行时暂停,并且可以在终端页面修改细胞的状态。
```cpp
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
using namespace std;
const int MAXN = 100;
class LifeGame {
public:
LifeGame(int _n, int _m);
void show();
void update();
void run();
private:
int n, m;
int g[MAXN][MAXN], ng[MAXN][MAXN];
bool pause;
};
LifeGame::LifeGame(int _n, int _m) : n(_n), m(_m), pause(false) {
srand(time(0));
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
g[i][j] = rand() % 2;
}
}
}
void LifeGame::show() {
printf("\033[2J\033[1;1H"); // 清屏
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
if (g[i][j] == 1) {
cout << "*";
} else {
cout << " ";
}
}
cout << endl;
}
}
void LifeGame::update() {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
int cnt = 0;
for (int dx = -1; dx <= 1; ++dx) {
for (int dy = -1; dy <= 1; ++dy) {
int ni = i + dx, nj = j + dy;
if (ni < 0 || ni >= n || nj < 0 || nj >= m) {
continue;
}
if (dx == 0 && dy == 0) {
continue;
}
cnt += g[ni][nj];
}
}
if (g[i][j] == 0 && cnt == 3) {
ng[i][j] = 1;
} else if (g[i][j] == 1 && (cnt == 2 || cnt == 3)) {
ng[i][j] = 1;
} else {
ng[i][j] = 0;
}
}
}
memcpy(g, ng, sizeof(g));
}
void LifeGame::run() {
while (true) {
if (!pause) {
show();
update();
}
char c = getchar();
if (c == 'q') {
break;
} else if (c == 'p') {
pause = !pause;
} else if (c == ' ') {
int i, j;
cin >> i >> j;
g[i][j] = (g[i][j] == 0 ? 1 : 0);
}
}
}
int main() {
LifeGame game(30, 80);
game.run();
return 0;
}
```
这个程序中,我们定义了一个 `LifeGame` 类,其中包含了游戏的基本功能。在构造函数中,我们随机生成了一个 `n` 行 `m` 列的细胞地图。`show` 函数用于显示当前的细胞地图,`update` 函数用于更新细胞地图,`run` 函数用于运行游戏。在 `run` 函数中,我们使用了 `getchar` 函数来读取用户输入的命令。当用户输入 `q` 时,程序退出;当用户输入 `p` 时,程序暂停或恢复;当用户输入空格时,程序将会读取两个整数 `i` 和 `j`,并将 `(i, j)` 这个位置的细胞状态取反。
这个程序使用了 ANSI Escape Code 来实现终端页面的清屏功能。如果你的终端不支持 ANSI Escape Code,你可以将 `show` 函数中的第一行注释掉,这样程序就不会清屏了。