我有以下代码:
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)
}
当我在批处理模式下#game
之后运行零件时,R也不会停止等待“你想先行?(Y / N)”也不重复重复块。当我逐行点击它时,一切都可以正常工作。
我做错了什么?我如何通过用户互动来解决问题以获得不错的程序流程? (或者我是否真的必须逐行点击这部分代码?我希望不要......)
答案 0 :(得分:0)
将其添加到代码的开头:
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]] }
})()
}
现在你得到了
> readline()
[1] "Y"
> readline()
[1] 5
> readline()
[1] 2
编辑:可选择清理(如果您运行的是更多脚本),请将rm(readline)
添加到脚本的末尾。
EDIT2:对于那些不喜欢<<-
的人,请将counter <<- counter + 1
替换为assign('counter', counter + 1, envir = parent.env(environment()))
。