用c++编写生命游戏,要求可以设置网格大小,模拟运行,直到用户触发停止信号,所需的以下功能 1run0:执行一次生成 2Display:显示当前状态 3lnit:初始化网格
时间: 2024-03-21 13:43:52 浏览: 15
好的,我可以帮您解答这个问题。
生命游戏是一种模拟细胞生长和死亡的经典游戏,它可以用C++来实现。以下是一个简单的生命游戏的实现,包括了设置网格大小、模拟运行、停止信号、执行一次生成、显示当前状态和初始化网格的功能。
```c++
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <chrono>
#include <thread>
using namespace std;
// 定义细胞的状态
enum CellState {
DEAD = 0,
ALIVE = 1
};
// 定义细胞类
class Cell {
public:
CellState state;
Cell() {
state = DEAD;
}
};
// 定义生命游戏类
class GameOfLife {
private:
vector<vector<Cell>> grid; // 网格
int rows, cols; // 网格大小
bool running; // 是否正在运行
public:
GameOfLife(int rows, int cols) {
this->rows = rows;
this->cols = cols;
running = false;
// 初始化网格
grid.resize(rows, vector<Cell>(cols));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
grid[i][j] = Cell();
}
}
}
// 执行一次生成
void runOnce() {
vector<vector<Cell>> newGrid(rows, vector<Cell>(cols));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int neighbors = countNeighbors(i, j);
if (grid[i][j].state == ALIVE) {
if (neighbors < 2) {
newGrid[i][j].state = DEAD; // under-population
} else if (neighbors == 2 || neighbors == 3) {
newGrid[i][j].state = ALIVE; // survival
} else {
newGrid[i][j].state = DEAD; // over-population
}
} else {
if (neighbors == 3) {
newGrid[i][j].state = ALIVE; // reproduction
}
}
}
}
grid.swap(newGrid);
}
// 显示当前状态
void display() {
system("clear"); // 清空屏幕
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (grid[i][j].state == ALIVE) {
cout << "* ";
} else {
cout << ". ";
}
}
cout << endl;
}
}
// 初始化网格
void init() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
grid[i][j].state = rand() % 2 ? ALIVE : DEAD;
}
}
}
// 开始游戏
void start() {
running = true;
while (running) {
display();
runOnce();
this_thread::sleep_for(chrono::milliseconds(500)); // 休眠500毫秒
}
}
// 停止游戏
void stop() {
running = false;
}
private:
// 计算(i,j)周围细胞的数量
int countNeighbors(int i, int j) {
int count = 0;
for (int ii = -1; ii <= 1; ii++) {
for (int jj = -1; jj <= 1; jj++) {
if (ii == 0 && jj == 0) {
continue;
}
int ni = i + ii;
int nj = j + jj;
if (ni < 0 || ni >= rows || nj < 0 || nj >= cols) {
continue;
}
if (grid[ni][nj].state == ALIVE) {
count++;
}
}
}
return count;
}
};
int main() {
srand(time(nullptr)); // 初始化随机数种子
GameOfLife game(10, 10);
game.init();
game.start();
return 0;
}
```
以上是一个简单的生命游戏的实现,您可以根据自己的需求进行修改和扩展。