import random
import os
import time
import sys
def create_grid(width, height, density=0.3):
"""
Create a grid of specified size with random initial live cells based on density.
"""
return [[1 if random.random() < density else 0 for _ in range(width)] for _ in range(height)]
def count_neighbors(grid, x, y, width, height):
"""
Count the number of live neighbors for a cell at (x, y). Uses toroidal (wrap-around) boundaries.
"""
count = 0
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue
nx = (x + i) % width
ny = (y + j) % height
count += grid[ny][nx]
return count
def next_generation(grid, width, height):
"""
Compute the next generation of the grid based on Conway's Game of Life rules.
"""
new_grid = [[0] * width for _ in range(height)]
for y in range(height):
for x in range(width):
neighbors = count_neighbors(grid, x, y, width, height)
if grid[y][x] == 1:
# Live cell survives if 2 or 3 neighbors
if neighbors == 2 or neighbors == 3:
new_grid[y][x] = 1
else:
# Dead cell becomes live if exactly 3 neighbors
if neighbors == 3:
new_grid[y][x] = 1
return new_grid
def display_grid(grid):
"""
Clear screen and display the grid using block characters for live cells.
"""
os.system('cls' if os.name == 'nt' else 'clear')
print("Conway's Game of Life (Press Ctrl+C to quit)")
print("=" * (len(grid[0]) * 2 + 2))
for row in grid:
print('|' + ''.join(['█ ' if cell else ' ' for cell in row]) + '|')
print("=" * (len(grid[0]) * 2 + 2))
def main():
try:
width = int(input("Enter grid width (e.g., 80): "))
height = int(input("Enter grid height (e.g., 40): "))
density = float(input("Enter initial live cell density (0.0 to 1.0, default 0.3): ") or 0.3)
if width < 10 or height < 10:
print("Warning: Small grids may evolve quickly. Minimum recommended: 20x20.")
grid = create_grid(width, height, density)
generation = 0
while True:
display_grid(grid)
print(f"Generation: {generation} | Density: {sum(sum(row) for row in grid) / (width * height):.2%}")
time.sleep(0.1) # Adjust speed here (lower = faster)
grid = next_generation(grid, width, height)
generation += 1
except ValueError:
print("Invalid input. Please enter integers for dimensions and a float for density.")
sys.exit(1)
except KeyboardInterrupt:
print("\nSimulation stopped.")
except Exception as e:
print(f"An error occurred: {e}")
if __name__ == "__main__":
main()
How to Run
- Save the code to a file, e.g.,
game_of_life.py.
- Run it with
python game_of_life.py.
- Enter grid dimensions (e.g., 80x40 for a good console size) and density (e.g., 0.3 for 30% live cells).
- Watch the simulation! Press Ctrl+C to quit.
Features
- Customizable: Width, height, and initial live cell density.
- Toroidal boundaries: Edges wrap around.
- Smooth animation: Clears screen and updates ~10 FPS (adjust
time.sleep(0.1)).
- Stats: Shows generation count and current density.
- Cross-platform: Works on Windows, macOS, Linux.
- Efficient: Pure Python, no external dependencies like NumPy or Pygame.
This faithfully implements Conway's rules and provides an engaging console-based simulation! 🚀