Search code examples
pythonanimationrandom-walk

FuncAnimation only returning one frame


I am trying to display a random walk for a population and show it in an animation, however, FuncAnimation does not seem to be getting past the first frame, although it is accessing the animate function as the frame is displayed in spyder.

The animation is meant to stop when the entire population (Npop) has Bool=1 or when t reaches 250

step_set = (-1, 0, 1)
    
def animate(t):
    global NpopCol,NpopA, NpopB, Npop,path, step,step_set,Bool, direction
    print(t)
    for i in range(0,Npop):
        path[i] =step[i]          
        direction =np.random.choice(step_set,2)
        for j in range(0,Npop):
            if(Bool[j]==1):
                if(path[j][0]==path[i][0])&(path[j][1]==path[i][1]):
                        Bool[i]=1 
        ##generate a path, moving 1 square right/left , up/down / diagonally
        step[i]=step[i]+ direction
    NpopCol=[]
    for i in range (0,Npop):
        if(Bool[i]==1):  
            NpopCol.append('r')
        if(Bool[i]==0)  &(i<NpopA)   : 
            NpopCol.append('b')
        if(Bool[i]==0)  &(i>=NpopA)   : 
            NpopCol.append('g')
    
    if (sum(Bool)==Npop) or t>250:
        anim.event_source.stop()
    ##t=t+1
    scat.set_offsets(path)   
    scat.set_color(NpopCol)     
    return scat,path
     

fig , ax=plt.subplots()
scat=plt.scatter(path[:,0], path[:,1],c=NpopCol,s=10)
anim=FuncAnimation(fig,animate,interval=10)
plt.show()

The above is the code I am using, any help on this matter would be greatly appreciated.

thanks in advance!


Solution

  • I turns out something was wrong with Spyder while running this (perhaps some kind of setting that I had set previously or some clashing libraries). My colleague also ran the same code and it worked for him.

    I tried the same code on Google Colab and it worked! If you have the same issue, I would suggest running it on a different environment.