view tools/simulate.js @ 37:a88effe4831e default tip

Added tag 1.0.0 for changeset a464bd43b76c
author ark
date 2026-10-21 22:36 +0200
parents a464bd43b76c
children
line wrap: on
line source

#!/usr/bin/env node
// headless simulation of the game with scripted players (doc/balancing.md).
// runs the game logic from www/ after a build: data/config.js, data/maps.js
// and the js/ files of the simulation, with MM.audio replaced by a stub. writes temp/preview/simulate.txt, the results as json in
// temp/preview/simulate.json (read by tools/balance.py), and prints a
// summary.
//
// usage: node tools/simulate.js [options]
//
//   --maps 0,1      maps to play (default all)
//   --players a,b   players (default naive,greedy); also naive_t0, naive_mix
//   --seeds n       seeds per map and player, 1 to n (default 5)
//   --need all      measure the coins needed for every wave, not only the
//                   last one (slower)
//   --waves file    json {"0": [{"monsters": {...}}, ...], ...}: wave lists
//                   that replace the config's for the maps named
//   --config file   a config.js to use instead of www/data/config.js
//   --json          print the results as json instead of the summary, and
//                   write no files
//
// players (all build at the first moment they can afford the next
// purchase, through the game's own shop, preview and upgrade functions):
//
//   naive       t1 only, level 1, on cells of median t1 coverage. never
//               starts a wave early
//   greedy      t1, cells picked by coverage of route not yet covered, and
//               upgrades when that adds more damage per second per coin
//               than a new tower (the rules of tools/balance.py). starts
//               every wave early for the bonus
//   naive_t0    as naive, t0 only, on cells of median t0 coverage
//   naive_mix   as naive, t1 and t0 in turn, each on cells of median
//               coverage for its own range
//
// coverage of a cell is the route length within range, the mean over the
// map's routes, as in tools/balance.py. the coins a wave needs are the cost of the smallest
// number of the player's purchases, in its order, that hold the wave
// without losing a heart. it is measured by playing the wave on its own
// from an empty map, with the same seed.

"use strict";

var fs = require("fs");
var path = require("path");
var vm = require("vm");

var ROOT = path.resolve(__dirname, "..");
var WWW = path.join(ROOT, "www");
var OUT = path.join(ROOT, "temp", "preview", "simulate.txt");
var OUT_JSON = path.join(ROOT, "temp", "preview", "simulate.json");
var DT = 1 / 60;
// distance between route samples for coverage, as in tools/balance.py
var SAMPLE_STEP = 4;
// naive cells: coverage within this share of the median counts as median
var MEDIAN_BAND = 0.05;
// longest purchase lists
var MAX_TOWERS = 80;
var MAX_SPENT = 4000;
// a run stops after this much game time
var MAX_TIME = 4000;
// hearts the naive player should have left (decided)
var HEARTS_TARGET = 5;

// options

function options(argv) {
    var o = { maps: null, players: ["naive", "greedy"], seeds: 5, needAll: false,
              waves: null, config: path.join(WWW, "data", "config.js"), json: false };
    for (var i = 0; i < argv.length; i++) {
        var a = argv[i];
        if (a === "--maps") o.maps = argv[++i].split(",").map(Number);
        else if (a === "--players") o.players = argv[++i].split(",");
        else if (a === "--seeds") o.seeds = Number(argv[++i]);
        else if (a === "--need") o.needAll = argv[++i] === "all";
        else if (a === "--waves") o.waves = JSON.parse(fs.readFileSync(argv[++i], "utf8"));
        else if (a === "--config") o.config = path.resolve(argv[++i]);
        else if (a === "--json") o.json = true;
        else {
            console.error("unknown option " + a + "; see the comment at the top of tools/simulate.js");
            process.exit(2);
        }
    }
    return o;
}

