Back to Gem Warden
SOURCE / PINNED RELEASE

Made of little things.

Gem Warden

Release
7c457bfe5427…
Author-recorded commit
fb5453b5fc06…
License
LICENSE
Author’s source reference
nostr://npub1eg5pfnws6tg6rtp33tugpppqtv5u05crmf983qp438cdycwzngys0gxzcs/wss%3A%2F%2Fgit.napplet.soy%2F/n-3929629ef1d

Archive hash verified: 895b8dd430aad9fe…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

tests/strategies.ts
// Scripted strategies against every field, to check that one-colour builds do
// not beat builds that use the specials. node tests/strategies.ts
import * as G from '../src/game.ts';

export interface Strategy {
  name: string;
  towers: G.GemColor[];
  traps: G.GemColor[];
  /** Call the next wave early while fewer than this many monsters are alive. */
  rushBelow: number;
}

export function coverage(g: G.Game, x: number, y: number, r: number): number {
  let c = 0;
  for (const k of g.pathTiles) {
    const [px, py] = k.split(',').map(Number);
    if (Math.hypot(px - x, py - y) <= r) c++;
  }
  return c;
}

export function towerSpot(g: G.Game): [number, number] | null {
  let best: [number, number] | null = null;
  let bc = -1;
  for (let x = 0; x < G.COLS; x++)
    for (let y = 0; y < G.ROWS; y++) {
      if (!G.canBuild(g, 'tower', x, y)) continue;
      const c = coverage(g, x, y, 4);
      if (c > bc) { bc = c; best = [x, y]; }
    }
  return best;
}

export function trapSpot(g: G.Game): [number, number] | null {
  // The earliest free path tile that a tower covers, so the special lands
  // before the towers shoot.
  for (let d = 0; d <= g.pathLength; d++) {
    const [px, py] = G.pathPos(g, d);
    const x = Math.floor(px);
    const y = Math.floor(py);
    if (!G.canBuild(g, 'trap', x, y)) continue;
    if (g.structures.some((s) => s.kind === 'tower' && Math.hypot(s.x - x, s.y - y) <= 3.5)) return [x, y];
  }
  return null;
}

export function run(f: number, s: Strategy, hpScale = 1) {
  const g = G.newGame(f);
  for (const w of g.waves) w.hp *= hpScale;
  const allowed = (c: G.GemColor) => g.field.colors.includes(c);
  const towers = s.towers.filter(allowed);
  const traps = s.traps.filter(allowed);
  if (!towers.length) return null;
  const plan: { kind: G.StructKind; color: G.GemColor }[] = [];
  // Build order: first tower, then traps, then the remaining towers.
  // Build order: towers and traps alternate, towers first.
  for (let i = 0; i < Math.max(towers.length, traps.length); i++) {
    if (towers[i]) plan.push({ kind: 'tower', color: towers[i] });
    if (traps[i]) plan.push({ kind: 'trap', color: traps[i] });
  }
  const color = new Map<number, G.GemColor>();
  let t = 0;
  const leaks: Record<string, number> = {};
  while (g.state === 'playing' && g.time < 4000) {
    G.step(g, 0.05);
    for (const e of g.events) if (e.type === 'banish') leaks[e.monster] = (leaks[e.monster] ?? 0) + 1;
    g.events.length = 0;
    t += 0.05;
    if (t < 0.25) continue;
    t = 0;
    // Keep enough mana to survive a couple of leaks from the current wave.
    const cur = g.waves[Math.max(0, g.nextWave - 1)];
    const reserve = g.nextWave > 0 ? 2 * (cur.hp * 0.6 + 10) : 0;
    g.mana -= reserve;
    try {
    const built = g.structures.length;
    // Grow wide only once what stands is strong enough, as a player would.
    const minGrade = Math.min(...g.structures.map((x) => (x.gem ? G.gemGrade(x.gem) : 0)));
    if (built < plan.length && (built === 0 || minGrade >= Math.ceil(built / 2) + 1)) {
      const p = plan[built];
      const cost = (p.kind === 'tower' ? G.towerCost(g) : G.trapCost(g)) + G.gemCost(1);
      if (g.mana >= cost) {
        const spot = p.kind === 'tower' ? towerSpot(g) : trapSpot(g);
        const st = spot && G.build(g, p.kind, spot[0], spot[1]);
        if (st) {
          color.set(st.id, p.color);
          const sl = G.createGem(g, p.color, 1);
          if (sl >= 0) G.moveGem(g, { kind: 'inv', index: sl }, { kind: 'struct', id: st.id });
        }
      }
      if (g.mana < cost) continue;
    }
    // Grow the pool whenever mana would otherwise overflow.
    if (g.mana >= g.manaCap * 0.9 && g.mana >= G.poolCost(g)) {
      G.expandPool(g);
      continue;
    }
    // Upgrade the weakest structure (towers weigh double) by one grade.
    const sorted = g.structures.filter((x) => x.gem).sort((a, b) => a.gem!.mass * (a.kind === 'tower' ? 0.5 : 1) - b.gem!.mass * (b.kind === 'tower' ? 0.5 : 1));
    const target = sorted[0];
    if (target) {
      const gr = G.gemGrade(target.gem!);
      if (g.mana >= G.gemCost(gr) + 30) {
        const sl = G.createGem(g, color.get(target.id)!, gr);
        if (sl >= 0) G.moveGem(g, { kind: 'inv', index: sl }, { kind: 'struct', id: target.id });
      }
    }
    } finally {
      g.mana += reserve;
    }
    if (g.nextWave > 0 && g.nextWave < g.waves.length && g.monsters.length < s.rushBelow) G.callWaveEarly(g);
  }
  const grades = g.structures.map((x) => (x.kind === 'trap' ? 't' : '') + (x.gem ? G.gemGrade(x.gem) : 0)).join(',');
  return { state: g.state, wave: g.nextWave, banished: g.banished, time: Math.round(g.time), grades, leaks };
}

