view game/js/input.js @ 36:a464bd43b76c 1.0.0

clean documentation rewrite
author ark
date 2026-10-21 22:34 +0200
parents 83e8b0e0f010
children
line wrap: on
line source

// pointer events: mouse and touch alike. hover only highlights the screen
// buttons and sets the cursor; nothing relies on it

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;
    // how far a press on the preview may move and still count as a tap that
    // builds, css pixels. a longer move drags the preview
    var DRAG_SLOP = 10;
    var REFUSED_TIME = 500;

    // app: {canvas, view, game(), layout(), and the screen actions
    // startSound(), play(), next(), retry(), restart()}
    function attach(app) {
        var c = app.canvas;
        // the press that moves the placement preview, followed until the
        // pointer is released. other pointers are ignored meanwhile
        var drag = null;

        function pos(e) {
            var r = c.getBoundingClientRect();
            return { x: e.clientX - r.left, y: e.clientY - r.top };
        }

        c.addEventListener("pointerdown", function (e) {
            e.preventDefault();
            MM.audio.unlock();
            if (drag) return;
            var p = pos(e);
            drag = press(app, p.x, p.y);
            if (!drag) return;
            drag.id = e.pointerId;
            // keep receiving the pointer when it leaves the canvas
            try { c.setPointerCapture(e.pointerId); } catch (err) { /* not supported */ }
        });
        c.addEventListener("pointermove", function (e) {
            var p = pos(e);
            if (drag && e.pointerId === drag.id) move(app, drag, p.x, p.y);
            // mouse only: the position for the hover highlight, and the
            // pointer cursor over buttons
            if (e.pointerType !== "mouse" || !app.game()) return;
            app.view.hover = p;
            c.style.cursor = MM.ui.hit(app.game(), app.layout(), p.x, p.y) ? "pointer" : "";
        });
        c.addEventListener("pointerup", function (e) {
            if (!drag || e.pointerId !== drag.id) return;
            var p = pos(e);
            release(app, drag, p.x, p.y);
            drag = null;
        });
        // the browser took the pointer, for example for a system gesture:
        // the preview stays where it is and nothing is built
        c.addEventListener("pointercancel", function (e) {
            if (drag && e.pointerId === drag.id) drag = null;
        });
        c.addEventListener("pointerleave", function () {
            app.view.hover = null;
            c.style.cursor = "";
        });
        // browsers count only some events as a user interaction that may
        // start sound: pointerdown for the mouse, pointerup and touchend
        // for touch
        document.addEventListener("pointerup", MM.audio.unlock);
        document.addEventListener("touchend", MM.audio.unlock);
        // 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(); });
    }

    // map position of css position x, y, or null outside the map
    function mapPos(game, L, x, y) {
        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 null;
        return { x: mx, y: my };
    }

    // a press at css position x, y. buttons and tower selection act at once,
    // apart from the logo and the email address on the help popup: tablets
    // open a new tab only when the finger is lifted, so the press on either
    // returns {game, button} and the release acts. a press on the map while a shop tower is chosen returns
    // the drag that places the preview:
    //   game      the game it belongs to
    //   onPreview the press was on the preview; it builds on release unless
    //             the pointer moved further than DRAG_SLOP
    //   moved     the pointer moved further than DRAG_SLOP
    //   found     a legal position was found during the drag
    //   sx, sy    css position of the press
    //   dx, dy    offset from the pointer to the preview in map pixels, so
    //             a preview grabbed off centre does not jump
    function press(app, x, y) {
        var game = app.game(), L = app.layout();
        var b = MM.ui.hit(game, L, x, y);
        if (b) {
            // the play button starts the sound. switching sound on or off
            // comes first, so the tap is heard when it goes on
            if (b.id === "play") MM.audio.start();
            if (b.id === "sound") MM.audio.toggle();
            MM.audio.play("button_tap");
            // any other button cancels an armed sell, and any button outside
            // the tower menu closes it
            if (b.id !== "sell") game.sellArmed = false;
            if (b.id !== "sell" && b.id !== "upgrade") game.selected = null;
            if (b.id === "logo" || b.id === "email") return { game: game, button: b.id };
            if (b.id === "start_sound") app.startSound();
            else if (b.id === "play") app.play();
            else if (b.id === "next") app.next();
            else if (b.id === "retry") app.retry();
            else if (b.id === "restart") app.restart();
            else if (b.id === "help") game.openHelp();
            else if (b.id === "close_help") game.closeHelp();
            else if (b.id === "pause") game.togglePause();
            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.paused && game.canAfford(MM.config.tower[b.tower].cost[0])) game.chooseShop(b.tower);
            else if (b.id === "upgrade") game.upgrade();
            else if (b.id === "sell") game.sell();
            return null;
        }
        if (game.result || game.paused) return null;
        var m = mapPos(game, L, x, y);
        if (!m) {
            game.sellArmed = false;
            game.selected = null;
            return null;
        }
        var hitR = Math.max(MM.config.placement.footprint_radius, PREVIEW_HIT / L.scale);
        var kind = game.pressMap(m.x, m.y, hitR);
        if (!kind) return null;
        var d = { game: game, onPreview: kind === "preview", moved: false, found: false,
                  sx: x, sy: y, dx: 0, dy: 0 };
        if (d.onPreview) {
            d.dx = game.preview.x - m.x;
            d.dy = game.preview.y - m.y;
            d.found = true;
        } else {
            d.found = game.movePreview(m.x, m.y);
        }
        return d;
    }

    // the pointer of a drag moved to css position x, y
    function move(app, d, x, y) {
        var game = app.game();
        if (d.button || game !== d.game || game.result || !game.shop) return;
        if (!d.moved && Math.hypot(x - d.sx, y - d.sy) <= DRAG_SLOP) {
            // a press on the preview stays a tap until it moves far enough
            if (d.onPreview) return;
        } else {
            d.moved = true;
        }
        var m = mapPos(game, app.layout(), x, y);
        if (m && game.movePreview(m.x + d.dx, m.y + d.dy)) d.found = true;
    }

    // the pointer of a drag was released at css position x, y. the logo
    // opens its web page and the email address a new mail when the pointer
    // is still on it. a tap on the preview builds; a drag that never found a
    // legal position is refused
    function release(app, d, x, y) {
        var game = app.game(), L = app.layout();
        if (d.button) {
            var b = MM.ui.hit(game, L, x, y), links = MM.config.links;
            if (!b || b.id !== d.button) return;
            if (b.id === "logo" && links.logo_url) window.location.href = links.logo_url;
            if (b.id === "email") {
                window.location.href = "mailto:" + links.email + "?subject=" +
                    encodeURIComponent(links.email_subject);
            }
            return;
        }
        if (game !== d.game || game.result || game.paused) return;
        var ok = d.onPreview && !d.moved ? game.build() : d.found;
        if (ok) return;
        MM.audio.play("placement_refused");
        app.view.refused = { x: (x - L.ox) / L.scale, y: (y - L.oy) / L.scale,
                             until: performance.now() + REFUSED_TIME };
    }

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