game of life cpp代码
时间: 2024-06-09 19:06:42 浏览: 119
game_of_life.zip_game of life_game of life java_game_of_life_lif
以下是Game of Life的C++代码示例:
```cpp
#include <iostream>
#include <vector>
#include <chrono>
#include <thread>
#include <cstdlib>
using namespace std;
class GameOfLife {
private:
vector<vector<int>> grid;
int rows, columns;
public:
GameOfLife(int r, int c) : rows(r), columns(c) {
grid.resize(rows, vector<int>(columns, 0));
}
void initialize() {
srand(time(NULL));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
grid[i][j] = rand() % 2;
}
}
}
int getNeighbourCount(int row, int col) {
int count = 0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
int r = row + i;
int c = col + j;
if (r >= 0 && r < rows && c >= 0 && c < columns && !(i == 0 && j == 0)) {
count += grid[r][c];
}
}
}
return count;
}
void nextGeneration() {
vector<vector<int>> newGrid(rows, vector<int>(columns, 0));
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
int neighbourCount = getNeighbourCount(i, j);
if (grid[i][j] == 0 && neighbourCount == 3) {
newGrid[i][j] = 1;
} else if (grid[i][j] == 1 && (neighbourCount == 2 || neighbourCount == 3)) {
newGrid[i][j] = 1;
} else {
newGrid[i][j] = 0;
}
}
}
grid = newGrid;
}
void print() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
if (grid[i][j] == 1) {
cout << "* ";
} else {
cout << ". ";
}
}
cout << endl;
}
}
};
int main() {
int rows = 40, columns = 40;
GameOfLife gol(rows, columns);
gol.initialize();
while (true) {
gol.print();
gol.nextGeneration();
this_thread::sleep_for(chrono::milliseconds(100));
system("clear");
}
return 0;
}
```
此代码实现了一个Game of Life模拟器,它使用随机值初始化单元格,并在每次迭代中计算每个单元格周围的邻居数量,然后使用规则进行更新。最后,它在控制台中打印游戏板并在每次迭代后清除屏幕。
阅读全文