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 |
#include <iostream> #include <vector> #include <unistd.h> // for sleep() const int WIDTH = 10; const int HEIGHT = 10; // Function to print the grid void printGrid(const std::vector<std::vector<int>>& grid) { for (const auto& row : grid) { for (int cell : row) { std::cout << (cell ? '*' : '.') << ' '; } std::cout << std::endl; } } // Function to get the number of alive neighbors int countAliveNeighbors(const std::vector<std::vector<int>>& grid, int x, int y) { const int directions[8][2] = { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} }; int count = 0; for (const auto& dir : directions) { int nx = x + dir[0]; int ny = y + dir[1]; if (nx >= 0 && nx < WIDTH && ny >= 0 && ny < HEIGHT) { count += grid[nx][ny]; } } return count; } // Function to update the grid based on Conway's rules void updateGrid(std::vector<std::vector<int>>& grid) { std::vector<std::vector<int>> newGrid = grid; for (int x = 0; x < WIDTH; ++x) { for (int y = 0; y < HEIGHT; ++y) { int aliveNeighbors = countAliveNeighbors(grid, x, y); if (grid[x][y] == 1) { if (aliveNeighbors < 2 || aliveNeighbors > 3) { newGrid[x][y] = 0; // Cell dies } } else { if (aliveNeighbors == 3) { newGrid[x][y] = 1; // Cell becomes alive } } } } grid = newGrid; } int main() { // Initialize the grid with a glider pattern std::vector<std::vector<int>> grid(HEIGHT, std::vector<int>(WIDTH, 0)); grid[1][2] = grid[2][3] = grid[3][1] = grid[3][2] = grid[3][3] = 1; // Number of iterations int iterations = 10; // Simulation loop for (int i = 0; i < iterations; ++i) { std::cout << "Generation " << i + 1 << std::endl; printGrid(grid); updateGrid(grid); sleep(1); // Pause for a second std::cout << std::endl; } return 0; } |
Explanation:
- Constants:
WIDTH
andHEIGHT
: Dimensions of the grid.
- printGrid Function:
- Prints the grid to the console, where
*
represents an alive cell and.
represents a dead cell.
- Prints the grid to the console, where
- countAliveNeighbors Function:
- Calculates the number of alive neighbors for a cell at position
(x, y)
. It checks all eight possible directions around the cell.
- Calculates the number of alive neighbors for a cell at position
- updateGrid Function:
- Creates a new grid based on Conway’s rules:
- An alive cell with fewer than 2 or more than 3 alive neighbors dies.
- A dead cell with exactly 3 alive neighbors becomes alive.
- Creates a new grid based on Conway’s rules:
- main Function:
- Initializes a 10×10 grid with a glider pattern.
- Runs the simulation for a specified number of iterations, updating and printing the grid each generation.
- Uses
sleep(1)
to pause for one second between generations.
Compilation:
To compile the program, use:
1g++ game_of_life.cpp -o game_of_life
1./game_of_life