TheWebPlaysGB/app.js

70 lines
1.6 KiB
JavaScript

const imageboy = require("imageboy");
const fastify = require("fastify")();
const path = require("path");
const fs = require("fs");
let lastFrame = "";
let emulator;
let currentKey = "";
let keyCooldown = 0;
const mainHTML = fs.readFileSync(path.join(__dirname, "html", "gb.html"), "utf8");
const KEYMAP = {
RIGHT: 0,
LEFT: 1,
UP: 2,
DOWN: 3,
A: 4,
B: 5,
SELECT: 6,
START: 7
};
async function run() {
if (!fs.existsSync(path.join(__dirname, "rom.gb"))) {
console.log("rom.gb missing.")
return;
}
emulator = imageboy.run({
path: "./rom.gb",
interval: 16.6666667,
onFrame: function(frame) {
if (currentKey !== "") {
emulator.gameboy.pressKey(currentKey);
keyCooldown--;
if (keyCooldown <= 0) {
currentKey = "";
}
}
lastFrame = frame;
}
});
fastify.get("/", async(request, reply) => {
reply.type("text/html");
reply.send(mainHTML);
});
fastify.get("/image", async(request, reply) => {
reply.type("image/png").send(lastFrame);
});
fastify.get("/control", async(request, reply) => {
const button = request.query.button;
if (button) {
if (keyCooldown > 0)
return;
if (KEYMAP[button] !== undefined) {
console.log()
currentKey = button;
keyCooldown = 10;
}
}
});
try {
await fastify.listen({ port: 3000 });
} catch (err) {
console.log(err);
}
}
run();