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

时间:2017-10-20 13:05:18

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

我实施了康威的生命游戏:

// check all your parameters
if(testarray == null) return E_INVALIDARG;
if(testarray->vartype != VT_ARRAY|VT_BSTR
  && testarray->vartype != VT_ARRAY|VT_VARIANT)
    return E_INVALIDARG;
if(testarray->parray == null) return E_INVALIDARG;


// Now we have established we have an array, and that it
// is either a string array or a variant array.

VARTYPE vt = VT_EMPTY;
SafeArrayGetVarType(testarray->pArray, &vt);
// Now we need to take different actions based on the vartype.
if(vt == VT_BSTR){
    // we have an array of strings
    // Proceed as above.
}else if(vt == VT_VARIANT){
    // we have an array of variants, probably supplied by VBScript
    // Read them one by one and use VariantChangeType to get a string

}else{
    // We have some other array type we don't support
    return E_INVALIDARG;
}

我想要显示结果,所以我尝试从Matplotlib animation example修改给定的示例:

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

但只是绘制the initial points

1 个答案:

答案 0 :(得分:4)

您拥有的代码实际上应该产生错误。问题是您在分配之前引用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