// load the game logic into this context, as the browser would
function load(configFile, waves) {
    globalThis.window = globalThis;
    var files = [configFile, path.join(WWW, "data", "maps.js")];
    ["util", "assets", "map", "monster", "tower", "projectile", "wave", "game"].forEach(function (f) {
        files.push(path.join(WWW, "js", f + ".js"));
    });
    files.forEach(function (f, i) {
        vm.runInThisContext(fs.readFileSync(f, "utf8"), { filename: f });
        if (i === files.length - 1) countMelee();
        if (i === 1) {
            if (waves) {
                Object.keys(waves).forEach(function (m) { MM.config.maps[m].waves = waves[m]; });
            }
            MM.audio = { play: function () {} };
        }
    });
}

// melee attacks and the monsters they hit, by tower type, counted from the
// game's own tower update and damage functions
var melee = {};

function countMelee() {
    var update = MM.tower.update, damage = MM.Game.prototype.damage, current = null;
    MM.tower.update = function (t, game, dt) {
        var before = t.cooldown;
        current = t.def.projectile_speed === 0 ? t : null;
        update(t, game, dt);
        if (current && t.cooldown > before) {
            var c = melee[t.type] || (melee[t.type] = { attacks: 0, hits: 0 });
            c.attacks++;
            c.hits += current.hitsNow || 0;
        }
        if (current) current.hitsNow = 0;
        current = null;
    };
    MM.Game.prototype.damage = function (m, amount) {
        if (current && m.alive) current.hitsNow = (current.hitsNow || 0) + 1;
        return damage.call(this, m, amount);
    };
}

// coverage

// route samples about SAMPLE_STEP apart, in the middle of equal pieces:
// {xs, ys, weight}, weight being the length of a piece
function resample(r) {
    var n = r.xs.length, cum = r.at, len = r.length;
    var k = Math.max(1, Math.ceil(len / SAMPLE_STEP));
    var xs = [], ys = [], seg = 1;
    for (var i = 0; i < k; i++) {
        var s = (i + 0.5) * len / k;
        while (seg < n - 1 && cum[seg] < s) seg++;
        var t = (s - cum[seg - 1]) / (cum[seg] - cum[seg - 1]);
        xs.push(r.xs[seg - 1] + (r.xs[seg] - r.xs[seg - 1]) * t);
        ys.push(r.ys[seg - 1] + (r.ys[seg] - r.ys[seg - 1]) * t);
    }
    return { xs: xs, ys: ys, weight: len / k };
}

// legal cells and route samples of a map
function MapData(index) {
    var gm = new MM.GameMap(index), d = gm.data;
    this.index = index;
    this.cells = [];
    for (var i = 0; i < d.grid.length; i++) {
        if (d.grid.charCodeAt(i) === 49) {
            this.cells.push([(i % d.cols) * d.cell + d.cell / 2, Math.floor(i / d.cols) * d.cell + d.cell / 2]);
        }
    }
    this.routes = gm.routes.map(resample);
    this.cache = {};
}

// per route, per cell: indices of the samples within range rng
MapData.prototype.within = function (rng) {
    if (this.cache[rng]) return this.cache[rng];
    var r2 = rng * rng, cells = this.cells;
    var out = this.routes.map(function (r) {
        return cells.map(function (c) {
            var hit = [];
            for (var i = 0; i < r.xs.length; i++) {
                var dx = r.xs[i] - c[0], dy = r.ys[i] - c[1];
                if (dx * dx + dy * dy <= r2) hit.push(i);
            }
            return hit;
        });
    });
    this.cache[rng] = out;
    return out;
};

// per cell: route length within range, the mean over routes
MapData.prototype.coverage = function (rng) {
    var w = this.within(rng), routes = this.routes;
    return this.cells.map(function (c, j) {
        var sum = 0;
        for (var r = 0; r < routes.length; r++) sum += w[r][j].length * routes[r].weight;
        return sum / routes.length;
    });
};

function median(v) {
    var s = v.slice().sort(function (a, b) { return a - b; }), n = s.length;
    return n % 2 ? s[(n - 1) / 2] : (s[n / 2 - 1] + s[n / 2]) / 2;
}