export const STRATEGIES: Strategy[] = [
  { name: '3 ruby', towers: ['red', 'red', 'red'], traps: [], rushBelow: 1 },
  { name: '3 topaz', towers: ['yellow', 'yellow', 'yellow'], traps: [], rushBelow: 1 },
  { name: '3 topaz rush', towers: ['yellow', 'yellow', 'yellow'], traps: [], rushBelow: 15 },
  { name: '3 ruby rush', towers: ['red', 'red', 'red'], traps: [], rushBelow: 15 },
  { name: '6 ruby', towers: ['red', 'red', 'red', 'red', 'red', 'red'], traps: [], rushBelow: 1 },
  { name: '2r+traps', towers: ['red', 'red'], traps: ['blue', 'green', 'purple'], rushBelow: 1 },
  { name: '3mix+traps', towers: ['red', 'yellow', 'red'], traps: ['blue', 'purple', 'green', 'blue'], rushBelow: 1 },
  { name: 'mixed', towers: ['red', 'yellow', 'red', 'yellow'], traps: ['purple', 'blue', 'green'], rushBelow: 1 },
  { name: 'mixed rush', towers: ['red', 'yellow', 'red', 'yellow'], traps: ['purple', 'blue', 'green'], rushBelow: 15 },
];

/** Largest monster health multiplier the strategy still wins with, to 5%. */
export function margin(f: number, s: Strategy): number {
  let lo = 0.1;
  let hi = 4;
  if (run(f, s, lo)?.state !== 'won') return 0;
  while (hi / lo > 1.05) {
    const mid = Math.sqrt(lo * hi);
    if (run(f, s, mid)!.state === 'won') lo = mid;
    else hi = mid;
  }
  return lo;
}

if (import.meta.url === `file://${process.argv[1]}` && process.argv.includes("--margin")) {
  for (const s of STRATEGIES) {
    const row: string[] = [];
    for (let f = 0; f < G.FIELDS.length; f++) row.push(run(f, s) ? margin(f, s).toFixed(2) : '  - ');
    console.log(s.name.padEnd(14), row.map((x) => x.padStart(6)).join(''));
  }
} else if (import.meta.url === `file://${process.argv[1]}`) {
  const only = process.argv[2];
  const verbose = process.argv[3] === '-v';
  for (const s of STRATEGIES) {
    if (only && !s.name.includes(only)) continue;
    const rows: string[] = [];
    for (let f = 0; f < G.FIELDS.length; f++) {
      const r = run(f, s);
      if (verbose && r) console.log(f, JSON.stringify(r));
      rows.push(r ? `${r.state === 'won' ? 'W' : 'L' + r.wave}${r.banished ? '/b' + r.banished : ''}` : '-');
    }
    console.log(s.name.padEnd(14), rows.map((x) => x.padEnd(9)).join(''));
  }
}