没有全局变量的python动画

Kee*_*ger 5 python graphics animation matplotlib scipy

我正在编写康威的生命游戏实现。我的第一次尝试只是在每次更新后在 1 和 0 的 NxN 板上使用 matplotlib 的 imshow 绘制板。但是,这不起作用,因为程序在显示情节时会暂停。您必须关闭绘图才能进行下一次循环迭代。

我发现 matplotlib 中有一个动画包,但它不接受(或给出)变量,所以我见过的每个实现(甚至matplotlib 的文档)都依赖于全局变量。

所以这里有两个问题:

1)这是一个可以使用全局变量的地方吗?我一直读到这从来都不是一个好主意,但这只是教条吗?

2)你将如何在没有全局变量的情况下在 python 中做这样的动画(即使这意味着放弃 matplotlib,我猜;标准库总是首选)。

phi*_*hag 5

这些只是示例程序。您可以使用对象代替全局变量,如下所示:

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)

请注意,对于非数学动画(没有标签、图形、比例等),您可能更喜欢pygletpygame

  • 我想,对我来说,这就是两种解决方案(全局和类)的问题,或者可能只是一般的动画方法的问题:通过我的函数式编程培训,我的直觉是希望明确地看到每次迭代的输出并处理它在while循环中回到生命游戏功能。 (2认同)