iTheresaApocalypse's picture hanoiy's picture
Add GameDojo game environments (#2)
c04dd6a
Raw History Blame Contribute Delete
2.57 kB
// Keyboard / mouse -> held-key set in the packet vocabulary (W A S D Space Shift J K L Q E R LMB RMB).
// Human play samples it every 33 ms sub-step, so a human session can be recorded as action packets and replayed.
(function (g) {
var BB = g.BB;
var MAP = { KeyW: 'W', KeyA: 'A', KeyS: 'S', KeyD: 'D', Space: 'Space', ShiftLeft: 'Shift', ShiftRight: 'Shift',
KeyJ: 'J', KeyK: 'K', KeyL: 'L', KeyQ: 'Q', KeyE: 'E', KeyR: 'R',
ArrowUp: 'W', ArrowLeft: 'A', ArrowDown: 'S', ArrowRight: 'D', KeyZ: 'Space', KeyX: 'J', KeyC: 'Shift', KeyV: 'K' };
function Input(target) {
var held = this.held = {}, self = this;
this.taps = {}; // pressed-and-released within one sub-step still count once
this.pointer = null;
target.addEventListener('keydown', function (e) {
var k = MAP[e.code]; if (!k) return;
if (!self.enabled) return;
e.preventDefault();
if (!held[k]) self.taps[k] = true; held[k] = true;
});
target.addEventListener('keyup', function (e) { var k = MAP[e.code]; if (k) held[k] = false; });
target.addEventListener('blur', function () { for (var k in held) held[k] = false; });
this.enabled = true;
}
Input.prototype.bindMouse = function (el) {
var held = this.held, self = this;
el.addEventListener('mousedown', function (e) { if (!self.enabled) return; var k = e.button === 0 ? 'LMB' : e.button === 2 ? 'RMB' : null; if (k) { if (!held[k]) self.taps[k] = true; held[k] = true; } });
g.addEventListener('mouseup', function (e) { var k = e.button === 0 ? 'LMB' : e.button === 2 ? 'RMB' : null; if (k) held[k] = false; });
el.addEventListener('mousemove', function (e) {
var rect = el.getBoundingClientRect();
if (rect.width && rect.height) self.pointer = [(e.clientX - rect.left) * el.width / rect.width, (e.clientY - rect.top) * el.height / rect.height];
});
el.addEventListener('contextmenu', function (e) { e.preventDefault(); });
};
Input.prototype.clear = function () { for (var k in this.held) this.held[k] = false; this.taps = {}; };
// keys held during the next sub-step (max 4, as in the packet format)
Input.prototype.sample = function () {
var out = {}, n = 0, order = ['A', 'D', 'W', 'S', 'Space', 'J', 'LMB', 'Shift', 'K', 'L', 'Q', 'E', 'R', 'RMB'];
for (var i = 0; i < order.length && n < 4; i++) { var k = order[i]; if (this.held[k] || this.taps[k]) { out[k] = true; n++; } }
this.taps = {};
return out;
};
BB.Input = Input;
})(typeof window !== 'undefined' ? window : globalThis);