Skip to content

Instantly share code, notes, and snippets.

@Raynos
Created December 11, 2011 15:39
Show Gist options
  • Select an option

  • Save Raynos/1461174 to your computer and use it in GitHub Desktop.

Select an option

Save Raynos/1461174 to your computer and use it in GitHub Desktop.
var pd = require("npm::pd/src/pd");
var requestAnimationFrame =
webkitRequestAnimationFrame ||
mozRequestAnimationFrame ||
oRequestAnimationFrame ||
msRequestAnimationFrame ||
requestAnimationFrame;
var EventEmitter = pd.Base.make({
constructor: function _constructor() {
this._events = [];
return this;
},
on: function _on(ev, handler) {
if (!this._events[ev]) {
this._events[ev] = [];
}
this._events[ev].push(handler);
},
removeListener: function _removeListener(ev, handler) {
if (!this._events[ev]) return;
this._events[ev].splice(this._events[ev].indexOf(handler), 1);
},
emit: function _emit(ev, data) {
if (!this._events[ev]) return;
this._events[ev].forEach(invokeHandler);
function invokeHandler(handler) {
handler(data);
}
}
});
var Game = pd.Base.make(EventEmitter, {
addComponent: function _addComponent(component) {
component.start(this);
},
constructor: function _constructor(canvas) {
EventEmitter.constructor.call(this);
this.context = canvas.getContext("2d");
this.canvas = canvas;
["loop", "handleKeyDown"].forEach(bindFunction, this);
function bindFunction(name) {
this[name] = this[name].bind(this);
}
},
components: [],
handleKeyDown: function _handleKeyDown(ev) {
var key = ev.keyIdentifier;
if (key === "Up" || key === "Down" || key === "Left" || key === "Right") {
this.emit(key);
}
},
loop: function _loop() {
var context = this.context,
canvas = this.canvas;
context.save();
context.fillStyle = '#FFFFFFF';
context.drawRect(0,0, canvas.width, canvas.height)
this.emit("draw", this.context);
requestAnimationFrame(this.loop);
},
start: function _start() {
window.addEventListener("keydown", this.handleKeyDown);
this.loop();
}
});
var Paddle = pd.Base.make({
constructor: function _constructor(props) {
["draw", "moveLeft"].forEach(bindFunction, this);
this.extend(props);
function bindFunction(name) {
this[name] = this[name].bind(this);
}
},
destroy: function _destroy() {
game.on("draw", this.draw);
},
draw: function _draw(context) {
context.fillRect(this.x, this.y, this.width, this.height);
},
moveLeft: function _moveLeft(ev) {
this.x--;
},
start: function _start(game) {
game.on("draw", this.draw);
game.on("Left", this.moveLeft);
}
});
var canvas = document.getElementsByTagName("canvas")[0];
var game = Game.beget(canvas);
var paddle = Paddle.beget({
height: 10,
width: 50,
x: canvas.width * 0.4,
y: canvas.height * 0.8
});
game.addComponent(paddle);
game.start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment