Play Zork in RStats

Frotz is an Infocom Z-Machine interpreter for playing text adventure games (also known as interactive fiction) such as Zork and Hitchhiker’s Guide to the Galaxy.

Here I’m using {processx} to read/write to frotz on the command line.

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Play Zork in the R console with 'frotz' + {processx}
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
play_zork <- function(game = "../infocom/zork.z3") {

  #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  # Initialise Game
  #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  sf  <- process$new('dfrotz', args = c(game),
                     stdin = '|', stdout = '|', stderr = '|')
  Sys.sleep(0.1)
  cat(sf$read_output())

  #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  # Game Loop
  #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  while(TRUE && sf$is_alive()) {
    cmd <- readline(">>> ")
    if (cmd == 'Q')  {sf$kill(); break }
    sf$write_input(paste(cmd, "\n"))
    Sys.sleep(0.1)
    cat(gsub("\\s+>$", "", trimws(sf$read_output())), "\n")
  }
}
play_zork()