Kee*_*ger 5 python graphics animation matplotlib scipy
我正在编写康威的生命游戏实现。我的第一次尝试只是在每次更新后在 1 和 0 的 NxN 板上使用 matplotlib 的 imshow 绘制板。但是,这不起作用,因为程序在显示情节时会暂停。您必须关闭绘图才能进行下一次循环迭代。
我发现 matplotlib 中有一个动画包,但它不接受(或给出)变量,所以我见过的每个实现(甚至matplotlib 的文档)都依赖于全局变量。
所以这里有两个问题:
1)这是一个可以使用全局变量的地方吗?我一直读到这从来都不是一个好主意,但这只是教条吗?
2)你将如何在没有全局变量的情况下在 python 中做这样的动画(即使这意味着放弃 matplotlib,我猜;标准库总是首选)。
这些只是示例程序。您可以使用对象代替全局变量,如下所示:
class GameOfLife(object):
def __init__(self, initial):
self.state = initial
def step(self):
# TODO: Game of Life implementation goes here
# Either assign a new value to self.state, or modify it
def plot_step(self):
self.step()
# TODO: Plot here
# TODO: Initialize matplotlib here
initial = [(0,0), (0,1), (0,2)]
game = GameOfLife(initial)
ani = animation.FuncAnimation(fig, game.plot_step)
plt.show()
Run Code Online (Sandbox Code Playgroud)
如果你真的想避免类,你也可以像这样重写程序:
def step(state):
newstate = state[:] # TODO Game of Life implementation goes here
return newstate
def plot(state):
# TODO: Plot here
def play_game(state):
while True:
yield state
state = step(state)
initial = [(0,0), (0,1), (0,2)]
game = play_game(initial)
ani = animation.FuncAnimation(fig, lambda: next(game))
plt.show()
Run Code Online (Sandbox Code Playgroud)
请注意,对于非数学动画(没有标签、图形、比例等),您可能更喜欢pyglet或pygame。