Save the result of the life game as a gif with python

What to do in this article

It's a story of $ n $ decoction, but in this article I will give a brief explanation of Life Game and try to simulate it with python. Then save the state of each era as a figure and combine it as a gif to make a simple animation.

What is a life game?

Conway's Game of Life is simply a simulation of the survival of living things. The plane is divided by a grid, and each square holds two states, with or without living things. The state changes with the following rules for the distribution of living things every unit time.

・ In the surrounding 8 squares excluding yourself in a certain square If there is only one organism → death (depopulation) If there are two → as it is (survival) If there are 3 animals → a creature will be born in that square (birth) If 4 or more → Death (overcrowding)   Despite these simple rules, it creates a very interesting pattern as a whole. First, let's take a look at the gif output from the program in this article.

simulation.gif    Not only does it increase or decrease the number of creatures, but it also creates and moves special patterns. It's interesting just looking at it. Even though individual organisms follow simple laws, they move in a complex manner that cannot be reduced to individual simple movements as a whole ... Such a system is called a complex system.

program

Module import and result output destination

1.py


#Modules
from random import randint
import matplotlib.pyplot as plt
import numpy as np
import os
from PIL import Image

#Output destination of simulation results
di = "./"
pics = di + "pictures/"
gif = di + "simulation_results/"

#Folder creation
try:
    os.mkdir(pics)
    os.mkdir(gif)
except:
    pass

Make a diagram of the result and save it

2.py


#Make a diagram of the result and save it
#The argument is a value indicating the state of the plane in the t era and the generation it is.
def make_fig(world,t):
    picsfname = pics + str(t) + ".png "
    pictitle = "Generation No." + str(t)
    plt.figure()
    plt.title(pictitle)
#Plot on a two-dimensional plane
    plt.imshow(world)
    plt.savefig(picsfname)
#Do not display the figure
    plt.close()

Explore the surrounding squares

3.py


def serch(world,x,y):
    #counter
    c = 0
    
    #search
    for i in range(x-1,x+2):
        for j in range(y-1,y+2):
            c += world[i][j]
    c -= world[x][y]
    
    #Survive if 3 animals are in the surroundings, remain as it is if 2 animals, die otherwise
    if c == 3:
        return 1
    elif c == 2:
        return  world[x][y]
    else:
        return 0

Initial field generation

4.py


#The initial position of the organism is determined by a random number
for i in range(d):
    tmp = []
    for j in range(d):
#The larger the number of divisions, the fewer early creatures
        if randint(0,100)%7 == 0:
            tmp.append(1)
        else:
            tmp.append(0)
    world.append(tmp)

Receiving parameters

5.py


#Parameter input
#Many frames and number of repeating generations
d = int(input("Frame size"))
n = int(input("Generations?"))
world = []

Main part

4.py


#Record the initial state
make_fig(world,0)

#Main loop
for t in range(1,n):
#Generate fields from outputting fields in the following states
    newworld = []
    for i in range(d):
        tmp = []
        for j in range(d):
            tmp.append(0)
        newworld.append(tmp)
#Explore each square in the field
    for i in range(1,d-1):
        for j in range(1,d-1):
            newworld[i][j] = serch(world,i,j)
#Transfer state to new field
    for i in range(d):
        for j in range(d):
            world[i][j] = newworld[i][j]
#Finally save the state
    make_fig(world,t)

Generate gif animation by grouping images

6.py


#./Connect the figures saved in pictures to make a gif
frames = []
#./simulation_results/Output to
giffname = gif + "simulation.gif"

# ./pictures/Image loading
for i in range(n):
    picname = pics + str(i) + ".png "
    new_frame = Image.open(picname)
    frames.append(new_frame)

#gif
frames[0].save(giffname,
               format='GIF',
               append_images=frames[1:],
               save_all=True,
               duration=400,
               loop=0)

#Reference: https://blog.fantom.co.jp/2019/12/28/make-gif-animation-from-multiple-images/

Overall

7.py


#Modules
from random import randint
import matplotlib.pyplot as plt
import numpy as np
import os
from PIL import Image

#Output destination of simulation results
di = "./"
pics = di + "pictures/"
gif = di + "simulation_results/"

#Folder creation
try:
    os.mkdir(pics)
    os.mkdir(gif)
except:
    pass

#Make a diagram of the result and save it
def make_fig(world,t):
    picsfname = pics + str(t) + ".png "
    pictitle = "Generation No." + str(t)
    plt.figure()
    plt.title(pictitle)
    plt.imshow(world)
    plt.savefig(picsfname)
    plt.close()

