SirSaleh SirSaleh - 1 year ago 100
R Question

Equivalent to C getch() in R

I'm developing a

2048
game in
R
for fun. I used a
scan(n=1)
to user enter him/her move key. But as always in script languages it needs to press
Enter
key to proceed.

Q: Is there any method to make something like
getch
in
C
to apply in
R
to proceed just buy pressing button without pressing
Enter
?

Any help will be appreciated.

Answer Source

I suggest you to use the windows/x11 graphic environment handlers (LINK).

Here's an example opening a window where you can move a blue square using your keyboard arrows :

keyboardAwareSquare <- function(){
  currPosition <- c(0,0,1,1) 
  drawRect <- function(){
    plot(c(0, 4), c(0, 4), type= "n", xlab = "", ylab = "",xaxt='n',yaxt='n')
    rect(currPosition[1],currPosition[2],currPosition[3],currPosition[4],col='lightblue')
  }
  keydown <- function(key) {
    offsetX <- 0
    offsetY <- 0
    if(key=='Left') offsetX <- -1
    if(key=='Right') offsetX <- 1
    if(key=='Down') offsetY <- -1
    if(key=='Up') offsetY <- 1
    if(!any(currPosition[c(1,3)] + offsetX < 0) && !any(currPosition[c(1,3)] + offsetX > 4)){
      tmp <- currPosition
      tmp[c(1,3)] <- tmp[c(1,3)] + offsetX
      currPosition <<- tmp
    }
    if(!any(currPosition[c(2,4)] + offsetY < 0) && !any(currPosition[c(2,4)] + offsetY > 4)){
      tmp <- currPosition
      tmp[c(2,4)] <- tmp[c(2,4)] + offsetY
      currPosition <<- tmp
    }
    drawRect()
  }
  drawRect()
  setGraphicsEventHandlers(prompt='use the keyboard arrows to move',onKeybd = keydown)
  eventEnv <- getGraphicsEventEnv()
}

# this part works differntly according to your OS 
if(.Platform$OS.type == 'unix')  x11(type = "Xlib") else x11()

keyboardAwareSquare()
getGraphicsEvent()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download