[R Games] R speed type (beta version 0.12)

#1
Hi Guys,

I got a little bored with my static battleship game. I also wanted to know if a way existed to read user input without breaking a loop (I need to do this for something else). So called "non-blocking user input", which is simple in other languages but I had no idea if this could work in R easily. For instance scan, menu, readline all don't have this functionality.

So I thought I might try to crack it by making a clone of a classic dos game. Platform games are too complex but a speed type game should be ideal. However after playing around the only way I can think of to do this (implement "non-blocking user input") is via a connection to a file. So I implement a GUI from e.g. a C++ code, and then type my words in there, which changes the contents of a file.. which can then be read by R. A major pain to say the least. You guys have any ideas on how to implement "non-blocking user input"?

How to play? In this early beta version you will need to open both R and a file editor. Copy & paste the code into R or use source(), then type "typespeed()" and the game should start. You can choose out of 3 libraries (please help me improve these, or add suggestions for your own). Make sure you open the textfile as specified, then choose a menu item (limited to 1 - 3 at this time) and play by editing the text file. Type the word you see on the screen as fast as you can (then hit ctrl + s) and type the next word (ctrl+a+del is a useful short cut). I know this interface sucks which is why I will improve it with time (suggestions are more than welcome).


Credit goes to Dason for showing us great new ways of procrastination in R.

Find the code here View attachment 1452

This has only been tested on Linux (PCLOS, e17,R 2.13.0).

As for copyright ect, the code is free for everyone to use and abuse. Give credit where credit is due, or don't- I don't mind as my coding is really is not that impressive (very basic R).
 

Dason

Ambassador to the humans
#2
Re: [R Games] R speed type (beta version 0.1)

If you're not opposed to using gWidgets/gWidgetsRGtk2 then you can get nonblocking user input because it implements handlers.

I haven't looked at the code yet but I'll take a look at it later. Is the file you open able to be read and written to from R?
 
#3
Re: [R Games] R speed type (beta version 0.1)

Hi Dason,

I'm not opposed at all, I was also thinking of using the R-Tcl/Tk interface. I'm still a bit disappointed it cant be done just with the base package. I'll look into it next time I feel like procrastinating on R games.

FOR NOW: To be able input commands in the file you need to open the file in an external editor, as going through R interrupts the program. This is the first thing I will implement as an improvement, but for now it works and I've had fun at speedtyping.

Ideally, you would want user input from the console without blocking, but i have no idea on how to implement that easily. Any easy solution would make great games possible (think of missile defense).

One other way I believe it could be done is through running a background script, one that operates the descent of words, while the main console is used for word input (actually that may be the easiest way to do this - to be implemented in version 0.2)

Check for updates.
 

trinker

ggplot2orBust
#4
Re: [R Games] R speed type (beta version 0.1)

Hi TheEcologist,

I tried your R speed type beta on a windows 7 machine (running [R] 2.14 beta version).

Anyway It gets me to the menu screen and gives me a warning (I posted the whole commander dialogue below) and stops. Am I doing something wrong or is because of my use of windows 7?

> typespeed()
"x"
"1" "input.txt"
[1] "type in the file input.txt in C:/Users/Rinker/Desktop/PhD Program/CEP 523-Stat Meth Ed Inference/R Stuff"

Choose menu item
1: 3
[1] "Game start"
Error in file(file, "rt") : cannot open the connection
In addition: Warning message:
In file(file, "rt") :
cannot open file 'input.txt': No such file or directory
Can't wait to pick apart the code and steal ideas (and enjoy the game too :yup:) as I have done (both steal and enjoy) with Dason's minsweeper. Though I haven't delved into the gwidgets his latest version uses. Thanks for answering the question and thanks for taking the time to write to code.
 
#6
Re: [R Games] R speed type (beta version 0.1)

Bugs are fixed. it works in my Win 7 VM.

version 0.12;