function farEnough(cells, picked, j, minDist) {
    for (var i = 0; i < picked.length; i++) {
        var a = cells[picked[i]], b = cells[j];
        if (Math.hypot(a[0] - b[0], a[1] - b[1]) < minDist) return false;
    }
    return true;
}

// cells for the naive players: the cells within MEDIAN_BAND of the median
// coverage in random order, then the others by distance from the median.
// towers keep the minimum distance from each other. returns cell indices.
function medianCells(md, rng, random, count, picked) {
    var cov = md.coverage(rng), med = median(cov);
    var idx = cov.map(function (_, j) { return j; });
    var band = idx.filter(function (j) { return Math.abs(cov[j] - med) <= MEDIAN_BAND * med; });
    for (var i = band.length - 1; i > 0; i--) {
        var k = Math.floor(random() * (i + 1)), t = band[i];
        band[i] = band[k];
        band[k] = t;
    }
    var rest = idx.filter(function (j) { return Math.abs(cov[j] - med) > MEDIAN_BAND * med; });
    rest.sort(function (a, b) { return Math.abs(cov[a] - med) - Math.abs(cov[b] - med); });
    var order = band.concat(rest), out = [];
    var minDist = MM.config.placement.min_tower_distance;
    for (i = 0; i < order.length && out.length < count; i++) {
        if (farEnough(md.cells, picked, order[i], minDist)) {
            out.push(order[i]);
            picked.push(order[i]);
        }
    }
    return out;
}

// cells picked one after the other by the route length in range that no
// earlier pick covers, mean over routes, keeping the minimum distance. once
// all route is covered, the cell with the most route in range is next.
function greedyCells(md, rng, count) {
    var w = md.within(rng), routes = md.routes, cells = md.cells;
    var full = md.coverage(rng);
    var covered = routes.map(function (r) { return new Uint8Array(r.xs.length); });
    var free = cells.map(function () { return true; });
    var minDist = MM.config.placement.min_tower_distance;
    var order = [];
    while (order.length < count) {
        var best = -1, bestGain = 0, bestFull = -1, bestFullV = -1;
        for (var j = 0; j < cells.length; j++) {
            if (!free[j]) continue;
            var gain = 0;
            for (var r = 0; r < routes.length; r++) {
                var hit = w[r][j], cv = covered[r], n = 0;
                for (var i = 0; i < hit.length; i++) if (!cv[hit[i]]) n++;
                gain += n * routes[r].weight;
            }
            gain /= routes.length;
            if (gain > bestGain) { bestGain = gain; best = j; }
            if (full[j] > bestFullV) { bestFullV = full[j]; bestFull = j; }
        }
        if (best < 0) best = bestFull;
        if (best < 0) break;
        order.push(best);
        for (r = 0; r < routes.length; r++) {
            w[r][best].forEach(function (i) { covered[r][i] = 1; });
        }
        for (j = 0; j < cells.length; j++) {
            if (free[j] && Math.hypot(cells[j][0] - cells[best][0], cells[j][1] - cells[best][1]) < minDist)
                free[j] = false;
        }
    }
    return order;
}

// players: a purchase list, each entry {type, x, y} for a new tower or
// {up: n} for an upgrade of the n-th tower built, with its cost

function mapSpacing(index) {
    var mc = MM.config.maps[index], mons = MM.config.monster;
    var interval = mc.spawn_interval !== undefined ? mc.spawn_interval : MM.config.waves.spawn_interval;
    var sum = 0, count = 0;
    mc.waves.forEach(function (w) {
        for (var k in w.monsters) {
            if (mons[k].boss) continue;
            sum += w.monsters[k] * mons[k].speed * interval;
            count += w.monsters[k];
        }
    });
    return sum / count;
}

function naiveList(md, types, seed) {
    var random = MM.util.rng(seed * 7919 + 17), picked = [], list = [], spent = 0;
    var cfg = MM.config;
    while (list.length < MAX_TOWERS && spent < MAX_SPENT) {
        var type = types[list.length % types.length], def = cfg.tower[type];
        var c = medianCells(md, def.range[0], random, 1, picked);
        if (!c.length) break;
        var cell = md.cells[c[0]];
        list.push({ type: type, x: cell[0], y: cell[1], cost: def.cost[0] });
        spent += def.cost[0];
    }
    return list;
}

function greedyList(md, index) {
    var def = MM.config.tower.t1, dmg = def.damage, cost = def.cost, at = def.attack_time;
    var cells = greedyCells(md, def.range[0], MAX_TOWERS);
    var cov = md.coverage(def.range[0]), spacing = mapSpacing(index);
    function busy(j) { return 1 - Math.exp(-cov[j] / spacing); }
    var levels = [], list = [], next = 0, spent = 0;
    while (spent < MAX_SPENT) {
        var best = 0, choice = null;
        if (next < cells.length) {
            best = dmg[0] / at * busy(cells[next]) / cost[0];
            choice = -1;
        }
        levels.forEach(function (t, n) {
            if (t.level >= dmg.length) return;
            var v = (dmg[t.level] - dmg[t.level - 1]) / at * busy(t.cell) / cost[t.level];
            if (v > best) { best = v; choice = n; }
        });
        if (choice === null) break;
        if (choice < 0) {
            var cell = md.cells[cells[next]];
            levels.push({ cell: cells[next], level: 1 });
            list.push({ type: "t1", x: cell[0], y: cell[1], cost: cost[0] });
            next++;
            spent += cost[0];
        } else {
            var t = levels[choice];
            list.push({ up: choice, cost: cost[t.level] });
            spent += cost[t.level];
            t.level++;
        }
    }
    return list;
}

function makePlayer(name, md, index, seed) {
    if (name === "naive") return { name: name, list: naiveList(md, ["t1"], seed), early: false };
    if (name === "naive_t0") return { name: name, list: naiveList(md, ["t0"], seed), early: false };
    if (name === "naive_mix") return { name: name, list: naiveList(md, ["t1", "t0"], seed), early: false };
    if (name === "greedy") return { name: name, list: greedyList(md, index), early: true };
    throw new Error("unknown player " + name);
}

// make purchase p through the game's functions. built: the towers built so
// far, in order. returns false when it could not be made.
function buy(g, p, built) {
    if (p.up !== undefined) {
        var t = built[p.up];
        g.selected = null;
        g.shop = null;
        g.pressMap(t.x, t.y, 0);
        if (g.selected !== t) return false;
        var level = t.level;
        g.upgrade();
        g.selected = null;
        return t.level > level;
    }
    if (g.shop !== p.type) g.chooseShop(p.type);
    if (!g.movePreview(p.x, p.y) || g.preview.x !== p.x || g.preview.y !== p.y) {
        g.shop = null;
        g.preview = null;
        return false;
    }
    var n = g.towers.length;
    if (!g.build()) return false;
    built.push(g.towers[n]);
    return true;
}

// play

function spentOn(g) {
    return g.towers.reduce(function (s, t) { return s + t.paid; }, 0);
}

// play map index with the player. returns per wave the coins on hand and
// the budget (coins on hand plus coins spent) at its start and the hearts
// lost in it, and the result.
function play(index, player, seed) {
    melee = {};
    var g = new MM.Game(index, seed, 1);
    var built = [], k = 0, recorded = 0, rows = [], stuck = false;
    function act() {
        while (k < player.list.length && g.canAfford(player.list[k].cost)) {
            if (!buy(g, player.list[k], built)) { stuck = true; break; }
            k++;
        }
    }
    while (!g.result && g.time < MAX_TIME) {
        act();
        if (player.early && g.waves.phase === "break") {
            g.startEarly();
            act();
        }
        if (g.waves.next !== recorded) {
            if (rows.length) rows[rows.length - 1].lost -= g.hearts;
            recorded = g.waves.next;
            rows.push({ coins: g.coins, budget: g.coins + spentOn(g), towers: g.towers.length,
                        bought: k, lost: g.hearts });
        }
        g.step(DT);
    }
    if (rows.length) rows[rows.length - 1].lost -= g.hearts;
    return { rows: rows, hearts: g.hearts, won: g.result === "won", stuck: stuck,
             coinsEnd: g.coins, purchases: k, melee: melee };
}

