【发布时间】:2020-01-11 00:14:24
【问题描述】:
我的 matplotlib 动画功能没有运行。任何建议都非常感谢。结果,应该有一个动画从当前运行到新一代(使用 new_state 函数)。
“state”是当前数组,是一个随机数组。这被传递到 new_state 函数中并且应该显示为动画。
'''
The code should generate John Conway's Game of Life, resulting in an animation that represents a transition from current
state to new state. This update of generations are based on the rules found here https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life.
'''
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
'''This function creates an array of elements of zeros, with a specified width and height.'''
def dead_state(height, width):
array = np.zeros((height,width), dtype=int)
return array
'''This function generates an array with random elements of ones and zeroes, with a specified width and height.'''
def random_state(width, height):
array = np.random.randint(0, high=2, size=(width, height), dtype=int)
return array
'''This function plots the array.'''
def plot(array):
plt.imshow(array)
plt.show()
def new_state(array):
array_padded = np.pad(array, 1)
updated_array=array.copy()
for x in range(1, array.shape[0]+1):
for y in range(1, array.shape[1]+1):
cell = array[x-1][y-1]
neighbours = (array_padded[x-1][y-1], array_padded[x][y-1], array_padded[x+1][y-1],
array_padded[x+1][y], array_padded[x+1][y+1], array_padded[x][y+1],
array_padded[x-1][y+1], array_padded[x-1][y])
neighbours_count = sum(neighbours)
if cell == 1:
if neighbours_count == 0 or neighbours_count == 1 or neighbours_count > 3:
updated_array[x-1,y-1]=0
elif neighbours_count == 2 or neighbours_count == 3:
updated_array[x-1,y-1]=1
elif cell == 0:
if neighbours_count == 3:
updated_array[x-1,y-1]=1
return updated_array
state = random_state(20,20)
im = plt.imshow(state)
plt.show()
def animate(frame):
im.set_data(new_state(state))
return im
"""Running the code below should generate the animation"""
fig = plt.figure()
animation.FuncAnimation(fig, animate, frames=200, interval=50)
plt.show()
【问题讨论】:
-
我现在有更深入的了解/尝试,但我认为这是因为您没有在
animate函数中重绘画布。添加一些像 plt.imshow(state) 这样的绘图命令可以做到这一点。这也可能是相似的,不是这样:stackoverflow.com/questions/10970492/…
标签: python numpy matplotlib animation conways-game-of-life