R code for CA

Below, you find the R code for computing the Game of life

n=20                          # Size of matrix
mat=matrix(0,ncol=n,nrow=n)   # Create a n x n matrix with zeros
mat[5:14,10]=1                # Add 10 live cells
temp_mat=mat                  # Create a temporary matrix
image(t(apply(mat, 2, rev)),col=c("grey50","seagreen1"),yaxt="n",xaxt="n") # Plot image
grid(nx=n,ny=n,col="grey70",lty=1)
mat1=mat[c(2:n,1),];mat2=mat[c(n,1:n-1),]; mat3=mat[,c(2:n,1)]; mat4=mat[,c(n,1:n-1)]; mat5=mat[c(2:n,1),c(2:n,1)]; mat6=mat[c(2:n,1),c(n,1:n-1)]
mat7=mat[c(n,1:n-1),c(n,1:n-1)];mat8=mat[c(n,1:n-1),c(2:n,1)];
for (k in 1:200){      # Repeat 200 times
 numb_alive=mat1+mat2+mat3+mat4+mat5+mat6+mat7+mat8
 temp_mat[mat==1 & numb_alive<2]=0
 temp_mat[mat==1 & numb_alive>3]=0
 temp_mat[mat==1 & (numb_alive==2 | numb_alive==3)]=1
 temp_mat[mat==0 & numb_alive==3]=1
 mat=temp_mat # Update matrix
 mat1=mat[c(2:n,1),];mat2=mat[c(n,1:n-1),];mat3=mat[,c(2:n,1)];mat4=mat[,c(n,1:n-1)]
 mat5=mat[c(2:n,1),c(2:n,1)];mat6=mat[c(2:n,1),c(n,1:n-1)];mat7=mat[c(n,1:n-1),c(2:n,1)]
 mat8=mat[c(n,1:n-1),c(n,1:n-1)]
 image(t(apply(mat, 2, rev)),col=c("grey50","seagreen1"),add=TRUE)   # Plot image
 grid(nx=n,ny=n,col="grey70",lty=1)
 Sys.sleep(0.5) # To see changes on the screen we need to pause the loop
}