R/gol_simulate_random.R

Defines functions gol_simulate_random

Documented in gol_simulate_random

#' GoL random simulation
#'
#' @description Function that simulates Game of Life with given size and length parameters
#'
#' @param side size of the side of the square board
#' @param loops amount of iterations of the simulation
#' @param filename output .gif filename, determines whether we want a live plot display or a saved .gif. FALSE by default
#'
#' @return .gif file of the simulation or live display of the simulation
#' @export
#'
#' @examples
#' gol_simulate_random(50, 25,"randomsim.gif")
#' gol_simulate_random(100, 10)

gol_simulate_random = function(side, loops, filename=""){
  tictoc::tic()
  board = matrix(sample(0:1,side*side, replace = TRUE),nrow = side, ncol = side)
  iter = 1
  col = ncol(board)
  row = nrow(board)
  from = board
  to = board
  if(nchar(filename)>0){
    storage <- array(from, c(col, row, loops + 1))} #array for gif storage, created only if filename given
  print("Simulating Game of Life...")
  while (iter <= loops){
    tictoc::tic(iter)
    if(!exists("storage")){
      Sys.sleep(0.05)
      print(lattice::levelplot((from[row:1,]), colorkey=FALSE, xlab = NULL, ylab = NULL,#live display
          par.settings = list(regions = list(col = c("#000000", "#5fc000")))))
    }
    for (i in 1:(row)){
      for (j in 1:(col)){
        neigh = sum(from[max(1,i-1):min(nrow(from),i+1),
                max(1,j-1):min(ncol(from),j+1)]) - from[i,j]
        if(from[i,j] == 0 & neigh == 3){ #reproduction
          to[i,j] = 1
        }else if (from[i,j] == 1 & (neigh == 3 | neigh == 2)){ #living on

        }else{ #death
          to[i,j] = 0
        }
      }
    }
    iter = iter + 1
    from = to
    if(exists("storage")){
    storage[,,iter] = to #gif creation solution from https://www.r-bloggers.com/2012/11/fast-conways-game-of-life-in-r/
    }
    tictoc::toc()
  }
  if(exists("storage")){
    storage = storage/max(storage)
    print("Writing gif...")
    caTools::write.gif(storage, filename, col="jet", delay=5)
  }
    print("Complete.")
  tictoc::toc()
}
wejengin2/golr documentation built on Dec. 23, 2021, 5:10 p.m.