以下代码使用Python和matplotlib创建了康威生命游戏的动画。
我不确定为什么要这样做:
如何更新与绘图相关联的数组,而不进行上述复制?
输出结果看起来正确 - 我可以看到滑翔机和其他预期的图案:
我不确定为什么要这样做:
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()
输出结果看起来正确 - 我可以看到滑翔机和其他预期的图案: