Take the 2-minute tour ×

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()
    game <- move(game,1,1)

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)

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())
  game <- altern.moves()

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...)

share|improve this question
From ?readline: This can only be used in an interactive session. –  sgibb Mar 23 at 11:52
@sgibb: So how do I have to change the code to give interaction in batch mode? –  vonjd Mar 23 at 11:55

1 Answer 1

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())).

share|improve this answer

Your Answer


