运用C++类的功能编写康威生命游戏代码 规则: 每个细胞处于两种可能状态中的一种,活的或死的 每个细胞与它的8个邻居相互作用: 1. 任何活细胞如果邻居少于两个就会死亡。 2. 任何一个活的细胞,只要有两到三个活的邻居,就会延续到下一代。 3.任何有三个以上邻居的活细胞都会死到下一代。 4. 任何一个死去的细胞只要有恰好三个活着的邻居,就会成为一个活细胞,延续到下一代。 要求:1.用户能够自定义创建网格大小 2.用户可以在命令行中通过鼠标点击的方式自定义细胞的初始状态 3.用户可以随时暂停和恢复游戏的进程
时间: 2024-03-18 10:40:28 浏览: 51
以下是使用C++类实现康威生命游戏的代码,包括用户自定义网格大小,自定义细胞初始状态和暂停/恢复游戏进程功能。其中,使用了Windows API库中的GetAsyncKeyState函数来检测键盘输入状态,需要在Windows系统中运行。
```c++
#include <iostream>
#include <windows.h>
using namespace std;
const int MAX_ROW = 100;
const int MAX_COL = 100;
class GameOfLife {
private:
int row, col;
bool grid[MAX_ROW][MAX_COL], nextGrid[MAX_ROW][MAX_COL];
bool isPaused;
void initGrid() {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
grid[i][j] = false;
nextGrid[i][j] = false;
}
}
}
void updateGrid() {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
int count = 0;
for (int k = -1; k <= 1; k++) {
for (int l = -1; l <= 1; l++) {
if (k == 0 && l == 0) continue;
int r = i + k, c = j + l;
if (r < 0 || r >= row || c < 0 || c >= col) continue;
if (grid[r][c]) count++;
}
}
if (grid[i][j]) {
if (count < 2 || count > 3) nextGrid[i][j] = false;
else nextGrid[i][j] = true;
} else {
if (count == 3) nextGrid[i][j] = true;
else nextGrid[i][j] = false;
}
}
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
grid[i][j] = nextGrid[i][j];
}
}
}
void printGrid() {
system("cls");
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (grid[i][j]) cout << "O";
else cout << ".";
}
cout << endl;
}
}
void pauseGame() {
isPaused = true;
while (isPaused) {
if (GetAsyncKeyState(VK_RETURN)) {
isPaused = false;
break;
}
Sleep(100);
}
}
public:
GameOfLife(int r, int c) {
row = r;
col = c;
isPaused = false;
initGrid();
}
void setCell(int r, int c) {
if (r >= 0 && r < row && c >= 0 && c < col) {
grid[r][c] = true;
}
}
void runGame() {
while (true) {
if (GetAsyncKeyState(VK_SPACE)) pauseGame();
updateGrid();
printGrid();
Sleep(100);
}
}
};
int main() {
int r, c;
cout << "Please input the row and column of the grid:" << endl;
cin >> r >> c;
GameOfLife game(r, c);
cout << "Please click on the cells to set the initial status, press ENTER to start the game." << endl;
while (true) {
if (GetAsyncKeyState(VK_RETURN)) break;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (GetAsyncKeyState(VK_LBUTTON)) game.setCell(i, j);
}
}
Sleep(100);
}
game.runGame();
return 0;
}
```
在程序运行时,会先要求用户输入网格的行数和列数,然后用户可以通过鼠标点击来设置细胞的初始状态。当用户按下ENTER键后,游戏开始运行,每隔100毫秒刷新一次屏幕,并根据规则更新细胞状态。当用户按下空格键时,游戏进程暂停,直到用户再次按下ENTER键才恢复运行。
阅读全文