Skip to content

Instantly share code, notes, and snippets.

@polux
Created May 28, 2011 13:36
Show Gist options
  • Save polux/996864 to your computer and use it in GitHub Desktop.
Save polux/996864 to your computer and use it in GitHub Desktop.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="flapjax.js"></script>
<script>
function onload() {
/****** utils ******/
// 2d vectors
function Vect(x,y) { this.x = x; this.y = y }
function cart(x,y) { return new Vect(x,y); }
function polar(r,a) { return new Vect(r*Math.cos(a), r*Math.sin(a)); }
Vect.prototype.add = function(v) { return cart(this.x + v.x, this.y + v.y) };
Vect.prototype.scale = function(l) { return cart(this.x*l, this.y*l); };
Vect.prototype.radius = function() { return Math.sqrt(this.x*this.x, this.y*this.y); };
Vect.prototype.angle = function() { return Math.atan2(this.y, this.x); };
Vect.prototype.rotate = function(a) { return polar(this.radius(), this.angle()+a); };
function vx(v) { return v.x; }
function vy(v) { return v.y; }
function vradius(v) { return v.radius(); }
function vangle(v) { return v.angle(); }
function vadd(v1, v2) { return v2.add(v1); }
function vscale(v, l) { return v.scale(l); }
function vrotate(v, a) { return v.rotate(a); }
// v -> "vpx"
function px(x) { return x + "px" }
/****** game logic ******/
// arrow keys event stream
function extractKeyCode(e) {
return e.keyCode;
}
function decodeArrow(n) {
switch(n) {
case 37: return 'left';
case 38: return 'up';
case 39: return 'right';
case 40: return 'down';
default: return null;
}
}
function notNull(x) {
return x != null
}
var arrowE = extractEventE(window, 'keydown')
.mapE(extractKeyCode)
.mapE(decodeArrow)
.filterE(notNull);
// sprite position
var directions = {
'up' : cart(0,-1),
'down' : cart(0,1),
'right': cart(1,0),
'left' : cart(-1,0)
};
function control(dir, pos) {
return pos.add(directions[dir].scale(10));
}
var initPos = cart(100, 100);
var posB = arrowE.collectE(initPos, control)
.startsWith(initPos);
// display
insertValueE(arrowE, 'test', 'textContent');
insertValueB(posB.liftB(vx).liftB(px), 'sprite', 'style', 'left');
insertValueB(posB.liftB(vy).liftB(px), 'sprite', 'style', 'top');
}
</script>
<style type="text/css">
body {
font-family: sans-serif;
}
#sprite {
background-color: blue;
position: absolute;
left: 400px;
top: 400px;
width: 10px;
height: 10px;
}
</style>
</head>
<body onload=onload()>
<p id="test"></p>
<div id="sprite">
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment