2024-05-19 04:37:53 +00:00
|
|
|
console.log("loading input system");
|
|
|
|
|
2024-05-19 22:07:43 +00:00
|
|
|
const inputStates = Object.freeze({
|
|
|
|
DEFAULT: 0,
|
|
|
|
});
|
2024-05-19 04:37:53 +00:00
|
|
|
|
|
|
|
const inputSystem = (engine) => {
|
|
|
|
engine("registerEvent", "moveDown");
|
|
|
|
engine("registerEvent", "moveUp");
|
|
|
|
engine("registerEvent", "moveLeft");
|
|
|
|
engine("registerEvent", "moveRight");
|
|
|
|
|
2024-05-19 22:07:43 +00:00
|
|
|
let state = inputStates.DEFAULT;
|
|
|
|
let currentPresses = new Set();
|
|
|
|
|
|
|
|
const stateEvents = {};
|
|
|
|
stateEvents[inputStates.DEFAULT] = {
|
|
|
|
ArrowDown: () => engine("queueEvent", "moveDown"),
|
|
|
|
ArrowUp: () => engine("queueEvent", "moveUp"),
|
|
|
|
ArrowLeft: () => engine("queueEvent", "moveLeft",),
|
|
|
|
ArrowRight: () => engine("queueEvent", "moveRight")
|
|
|
|
};
|
|
|
|
|
|
|
|
const process = () => {
|
|
|
|
currentPresses.forEach(press => {
|
|
|
|
// nop function for unmapped keypresses
|
|
|
|
(stateEvents[state][press] || (() => null))();
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2024-05-19 04:37:53 +00:00
|
|
|
document.addEventListener('keydown', (event) => {
|
2024-05-20 19:40:17 +00:00
|
|
|
event.preventDefault();
|
2024-05-19 22:07:43 +00:00
|
|
|
currentPresses.add(event.key);
|
2024-05-20 19:40:17 +00:00
|
|
|
event.stopPropagation();
|
2024-05-19 22:07:43 +00:00
|
|
|
process();
|
|
|
|
});
|
|
|
|
|
|
|
|
document.addEventListener('keyup', (event) => {
|
2024-05-20 19:40:17 +00:00
|
|
|
event.preventDefault();
|
2024-05-19 22:07:43 +00:00
|
|
|
currentPresses.delete(event.key);
|
2024-05-20 19:40:17 +00:00
|
|
|
event.stopPropagation();
|
2024-05-19 22:07:43 +00:00
|
|
|
process();
|
|
|
|
});
|
|
|
|
|
|
|
|
return (message, ...messageArgs) => {
|
|
|
|
switch (message) {
|
|
|
|
case "inputState": {
|
|
|
|
return state;
|
|
|
|
}
|
|
|
|
case "setInputState": {
|
|
|
|
let stateKey = messageArgs[0];
|
|
|
|
state = inputStates[stateKey];
|
2024-05-19 04:37:53 +00:00
|
|
|
break;
|
|
|
|
}
|
2024-05-19 22:07:43 +00:00
|
|
|
};
|
|
|
|
};
|
2024-05-19 04:37:53 +00:00
|
|
|
};
|