Program Conway’s game of life in Python.
Question Analysis
Conway's Game of Life is a cellular automaton devised by the mathematician John Conway. The game is played on an infinite two-dimensional grid of square cells, where each cell can be in one of two states: alive or dead. The state of the grid evolves through discrete time steps according to a set of rules based on the states of neighboring cells. The rules are:
- Any live cell with fewer than two live neighbors dies (underpopulation).
- Any live cell with two or three live neighbors lives on to the next generation.
- Any live cell with more than three live neighbors dies (overpopulation).
- Any dead cell with exactly three live neighbors becomes a live cell (reproduction).
The goal is to implement these rules in Python to simulate the evolution of the grid over time. The primary challenge is to efficiently handle the state transitions and potentially large grids.
Answer
def get_neighbors(x, y, grid):
"""Return a list of the live neighbors for a given cell."""
neighbors = [
(i, j)
for i in range(x - 1, x + 2)
for j in range(y - 1, y + 2)
if (i, j) != (x, y) and 0 <= i < len(grid) and 0 <= j < len(grid[0])
]
return sum(grid[i][j] for i, j in neighbors)
def next_generation(grid):
"""Compute the next generation of the grid."""
rows, cols = len(grid), len(grid[0])
new_grid = [[0] * cols for _ in range(rows)]
for i in range(rows):
for j in range(cols):
live_neighbors = get_neighbors(i, j, grid)
if grid[i][j] == 1: # Cell is alive
if live_neighbors == 2 or live_neighbors == 3:
new_grid[i][j] = 1
else:
new_grid[i][j] = 0
else: # Cell is dead
if live_neighbors == 3:
new_grid[i][j] = 1
return new_grid
def print_grid(grid):
"""Print the grid."""
for row in grid:
print(' '.join(str(cell) for cell in row))
print()
# Example usage
initial_grid = [
[0, 1, 0],
[0, 0, 1],
[1, 1, 1],
[0, 0, 0]
]
print("Initial Grid:")
print_grid(initial_grid)
# Simulate a few generations
generation_count = 5
current_grid = initial_grid
for gen in range(generation_count):
print(f"Generation {gen + 1}:")
current_grid = next_generation(current_grid)
print_grid(current_grid)
This implementation defines a simple version of Conway's Game of Life. It includes functions to calculate the number of live neighbors for a given cell, compute the next generation of the grid, and print the grid. The next_generation
function applies the rules of the game to update the grid. The example usage demonstrates the evolution of the grid over a few generations.