About Cellular Automata
Cellular automata are mathematical models that consist of a grid of cells, each of which can be in one of a finite number of states. The state of each cell changes over time according to a set of rules that depend on the states of neighboring cells.
Conway's Game of Life, created by mathematician John Conway in 1970, is one of the most famous cellular automata. In this simulation, a cell can either be "alive" or "dead." The state of the grid evolves over time based on simple rules, leading to complex, often beautiful patterns.
Code Snippets
Below is a Python implementation of Conway's Game of Life:
# -*- coding: utf-8 -*-
import numpy as np
# Initializes the grid with random states
# @param size: Integer, the size of the grid (NxN)
# @return: NumPy array representing the initial state of the grid
def initialize_grid(size):
return np.random.choice([0, 1], size=(size, size))
# Updates the grid based on the Game of Life rules
# @param grid: NumPy array representing the current state of the grid
# @return: NumPy array representing the new state of the grid
def update_grid(grid):
new_grid = grid.copy()
for i in range(grid.shape[0]):
for j in range(grid.shape[1]):
# Count neighbors
total = np.sum(grid[max(0, i-1):i+2, max(0, j-1):j+2]) - grid[i, j]
# Apply the rules of the Game of Life
if grid[i, j] == 1 and (total < 2 or total > 3):
new_grid[i, j] = 0
elif grid[i, j] == 0 and total == 3:
new_grid[i, j] = 1
return new_grid
if __name__ == "__main__":
grid_size = 50
grid = initialize_grid(grid_size)
for _ in range(100): # Run for 100 steps
grid = update_grid(grid)
print(grid)