没有全局变量的Python动画

2024-01-25

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

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

所以这里有两个问题:

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

2)如果没有全局变量,你会如何在 python 中制作这样的动画(即使这意味着放弃 matplotlib,我猜;标准库始终是首选)。


这些只是示例程序。您可以使用object http://docs.python.org/dev/tutorial/classes.html而不是全局变量,如下所示:

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()

如果你真的想避免类,你也可以像这样重写程序:

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()

请注意,对于非数学动画(没有标签、图表、比例等),您可能更喜欢pyglet http://pyglet.org/ or pygame http://www.pygame.org/news.html.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

没有全局变量的Python动画 的相关文章