Python Matplotlib Makes Conway’s Game of Life Come Alive : Sensei

Python Matplotlib Makes Conway’s Game of Life Come Alive
by: Sensei
blow post content copied from  Finxter
click here to view original post


5/5 - (1 vote)

In this article, you’ll learn how to make this beautiful and interesting animation using only Python, NumPy, and Matplotlib — nothing else: 👇

But how does the Game of Life work – and what’s behind the classical visualization anyways?

The Game of Life

Conway’s Game of Life is a cellular automaton devised by the British mathematician John Horton Conway in 1970. The game is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input.

The game is played on a 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 neighbors, which are the cells that are horizontally, vertically, or diagonally adjacent.

At each step in time, the following rules apply:

  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.

The initial pattern constitutes the seed of the system.

The first generation is created by applying the above rules simultaneously to every cell in the seed; births and deaths occur simultaneously, and the discrete moment at which this happens is sometimes called a tick.

Each generation is a pure function of the preceding one. The rules continue to be applied repeatedly to create further generations.

How to Implement the “Game of Life” in Python?

This code creates a universe of size NxN with a probability p of being populated.

It then animates the universe for 200 frames with a 200ms interval between each frame, and displays it using Matplotlib.

The rules of the animation are defined in the animate() function, which iterates over each cell in the universe and applies the rules of Conway’s Game of Life.

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


def create_universe(N=50, p=0.5):
    return np.random.choice([0, 1], size=(N, N), p=[1-p, p])


def animate(frame, universe, img):
    new_u = np.zeros((N, N))
    for i in range(N):
        for j in range(N):
            n = (universe[(i+1)%N][j] + universe[(i-1)%N][j]
                 + universe[i][(j+1)%N] + universe[i][(j-1)%N]
                 + universe[(i+1)%N][(j+1)%N] + universe[(i-1)%N][(j-1)%N]
                 + universe[(i+1)%N][(j-1)%N] + universe[(i-1)%N][(j+1)%N])
            if universe[i][j] == 0 and n == 3:
                new_u[i][j] = 1
            elif universe[i][j] == 1 and (n < 2 or n > 3):
                new_u[i][j] = 0
            else:
                new_u[i][j] = universe[i][j]
    img.set_data(new_u)
    universe[:] = new_u[:]
    return img


N = 50
universe = create_universe(N=N, p=0.5)
fig = plt.figure(figsize=(7, 7))
ax = plt.axes()
img = ax.imshow(universe, interpolation='nearest')
ani = FuncAnimation(fig, animate, fargs=(universe, img,),
                    frames=200, interval=200, save_count=50)
plt.show()

Quick Code Explanation

The Python code creates an animation of Conway’s hugely famous “Game of Life”.

First, you import the NumPy and Matplotlib libraries.

Second, you define a create_universe() function that takes two parameters and returns a random array of 0’s and 1’s.

Third, you create the animate() function that uses a for loop to iterate through the array and update each cell using the “Game of live rules” discussed above.

Fourth, the animation is displayed with the FuncAnimation() function from Matplotlib’s powerful animation capabilities.

🌍 Recommended: Matplotlib Animations – A Helpful Guide with Video

Feel free to also watch our background explainer video on Matplotlib’s animation functionality — it’s a good investment in your education!

YouTube Video


December 12, 2022 at 05:38PM
Click here for more details...

=============================
The original post is available in Finxter by Sensei
this post has been published as it is through automation. Automation script brings all the top bloggers post under a single umbrella.
The purpose of this blog, Follow the top Salesforce bloggers and collect all blogs in a single place through automation.
============================

Salesforce