Question

I have the following code:

first.moves <- function()
{
  go.first <- readline("Do you want to go first? (Y/N) ")
  if (go.first == "Y" || go.first == "y")
  {
    game <- altern.moves()
  }
  else
  {
    game <- move(game,1,1)
  }
  return(game)
}

altern.moves <- function()
{
  plyr.mv <- as.numeric(readline("Please make a move (1-9) "))
  game <- move(game,plyr.mv,0)
  cmp.mv <- valid.moves(game)[1]
  game <- move(game,cmp.mv,1)
  return(game)
}

#game
game <- matrix(rep(NA,9),nrow=3)
print("Let's play a game of tic-tac-toe. You have 0's, I have 1's.")
(game <- first.moves())
repeat
{
  game <- altern.moves()
  print(game)
}

When I run the part after #game in batch mode neither does R stop to wait for "Do you want to go first? (Y/N)" nor does it repeat the repeat block. Everything works fine on its own and when I click through it line-by-line.

What am I doing wrong and how can I remedy the situation to have a decent program flow but with user interaction? (or do I really have to click through this part of the code line-by-line? I hope not...)

Was it helpful?

Solution

Add this to the beginning of your code:

if (!interactive()) {
  batch_moves <- list('Y', 5, 2) # Add more moves or import from a file
  readline <- (function() {
    counter <- 0
    function(...) { counter <<- counter + 1; batch_moves[[counter]] }
  })()
}

Now you get

> readline()
 [1] "Y"
> readline()
 [1] 5
> readline()
 [1] 2

EDIT: Optionally, to clean up (if you are running more scripts), add rm(readline) to the end of your script.

EDIT2: For those who don't like <<-, replace counter <<- counter + 1 with assign('counter', counter + 1, envir = parent.env(environment())).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top