这些只是示例程序。您可以使用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.