Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Partial Application / javascript games with underscore.js
//our simple data structure
function Spatial(x,y,vx,vy){
this.x = x;
this.y = y;
this.vx = vx || Math.random();
this.vy = vy || Math.random();
//use partial application here so that we can compose this in our main update
function processEvents(keys){
return function(spatial){
if(keys[68]){ spatial.vx += 0.1; }
if(keys[83]){ spatial.vy += 0.1; }
if(keys[65]){ spatial.vx -= 0.1; }
if(keys[87]){ spatial.vy -= 0.1; }
return spatial;
function move(spatial){
spatial.x += spatial.vx;
spatial.y += spatial.vy;
return spatial;
//use partial application here so that we can compose this in our main update
function render(context,image){
return function(spatial){
return spatial;
function inViewport(spatial){
return spatial.x < canvas.width && spatial.y < canvas.height;
//we return a function here that closes over the initial local variables
//also means we can call _.delay with the same or different args to potentially evolve the loop
function iterate(input,spatials,context,image){
return function(){
var _spatials =,_.compose(processEvents(input),move,render(context,image)));
_spatials = _.filter(_spatials,inViewport);
window.onload = function(){
//simple map to hold keys to query
var input = {};
window.onkeydown = function(e){
input[e.keyCode] = true;
window.onkeyup = function(e){
input[e.keyCode] = false;
//grab stuff for rendering
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var image = document.getElementById("image");
//simple list of spatials
var spatials = [
new Spatial(0,0),new Spatial(5,7)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.