// hearts lost in wave w (from 0) played on its own from an empty map with
// the first k purchases of the player
function waveLoss(index, player, seed, w, k) {
    var g = new MM.Game(index, seed, w + 1), built = [];
    g.coins = 1e9;
    for (var i = 0; i < k; i++) {
        if (!buy(g, player.list[i], built)) throw new Error("purchase " + i + " failed in a wave test");
    }
    var h = g.hearts;
    g.startEarly();
    // the break after the wave starts while its monsters are still on the
    // map; it is held so the next wave does not start
    while (!g.result && (g.waves.phase === "spawning" || g.monsters.length) && g.time < MAX_TIME) {
        if (g.waves.phase === "break") g.waves.left = Infinity;
        g.step(DT);
    }
    return h - g.hearts;
}

// coins of the smallest purchase prefix that holds wave w, null if none in
// the list does
function need(index, player, seed, w) {
    var lo = 0, hi = player.list.length;
    if (waveLoss(index, player, seed, w, hi) > 0) return null;
    while (lo < hi) {
        var mid = (lo + hi) >> 1;
        if (waveLoss(index, player, seed, w, mid) === 0) hi = mid;
        else lo = mid + 1;
    }
    var c = 0;
    for (var i = 0; i < lo; i++) c += player.list[i].cost;
    return c;
}

// report

function mean(v) {
    return v.reduce(function (a, b) { return a + b; }, 0) / v.length;
}

function pad(s, n) {
    s = String(s);
    return s.length >= n ? s : " ".repeat(n - s.length) + s;
}

function fmt(v, d) {
    return v === null || v === undefined || Number.isNaN(v) ? "-" : v.toFixed(d || 0);
}

function summary(index, name, runs) {
    var last = runs.map(function (r) { return r.rows[r.rows.length - 1]; });
    var needs = runs.map(function (r) { return r.need[r.need.length - 1]; });
    var surplus = runs.map(function (r, i) {
        return needs[i] === null || !last[i] ? null : last[i].budget - needs[i];
    });
    var ok = surplus.filter(function (v) { return v !== null; });
    return {
        map: index, player: name, seeds: runs.length,
        won: runs.filter(function (r) { return r.won; }).length,
        hearts: mean(runs.map(function (r) { return r.hearts; })),
        heartsMin: Math.min.apply(null, runs.map(function (r) { return r.hearts; })),
        heartsMax: Math.max.apply(null, runs.map(function (r) { return r.hearts; })),
        coinsLast: mean(last.map(function (r) { return r ? r.coins : 0; })),
        budgetLast: mean(last.map(function (r) { return r ? r.budget : 0; })),
        needLast: ok.length ? mean(needs.filter(function (v) { return v !== null; })) : null,
        surplus: ok.length === runs.length ? mean(ok) : null,
        lost: runs[0].rows.map(function (_, w) {
            return mean(runs.map(function (r) { return r.rows[w] ? r.rows[w].lost : 0; }));
        }),
        need: runs[0].need.map(function (_, w) {
            var v = runs.map(function (r) { return r.need[w]; });
            return v.indexOf(null) >= 0 || v[0] === undefined ? null : mean(v);
        }),
        budget: runs[0].rows.map(function (_, w) {
            return mean(runs.map(function (r) { return r.rows[w] ? r.rows[w].budget : 0; }));
        }),
        stuck: runs.some(function (r) { return r.stuck; }),
        // monsters hit per t0 attack, over all runs
        t0Hits: (function () {
            var a = 0, h = 0;
            runs.forEach(function (r) { if (r.melee.t0) { a += r.melee.t0.attacks; h += r.melee.t0.hits; } });
            return a ? h / a : null;
        })()
    };
}

