[R Games] - Pong (version 0.0.1)

Dason

Ambassador to the humans
#1
I got bored so I made a quick proof of concept for a pong type game. I think if somebody wanted to they could use the same ideas and make a version of Snake that would be pretty sweet.

As of right now all it does is accept input in the form of "w" to make the player paddle go up and "s" to make the player paddle go down. Once you enter any input the ball will head towards the player's paddle and if it makes contact with the paddle will head toward the opponent's paddle. Right now there is no vertical movement for the ball and the opponent does nothing. Like I said it's just a proof of concept to show that we can accept user input while continuously updating the play field.

Code:
win <- gwindow()
gg <- gframe("Input Box", cont = win)
input <- gedit(cont = gg)


BASE.SPEED <- 1
UPDATE.SPEED <- .1
PLAYER.SPEED <- .05
pong.location <- c(0.5, 0.5)
pong.direction <- c(-0.5*UPDATE.SPEED, 0)
player.location <- 0.5
player.width <- .1
opponent.location <- 0.5
opponent.width <- .1

start <- FALSE

inputhandler <- function(h, ...){
    if(start){
        player.input <- h$key
        svalue(input) <- ""
        player.location <<- player.location + PLAYER.SPEED*((player.input == "w") - (player.input == "s"))
    }else{
        start <<- TRUE
    
    }
}
addHandlerKeystroke(input, inputhandler)


update <- function(h, ...){
    if(start){
        pong.location <<- pong.location + pong.direction
    }
    if(pong.location[1] <= 0.01 & pong.location[1] >= -0.01){
        y <- pong.location[2]
        if(y >= player.location - player.width & y <= player.location + player.width){
            pong.direction <<- pong.direction*c(-1,1)
        }
    }

    if(pong.location[1] >= 0.99 & pong.location[1] <= 1.01){
        y <- pong.location[2]
        if(y >= opponent.location - opponent.width & y <= opponent.location + opponent.width){
            pong.direction <<- pong.direction*c(-1,1)
        }
    }
    
    if(pong.location[1] < -.01 | pong.location[1] > 1.01){
        start <<- FALSE
        removeHandler(input, idleID)
    }
    plot(pong.location[1], pong.location[2], xlim = c(0,1), ylim = c(0,1), pch = 16)
    lines(c(0,0), c(player.location - player.width, player.location + player.width), lwd = 4)
    lines(c(1,1), c(opponent.location - opponent.width, opponent.location + opponent.width), lwd = 4)
}

idleID <- addHandlerIdle(input, update, interval = 1000*UPDATE.SPEED)
It's really ugly and isn't even in the form of a function right now - it just is a runnable script. You need gWidgetsRGtk2 to make this work.
 

Dason

Ambassador to the humans
#2
Just realized this. You probably should add this to the code to make it run:
Code:
library(gWidgets)
options(guiToolkit = "RGtk2")