96 lines
2.4 KiB
JavaScript

export class Gamelib {
keysPressed = new Set();
keyPressHandlers = new Map();
keyReleaseHandlers = new Map();
constructor(console, codeStopper, spriteProvider, canvasElement) {
this.console = console;
this.codeStopper = codeStopper;
this.spriteProvider = spriteProvider;
this.canvas = canvasElement;
this.width = 480;
this.height = 360;
this.canvas.width = this.width;
this.canvas.height = this.height;
this.cx = this.canvas.getContext("2d");
this.cx.imageSmootingEnabled = false;
document.body.addEventListener("keydown", (ev) => {
this.keysPressed.add(ev.key);
this.keyPressHandlers.get(ev.key)?.();
});
document.body.addEventListener("keyup", (ev) => {
this.keysPressed.delete(ev.key);
this.keyReleaseHandlers.get(ev.key)?.();
});
}
println(msg) {
this.console.log(msg);
}
startGameLoop(loopFunction) {
let before = Date.now();
const loopInterval = setInterval(() => {
const now = Date.now();
const deltaT = (now - before) / 1000;
before = now;
try {
loopFunction(deltaT);
} catch (error) {
this.console.log(error);
}
}, 16);
if (this.codeStopper.isStopped()) {
clearInterval(loopInterval);
}
this.codeStopper.addListener(() => {
clearInterval(loopInterval);
});
}
isPressed(key) {
return this.keysPressed.has(key);
}
onPress(key, handlerFunction) {
this.keyPressHandlers.set(key, handlerFunction);
}
onRelease(key, handlerFunction) {
this.keyReleaseHandlers.set(key, handlerFunction);
}
rgb(red, green, blue) {
return `rgb(${red}, ${green}, ${blue})`;
}
clear(color) {
const cx = this.cx;
cx.fillStyle = color;
cx.fillRect(0, 0, this.width, this.height);
}
drawSprite(x, y, width, height, name) {
const cx = this.cx;
const image = new Image();
image.src = this.spriteProvider.url(name);
image.onload = () => {
cx.drawImage(image, x, y, width, height);
};
}
drawRect(x, y, width, height, color) {
const cx = this.cx;
cx.fillStyle = color;
cx.fillRect(x, y, width, height);
}
}