function table(results, o) {
    var lines = ["simulation, written by tools/simulate.js", "",
                 "seeds 1 to " + o.seeds + " per map and player. hearts: left at the end, mean (min to max).",
                 "coins: on hand at the start of the last wave. budget: coins on hand plus",
                 "coins spent then. need: coins of the purchases that hold the last wave",
                 "on its own. surplus: budget minus need, at the last wave. per wave: hearts",
                 "lost, mean over seeds; budget and need by wave where measured.", "",
                 "map  player      won   hearts          coins  budget   need  surplus"];
    results.forEach(function (s) {
        lines.push(pad("map" + s.map, 4) + "  " + (s.player + "          ").slice(0, 10)
                   + pad(s.won + "/" + s.seeds, 5)
                   + pad(fmt(s.hearts, 1), 7) + " (" + s.heartsMin + " to " + s.heartsMax + ")"
                   + pad("", 13 - (" (" + s.heartsMin + " to " + s.heartsMax + ")").length)
                   + pad(fmt(s.coinsLast, 1), 7) + pad(fmt(s.budgetLast), 8) + pad(fmt(s.needLast), 7)
                   + pad(fmt(s.surplus), 9) + (s.stuck ? "  (a purchase failed)" : "")
                   + (s.t0Hits !== null ? "  t0 hits per attack " + fmt(s.t0Hits, 2) : ""));
    });
    results.forEach(function (s) {
        lines.push("", "map" + s.map + " " + s.player + ", per wave:",
                   "  lost   " + s.lost.map(function (v) { return pad(fmt(v, 1), 6); }).join(""),
                   "  budget " + s.budget.map(function (v) { return pad(fmt(v), 6); }).join(""),
                   "  need   " + s.need.map(function (v) { return pad(fmt(v), 6); }).join(""));
    });
    return lines;
}

function main() {
    var o = options(process.argv.slice(2));
    load(o.config, o.waves);
    var maps = o.maps || MM.maps.map(function (_, i) { return i; });
    var results = [];
    maps.forEach(function (index) {
        var md = new MapData(index);
        var n = MM.config.maps[index].waves.length;
        o.players.forEach(function (name) {
            var runs = [];
            for (var seed = 1; seed <= o.seeds; seed++) {
                var player = makePlayer(name, md, index, seed);
                var run = play(index, player, seed);
                run.need = [];
                for (var w = 0; w < n; w++) {
                    run.need.push(o.needAll || w === n - 1 ? need(index, player, seed, w) : undefined);
                }
                runs.push(run);
            }
            results.push(summary(index, name, runs));
        });
    });
    if (o.json) {
        console.log(JSON.stringify(results));
        return;
    }
    var lines = table(results, o);
    fs.mkdirSync(path.dirname(OUT), { recursive: true });
    fs.writeFileSync(OUT, lines.join("\n") + "\n");
    fs.writeFileSync(OUT_JSON, JSON.stringify(results, null, 1) + "\n");
    results.forEach(function (s) {
        console.log("map" + s.map + " " + s.player + ": won " + s.won + "/" + s.seeds + ", hearts "
                    + fmt(s.hearts, 1) + ", coins at the last wave " + fmt(s.coinsLast, 1)
                    + ", surplus " + fmt(s.surplus) + (s.player === "naive" && s.hearts > HEARTS_TARGET + 1
                    ? " (target " + HEARTS_TARGET + " hearts)" : ""));
    });
    console.log("simulate: wrote temp/preview/simulate.txt, simulate.json");
}

if (require.main === module) main();

module.exports = { options: options, load: load, MapData: MapData, greedyCells: greedyCells,
                   makePlayer: makePlayer, play: play, need: need, waveLoss: waveLoss,
                   summary: summary };