Conway's Game of Life, also known as the "state of life", is a cellular automaton invented by mathematician John Horton Conway in 1970. It's a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input. The "game" happens on an infinite two-dimensional grid of square cells, each of which is in one of two possible states, alive or dead.
Every cell interacts with its eight neighbours, which are the cells that are horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:
- Any live cell with fewer than two live neighbors dies, as if by 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, as if by overpopulation.
- Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.
The initial pattern constitutes the 'seed' of the system, and the system is left to evolve according to the rules. Despite its simplicity, the system can display incredibly complex behavior.
Here is a simple Python implementation of Conway's Game of Life:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Define the size of the grid
N = 100
# Initialize the grid with random values
grid = np.random.choice([0, 1], N*N, p=[0.2, 0.8]).reshape(N, N)
def update(data):
global grid
# Copy grid and we'll use this to create the next generation
newGrid = grid.copy()
for i in range(N):
for j in range(N):
# Compute the sum of the neighbors
total = (grid[i, (j-1)%N] + grid[i, (j+1)%N] +
grid[(i-1)%N, j] + grid[(i+1)%N, j] +
grid[(i-1)%N, (j-1)%N] + grid[(i-1)%N, (j+1)%N] +
grid[(i+1)%N, (j-1)%N] + grid[(i+1)%N, (j+1)%N])
# Apply the rules
if grid[i, j] == 1:
if (total < 2) or (total > 3):
newGrid[i, j] = 0
else:
if total == 3:
newGrid[i, j] = 1
# Update the data
mat.set_data(newGrid)
grid = newGrid
return [mat]
# Create the plot
fig, ax = plt.subplots()
mat = ax.matshow(grid)
ani = animation.FuncAnimation(fig, update, interval=50,
save_count=50)
plt.show()
Make sure to install numpy and matplotlib before running this script.
pip install numpy matplotlib