R/ep.R

# ep stands for experimental play
#
# It is a global object that manages the state of play
# possible for several human players
#
# A specific app object has a reference to an ep
# and a player field

get.ep = function(app=getApp()) {
	app[["ep"]]
}

ep.game = function(ep=get.ep()) {
  ep$play$game
}

ep.stage = function(ep=get.ep()) {
  stage.num = ep$stage.num
	if (stage.num < 1 | stage.num > length(ep$vg$stages)) return(NULL)
	ep$vg$stages[[stage.num]]
}


ep.page.name = function(ep=get.ep()) {
  stage.num = ep$stage.num
  if (stage.num==0) {
    return("start-page")
  } else if (stage.num > length(ep$vg$stages)) {
    return("end-page")
  } else {
    return(ep.stage(ep)$name)
  }
}

# Get rmd file of currently shown page
ep.page.file = function(ep=get.ep(), copy.auto=FALSE, make.auto=TRUE) {
  page.name = ep.page.name(ep)
  page.dir = get.pages.dir(ep.game())
  file = file.path(page.dir, paste0(page.name,".Rmd"))
  if (file.exists(file)) return(file)
  auto.file = file.path(page.dir, paste0(page.name,".auto.Rmd"))
  if (!file.exists(auto.file) & make.auto) {
    make.page.rmd(ep.game(ep),page.name = page.name, stage=ep.stage(ep))
  }
  if (file.exists(auto.file)) {
    if (copy.auto) {
      file.copy(auto.file, file)
      return(file)
    }
    return(auto.file)
  }
  return(NULL)
}


# new experiment play
new.ep = function(game,bots,human=1, mainUI="mainUI", verbose=FALSE) {
	restore.point("new.ep")

  play = new_play(game,bots, human)
	ep = as.environment(list(play=play, vg=game$vg, stage.num=0, human=human, mainUI=mainUI, num.stages = length(game$vg$stages), verbose=verbose))
	ep
}

ep.copy = function(ep) {
  as.environment(as.list(ep))
}

ep.play.until.human = function(ep) {
  restore.point("ep.play.until.human")
  play = ep$play
  game = ep.game(ep)

  while(
    ((play$is.human.stage==FALSE) |
     (play$human.stage.finished >= play$auto.stage.finished)) &
    (play$auto.stage.finished < ep$num.stages)
  ) {
    if (ep$verbose) {
      num = play$auto.stage.finished+1
      cat("\nPlay auto stage ",num, " ", ep$vg$stages[[num]]$name,"\n")
    }
    play = play_stage_auto(play)
    if (ep$verbose) {
      li = c(list(.cond=play$.last.condition,.player=paste0(play$.last.player, collapse=", "),is.human = play$is.human.stage), play$hist)
      print(as.data.frame(li, row.names=FALSE))
      cat("\n")
    }

  }
  ep$play = play
  if (play$is.human.stage & (play$auto.stage.finished > play$human.stage.finished)) {
    ep$stage.num = play$auto.stage.finished
    if (ep$verbose) {
      cat("\nWait for human input in stage", ep$stage.num, ep$vg$stages[[ep$stage.num]]$name)
    }

  } else {
    ep$stage.num = ep$num.stages +1
    if (ep$verbose) {
      cat("\nAll stages finished.")
    }

  }
  return(ep)
}
skranz/gtreeWebExp documentation built on June 16, 2019, 12:07 a.m.