我有一个实现的康威生命游戏:

def neighbors(point):
    x, y = point
    for i, j in itertools.product(range(-1, 2), repeat=2):
        if any((i, j)):
            yield (x + i, y + j)

def advance(board):
    newstate = set()
    recalc = board | set(itertools.chain(*map(neighbors, board)))

    for point in recalc:
        count = sum((neigh in board)
                for neigh in neighbors(point))
        if count == 3 or (count == 2 and point in board):
            newstate.add(point)

    return newstate

我想将结果可视化,因此我尝试修改 Matplotlib animation example 中的给定示例:
glider = set([(0, 0), (1, 0), (2, 0), (0, 1), (1, 2)])

fig, ax = plt.subplots()

x, y = zip(*glider)
mat, = ax.plot(x, y, 'o')

def animate(i):
    glider = advance(glider)
    x, y = zip(*glider)
    mat.set_data(x, y)
    return mat,

ani = animation.FuncAnimation(fig, animate, interval=50)
plt.show()

但这只是绘制 the initial points

最佳答案

您拥有的代码实际上应该会产生错误。问题是您在分配之前引用了 glider

注意 python 函数中变量的局部范围。例如。尝试

a = 0
def f():
    a = a + 1
f()

这会给你同样的错误。

在您的 Conway's Game of Life 代码中,您可以通过使 glider 可用于全局范围 global glider 来规避此问题。还要确保您的轴限制允许看到动画。

完整示例:
import itertools
import matplotlib.pyplot as plt
import matplotlib.animation as animation

def neighbors(point):
    x, y = point
    for i, j in itertools.product(range(-1, 2), repeat=2):
        if any((i, j)):
            yield (x + i, y + j)

def advance(board):
    newstate = set()
    recalc = board | set(itertools.chain(*map(neighbors, board)))

    for point in recalc:
        count = sum((neigh in board)
                for neigh in neighbors(point))
        if count == 3 or (count == 2 and point in board):
            newstate.add(point)

    return newstate

glider = set([(0, 0), (1, 0), (2, 0), (0, 1), (1, 2)])

fig, ax = plt.subplots()

x, y = zip(*glider)
mat, = ax.plot(x, y, 'o')

def animate(i):
    global glider
    glider = advance(glider)
    x, y = zip(*glider)
    mat.set_data(x, y)
    return mat,

ax.axis([-15,5,-15,5])
ani = animation.FuncAnimation(fig, animate, interval=50)
plt.show()

python - 如何使用 matplotlib 为一组点设置动画?-LMLPHP

关于python - 如何使用 matplotlib 为一组点设置动画?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46849712/

10-12 17:00