用c++写一个生命游戏代码,要求网格尺寸可以被设置,演变不停知道出发停止信号,使用以下自定义函数1.run()运行一代,2.display()展示最近的状态,3.init()初始化网格
时间: 2024-05-06 10:18:52 浏览: 5
以下是一个基本的 C++ 生命游戏代码,包含了所要求的自定义函数:
```c++
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
class GameOfLife {
public:
GameOfLife(int rows, int cols) :
rows_(rows), cols_(cols), cur_(rows, vector<int>(cols)), next_(rows, vector<int>(cols)) {}
void run() {
// 计算下一代细胞状态
for (int i = 0; i < rows_; ++i) {
for (int j = 0; j < cols_; ++j) {
int count = countNeighbors(i, j);
if (count == 3 || (cur_[i][j] == 1 && count == 2)) {
next_[i][j] = 1;
} else {
next_[i][j] = 0;
}
}
}
// 更新当前状态
cur_ = next_;
}
void display() {
for (int i = 0; i < rows_; ++i) {
for (int j = 0; j < cols_; ++j) {
cout << (cur_[i][j] == 1 ? "X" : "-") << " ";
}
cout << endl;
}
cout << endl;
}
void init() {
srand(time(nullptr));
for (int i = 0; i < rows_; ++i) {
for (int j = 0; j < cols_; ++j) {
cur_[i][j] = rand() % 2;
}
}
}
private:
int countNeighbors(int x, int y) {
int count = 0;
for (int i = -1; i <= 1; ++i) {
for (int j = -1; j <= 1; ++j) {
if (i == 0 && j == 0) continue;
int nx = x + i, ny = y + j;
if (nx >= 0 && nx < rows_ && ny >= 0 && ny < cols_) {
count += cur_[nx][ny];
}
}
}
return count;
}
int rows_;
int cols_;
vector<vector<int>> cur_;
vector<vector<int>> next_;
};
int main() {
int rows, cols;
cout << "请输入网格的行数和列数:";
cin >> rows >> cols;
GameOfLife game(rows, cols);
game.init();
game.display();
while (true) {
cout << "按任意键继续,输入 q 退出:";
char c;
cin >> c;
if (c == 'q' || c == 'Q') break;
game.run();
game.display();
}
return 0;
}
```
在该代码中,我们使用了一个二维向量来表示网格,其中 `cur_` 表示当前状态,`next_` 表示下一代状态。在 `run()` 函数中,我们计算了每个格子周围的细胞数量,并根据规则更新下一代状态,然后将 `next_` 赋值给 `cur_`,从而完成一次演化。在 `display()` 函数中,我们将当前状态打印出来。在 `init()` 函数中,我们随机初始化了网格。
程序运行时,会先要求用户输入网格的行数和列数,然后进行初始化,并展示当前状态。接下来,程序会进入一个无限循环,每次循环会等待用户按下任意键,然后计算并展示下一代状态。用户可以在任何时候输入 `q` 或 `Q` 退出程序。