停止动画-康威的生活游戏 [英] stopping animation - Conway's game of life
本文介绍了停止动画-康威的生活游戏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是康威(Conway)的生活游戏代码,我是在两个相互配合的细胞之间进行的. 我想说十代之后停止动画. 我尝试使用动画的帧",但动画不会停止. 十个世代后该如何停止呢? 这是代码:
Here is a code of Conway's game of life I made between two spices of cells which cooperate. I want to stop the animation after let's say 10 generations. I tried to use the "frames" of animation, but the animation doesn't stop. How do I stop it after 10 genetaions? Here is the code:
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()
推荐答案
您需要添加参数repeat=False
告诉动画在10帧后不要重新启动,
You need to add the argument repeat=False
to tell the animation not to restart after 10 frames,
ani = animation.FuncAnimation(fig, update, frames=10,
interval=50, save_count=50, blit=True, repeat=False )
这篇关于停止动画-康威的生活游戏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文