New: the game now reads the final line in your text file, therefore for every new word you just need to press enter and type it (don't forget to save the file with ctrl+s otherwise there is no input to R).
 

Dason

Ambassador to the humans
#7
Re: [R Games] R speed type (beta version 0.1)

Here's an example of using gWidgetsRGtk2 to allow for unblocked user entry. I added an option to add text to the right side of the plot and erase the input afterwards so you could work from there. There's a lot that you don't need to learn how to use the interface but I had this example lying around so it was easy to modify. You need gWidgetsRGtk2 and cairoDevice installed to get this to work though.

Code:
gwtkdensity = function(samplesizes=c(50,100,200,300), ...){
  require(gWidgetsRGtk2)
  require(cairoDevice)
  
  #Creating the vectors of names we care about
  availDists = c(Normal = "rnorm", Exponential = "rexp", Uniform = "runif")
  availKernels = c("gaussian", "epanechnikov", "rectangular",
			"triangular","biweight","cosine","optcosine")

  # Get some initial data
  # x holds the data we'll be smoothing
  x <- rnorm(samplesizes[1])

  # Handler we'll use to update the plot  
  updatePlot = function(h,...){
	  plot(density(x,adjust = svalue(bandwidthAdjust),
	  	kernel = svalue(kernel)),main="Density plot")
	  rug(x)
  }
                
  # Called when we want to update the plot and
  # get a new sample at the same time
  updatePlot1 = function(h,...){
    newSample()
	  updatePlot
  }

  newSample <- function(h, ...){
    x <<- do.call(availDists[svalue(distribution)],list(svalue(sampleSize)))
  }
  
  # Make the main window
  win = gwindow("gwtkdensity")
  # Need a group to add things to
  BigGroup = ggroup(cont=win)
  # Group for the options on the left
  gp = ggroup(horizontal=F,cont = BigGroup)

  # Stuff to control the distribution of the sample
  tmp = gframe("Distribution",container = gp,expand=T)
  distribution = gradio(names(availDists),horizontal = F,
			cont=tmp, handler = updatePlot1)

  # Control sample size
  tmp = gframe("Sample size", container = gp, expand=T)
  sampleSize = gradio(samplesizes,cont = tmp,
			handler = updatePlot1)

  # Control the kernel of the kde
  tmp = gframe("Kernel",container=gp,expand=T)
  kernel = gcombobox(availKernels, cont=tmp,handler = updatePlot)

  # Control the bandwidth
  tmp = gframe("Bandwidth adjust", container = gp, expand=T)
  bandwidthAdjust = gslider(from=0.01,to=2,by=.01,value=1,
				cont =tmp,expand=T,handler=updatePlot)
                        
  # Give option to get a new sample
  tmp = gframe("Resample",container = gp,expand=T)
  resample = gbutton("Resample",container=tmp,handler=updatePlot1)
  
  # Added just for you TheEcologist
  tmp = gframe("Add text", container = gp, expand = T)
  plottextandremove <- function(h, ...){
    txt <- svalue(h$obj)
    if(txt != ""){
      mtext(txt, side = 4)
      svalue(h$obj) <- ""
    }
  }
  textadd = gedit(cont = tmp, handler = plottextandremove)

  #Without this we don't get the graphics connected to
  #the controls.
  add(BigGroup,ggraphics())

  #If we don't call updatePlot then we don't get
  #an image until we change something.
  updatePlot()
}

gwtkdensity()
 
#8
Re: [R Games] R speed type (beta version 0.1)

Hee Dason,

Thanks allot! You did not need to do that, I had a C++ interface running, but the C integration isn't as platform or user friendly to implement.


Anyway this should speed up the next version greatly, thanks man! So check for updates.

Also are you still serious about packaging this to R? Cause I definitely still want to try.

Cheers,

M.
 

Dason

Ambassador to the humans
#9
Re: [R Games] R speed type (beta version 0.1)

Created an example more suited to your speed test. It has a handler which automatically updates the plot and allows user input to modify the plot as well. It's clearly not exactly what you need but hopefully gives a good idea of how to use the handlers or what not - let me know if you have questions.
Code:
simpleexample = function(){
  require(gWidgetsRGtk2)
  require(cairoDevice)

  count <- 0
  usercount <- 0
  
  # function to make the first plot.
  startPlot = function(){
    x <- 1:5
    pnts <- (x-1)/x
    plot(pnts, pnts, type = "n", xlab = "", ylab = "", xlim = c(0,1), ylim = c(0,1))
  }

  # What the idle handler calls 
  inc <- function(h, ...){
    count <<- count + 1
    val <- (count-1)/count
    points(val, val, col = count)
  }

  # What gets called when a user inputs stuff...
  userinput <- function(h, ...){
    txt <- svalue(h$obj)
    if(txt != ""){
      usercount <<- usercount + 1
      val <- (usercount-1)/usercount
      text(val, val+.1, txt)
      svalue(h$obj) <- ""
    }
  }
 
  # Make the main window
  win = gwindow("gwtkdensity")
  
  # Need a group to add things to
  BigGroup = ggroup(cont=win)
  
  # Group for the options on the left
  gp = ggroup(horizontal=F,cont = BigGroup)

  # Added just for you TheEcologist
  tmp = gframe("Add text", container = gp, expand = F)
  textadd = gedit(cont = tmp, handler = userinput)
  
  #Was going to add a space to edit where the x, y location
  # of the text was but got lazy...
#   tmp = gframe("Location", container = gp, hor = T, expand = F)
#   xtmp = gframe("x", container = tmp, expand = T)
#   ytmp = gframe("y", cont = tmp, expand = T)
#   xedit = gedit()
    
  #Without this we don't get the graphics connected to
  #the controls. But this is why we need cairoDevice...
  add(BigGroup, ggraphics())

  #If we don't call updatePlot then we don't get
  #an image until we change something.
  startPlot()
  addHandlerIdle(gp, interval= 1000, handler = inc)
}

simpleexample()
I am still serious about packaging it up - I got an Rforge page and everything - but I haven't actually done anything to get the repository set up or customize the page...

The thing I'm thinking of is I'm wondering if there should be two packages instead of just one. One where we have the basic versions of things that doesn't require gWidgets and another that uses gWidgets. I'm just not sure the best way to do it.
 

Dason

Ambassador to the humans
#10
Re: [R Games] R speed type (beta version 0.1)

You know I'm used to dealing with gWidgets and it can be a nice package if you can get gWidgetsRGtk2 up and running (not necessarily an easy task on all computers) but it looks like some of the functionality might be reproducible using tcltk. Now I don't like tcltk looks quite as nice as Gtk (but then again Gtk looks kind of ... bland if you don't have a nice theme installed) so that's a drawback but it does come standard so there wouldn't be a dependency there.
 

Dason

Ambassador to the humans
#11
Re: [R Games] R speed type (beta version 0.1)

I was looking for the R-Forge page I started and I ran across this. I think I might have to check out the code for this...

Edit: Are you familiar with any source control programs? Have you used subversion or git before? If so which do you prefer? Because we could get a github repository instead if you prefer git. I haven't used SVN yet but I don't suppose it would be a bad thing to learn at some point.

Edit the dos: I finally was able to fix my gWidgetsRGtk2 on my windows machine! Turns out the version of Gtk2 I installed didn't come with the necessarily cairo libraries or something so I uninstalled it and reinstalled the version found here.
 
Last edited:
#12
Re: [R Games] R speed type (beta version 0.1)

Great that you got an R-Forge page started. Also if I can make a suggestion, the selling point for an R-games package should not only be "a good way to kill the time between classes" but first and foremost to showcase and expand R's graphical and interactive features. Besides gaming there are allot of valid statistical applications that can be greatly improved upon with some interaction. Don't you agree?

NWWgames only has UNO implemented yet, not really a great selection. We can do better than that!

I will be happy to use git, as I have little experience with revision control software like these.

I need to update my GTK libraries before your code will work, doing that now.

EDIT: I upgraded to 3.0, but still get the error "configure: error: GTK version 2.8.0 required".. too late to figure this out now.. tomorrow is a new day.

Cheers,

M.
 

trinker

ggplot2orBust
#13
I ran across this
Nice find!

Rforge has it listed under education. See games are educational. Where were you Rforge when my mom was yelling at my middle school self to "turn off that ninetendo; it's going to rot your brain."
 
Last edited: