2014-03-09 14:32:30 +01:00
|
|
|
function KeyboardInputManager() {
|
|
|
|
this.events = {};
|
|
|
|
|
|
|
|
this.listen();
|
|
|
|
}
|
|
|
|
|
|
|
|
KeyboardInputManager.prototype.on = function (event, callback) {
|
|
|
|
if (!this.events[event]) {
|
|
|
|
this.events[event] = [];
|
|
|
|
}
|
|
|
|
this.events[event].push(callback);
|
|
|
|
};
|
|
|
|
|
|
|
|
KeyboardInputManager.prototype.emit = function (event, data) {
|
|
|
|
var callbacks = this.events[event];
|
|
|
|
if (callbacks) {
|
|
|
|
callbacks.forEach(function (callback) {
|
|
|
|
callback(data);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
KeyboardInputManager.prototype.listen = function () {
|
|
|
|
var self = this;
|
|
|
|
|
|
|
|
var map = {
|
|
|
|
38: 0, // Up
|
|
|
|
39: 1, // Right
|
|
|
|
40: 2, // Down
|
|
|
|
37: 3 // Left
|
|
|
|
};
|
|
|
|
|
|
|
|
document.addEventListener("keydown", function (event) {
|
|
|
|
var modifiers = event.altKey && event.ctrlKey && event.metaKey &&
|
|
|
|
event.shiftKey;
|
|
|
|
var mapped = map[event.which];
|
|
|
|
|
2014-03-10 12:29:35 +01:00
|
|
|
if (!modifiers) {
|
|
|
|
if (mapped !== undefined) {
|
|
|
|
event.preventDefault();
|
|
|
|
self.emit("move", mapped);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (event.which === 32) self.restart.bind(self)(event);
|
2014-03-09 14:32:30 +01:00
|
|
|
}
|
|
|
|
});
|
2014-03-10 11:31:10 +01:00
|
|
|
|
|
|
|
var retry = document.getElementsByClassName("retry-button")[0];
|
2014-03-10 12:29:35 +01:00
|
|
|
retry.addEventListener("click", this.restart.bind(this));
|
2014-03-10 18:47:10 +01:00
|
|
|
|
|
|
|
// Listen to swipe events
|
|
|
|
var gestures = [Hammer.DIRECTION_UP, Hammer.DIRECTION_RIGHT,
|
|
|
|
Hammer.DIRECTION_DOWN, Hammer.DIRECTION_LEFT];
|
|
|
|
|
|
|
|
var gameContainer = document.getElementsByClassName("game-container")[0];
|
|
|
|
var handler = Hammer(gameContainer, {
|
|
|
|
drag_block_horizontal: true,
|
|
|
|
drag_block_vertical: true
|
|
|
|
});
|
|
|
|
|
|
|
|
handler.on("swipe", function (event) {
|
|
|
|
event.gesture.preventDefault();
|
|
|
|
mapped = gestures.indexOf(event.gesture.direction);
|
|
|
|
|
|
|
|
if (mapped !== -1) self.emit("move", mapped);
|
|
|
|
});
|
2014-03-10 12:29:35 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
KeyboardInputManager.prototype.restart = function (event) {
|
|
|
|
event.preventDefault();
|
|
|
|
this.emit("restart");
|
2014-03-09 14:32:30 +01:00
|
|
|
};
|