#Search for 8 squares around you and check for the presence of living things
def serch(world,x,y):
    #counter
    c = 0
    
    #search
    for i in range(x-1,x+2):
        for j in range(y-1,y+2):
            c += world[i][j]
    c -= world[x][y]
    
    #Survive if 3 animals are in the surroundings, remain as it is if 2 animals, die otherwise
    if c == 3:
        return 1
    elif c == 2:
        return  world[x][y]
    else:
        return 0

#Parameter input
d = int(input("Frame size"))
n = int(input("Generations?"))
world = []

#Field generation
#The initial position of the organism is determined by a random number
for i in range(d):
    tmp = []
    for j in range(d):
        if randint(0,100)%7 == 0:
            tmp.append(1)
        else:
            tmp.append(0)
    world.append(tmp)
    
#Record the initial state
make_fig(world,0)

#Main loop
for t in range(1,n):
    newworld = []
    for i in range(d):
        tmp = []
        for j in range(d):
            tmp.append(0)
        newworld.append(tmp)

    for i in range(1,d-1):
        for j in range(1,d-1):
            newworld[i][j] = serch(world,i,j)
            
    for i in range(d):
        for j in range(d):
            world[i][j] = newworld[i][j]
    make_fig(world,t)

#./Connect the figures saved in pictures to make a gif
frames = []
giffname = gif + "simulation.gif"

#Loading images
for i in range(n):
    picname = pics + str(i) + ".png "
    new_frame = Image.open(picname)
    frames.append(new_frame)

#gif
frames[0].save(giffname,
               format='GIF',
               append_images=frames[1:],
               save_all=True,
               duration=400,
               loop=0)
print("finished")

Recommended Posts

Save the result of the life game as a gif with python
Life game with Python! (Conway's Game of Life)
Output the output result of sklearn.metrics.classification_report as a CSV file
The story of making a tool to load an image with Python ⇒ save it as another name
As a result of mounting and tuning with POH! Lite
Tank game made with python About the behavior of tanks
[Python] The first step to making a game with Pyxel
I tried a stochastic simulation of a bingo game with Python
Implementation of life game in Python
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
Life game with Python [I made it] (on the terminal & Tkinter)
[python, ruby] fetch the contents of a web page with selenium-webdriver
[Introduction to StyleGAN] I played with "The Life of a Man" ♬
The story of making a standard driver for db with python.
The idea of feeding the config file with a python file instead of yaml
Calculated the ease of stopping the house of the board game "Bunkers" with Python
The story of making a module that skips mail with python
Create a compatibility judgment program with the random module of python.
Let's make a shiritori game with Python
Install Python as a Framework with pyenv
Check the existence of the file with python
Search the maze with the python A * algorithm
The result of installing python in Anaconda
[python] [meta] Is the type of python a type?
I made a life game with Numpy
The story of blackjack A processing (python)
I made a roguelike game with Python
The story of making a university 100 yen breakfast LINE bot with Python
[AtCoder explanation] Control the A, B, C problems of ABC182 with Python!
Calculate the shortest route of a graph with Dijkstra's algorithm and Python
If you want a singleton in python, think of the module as a singleton
Get the number of searches with a regular expression. SeleniumBasic VBA Python
[AtCoder explanation] Control the A, B, C problems of ABC186 with Python!
[Introduction to Python] How to sort the contents of a list efficiently with list sort
[AtCoder explanation] Control the A, B, C problems of ABC185 with Python!
Calculate the probability of being a squid coin with Bayes' theorem [python]
Hit a method of a class instance with the Python Bottle Web API
Receive a list of the results of parallel processing in Python with starmap
The result of making the first thing that works with Python (image recognition)
[AtCoder explanation] Control the A, B, C problems of ABC187 with Python!
[AtCoder explanation] Control the A, B, C problems of ABC184 with Python!
[Python] Get the files in a folder with Python
Prepare the execution environment of Python3 with Docker
[Python] Make a game with Pyxel-Use an editor-
2016 The University of Tokyo Mathematics Solved with Python
[Note] Export the html of the site with python.
Get the caller of a function in Python
View the result of geometry processing in Python
Try to draw a life curve with python
Calculate the total number of combinations with python
I want to make a game with Python
Make a copy of the list in Python
Check the date of the flag duty with Python
Solve A ~ D of yuki coder 247 with python
A note about the python version of python virtualenv
[Python] Make a simple maze game with Pyxel
Save the object to a file with pickle
[Python] A rough understanding of the logging module
Output in the form of a python array
Convert the character code of the file with Python3
A discussion of the strengths and weaknesses of Python