R/game.R

#' A Reference Class to represent a Game of Life
#'
#' @field board Board-object to manage states and state-transistion
#' @field rule Rule-object to control state-changes of the board
#' @field verbose decide if basic information should be printed in each iteration
#' @field plot decide if board should be plotted in each iteration
#' @field max_iterations numeric to set the maximum number of iterations
#' @field endless decide if game is endless
#' @field sleep_duration set time to sleep for plotting
#' @export Game
#' @exportClass game
#' @include board.R
#' @include rule.R
#' @examples
#' library(gameOfLife)
#'
#' rule = Rule(survive = c(2, 3), revive = c(3))
#'
#' gol = Game(
#'   board = Board(
#'     matrix = gliders,
#'     shrink_counter = 0),
#'   rule = rule,
#'   iteration = 0,
#'   endless = FALSE,
#'   max_iterations = 100,
#'   sleep_duration = 0.05,
#'   plot = TRUE,
#'   verbose = TRUE
#' )
#'
#' gol$run()

Game = setRefClass("game",
  fields = list(
    board = "board",
    rule = "rule",
    iteration = "numeric",
    endless = "logical",
    max_iterations = "numeric",
    sleep_duration = "numeric",
    plot = "logical",
    verbose = "logical"
  ),
  methods = list(
    nextState = function(){
      "Takes the game to it's next state"
      if(verbose){
        if(iteration == 0) print("| it | living | size |")
        print(paste("| ",iteration, " | ",sum(board$matrix)," | ",length(board$matrix)," |"))
      }
      board$applyRule(rule)

      if(plot){
        board$plotBoard()
        Sys.sleep(sleep_duration)
      }
      iteration <<- iteration + 1
    },
    run = function(){
      "Iterate game constantly until maximum number of iterations is reached or endlessly"

      if(endless == TRUE) condition = function() TRUE
      else condition = function() iteration < max_iterations

      while(condition()) nextState()
    }
  ))
chrlen/gameOfLifeAgain documentation built on July 9, 2019, 11:42 a.m.