diff game/js/main.js @ 1:5492efd60e2c

first prototype + updated art sheet
author ark
date 2026-10-18 14:50 +0200
parents
children 2d46729a022e
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/game/js/main.js	Sun Oct 18 14:50:20 2026 +0200
@@ -0,0 +1,82 @@
+// start-up and main loop
+
+window.MM = window.MM || {};
+
+(function () {
+    "use strict";
+
+    var cfg = MM.config;
+    var STEP = 1 / 60;
+    // most simulation steps per frame and game speed step; the rest of a
+    // long frame is dropped, so the game slows down instead of freezing
+    var MAX_STEPS = 4;
+
+    var canvas = document.getElementById("game");
+    var ctx = canvas.getContext("2d");
+    var game = null;
+    var L = null;
+    var view = { dpr: 1, now: 0, refused: null, stats: { ms: 0 } };
+
+    function newGame() {
+        var m = MM.util.clamp(cfg.debug.start_map, 0, MM.maps.length - 1);
+        var seed = cfg.debug.seed || (Math.random() * 4294967296) >>> 0;
+        game = new MM.Game(m, seed);
+        resize();
+    }
+
+    // canvas resolution follows the device pixel ratio
+    function resize() {
+        var w = canvas.clientWidth, h = canvas.clientHeight;
+        view.dpr = window.devicePixelRatio || 1;
+        canvas.width = Math.round(w * view.dpr);
+        canvas.height = Math.round(h * view.dpr);
+        if (game) L = MM.ui.layout(w, h, game.map);
+    }
+
+    var last = 0, acc = 0;
+
+    function frame(now) {
+        var dt = last ? (now - last) / 1000 : 0;
+        last = now;
+        view.now = now;
+        var t0 = performance.now();
+
+        if (!game.paused && !game.result) {
+            var speed = game.speed();
+            acc += dt * speed;
+            var n = 0;
+            while (acc >= STEP && n < MAX_STEPS * speed) {
+                game.step(STEP);
+                acc -= STEP;
+                n++;
+            }
+            if (n >= MAX_STEPS * speed) acc = 0;
+        } else {
+            acc = 0;
+        }
+
+        ctx.setTransform(1, 0, 0, 1, 0, 0);
+        ctx.fillStyle = "#e8e2d4";
+        ctx.fillRect(0, 0, canvas.width, canvas.height);
+        MM.render.draw(ctx, game, L, view);
+        MM.ui.draw(ctx, game, L, view);
+        MM.render.drawFlights(ctx, game, L, view);
+
+        view.stats.ms = view.stats.ms * 0.9 + (performance.now() - t0) * 0.1;
+        requestAnimationFrame(frame);
+    }
+
+    window.addEventListener("resize", resize);
+    MM.input.attach({
+        canvas: canvas,
+        view: view,
+        game: function () { return game; },
+        layout: function () { return L; },
+        restart: newGame
+    });
+    MM.assets.load(function (failed) {
+        if (failed.length) console.error("images not loaded:", failed);
+        newGame();
+        requestAnimationFrame(frame);
+    });
+})();