一段python代码,实现元胞自动机,生命游戏
出现如图报错,创建变量ani后,依然没能保存动画进行显示
代码如下
import sys, argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.colors import ListedColormap
#设置显示颜色
yeah = ('purple', 'yellow')
camp = ListedColormap(yeah)
#设置元胞状态255生,0死
ON = 255
OFF = 0
vals = [ON, OFF]
#随机生成N*N网格
def randomGrid(N):
return np.random.choice(vals, N * N, p = [0.2, 0.8]).reshape(N, N) #分别以0.2, 0.8的概率将vals的值填入N*N网格
#初始添加滑翔机
def addGlider(i, j, grid):
glider = np.array([[0, 0, 255], [255, 0, 255], [0, 255, 255]]) #滑翔机
grid[i: i + 3, j: j + 3] = glider #设置3*3区域的起始状态
return 0
#更新元胞状态
def update(frameNum, img, grid, N):
newGrid = grid.copy() #生成一个与grid一致的网格
#判断8个邻居的状态,统计ON状态的元胞的总数,取余:边界折返,更新元胞状态
for i in range(N):
for j in range(N):
total = int((
grid[i, (j - 1) % N] + grid[i, (j + 1) % N] +
grid[(i + 1), j % N] + grid[(i - 1), j % N] +
grid[(i + 1), (j - 1) % N] + grid[(i + 1), (j + 1) % N] +
grid[(i - 1), (j - 1) % N] + grid[(i - 1), (j + 1) % N]
) / 255)
if grid[i, j] == ON:
if(total < 2) or (total > 3):
newGrid[i, j] = OFF
else:
if total == 3:
newGrid[i, j] = ON
img.set_data(newGrid) #更新图形数据
grid[ : ] = newGrid[ : ] #更新Grid
return img
#程序运行参数设置
def main():
parser = argparse.ArgumentParser(description = "Run life game simulation")
parser.add_argument('--grid-size', dest = 'N', required = False) #网格大小
parser.add_argument('--mov-file', dest = 'movfile', required=False) #.mov文件名
parser.add_argument('--interval', dest = 'interval', required=False) #视频每帧更新间隔ms
parser.add_argument('--glider', action = 'store_true', required=False) #以滑翔机开始
parser.add_argument('--gosper', action = 'store_true', required=False) #unkonwn
args = parser.parse_args()
N = 100 #grid默认值
if args.N and int(args.N) > 8:
N = int(args.N)
updateInterval = 50 #默认刷新间隔
if args.interval:
updateInterval = int(args.interval)
grid = np.array([])
if args.glider:
grid = np.zeros(N * N).reshape(N, N) #初始化N*N,0
addGlider(1, 1, grid) #初始化滑翔机
else:
grid = randomGrid(N) #初始化N*N
fig, ax = plt.subplots(facecolor = 'pink') #创建fig图形对象,ax坐标轴对象,设置背景颜色为粉色
img = ax.imshow(grid, cmap = camp, interpolation = 'nearest') #返回,用于访问图像的对象
ani = animation.FuncAnimation(fig, update, fargs = (img, grid, N), frames = 10,
interval = updateInterval, save_count = 50) #创建动画
if args.movfile:
ani.save(args.movfile, fps = 30, extra_args = ['-vcodec', 'libx264']) #将视频文件保存到指定路径
plt.show()
return 0
main()
![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/455536382386174.png?x-oss-process=image/auto-orient,1/resize,w_320,m_lfit)
![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/226038382386121.png?x-oss-process=image/auto-orient,1/resize,w_320,m_lfit)
![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/432008382386112.png?x-oss-process=image/auto-orient,1/resize,w_320,m_lfit)