Generate a Python3 life simulator
- User
Generate a Python3 life simulator
- Assistant
Generate a Python3 life simulator
Certainly! Below is a Python3 implementation of Conway's Game of Life, a popular cellular automaton that simulates the birth, survival, and death of cells on a grid based on simple rules. This simulation provides a visual representation in the terminal, updating the grid in real-time.
Below is the Python3 code for the Game of Life simulator. This script uses the numpy library for efficient grid management and the time and os libraries for controlling the simulation's display.
import numpy as np
import time
import os
import sys
def clear_console():
"""Clears the console based on the user's operating system."""
os.system('cls' if os.name == 'nt' else 'clear')
def initialize_grid(rows, cols):
"""
Initializes the grid with random live and dead cells.
Args:
rows (int): Number of rows in the grid.
cols (int): Number of columns in the grid.
Returns:
np.ndarray: Initialized grid.
"""
return np.random.choice([0, 1], size=(rows, cols), p=[0.8, 0.2])
def print_grid(grid, generation):
"""
Prints the grid to the console.
Args:
grid (np.ndarray): Current state of the grid.
generation (int): Current generation number.
"""
clear_console()
print(f"Conway's Game of Life - Generation {generation}")
print('-' * (grid.shape[1] + 2))
for row in grid:
line = '|'
for cell in row:
line += '█' if cell else ' '
line += '|'
print(line)
print('-' * (grid.shape[1] + 2))
def update_grid(grid):
"""
Computes the next generation of the grid based on Conway's rules.
Args:
grid (np.ndarray): Current state of the grid.
Returns:
np.ndarray: Next generation grid.
"""
rows, cols = grid.shape
new_grid = grid.copy()
for r in range(rows):
for c in range(cols):
# Count live neighbors with wrap-around edges (toroidal)
total = (
grid[r, (c-1)%cols] + grid[r, (c+1)%cols] +
grid[(r-1)%rows, c] + grid[(r+1)%rows, c] +
grid[(r-1)%rows, (c-1)%cols] + grid[(r-1)%rows, (c+1)%cols] +
grid[(r+1)%rows, (c-1)%cols] + grid[(r+1)%rows, (c+1)%cols]
)
# Apply Conway's rules
if grid[r, c] == 1:
if total < 2 or total > 3:
new_grid[r, c] = 0
else:
if total == 3:
new_grid[r, c] = 1
return new_grid
def main():
# Set grid size
rows, cols = 20, 60 # You can adjust the size as needed
# Initialize grid
grid = initialize_grid(rows, cols)
try:
generation = 0
while True:
print_grid(grid, generation)
grid = update_grid(grid)
generation += 1
time.sleep(0.2) # Adjust the speed of the simulation
except KeyboardInterrupt:
print("\nSimulation terminated by user.")
sys.exit()
if __name__ == "__main__":
main()
Prerequisites:
numpy library if you haven't already. You can install it using pip:
pip install numpy
Save the Script:
game_of_life.py.Run the Script:
game_of_life.py.python3 game_of_life.py
Terminate the Simulation:
Ctrl + C in the terminal to stop the simulation.Grid Size:
rows and cols variables in the main() function to change the size of the grid.Initial Population Density:
initialize_grid function, the p=[0.8, 0.2] parameter sets the probability of a cell being dead (0) or alive (1). Modify these values to change the initial density.Simulation Speed:
time.sleep(0.2) controls the speed of the simulation. Decrease the value for a faster simulation or increase it for a slower one.For a more advanced simulation, consider implementing the following features:
pygame or tkinter to create a graphical interface.Feel free to modify and expand upon this basic simulator to explore the fascinating behaviors that emerge from simple rules!
Not yet included in a published release.