view game/js/game.js @ 8:2c4fed8baed9

art update, persistent sound setting, tower selling as double action
author ark
date 2026-10-19 13:37 +0200
parents 910b26feca76
children a77857594150
line wrap: on
line source

// game state and rules: coins, hearts, building, upgrading, selling, win
// and loss

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

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

    var cfg = MM.config;
    var dbg = cfg.debug;

    // firstWave counts from 1
    function Game(mapIndex, seed, firstWave) {
        var mc = cfg.maps[mapIndex];
        this.map = new MM.GameMap(mapIndex);
        this.seed = seed;
        this.random = MM.util.rng(seed);
        this.coins = dbg.start_coins >= 0 ? dbg.start_coins : mc.starting_coins;
        this.hearts = cfg.hearts.per_map;
        this.monsters = [];
        this.towers = [];
        this.projectiles = [];
        this.flights = [];      // coins flying to the counter
        this.puffs = [];        // death puffs, {x, y, boss, t}
        this.waves = new MM.Waves(mapIndex, MM.util.clamp(firstWave - 1, 0, mc.waves.length - 1));
        this.time = 0;
        this.paused = false;
        this.pauses = 0;        // number of pauses so far, for the sell refund
        this.speeds = cfg.controls.speeds.concat(dbg.extra_speeds);
        this.speedIndex = 0;
        this.result = null;     // "won" or "lost"
        this.splash = false;    // splash screen shown over the paused map
        // player selection: shop tower type, its snapped preview, a built tower
        this.shop = null;
        this.preview = null;
        this.selected = null;
        this.sellArmed = false; // sell was tapped once and waits for the second tap
    }

    Game.prototype.speed = function () {
        return this.speeds[this.speedIndex];
    };

    Game.prototype.lastMap = function () {
        return this.map.index === MM.maps.length - 1;
    };

    Game.prototype.togglePause = function () {
        this.paused = !this.paused;
        if (this.paused) this.pauses++;
    };

    // number of the current pause, 0 while the game runs
    Game.prototype.pauseNumber = function () {
        return this.paused ? this.pauses : 0;
    };

    Game.prototype.canAfford = function (cost) {
        return dbg.unlimited_coins || this.coins >= cost;
    };

    Game.prototype.pay = function (cost) {
        if (!dbg.unlimited_coins) this.coins -= cost;
    };

    // one simulation step of dt seconds
    Game.prototype.step = function (dt) {
        if (this.result) return;
        var self = this;
        this.time += dt;
        this.waves.update(dt, this.monsters.length, function (kind) {
            var m = MM.monster.create(self, kind);
            self.monsters.push(m);
            MM.audio.play(m.boss ? "boss_enter" : "monster_enter");
        });
        this.monsters.forEach(function (m) {
            if (m.alive && MM.monster.update(m, dt)) self.escape(m);
        });
        this.towers.forEach(function (t) { MM.tower.update(t, self, dt); });
        this.projectiles.forEach(function (p) { MM.projectile.update(p, self, dt); });
        this.monsters = this.monsters.filter(function (m) { return m.alive; });
        this.projectiles = this.projectiles.filter(function (p) { return !p.done; });
        this.flights.forEach(function (f) { f.t += dt; });
        this.puffs.forEach(function (p) { p.t += dt; });
        this.puffs = this.puffs.filter(function (p) { return p.t < cfg.animation.death_puff; });
        var flying = this.flights.length;
        this.flights = this.flights.filter(function (f) { return f.t < cfg.coins.flight_time; });
        if (this.flights.length < flying) MM.audio.play("coins_arrive");

        // the end sound waits for the last exit or death sound
        if (this.hearts <= 0) {
            this.result = "lost";
            MM.audio.play("map_lost", ["monster_exit", "boss_exit"]);
        } else if (this.waves.phase === "done" && this.monsters.length === 0) {
            this.result = "won";
            MM.audio.play("map_won", ["monster_die", "boss_die"]);
        }
        // the simulation stops here; the coins in flight are counted already
        if (this.result) {
            this.flights = [];
            this.puffs = [];
        }
    };

    // a monster reached the exit
    Game.prototype.escape = function (m) {
        m.alive = false;
        MM.audio.play(m.boss ? "boss_exit" : "monster_exit");
        if (!dbg.no_heart_loss) {
            this.hearts = Math.max(0, this.hearts - (m.boss ? cfg.hearts.boss : cfg.hearts.monster));
        }
    };

    Game.prototype.damage = function (m, amount) {
        if (!m.alive) return;
        m.hp -= amount;
        if (m.hp > 0) {
            MM.audio.play("monster_hit");
            return;
        }
        m.alive = false;
        MM.audio.play(m.boss ? "boss_die" : "monster_die");
        this.puffs.push({ x: m.x, y: m.y, boss: m.boss, t: 0 });
        // coins count at once; the flying coins only show it (balance.md)
        this.coins += m.coins;
        var n = Math.min(m.coins, cfg.coins.max_sprites);
        for (var i = 0; i < n; i++) {
            this.flights.push({
                x: m.x + (this.random() - 0.5) * m.w,
                y: m.y - m.h / 2 + (this.random() - 0.5) * m.h / 2,
                sprite: "c" + Math.floor(this.random() * 4),
                // stagger the coins a little
                t: -i * 0.05
            });
        }
    };

    Game.prototype.startEarly = function () {
        var bonus = this.waves.startEarly();
        this.coins += bonus;
        if (bonus > 0) MM.audio.play("early_bonus");
    };

    Game.prototype.towerAt = function (x, y) {
        var r = cfg.placement.footprint_radius;
        for (var i = 0; i < this.towers.length; i++) {
            var t = this.towers[i];
            if (Math.hypot(t.x - x, t.y - y) <= r) return t;
        }
        return null;
    };

    Game.prototype.chooseShop = function (type) {
        this.selected = null;
        this.preview = null;
        this.shop = this.shop === type ? null : type;
    };

    // a tap on the map at map position x, y. hitRadius is how close the tap
    // must be to the preview to build. returns false when no legal position
    // was found for a preview.
    Game.prototype.tapMap = function (x, y, hitRadius) {
        var t = this.towerAt(x, y);
        this.sellArmed = false;
        if (t && !(this.preview && Math.hypot(this.preview.x - x, this.preview.y - y) <= hitRadius)) {
            this.shop = null;
            this.preview = null;
            this.selected = t === this.selected ? null : t;
            return true;
        }
        this.selected = null;
        if (!this.shop) return true;
        if (this.preview && Math.hypot(this.preview.x - x, this.preview.y - y) <= hitRadius) {
            return this.build();
        }
        this.preview = this.map.snap(x, y, this.towers);
        if (!this.preview) return false;
        // t0 draws spikes only towards the path, judged by its top level range
        var def = cfg.tower[this.shop];
        if (def.projectile_speed === 0) {
            this.preview.sides = this.map.facingSides(this.preview.x, this.preview.y,
                                                      def.range[def.range.length - 1]);
        }
        return true;
    };

    Game.prototype.build = function () {
        var cost = cfg.tower[this.shop].cost;
        if (!this.canAfford(cost)) return false;
        this.pay(cost);
        var pv = this.preview;
        var t = MM.tower.create(this.shop, pv.x, pv.y, pv.sides);
        t.paid.push({ cost: cost, pause: this.pauseNumber() });
        this.towers.push(t);
        MM.audio.play("tower_built");
        this.shop = null;
        this.preview = null;
        return true;
    };

    // upgrade the selected tower by one level
    Game.prototype.upgrade = function () {
        var t = this.selected;
        var cost = t && MM.tower.upgradeCost(t);
        if (!cost || !this.canAfford(cost)) return;
        this.pay(cost);
        t.level++;
        t.paid.push({ cost: cost, pause: this.pauseNumber() });
        MM.audio.play("tower_upgraded");
    };

    // the first tap arms selling, the second sells
    Game.prototype.sell = function () {
        var t = this.selected;
        if (!t) return;
        if (!this.sellArmed) {
            this.sellArmed = true;
            return;
        }
        this.sellArmed = false;
        this.coins += MM.tower.refund(t, this.pauseNumber());
        this.towers.splice(this.towers.indexOf(t), 1);
        this.selected = null;
        MM.audio.play("tower_sold");
    };

    return Game;
})();