Article

Conways's Game of life Implemented in Python

Last updated Dec. 11, 2022

...

Implementing Conway's game of life in Python.

Conway's Game of Life is a cellular automaton devised by the mathematician John Horton Conway in 1970. It is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input. One interacts with the Game of Life by creating an initial configuration and observing how it evolves, or, for advanced players, by creating patterns with particular properties.

The rules of Conway's Game of Life are fairly simple. The game takes place on a two-dimensional grid of cells, where each cell can be either alive or dead. At each step in time, the following rules are applied to every cell simultaneously:

  1. Any live cell with fewer than two live neighbors dies, as if by underpopulation.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by overpopulation.
  4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.

These rules continue to be applied repeatedly to create the evolution of the grid. The initial state of the grid is called the seed, and the resulting patterns are called the generations. The Game of Life is often described as a zero-player game because it requires no further input once the initial seed is created. It is a fascinating example of how simple rules can give rise to complex and seemingly intelligent behavior.

The Game of Life does not have a specific end point or goal. It is a cellular automaton, meaning that it is a mathematical model that consists of a grid of cells that evolve over time according to a set of rules. Because the game is determined by its initial state, it is said to be a "zero-player game," meaning that once the initial state is set, the game runs on its own without any further input.

The game will continue to evolve and generate new generations of cells according to the rules of the game, but there is no specific point at which the game ends. Some patterns may evolve into stable states where the cells do not change over time, while others may grow indefinitely or eventually die out. The behavior of the game can be very complex and can produce some fascinating and unpredictable patterns.

Here is a basic implementation of the game using the Python programming language:

# define the size of the grid
N = 100

# create an empty grid of size N x N
grid = [[0] * N for i in range(N)]

# initialize the grid with a seed pattern
# (in this case, a glider)
grid[0][1] = 1
grid[1][2] = 1
grid[2][0] = 1
grid[2][1] = 1
grid[2][2] = 1

# iterate over the grid and apply the rules of the game
for i in range(N):
    for j in range(N):
        # count the number of live neighbors
        neighbors = 0
        for x in range(-1, 2):
            for y in range(-1, 2):
                if x == 0 and y == 0:
                    continue
                if (i + x >= 0 and i + x < N and j + y >= 0 and j + y < N and grid[i+x][j+y] == 1):
                    neighbors += 1
        # apply the rules of the game
        if grid[i][j] == 1 and (neighbors < 2 or neighbors > 3):
            grid[i][j] = 0
        elif grid[i][j] == 0 and neighbors == 3:
            grid[i][j] = 1

# print the final state of the grid
for i in range(N):
    for j in range(N):
        print(grid[i][j], end="")
    print()

This implementation will create a grid of size N x N, initialize it with a glider seed pattern, and then apply the rules of the Game of Life repeatedly to generate new generations of cells. You can change the size of the grid and the initial seed pattern to explore different configurations of the game.

To visualize the Game of Life, you can use the Python matplotlib library to create a graphical representation of the game. Here is an example of how you might do this:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

# Set the grid size and initialize the grid
N = 100
grid = np.zeros((N, N))

# Set the initial configuration of cells
grid[25, 25] = 1
grid[26, 25] = 1
grid[27, 25] = 1
grid[27, 26] = 1
grid[26, 27] = 1

# Function to update the grid at each time step
def update(frameNum, img, grid):
    # Copy the grid so we can update it without affecting the
    # current state
    newGrid = grid.copy()

    # Iterate over the grid and apply the rules of the game
    for i in range(N):
        for j in range(N):
            # Compute the number of live neighbors
            neighbors = 0
            for x in range(i-1, i+2):
                for y in range(j-1, j+2):
                    if (x >= 0 and x < N and y >= 0 and y < N and
                        (x != i or y != j) and grid[x, y] == 1):
                        neighbors += 1

            # Apply the rules of the game
            if grid[i, j] == 0 and neighbors == 3:
                newGrid[i, j] = 1 # Cell is born
            elif grid[i, j] == 1 and (neighbors < 2 or neighbors > 3):
                newGrid[i, j] = 0 # Cell dies

    # Update the grid
    img.set_data(newGrid)
    grid[:] = newGrid[:]
    return img

# Set up the animation

fig, ax = plt.subplots()
img = ax.imshow(grid, interpolation='nearest')
ani = animation.FuncAnimation(fig, update, fargs=(img, grid),
                              frames=100, interval=100,
                              save_count=50)
plt.show()

This code will create a scatter plot of the live cells in the grid, with the x coordinate representing the column of the cell and the y coordinate representing the row. You can adjust the size of the grid, the initial seed pattern, and the number of generations to explore different configurations of the game.

Post a Comment

To leave a comment, click the button below to sign in with Google.

Signup To My Newsletter

By subscribing, you will get one email every month on tips, tutorials, and resources to improve your skills as a developer. You will get early access to my courses and videos and also access to special bonus of the time. No spam, unsubscribe at any time





Subscribe
Contact
Contact form