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

标签 python animation matplotlib conways-game-of-life

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

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

这会给你同样的错误。

在您的康威生命游戏代码中,您可以通过使 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()

enter image description here

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

相关文章:

python - 为什么del是指令而不是python中的方法?

ios - 来自 XIB 的自定义 UIView 加载巨大的 subview

java - java小程序中的移动图像

javascript - 如何在 paper.js 中沿着贝塞尔曲线路径对对象进行动画处理?

python - 如何在 matplotlib 颜色条中创建自定义断点?

Python 在 PIL Image 对象上保存 matplotlib 图

python - 无法对齐 matplotlib twinx 轴的刻度

python - 如何让我的程序随机列出列表中的每个项目并且只列出一次

Python - 对数组列表进行分类第 2 部分

python - 如何监控 Python 文件的变化?