2017-10-20 130 views
2

我有生命的實施康威的遊戲新作:如何使用matplotlib動畫一組點?

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

+0

您可能會感興趣的遊戲生活的其他matplotlib的實現,如[這一個](https://stackoverflow.com/questions/45653550/停止動畫conways遊戲的生活)或[這一個](https://stackoverflow.com/questions/46196346/why-does-my-game-of-life-simulation-slow-down-to-一個抓取中之秒-matplot)。 – ImportanceOfBeingErnest

回答

3

您擁有的代碼實際上應該會產生錯誤。問題在於您在分配之前先參考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

+0

出於好奇@ImportanceOfBeingness,你是如何產生這個gif的? –

+1

@ReblochonMasque在這種情況下,您可以[保存任何動畫](http://matplotlib.org/api/_as_gen/matplotlib.animation.Animation.html#matplotlib.animation.Animation.save):'ani.save(「output。 gif「writer =」imagemagick「)'。 – ImportanceOfBeingErnest

+0

非常感謝! –