#' GoL simulation from input
#'
#' @description Function that simulates Game of Life starting with a given input
#'
#' @param board input .csv for the simulation
#' @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
#' tf = system.file("exampledata/exampleboard.csv", package = "golr")
#'
#' gol_simulate_input(tf, 50, "inputsim.gif")
#' gol_simulate_input(tf, 25)
#'
#' unlink(tf)
gol_simulate_input = function(board, loops, filename = ""){
tictoc::tic()
board = as.matrix(utils::read.csv(board))
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()
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.