2017-08-12 90 views
0

這裏是康威的生命遊戲代碼,我在兩種配合的細胞香料之間製作的遊戲。 我想讓我們說10代後停止動畫。 我試圖使用動畫的「幀」,但動畫不停止。 如何在10個基因組後停止它? 下面是代碼:停止動畫 - 康威的生命遊戲

import numpy as np 
import matplotlib.pyplot as plt 
import matplotlib.animation as animation 
import random 

N = 100 
OnTypeOne = 10 
OnTypeTwo= -10 
OFF = 0 
vals = [OnTypeOne , OnTypeTwo, OFF] 


# populate grid with random on/off - more off than on 
grid = np.random.choice(vals, N*N, p=[0.2,0.2, 0.6]).reshape(N, N) 

def update(data): 
    global grid 
    x=0 
    # copy grid since we require 8 neighbors for calculation 
    # and we go line by line 
    newGrid = grid.copy() 
    for i in range(N): 
    for j in range(N): 
     # compute 8-neghbor sum 
     # using toroidal boundary conditions - x and y wrap around 
     # so that the simulaton takes place on a toroidal surface. 
     total = (abs (grid[i, (j-1)%N])+ abs (grid[i, (j+1)%N]) + 
      abs (grid[(i-1)%N, j]) + abs (grid[(i+1)%N, j]) + 
      abs (grid[(i-1)%N, (j-1)%N]) + abs (grid[(i-1)%N, (j+1)%N]) + 
      abs (grid[(i+1)%N, (j-1)%N]) + abs (grid[(i+1)%N, (j+1)%N]))/10 
     # apply Conway's rules 
     if grid[i, j] == OnTypeOne: 
     if (total < 2) or (total > 3): 
      newGrid[i, j] = OFF 
     if (total==3): 
      newGrid[i, j] = OnTypeOne 
     if grid[i, j] == OnTypeTwo: 
      if (total < 2) or (total > 3): 
       newGrid[i, j] = OFF 
      if (total==3): 
       newGrid[i, j] = OnTypeTwo 
     if grid[i, j] == OFF: 
      if total==3: 
       x=random.random() 
       if x<=0.5: 
        newGrid[i,j]=OnTypeOne 
       elif x>0.5: 
        newGrid[i,j]=OnTypeTwo 
      if total!=3: 
       newGrid[i,j]=OFF 




    # update data 
    mat.set_data(newGrid) 
    grid = newGrid 
    return [mat] 

# set up animation 
fig, ax = plt.subplots() 
mat = ax.matshow(grid) 

ani = animation.FuncAnimation(fig, update, frames=10, 
interval=50,save_count=50 
         , blit=True) 

plt.show() 

回答

1

您需要添加參數repeat=False告訴不要在10幀啓動動畫,

ani = animation.FuncAnimation(fig, update, frames=10, 
           interval=50, save_count=50, blit=True, repeat=False) 
+0

非常感謝你。有用! – Idit