2017-10-20 13 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/ 애니메이션 - 콘웨이 - 게임 라이프) 또는 [this one] (https://stackoverflow.com/questions/46196346/why-does-my-game-of-life-simulation-slow-down-to- a-crawl-within-seconds-matplot). – ImportanceOfBeingErnest

답변

3

코드는 실제로 오류가 발생합니다. 문제는 할당하기 전에 glider을 참조하는 것입니다.

python 함수에서 지역 변수 범위를주의하십시오. 예 : 시도해보십시오.

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

동일한 오류가 발생합니다.

Conway의 Game of Life에서 gliderglobal 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 ("출력. gif "writer ="imagemagick ")'. – ImportanceOfBeingErnest

+0

대단히 감사합니다! –