Outlining Game of Life Code
The user wants Python code for simulating the Game of Life with a customizable grid size, but didn’t specify if it should be text-based or GUI. I think I should provide a generic solution that accepts parameters for grid size, random initial states or customizable ones, and steps through iterations. A concise approach is better to keep it focused.
I can define the grid using 2D NumPy arrays or plain lists, which might make counting neighbors easier. I'll ensure it's customizable in size and provide options for neighbor counting with or without wrap-around boundaries.Creating Game of Life Simulation Code
I'm thinking of how to simulate the steps of the Game of Life and print the grid using Python. I want to implement a time delay for animation and clear the screen effectively. It's important that my code is ready for easy copying and pasting.
I’ll design functions like create_grid, count_neighbors, step, and print_grid. In the main part of the script, I’ll prompt the user for grid dimensions and steps. A concise commentary will accompany the code, while still ensuring customization options are clear.Structuring Game of Life Code
I’m sketching out the structure for the Game of Life simulation in Python. I'll use basic lists instead of NumPy to keep things straightforward. I'll define constants for alive and dead cells, then create functions: create_grid, step, and print_grid.
In the main function, I’ll prompt the user for the number of rows, columns, and generations, allowing for an infinite option. This way, the code remains clear and easy to understand, while also being functional.Detailing Game of Life Implementation
For the Game of Life implementation, I’m outlining the create_grid function to fill the grid based on a specified probability. The step function will compute the next generation by counting live neighbors and updating cell states accordingly. I’ll ensure it returns the new grid correctly.
In the print_grid function, I’ll include logic to clear the screen, display the grid, and pause for animations. I’ll also ensure that the grid size can be customized, allowing for flexible interactions and initialization density. I'll keep the code mostly and provide a concise explanation on running it. ```python
import random
import time
import os
Characters for display
ALIVE = "█"
DEAD = " "
def create_grid(rows, cols, fill_prob=0.2):
"""
Create an initial grid.
rows, cols: grid size
fill_prob: probability a cell starts alive (0.0–1.0)
"""
return [
[1 if random.random() < fill_prob else 0 for _ in range(cols)]
for _ in range(rows)
]
def count_neighbors(grid, r, c):
"""
Count live neighbors of cell (r, c).
Does NOT wrap around edges.
"""
rows = len(grid)
cols = len(grid[0])
count = 0
for dr in (-1, 0, 1):
for dc in (-1, 0, 1):
if dr == 0 and dc == 0:
continue # skip self
rr, cc = r + dr, c + dc
if 0 <= rr < rows and 0 <= cc < cols:
count += grid[rr][cc]
return count
def step(grid):
"""
Compute next generation from current grid.
"""
rows = len(grid)
cols = len(grid[0])
new_grid = [[0] * cols for _ in range(rows)]
for r in range(rows):
for c in range(cols):
live_neighbors = count_neighbors(grid, r, c)
if grid[r][c] == 1:
# Survival
new_grid[r][c] = 1 if live_neighbors in (2, 3) else 0
else:
# Birth
new_grid[r][c] = 1 if live_neighbors == 3 else 0
return new_grid
def print_grid(grid, generation, delay=0.1):
"""
Clear screen and print current grid.
"""
os.system("cls" if os.name == "nt" else "clear")
print(f"Conway's Game of Life - Generation {generation}")
for row in grid:
print("".join(ALIVE if cell else DEAD for cell in row))
time.sleep(delay)
def main():
# Customize grid size and simulation parameters here
rows = int(input("Number of rows: "))
cols = int(input("Number of columns: "))
fill_prob = float(input("Initial live cell probability (0.0–1.0, e.g. 0.2): ") or 0.2)
delay = float(input("Delay between generations in seconds (e.g. 0.1): ") or 0.1)
generations = input("Number of generations (blank for infinite): ")
generations = int(generations) if generations.strip() else None
grid = create_grid(rows, cols, fill_prob)
gen = 0
try:
while True:
print_grid(grid, gen, delay=delay)
grid = step(grid)
gen += 1
if generations is not None and gen >= generations:
break
except KeyboardInterrupt:
# Allow stopping with Ctrl+C
print("\nSimulation stopped.")
if name == "main":
main()
How to use:
1. Save as `game_of_life.py`.
2. Run:
`python game_of_life.py`
3. Enter:
- Desired number of rows and columns (grid size is fully customizable).
- Initial live cell probability (how dense the starting pattern is).
- Delay between generations.
- Number of generations or leave blank for infinite until Ctrl+C.