gpt4 book ai didi

没有全局变量的python动画

转载 作者:太空狗 更新时间:2023-10-30 02:47:03 25 4
gpt4 key购买 nike

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

我发现 matplotlib 中有一个动画包,但它不接受(或提供)变量,所以我见过的每个实现(甚至是 matplotlib's documentation)都依赖于全局变量。

所以这里有两个问题:

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

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

最佳答案

这些只是示例程序。您可以使用 object而不是全局变量,像这样:

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

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

关于没有全局变量的python动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17511843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com