Save matrix of color images

With so much effort I managed to simulate (roughly) an animated version of Gonway’s “Game of Life”.

julia> using Plots,IterTools, Colors

julia> function gol1(n, init=rand(Bool, 10,10))
       
           function gen(m)
               M=copy(m)
               for c in eachindex(m)
                   snb=sum(m[intersect(ci[c] .+ nb, ci)]) - m[c]
                   (m[c] && (snb<2 || snb>3)) ? M[c]=false : (!m[c] && snb==3) ? M[c]=true  : nothing # M[c]=m[c]
               end
               M
           end
       
           m=init
           ci=CartesianIndices(m)
           nb=CartesianIndices((-1:1,-1:1))
           xl,xr = 0.5,size(m,1)+.5
           cm=collect(takestrict(iterated(gen, m),n))
          anim= @animate for fr in eachindex(cm)
               heatmap(cm[fr], yflip=true, legend=:none, aspect_ratio = :equual , xlims=(xl,xr), ticks=false);
               vline!(1+xl:xr,c=:red);
               hline!(1+xl:xr,c=:red)
               #display(hline!(1+xl:xr,c=:red))
               #sleep(1)
           end
           gif(anim, "gol1_anim_fps2.gif", fps = 2)
       end
gol1 (generic function with 2 methods)

julia> 
       function init7(n)
           I0=zeros(Bool,9,9)
           I0[:, 5].=true
           repeat(I0, n,n)
       end
init7 (generic function with 1 method)

julia> gol1(20,init7(2))
[ Info: Saved animation to C:\Users\sprmn\.julia 1.8.3\gol1_anim_fps2.gif   

gol1_anim_fps2
game of live nX2

I found that it is possible to obtain an array of colors by using the Colors package and populating the arrays with values of type RGB, which looks even nicer to me.

julia> function gen(m)
           M=copy(m)
           foreach(c -> let
               snb=count(w->w==one(RGB),m[intersect(c .+ CartesianIndices((-1:1,-1:1)),CartesianIndices(m))]) - (m[c]==one(RGB))
               (m[c]==one(RGB) && (snb<2 || snb>3)) ? M[c]=zero(RGB) : (m[c]==zero(RGB) && snb==3) ? M[c]=one(RGB)  : nothing
           end , CartesianIndices(m))
           M
       end
gen (generic function with 1 method)

julia> cm=collect(takestrict(iterated(gen, begin I0=zeros(RGB,9,9);
       I0[:, 5].=one(RGB);repeat(I0,2,2) end),30))

What I can’t do is get the images in a form that I can save and then create an animated gif with.

Does

using FileIO
save("gol.gif", img; fps=10)

work for you? In this case img should be a 3d RGB or Gray array, where the third axis is time.

1 Like

And thanks to this I managed to fit everything into

seven lines,

even if they were very narrow :smile:.

PS
In fact, I had arrived at this solution a little earlier by better reading one of your answers (very concise/dry in an old post on a similar topic, even if very precise and exhaustive)