1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
#include <iostream> #include <vector> #include <iomanip> const int WIDTH = 10; const int HEIGHT = 10; // CellularAutomaton class class CellularAutomaton { public: std::vector<std::vector<bool>> grid; std::vector<std::vector<bool>> nextGrid; CellularAutomaton() : grid(HEIGHT, std::vector<bool>(WIDTH, false)), nextGrid(HEIGHT, std::vector<bool>(WIDTH, false)) {} void setCell(int x, int y, bool alive) { if (x >= 0 && x < WIDTH && y >= 0 && y < HEIGHT) { grid[y][x] = alive; } } void printGrid() const { for (const auto& row : grid) { for (bool cell : row) { std::cout << (cell ? '*' : '.') << ' '; } std::cout << std::endl; } std::cout << std::endl; } void update() { for (int y = 0; y < HEIGHT; ++y) { for (int x = 0; x < WIDTH; ++x) { int aliveNeighbors = countAliveNeighbors(x, y); if (grid[y][x]) { nextGrid[y][x] = (aliveNeighbors == 2 || aliveNeighbors == 3); } else { nextGrid[y][x] = (aliveNeighbors == 3); } } } grid = nextGrid; } private: int countAliveNeighbors(int x, int y) const { int count = 0; for (int dy = -1; dy <= 1; ++dy) { for (int dx = -1; dx <= 1; ++dx) { if (dx == 0 && dy == 0) continue; int nx = x + dx; int ny = y + dy; if (nx >= 0 && nx < WIDTH && ny >= 0 && ny < HEIGHT && grid[ny][nx]) { ++count; } } } return count; } }; int main() { CellularAutomaton automaton; // Initialize some cells automaton.setCell(4, 1, true); automaton.setCell(4, 2, true); automaton.setCell(4, 3, true); // Print initial state std::cout << "Initial State:" << std::endl; automaton.printGrid(); // Update and print the grid multiple times for (int i = 0; i < 5; ++i) { automaton.update(); std::cout << "Generation " << (i + 1) << ":" << std::endl; automaton.printGrid(); } return 0; } |
Explanation:
- CellularAutomaton Class:
grid
: The current state of the grid, where each cell can be eithertrue
(alive) orfalse
(dead).nextGrid
: The grid that will hold the state of the cells after the update.setCell(int x, int y, bool alive)
: Sets the state of a specific cell.printGrid() const
: Prints the current state of the grid, using ‘*’ for alive cells and ‘.’ for dead cells.update()
: Computes the next state of the grid based on the rules of Conway’s Game of Life.countAliveNeighbors(int x, int y) const
: Counts the number of alive neighbors surrounding a given cell.
- Main Function:
- Creates a
CellularAutomaton
object. - Initializes some cells to be alive to set up an initial state.
- Prints the initial state of the grid.
- Updates the grid and prints the state for several generations to demonstrate how the cells evolve.
- Creates a