gpt4 book ai didi

Python matplotlib - 在 Conway 的 Game of Life 动画期间更新数据

转载 作者:太空宇宙 更新时间:2023-11-03 11:31:53 27 4
gpt4 key购买 nike

下面的代码使用 Python 和 matplotlib 为 Conway 的生命游戏创建动画。

我不确定为什么我必须这样做:

grid = newGrid.copy()
mat.set_data(grid)

而不是简单地:

mat.set_data(newGrid)

如何在不进行上述复制的情况下更新与绘图关联的数组?

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

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

# populate grid with random on/off - more off than on
grid = np.random.choice(vals, N*N, p=[0.2, 0.8]).reshape(N, N)

def update(data):
global grid
newGrid = grid.copy()
for i in range(N):
for j in range(N):
total = (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

if grid[i, j] == ON:
if (total < 2) or (total > 3):
newGrid[i, j] = OFF
else:
if total == 3:
newGrid[i, j] = ON

grid = newGrid.copy()
mat.set_data(grid)
return mat

fig, ax = plt.subplots()
mat = ax.matshow(grid)
ani = animation.FuncAnimation(fig, update, interval=50,
save_count=50)
plt.show()

输出似乎是正确的——我可以看到滑翔机和其他预期的模式:

Conway's Game of Life using Python/matplotlib

最佳答案

mat.set_data() 需要 newGrid 的副本没有特别的原因 - 重要的是全局 grid 得到更新从迭代到迭代:

def update(data):
global grid
newGrid = grid.copy()

"""
do your updating. this needs to be done on a copy of 'grid' because you are
updating element-by-element, and updates to previous rows/columns will
affect the result at 'grid[i,j]' if you don't use a copy
"""

# you do need to update the global 'grid' otherwise the simulation will
# not progress, but there's no need to copy()
mat.set_data(newGrid)
grid = newGrid

# # there's no reason why you couldn't do it in the opposite order
# grid = newGrid
# mat.set_data(grid)

# at least in my version of matplotlib (1.2.1), the animation function must
# return an iterable containing the updated artists, i.e. 'mat,' or '[mat]',
# not 'mat'
return [mat]

此外,在 FuncAnimation 中,我建议传递 blit=True,这样您就不会在每一帧都重新绘制背景。

关于Python matplotlib - 在 Conway 的 Game of Life 动画期间更新数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17230163/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com