In the vast world of programming, various fascinating concepts emerge from time to time. One such concept is Conway's Game of Life, which is not precisely a game in the traditional sense, but rather a cellular automaton devised by mathematician John Horton Conway. It is a simple yet powerful model with the ability to generate intricate patterns based on a few basic rules.
In this blog post, we will learn the core idea behind Conway's Game of Life and how to create a basic implementation in Python.
The Game of Life consists of a two-dimensional grid, with each cell being either "alive" or "dead." The game progresses through generations, and the state of a cell in the next generation is determined by the following rules:
Here's a Python implementation of Conway's Game of Life, using the numpy
library to handle the grid structures:
import numpy as np import time import os def count_neighbors(grid, row, col): rows, cols = grid.shape neighbors = sum((grid[(row + i) % rows, (col + j) % cols] for i in (-1, 0, 1) for j in (-1, 0, 1) if (i != 0 or j != 0))) return neighbors def game_of_life(grid, generations): rows, cols = grid.shape for _ in range(generations): new_grid = np.zeros((rows, cols), dtype=int) for row in range(rows): for col in range(cols): neighbors = count_neighbors(grid, row, col) if (grid[row, col] and neighbors in (2, 3)) or (not grid[row, col] and neighbors == 3): new_grid[row, col] = 1 grid = new_grid os.system('clear') print(grid) time.sleep(0.2) if __name__ == "__main__": grid = np.random.randint(0, 2, (10, 10)) generations = 20 game_of_life(grid, generations)
This code creates an initial 10x10 grid with random live and dead cells. It then evolves the grid for 20 generations, following the rules of Conway's Game of Life. The grid is printed to the console, and the process repeats for the specified number of generations.
Conway's Game of Life is a captivating concept in the world of programming, stirring the curiosity of developers, mathematicians, and enthusiasts alike. The beauty of such cellular automata demonstrates the potential of simple rules governing complex systems.
Now that you have a fundamental understanding of Conway's Game of Life and how to implement it in Python, you can experiment with different grid sizes, initial states, and generations to discover intriguing patterns and behaviors.