Saturday, February 8, 2025

 import numpy as np

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# User input for grid dimensions
grid_size_x = int(input("Enter the number of rows for the grid: "))
grid_size_y = int(input("Enter the number of columns for the grid: "))
frames = 100
Python Life Game

# Initialize grid with random cells
grid = np.random.choice([0, 1], size=(grid_size_x, grid_size_y), p=[0.8, 0.2])

def update_grid(grid):
"""Apply Conway's Game of Life rules to update the grid."""
new_grid = grid.copy()
for i in range(grid_size_x):
for j in range(grid_size_y):
# Count the number of live neighbors
neighbors = sum([
grid[i, (j-1)%grid_size_y], grid[i, (j+1)%grid_size_y],
grid[(i-1)%grid_size_x, j], grid[(i+1)%grid_size_x, j],
grid[(i-1)%grid_size_x, (j-1)%grid_size_y], grid[(i-1)%grid_size_x, (j+1)%grid_size_y],
grid[(i+1)%grid_size_x, (j-1)%grid_size_y], grid[(i+1)%grid_size_x, (j+1)%grid_size_y]
])
# Apply the rules of Game of Life
if grid[i, j] == 1:
if neighbors < 2 or neighbors > 3:
new_grid[i, j] = 0
else:
if neighbors == 3:
new_grid[i, j] = 1
return new_grid

# Animation setup
fig, ax = plt.subplots()
img = ax.imshow(grid, cmap='binary')
plt.title("Conway's Game of Life")

def update(frame):
global grid
grid = update_grid(grid)
img.set_array(grid)
return [img]

ani = FuncAnimation(fig, update, frames=frames, blit=True, interval=200)
plt.show()

No comments:

Post a Comment