# Conway life game

The game of life is built on a grid of nine squares, each with eight adjacent cells.
The game has three rules:
1. If there are 3 cells living around a cell (there are 8 cells around a cell), the cell is living (that is, if the cell was originally dead, it will become living, if it was originally living, it will remain unchanged).
2. If there are two cells around a cell, the life and death state of the cell remains unchanged;
3. In other cases, the cell is dead (that is, if the cell was originally living, it will turn to dead, if it was originally dead, it will remain unchanged)

```import sys, argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

ON = 255
OFF = 0
vals = [ON, OFF]

#np's choice() method will select a value from the given list vals, with a probability from 0.2 to 0.8. n*n values are created, and reshape() method is used to make it a two-dimensional array
def randomGrid(N):
return np.random.choice(vals, N*N, p=[0.2, 0.8]).reshape(N, N)

#Define a pattern with numpy array and copy it to 2D mesh with slice operation
"""adds a glider with top left cell at (i, j)"""
glider = np.array([[0,    0, 255],
[255,  0, 255],
[0,  255, 255]])
grid[i:i+3, j:j+3] = glider

gun = np.zeros(11*38).reshape(11, 38)

gun = gun = 255
gun = gun = 255

gun = gun = 255
gun = gun = 255
gun = gun = 255
gun = gun = gun = gun = 255
gun = gun = 255
gun = gun = 255
gun = gun = 255

gun = 255
gun = gun = 255
gun = gun = 255
gun = gun = 255
gun = gun = 255
gun = gun = 255
gun = 255

gun = gun = 255
gun = gun = 255

grid[i:i+11, j:j+38] = gun

# copy grid since we require 8 neighbors for calculation
# and we go line by line
newGrid = grid.copy()
for i in range(N):
for j in range(N):
#Calculate the values of eight neighboring neighbors and divide the sum by 255 to obtain the number of cells ON
total = int((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])/255)
# apply Conway's rules
if grid[i, j]  == ON:
if (total < 2) or (total > 3):
newGrid[i, j] = OFF
else:
if total == 3:
newGrid[i, j] = ON
# update data
img.set_data(newGrid)
grid[:] = newGrid[:]
return img,

# main() function
def main():
# Command line args are in sys.argv, sys.argv ..
# sys.argv is the script name itself and can be ignored
# parse arguments
parser = argparse.ArgumentParser(description="Runs Conway's Game of Life simulation.")
#dest: parameter name
#Dest: if dest is provided, for example dest="a", the parameter can be accessed through args.a
#Store? True and store? False: store values as true or false
#The parse_args() method actually returns some data from our command line arguments
args = parser.parse_args()

#Set grid size
N = 100
if args.N and int(args.N) > 8:
N = int(args.N)

# set animation update interval
updateInterval = 50
if args.interval:
updateInterval = int(args.interval)

# declare grid
grid = np.array([])
# check if "glider" demo flag is specified
if args.glider:
grid = np.zeros(N*N).reshape(N, N)
elif args.gosper:
grid = np.zeros(N*N).reshape(N, N)
else:
# populate grid with random on/off - more off than on
grid = randomGrid(N)

#Set animation
fig, ax = plt.subplots()
img = ax.imshow(grid, interpolation='nearest')
ani = animation.FuncAnimation(fig, update, fargs=(img, grid, N, ),
frames = 10,
interval=updateInterval,
save_count=50)

# # of frames?
# set output file
if args.movfile:
ani.save(args.movfile, fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()

# call main
if __name__ == '__main__':
main()
``` The reference for argparse is as follows
https://blog.csdn.net/lis_12/article/details/54618868
https://www.cnblogs.com/zknublx/p/6106343.html

The main references for Matplotlib library are:
https://www.cnblogs.com/LHWorldBlog/p/7819331.html
http://python.jobbole.com/85106/

Keywords: Python

Added by findshorty on Fri, 03 Apr 2020 10:10:00 +0300