view game/js/input.js @ 3:cc0c32e71090

added sound sources
author ark
date 2026-10-18 20:09 +0200
parents 5492efd60e2c
children 2d46729a022e
line wrap: on
line source

// pointer events: mouse and touch alike, nothing relies on hover

window.MM = window.MM || {};

MM.input = (function () {
    "use strict";

    // how close a tap must be to the placement preview to build, css pixels
    var PREVIEW_HIT = 28;
    var REFUSED_TIME = 500;

    // app: {canvas, game(), layout(), restart(), view}
    function attach(app) {
        var c = app.canvas;
        c.addEventListener("pointerdown", function (e) {
            e.preventDefault();
            var r = c.getBoundingClientRect();
            tap(app, e.clientX - r.left, e.clientY - r.top);
        });
        // block the context menu, double tap zoom and pinch gestures
        c.addEventListener("contextmenu", function (e) { e.preventDefault(); });
        c.addEventListener("touchstart", function (e) { e.preventDefault(); }, { passive: false });
        document.addEventListener("gesturestart", function (e) { e.preventDefault(); });
        document.addEventListener("dblclick", function (e) { e.preventDefault(); });
    }

    function tap(app, x, y) {
        var game = app.game(), L = app.layout();
        var b = MM.ui.hit(game, L, x, y);
        if (b) {
            if (b.id === "restart") app.restart();
            else if (b.id === "pause") game.paused = !game.paused;
            else if (b.id === "speed") game.speedIndex = (game.speedIndex + 1) % game.speeds.length;
            else if (b.id === "early") game.startEarly();
            else if (b.id === "shop" && game.canAfford(MM.config.tower[b.tower].cost)) game.chooseShop(b.tower);
            return;
        }
        if (game.result) return;
        var mx = (x - L.ox) / L.scale, my = (y - L.oy) / L.scale;
        if (mx < 0 || my < 0 || mx > game.map.width || my > game.map.height) return;
        var hitR = Math.max(MM.config.placement.footprint_radius, PREVIEW_HIT / L.scale);
        if (!game.tapMap(mx, my, hitR)) {
            app.view.refused = { x: mx, y: my, until: performance.now() + REFUSED_TIME };
        }
    }

    return { attach: attach };
})();