#include <SFML/Graphics.hpp>
#include <vector>
using namespace std;
using namespace sf;
// Function to update the grid based on the Game of Life rules
void updateGrid(vector<vector<bool>>& grid) {
int rows = grid.size();
int cols = grid[0].size();
vector<vector<bool>> newGrid(rows, vector<bool>(cols, false));
// Helper function to count live neighbors
auto countLiveNeighbors = [&](int x, int y) {
int count = 0;
for (int i = -1; i <= 1; ++i) {
for (int j = -1; j <= 1; ++j) {
if (i == 0 && j == 0) continue;
int ni = x + i, nj = y + j;
if (ni >= 0 && ni < rows && nj >= 0 && nj < cols && grid[ni][nj]) {
++count;
}
}
}
return count;
};
// Update each cell based on its neighbors
for (int x = 0; x < rows; ++x) {
for (int y = 0; y < cols; ++y) {
int liveNeighbors = countLiveNeighbors(x, y);
if (grid[x][y]) {
newGrid[x][y] = (liveNeighbors == 2 || liveNeighbors == 3);
} else {
newGrid[x][y] = (liveNeighbors == 3);
}
}
}
grid = newGrid;
}
// Main function
int main() {
const int cellSize = 10;
const int width = 80;
const int height = 60;
const int windowWidth = width * cellSize;
const int windowHeight = height * cellSize;
// Create the window
RenderWindow window(VideoMode(windowWidth, windowHeight), "Game of Life");
// Initialize grid
vector<vector<bool>> grid(height, vector<bool>(width, false));
// Set initial pattern (glider)
grid[10][10] = true;
grid[10][11] = true;
grid[10][12] = true;
grid[11][12] = true;
grid[12][11] = true;
Clock clock;
float elapsed = 0;
float interval = 0.1f; // Update interval in seconds
while (window.isOpen()) {
// Event handling
Event event;
while (window.pollEvent(event)) {
if (event.type == Event::Closed)
window.close();
}
// Update the grid at regular intervals
elapsed += clock.restart().asSeconds();
if (elapsed >= interval) {
elapsed = 0;
updateGrid(grid);
}
// Clear the window
window.clear(Color::White);
// Draw the grid
for (int x = 0; x < height; ++x) {
for (int y = 0; y < width; ++y) {
RectangleShape cell(Vector2f(cellSize, cellSize));
cell.setPosition(y * cellSize, x * cellSize);
cell.setFillColor(grid[x][y] ? Color::Black : Color::White);
window.draw(cell);
}
}
// Display the updated window
window.display();
}
return 0;
}