生命游戏建立在9个方格的网格中,每个细胞有8个相邻细胞。
游戏有三个规则:
1. 如果一个细胞周围有3个细胞为生(一个细胞周围共有8个细胞),则该细胞为生(即该细胞若原先为死,则转为生,若原先为生,则保持不变) 。
2. 如果一个细胞周围有2个细胞为生,则该细胞的生死状态保持不变;
3. 在其它情况下,该细胞为死(即该细胞若原先为生,则转为死,若原先为死,则保持不变)
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的choice()方法将从给定列表vals中选择一个值,概率从0.2到0.8,创建了n*n个值,使用reshape()方法使它成为一个二维数组
def randomGrid(N):
return np.random.choice(vals, N*N, p=[0.2, 0.8]).reshape(N, N)
#用numpy数组定义一个图案并用切片操作将其复制到二维网格中
def addGlider(i, j, grid):
"""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
#添加高斯帕滑翔枪图形
def addGosperGliderGun(i, j, grid):
gun = np.zeros(11*38).reshape(11, 38)
gun[5][1] = gun[5][2] = 255
gun[6][1] = gun[6][2] = 255
gun[3][13] = gun[3][14] = 255
gun[4][12] = gun[4][16] = 255
gun[5][11] = gun[5][17] = 255
gun[6][11] = gun[6][15] = gun[6][17] = gun[6][18] = 255
gun[7][11] = gun[7][17] = 255
gun[8][12] = gun[8][16] = 255
gun[9][13] = gun[9][14] = 255
gun[1][25] = 255
gun[2][23] = gun[2][25] = 255
gun[3][21] = gun[3][22] = 255
gun[4][21] = gun[4][22] = 255
gun[5][21] = gun[5][22] = 255
gun[6][23] = gun[6][25] = 255
gun[7][25] = 255
gun[3][35] = gun[3][36] = 255
gun[4][35] = gun[4][36] = 255
grid[i:i+11, j:j+38] = gun
def update(frameNum, img, grid, N):
# 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):
#计算与其相邻的八个邻居的值,求和除于255来获取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[1], sys.argv[2] ..
# sys.argv[0] is the script name itself and can be ignored
# parse arguments
parser = argparse.ArgumentParser(description="Runs Conway's Game of Life simulation.")
# add arguments
#dest :参数名
#dest:如果提供dest,例如dest="a",那么可以通过args.a访问该参数
parser.add_argument('--grid-size', dest='N', required=False)
parser.add_argument('--mov-file', dest='movfile', required=False)
parser.add_argument('--interval', dest='interval', required=False)
#store_true和store_false:值存为True或False
parser.add_argument('--glider', action='store_true', required=False)
parser.add_argument('--gosper', action='store_true', required=False)
#parse_args()方法实际上从我们的命令行参数中返回了一些数据
args = parser.parse_args()
#设置网格尺寸
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)
addGlider(1, 1, grid)
elif args.gosper:
grid = np.zeros(N*N).reshape(N, N)
addGosperGliderGun(10, 10, grid)
else:
# populate grid with random on/off - more off than on
grid = randomGrid(N)
#设置动画
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()
对于argparse的参考有以下的资料
https://blog.csdn.net/lis_12/article/details/54618868
https://www.cnblogs.com/zknublx/p/6106343.html
对于Matplotlib库的参考主要有:
https://www.cnblogs.com/LHWorldBlog/p/7819331.html
http://python.jobbole.com/85106/