Skip to content
1        10        20        30        40        50        60        70        80        90        1001// Headless turn-based tactics engine.2//3// A battle is a sequence of rounds. Every living unit acts once per round in4// initiative order. A unit may move, then perform one action: a basic attack or5// an ability card. Attacking or playing a card ends that unit's turn.67import * as hex from './hex.js';8import { CHARACTERS, cardById, heroineDeck } from './catalog.js';910export const MAX_ROUNDS = 20;11export const FERVOR_MAX = 6;12export const FERVOR_START = 2;13export const FERVOR_PER_TURN = 2;14export const HAND_START = 3;15export const HAND_MAX = 6;1617// Weights for the Torment's targeting and positioning. Keeping them together18// makes the tactics legible and keeps balance tuning in one place.19const ENEMY_TACTICS = Object.freeze({20  wounded: 600, // reward finishing a heroine who is already hurt21  hitsToKill: 10, // prefer the heroine that takes fewest blows to break22  threatDamage: 7, // dangerous heroines are worth removing early23  threatRange: 5, // reach makes a heroine more dangerous24  armor: 9, // tough heroines are less attractive targets25  ward: 8,26  distance: 12, // per hex from the cell being judged27  reach: 1200, // never pass up a hit this turn28  kill: 2600, // finish a heroine when the blow would land29  retaliation: 3, // per point of expected counter-damage30  attack: 10000, // a cell that can attack beats one that cannot31  kite: 22, // per hex inside a ranged unit's reach32  meleeExposure: 16, // per adjacent melee heroine a ranged unit backs into33  approach: 100, // per hex of walking distance34  moveCost: 2,35  hysteresis: 6, // only reposition for a meaningful gain36});3738export class BattleError extends Error {39  constructor(message) {40    super(message);41    this.name = 'BattleError';42  }43}4445class Rng {46  constructor(seed) {47    this.state = (Number(seed) >>> 0) || 0x9e3779b9;48  }4950  next() {51    this.state = (Math.imul(this.state, 1664525) + 1013904223) >>> 0;52    return this.state;53  }5455  shuffle(values) {56    for (let index = values.length - 1; index > 0; index -= 1) {57      const swap = this.next() % (index + 1);58      [values[index], values[swap]] = [values[swap], values[index]];59    }60    return values;61  }62}6364function makeUnit(spec, id, rng) {65  const template = CHARACTERS[spec.character];66  if (!template) throw new BattleError(`Unknown character: ${spec.character}`);67  let deck = [];68  const hand = [];69  if (template.team === 'allies') {70    // A heroine fights with the cards the player owns, or her full deck when71    // no collection is given.72    const owned = spec.cards ?? heroineDeck(template.id);73    for (const cardId of owned) cardById(cardId);74    deck = rng.shuffle([...owned]);75  }76  return {77    id,78    character: template.id,79    name: template.name,80    title: template.title,81    team: template.team,82    health: template.health,83    maxHealth: template.health,84    damage: template.damage,85    armor: template.armor,86    initiative: template.initiative,87    movement: template.movement,88    range: template.range,89    color: template.color,90    shape: template.shape ?? 'heroine',91    hex: { ...spec.hex },92    ward: 0,93    wardRounds: 0,94    poison: 0,95    poisonRounds: 0,96    marked: 0,97    markedRounds: 0,98    rooted: 0,99    haste: 0,100    movementLeft: 0,101    hasActed: false,102    retaliated: false,103    fervor: template.team === 'allies' ? FERVOR_START : 0,104    deck,105    hand,106    discard: [],107  };108}109110export class Battle {111  constructor(spec, seed = 1) {112    if (!spec || !Array.isArray(spec.allies) || !Array.isArray(spec.enemies)) {113      throw new BattleError('A battle needs both sides.');114    }115    if (spec.allies.length === 0 || spec.enemies.length === 0) {116      throw new BattleError('Both sides need at least one unit.');117    }118119    this.encounter = spec.encounter ?? 0;120    this.encounterName = spec.name ?? 'Battle';121    this.rng = new Rng(seed);122    this.units = [];123    this.events = [];124    this.version = 0;125    this.round = 0;126    this.order = [];127    this.turnIndex = 0;128    this.current = null;129    this.outcome = null;130    this.logLines = [];131132    const seen = new Set();133    let id = 1;134    for (const unitSpec of [...spec.allies, ...spec.enemies]) {135      if (!hex.makeHex(unitSpec.hex.column, unitSpec.hex.row)) {136        throw new BattleError('A unit stands outside the arena.');137      }138      const occupied = hex.key(unitSpec.hex);139      if (seen.has(occupied)) throw new BattleError('Two units share a hex.');140      seen.add(occupied);141      this.units.push(makeUnit(unitSpec, id, this.rng));142      id += 1;143    }144    const allies = this.units.filter((unit) => unit.team === 'allies');145    for (const ally of allies) this.drawCards(ally, HAND_START);146147    this.log(`${this.encounterName} — the battle begins.`);148    this.nextActor();149  }150151  /**152   * A plain, JSON-safe copy of the battle, enough to resume it exactly: the153   * seeded shuffle state, every unit, the turn order and the chronicle.154   */155  toState() {156    return {157      encounter: this.encounter,158      encounterName: this.encounterName,159      rng: this.rng.state,160      units: structuredClone(this.units),161      version: this.version,162      round: this.round,163      order: [...this.order],164      turnIndex: this.turnIndex,165      current: this.current,166      outcome: this.outcome,167      logLines: [...this.logLines],168    };169  }170171  /** Rebuild a battle from `toState()` output without replaying its history. */172  static fromState(state) {173    if (!state || !Array.isArray(state.units) || state.units.length === 0) {174      throw new BattleError('The saved battle is damaged.');175    }176    for (const unit of state.units) {177      if (!CHARACTERS[unit.character]) throw new BattleError('The saved battle is damaged.');178      for (const cardId of [...unit.hand, ...unit.deck, ...unit.discard]) cardById(cardId);179    }180    const battle = Object.create(Battle.prototype);181    battle.encounter = state.encounter;182    battle.encounterName = state.encounterName;183    battle.rng = new Rng(state.rng);184    battle.units = structuredClone(state.units);185    battle.events = [];186    battle.version = state.version;187    battle.round = state.round;188    battle.order = [...state.order];189    battle.turnIndex = state.turnIndex;190    battle.current = state.current;191    battle.outcome = state.outcome;192    battle.logLines = [...state.logLines];193    return battle;194  }195196  // ---------------------------------------------------------------- queries197198  unit(id) {199    return this.units.find((candidate) => candidate.id === id) ?? null;200  }201202  currentUnit() {203    return this.current === null ? null : this.unit(this.current);204  }205206  livingUnits(team = null) {207    return this.units.filter(208      (unit) => unit.health > 0 && (team === null || unit.team === team),209    );210  }211212  unitAt(hexSlot) {213    if (!hexSlot) return null;214    return (215      this.livingUnits().find((unit) => hex.sameHex(unit.hex, hexSlot)) ?? null216    );217  }218219  isPlayerTurn() {220    const unit = this.currentUnit();221    return Boolean(unit && unit.team === 'allies' && !this.outcome);222  }223224  needsEnemyTurn() {225    const unit = this.currentUnit();226    return Boolean(unit && unit.team !== 'allies' && !this.outcome);227  }228229  // --------------------------------------------------------------- internal230231  emit(event) {232    this.events.push(event);233    this.version += 1;234  }235236  drainEvents() {237    const drained = this.events;238    this.events = [];239    return drained;240  }241242  log(line) {243    this.logLines.push(line);244    if (this.logLines.length > 60) this.logLines.shift();245  }246247  drawCards(unit, count) {248    for (let drawn = 0; drawn < count; drawn += 1) {249      if (unit.hand.length >= HAND_MAX) break;250      if (unit.deck.length === 0) {251        unit.deck = this.rng.shuffle(unit.discard);252        unit.discard = [];253      }254      if (unit.deck.length === 0) break;255      unit.hand.push(unit.deck.pop());256    }257  }258259  occupied(hexSlot, exceptId = null) {260    return this.livingUnits().some(261      (unit) => unit.id !== exceptId && hex.sameHex(unit.hex, hexSlot),262    );263  }264265  checkOutcome() {266    if (this.outcome) return;267    const allies = this.livingUnits('allies').length > 0;268    const enemies = this.livingUnits('torment').length > 0;269    if (!allies && !enemies) this.finish('draw');270    else if (!enemies) this.finish('victory');271    else if (!allies) this.finish('defeat');272  }273274  finish(outcome) {275    if (this.outcome) return;276    this.outcome = outcome;277    this.current = null;278    this.emit({ type: 'finished', outcome });279    const line =280      outcome === 'victory'281        ? 'The Torment breaks. Victory.'282        : outcome === 'defeat'283          ? 'The heroines fall silent. Defeat.'284          : 'Neither side yields. The battle is a draw.';285    this.log(line);286  }287288  nextActor() {289    for (let guard = 0; guard < 1000; guard += 1) {290      if (this.outcome) {291        this.current = null;292        return;293      }294      this.turnIndex += 1;295      if (this.turnIndex >= this.order.length) {296        this.round += 1;297        if (this.round > MAX_ROUNDS) {298          this.finish('draw');299          return;300        }301        this.order = this.livingUnits()302          .sort((left, right) => right.initiative - left.initiative || left.id - right.id)303          .map((unit) => unit.id);304        for (const unit of this.units) unit.retaliated = false;305        this.turnIndex = 0;306        this.emit({ type: 'round', round: this.round });307        this.log(`Round ${this.round}.`);308      }309      const id = this.order[this.turnIndex];310      const unit = this.unit(id);311      if (!unit || unit.health <= 0) continue;312      if (this.beginTurn(unit)) return;313    }314  }315316  beginTurn(unit) {317    this.current = unit.id;318    unit.movementLeft = unit.rooted > 0 ? 0 : unit.movement + unit.haste;319    unit.haste = 0;320    unit.hasActed = false;321322    if (unit.team === 'allies') {323      unit.fervor = Math.min(FERVOR_MAX, unit.fervor + FERVOR_PER_TURN);324      this.drawCards(unit, 1);325    }326327    this.emit({ type: 'turn', unit: unit.id });328    this.log(`${unit.name} acts.`);329330    if (unit.poisonRounds > 0) {331      this.emit({ type: 'status', unit: unit.id, status: 'poison' });332      this.damageUnit(unit, unit.poison, { ignoreArmor: true, source: 'poison' });333      unit.poisonRounds -= 1;334      if (unit.poisonRounds === 0) unit.poison = 0;335      if (unit.health <= 0) {336        this.checkOutcome();337        return false;338      }339    }340    return true;341  }342343  endTurn() {344    const unit = this.currentUnit();345    if (unit) {346      this.expireStatuses(unit);347      this.emit({ type: 'turnEnd', unit: unit.id });348    }349    this.current = null;350    this.nextActor();351  }352353  expireStatuses(unit) {354    if (unit.wardRounds > 0) {355      unit.wardRounds -= 1;356      if (unit.wardRounds === 0) unit.ward = 0;357    }358    if (unit.markedRounds > 0) {359      unit.markedRounds -= 1;360      if (unit.markedRounds === 0) unit.marked = 0;361    }362    if (unit.rooted > 0) unit.rooted -= 1;363  }364365  damageUnit(target, raw, { ignoreArmor = false, source = null } = {}) {366    if (target.health <= 0) return 0;367    let amount = raw;368    if (!ignoreArmor) {369      amount = Math.max(1, amount - target.armor - target.ward);370    }371    amount += target.marked;372    amount = Math.max(1, Math.min(amount, target.health));373    target.health -= amount;374    this.emit({ type: 'damage', unit: target.id, amount, source });375    this.log(`${target.name} takes ${amount} damage.`);376    if (target.health === 0) {377      this.emit({ type: 'death', unit: target.id });378      this.log(`${target.name} falls.`);379    }380    return amount;381  }382383  healUnit(target, amount) {384    const healed = Math.max(0, Math.min(amount, target.maxHealth - target.health));385    if (healed === 0) return 0;386    target.health += healed;387    this.emit({ type: 'heal', unit: target.id, amount: healed });388    this.log(`${target.name} recovers ${healed} health.`);389    return healed;390  }391392  resolveAttack(attacker, defender) {393    this.emit({ type: 'attack', attacker: attacker.id, target: defender.id, range: attacker.range });394    this.damageUnit(defender, attacker.damage, { source: attacker.id });395    if (396      defender.health > 0 &&397      !defender.retaliated &&398      hex.distance(attacker.hex, defender.hex) <= defender.range399    ) {400      defender.retaliated = true;401      const back = Math.max(1, Math.floor(defender.damage / 2));402      this.emit({ type: 'retaliate', attacker: defender.id, target: attacker.id, range: defender.range });403      this.damageUnit(attacker, back, { source: defender.id });404    }405    this.checkOutcome();406  }407408  // ---------------------------------------------------------------- movement409410  /** Map of hex key -> movement cost for a unit's remaining movement. */411  reachable(unit) {412    const costs = new Map([[hex.key(unit.hex), 0]]);413    if (unit.movementLeft <= 0) return costs;414    const queue = [unit.hex];415    for (let index = 0; index < queue.length; index += 1) {416      const current = queue[index];417      const cost = costs.get(hex.key(current));418      if (cost >= unit.movementLeft) continue;419      for (const next of hex.neighbors(current)) {420        const nextKey = hex.key(next);421        if (costs.has(nextKey) || this.occupied(next, unit.id)) continue;422        costs.set(nextKey, cost + 1);423        queue.push(next);424      }425    }426    costs.delete(hex.key(unit.hex));427    return costs;428  }429430  reachableHexes(unit) {431    return [...this.reachable(unit).keys()].map(hex.fromKey);432  }433434  attackTargets(unit) {435    if (unit.hasActed) return [];436    return this.livingUnits().filter(437      (target) =>438        target.team !== unit.team &&439        hex.distance(unit.hex, target.hex) <= unit.range,440    );441  }442443  // ------------------------------------------------------------------- cards444445  targetHexes(unit, card) {446    const rule = card.rule;447    if (rule.kind === 'self') return [];448    const result = [];449    if (rule.kind === 'enemy' || rule.kind === 'ally') {450      const team = rule.kind === 'enemy' ? 'other' : unit.team;451      for (const other of this.livingUnits()) {452        if (team === 'other' ? other.team === unit.team : other.team !== team) continue;453        const gap = hex.distance(unit.hex, other.hex);454        if (gap >= rule.min && gap <= rule.max) result.push({ ...other.hex });455      }456    } else if (rule.kind === 'empty') {457      for (const cell of hex.allHexes()) {458        const gap = hex.distance(unit.hex, cell);459        if (gap < Math.max(1, rule.min) || gap > rule.max) continue;460        if (this.occupied(cell)) continue;461        result.push(cell);462      }463    }464    return result;465  }466467  cardTargets(handIndex) {468    const unit = this.currentUnit();469    if (!unit || unit.team !== 'allies') return [];470    const cardId = unit.hand[handIndex];471    if (!cardId) return [];472    return this.targetHexes(unit, cardById(cardId));473  }474475  validateTarget(unit, card, targetHex) {476    const rule = card.rule;477    if (rule.kind === 'self') {478      if (targetHex) throw new BattleError('This card targets only its caster.');479      return;480    }481    if (!targetHex) throw new BattleError('Choose a target hex.');482    if (!hex.makeHex(targetHex.column, targetHex.row)) {483      throw new BattleError('That hex is outside the arena.');484    }485    const gap = hex.distance(unit.hex, targetHex);486    if (gap < rule.min || gap > rule.max) {487      throw new BattleError(488        `Target must be ${rule.min}–${rule.max} hexes away (it is ${gap}).`,489      );490    }491    if (rule.kind === 'empty') {492      if (this.unitAt(targetHex)) throw new BattleError('That hex is occupied.');493      return;494    }495    const target = this.unitAt(targetHex);496    if (!target) throw new BattleError('That hex is empty.');497    const wantAlly = rule.kind === 'ally';498    if ((target.team === unit.team) !== wantAlly) {499      throw new BattleError(wantAlly ? 'Choose an ally.' : 'Choose an enemy.');500    }501  }502503  // --------------------------------------------------------------- commands504505  receive(command) {506    if (this.outcome) throw new BattleError('The battle is already over.');507    if (!command || typeof command !== 'object') {508      throw new BattleError('Unknown command.');509    }510    const unit = command.unit === undefined ? this.currentUnit() : this.unit(command.unit);511    if (!unit || unit.id !== this.current) {512      throw new BattleError('It is not that unit’s turn.');513    }514    if (unit.team !== 'allies') throw new BattleError('The Torment acts on its own.');515516    switch (command.type) {517      case 'move':518        return this.commandMove(unit, command.to);519      case 'attack':520        return this.commandAttack(unit, command.target);521      case 'playCard':522        return this.commandPlayCard(unit, command.handIndex, command.target ?? null);523      case 'endTurn':524        this.endTurn();525        return this.drainEvents();526      default:527        throw new BattleError('Unknown command.');528    }529  }530531  commandMove(unit, to) {532    if (!hex.makeHex(to?.column, to?.row)) throw new BattleError('That hex is outside the arena.');533    if (unit.rooted > 0) throw new BattleError(`${unit.name} is rooted and cannot move.`);534    const costs = this.reachable(unit);535    const cost = costs.get(hex.key(to));536    if (cost === undefined) throw new BattleError('That hex is out of reach.');537    const from = { ...unit.hex };538    unit.hex = { ...to };539    unit.movementLeft -= cost;540    this.emit({ type: 'move', unit: unit.id, from, to: { ...to } });541    this.log(`${unit.name} moves ${cost} hex${cost === 1 ? '' : 'es'}.`);542    return this.drainEvents();543  }544545  commandAttack(unit, targetId) {546    if (unit.hasActed) throw new BattleError(`${unit.name} has already acted.`);547    const target = this.unit(targetId);548    if (!target || target.health <= 0 || target.team === unit.team) {549      throw new BattleError('Choose a living enemy.');550    }551    if (hex.distance(unit.hex, target.hex) > unit.range) {552      throw new BattleError('That enemy is out of range.');553    }554    unit.hasActed = true;555    this.resolveAttack(unit, target);556    if (!this.outcome) this.endTurn();557    return this.drainEvents();558  }559560  commandPlayCard(unit, handIndex, targetHex) {561    if (unit.hasActed) throw new BattleError(`${unit.name} has already acted.`);562    const cardId = unit.hand[handIndex];563    if (!cardId) throw new BattleError('No such card in hand.');564    const card = cardById(cardId);565    if (unit.fervor < card.cost) {566      throw new BattleError(`Not enough fervor for ${card.name}.`);567    }568    this.validateTarget(unit, card, targetHex);569570    unit.hand.splice(handIndex, 1);571    unit.discard.push(cardId);572    unit.fervor -= card.cost;573    this.emit({ type: 'card', unit: unit.id, card: cardId, target: targetHex });574    this.log(`${unit.name} plays ${card.name}.`);575576    this.applyCard(unit, card, targetHex);577    unit.hasActed = true;578    if (!this.outcome) this.endTurn();579    return this.drainEvents();580  }581582  applyCard(unit, card, targetHex) {583    const primary = targetHex584      ? this.unitAt(targetHex)585      : card.rule.kind === 'self'586        ? unit587        : null;588    for (const effect of card.effects) {589      switch (effect.type) {590        case 'damage':591          if (primary) {592            this.damageUnit(primary, effect.amount, {593              ignoreArmor: effect.ignoreArmor,594              source: unit.id,595            });596          }597          break;598        case 'heal':599          if (primary) this.healUnit(primary, effect.amount);600          break;601        case 'ward':602          if (primary) {603            primary.ward = Math.max(primary.ward, effect.amount);604            primary.wardRounds = Math.max(primary.wardRounds, effect.rounds);605            this.emit({ type: 'status', unit: primary.id, status: 'ward' });606            this.log(`${primary.name} is warded.`);607          }608          break;609        case 'root':610          if (primary) {611            primary.rooted = Math.max(primary.rooted, effect.rounds);612            this.emit({ type: 'status', unit: primary.id, status: 'rooted' });613            this.log(`${primary.name} is rooted.`);614          }615          break;616        case 'poison':617          if (primary) {618            primary.poison = Math.max(primary.poison, effect.damage);619            primary.poisonRounds = Math.max(primary.poisonRounds, effect.rounds);620            this.emit({ type: 'status', unit: primary.id, status: 'poison' });621            this.log(`${primary.name} is poisoned.`);622          }623          break;624        case 'mark':625          if (primary) {626            primary.marked = Math.max(primary.marked, effect.bonus);627            primary.markedRounds = Math.max(primary.markedRounds, effect.rounds);628            this.emit({ type: 'status', unit: primary.id, status: 'marked' });629            this.log(`${primary.name} is marked.`);630          }631          break;632        case 'haste':633          if (primary) {634            if (primary.id === unit.id) primary.movementLeft += effect.movement;635            else primary.haste += effect.movement;636            this.emit({ type: 'status', unit: primary.id, status: 'haste' });637            this.log(`${primary.name} gains ${effect.movement} movement.`);638          }639          break;640        case 'blink': {641          if (!targetHex) break;642          const from = { ...unit.hex };643          unit.hex = { ...targetHex };644          this.emit({ type: 'move', unit: unit.id, from, to: { ...targetHex } });645          this.log(`${unit.name} steps through the veil.`);646          break;647        }648        case 'line': {649          if (!targetHex) break;650          const cells = hex.line(unit.hex, targetHex).slice(1);651          this.emit({ type: 'line', from: { ...unit.hex }, cells, color: 0x9fe8ff });652          for (const cell of cells) {653            const victim = this.unitAt(cell);654            if (victim && victim.team !== unit.team) {655              this.damageUnit(victim, effect.amount, {656                ignoreArmor: true,657                source: unit.id,658              });659            }660          }661          break;662        }663        case 'volley': {664          if (!targetHex) break;665          this.emit({ type: 'burst', hex: { ...targetHex }, radius: effect.radius });666          for (const victim of this.livingUnits()) {667            if (668              victim.team !== unit.team &&669              hex.distance(victim.hex, targetHex) <= effect.radius670            ) {671              this.damageUnit(victim, effect.amount, {672                ignoreArmor: false,673                source: unit.id,674              });675            }676          }677          break;678        }679        case 'assassinate': {680          if (!primary) break;681          const wounded = primary.health * 100 <= primary.maxHealth * effect.threshold;682          this.damageUnit(primary, wounded ? effect.wounded : effect.healthy, {683            ignoreArmor: false,684            source: unit.id,685          });686          break;687        }688        default:689          throw new BattleError(`Unknown card effect: ${effect.type}`);690      }691    }692    this.checkOutcome();693  }694695  // ------------------------------------------------------------------ enemy696697  /** Damage this unit can expect to deal after armour, wards, and marks. */698  expectedDamage(unit, target) {699    const mitigated = Math.max(1, unit.damage - target.armor - target.ward);700    return Math.max(1, mitigated + target.marked);701  }702703  /** Blows this unit needs to break the target, at least one. */704  hitsToKill(unit, target) {705    return Math.ceil(target.health / this.expectedDamage(unit, target));706  }707708  /**709   * Value of landing one hit on a heroine from a given cell. Wounded heroines710   * are worth finishing, dangerous ones are worth removing early, and tough or711   * warded ones are less attractive. A blow that would kill is decisive, while712   * a survivor's counter-attack counts against the trade.713   */714  enemyAttackScore(unit, target, from = unit.hex) {715    const damage = this.expectedDamage(unit, target);716    const gap = hex.distance(from, target.hex);717    const wounded = 1 - target.health / target.maxHealth;718    let score =719      wounded * ENEMY_TACTICS.wounded -720      this.hitsToKill(unit, target) * ENEMY_TACTICS.hitsToKill +721      target.damage * ENEMY_TACTICS.threatDamage +722      target.range * ENEMY_TACTICS.threatRange -723      target.armor * ENEMY_TACTICS.armor -724      target.ward * ENEMY_TACTICS.ward -725      gap * ENEMY_TACTICS.distance;726    if (damage >= target.health) {727      score += ENEMY_TACTICS.kill;728    } else if (gap <= target.range && !target.retaliated) {729      const back = Math.max(1, Math.floor(target.damage / 2) - unit.armor - unit.ward);730      score -= back * ENEMY_TACTICS.retaliation;731    }732    return score;733  }734735  /**736   * How much an enemy wants to hunt a heroine from where it stands. A target it737   * can reach and strike this turn gets a large bonus, so an enemy never walks738   * past a hit it could take.739   */740  enemyTargetScore(unit, target, { from = unit.hex, inReach = false } = {}) {741    let score = this.enemyAttackScore(unit, target, from);742    if (inReach) score += ENEMY_TACTICS.reach;743    return score;744  }745746  /** The heroine this enemy should hunt: the most valuable one it can reach. */747  chooseEnemyTarget(unit, costs) {748    const reach = [...costs.keys()].map(hex.fromKey);749    let best = null;750    let bestScore = -Infinity;751    for (const target of this.livingUnits('allies')) {752      const inReach =753        hex.distance(unit.hex, target.hex) <= unit.range ||754        reach.some((cell) => hex.distance(cell, target.hex) <= unit.range);755      const score = this.enemyTargetScore(unit, target, { inReach });756      if (score > bestScore || (score === bestScore && best && target.id < best.id)) {757        best = target;758        bestScore = score;759      }760    }761    return best;762  }763764  /** Walking distance from a hex to every open hex, treating units but `exceptId` as walls. */765  distanceMap(start, exceptId = null) {766    const distances = new Map([[hex.key(start), 0]]);767    const queue = [start];768    for (let index = 0; index < queue.length; index += 1) {769      const current = queue[index];770      const distance = distances.get(hex.key(current));771      if (distance >= 20) continue;772      for (const next of hex.neighbors(current)) {773        const nextKey = hex.key(next);774        if (distances.has(nextKey) || this.occupied(next, exceptId)) continue;775        distances.set(nextKey, distance + 1);776        queue.push(next);777      }778    }779    return distances;780  }781782  /**783   * Score one reachable cell. A cell that can strike a heroine is worth far784   * more than one that cannot; otherwise the cell is ranked by walking distance785   * toward the chosen target. The best victim is returned with the score so the786   * plan and the attack always agree.787   */788  enemyStepScore(unit, cell, cost, approach, approachMap, canWalk) {789    const allies = this.livingUnits('allies');790    // A ranged unit that backs into a melee heroine is not really retreating.791    const exposed =792      unit.range > 1793        ? allies.filter(794            (other) => other.range === 1 && hex.distance(cell, other.hex) === 1,795          ).length796        : 0;797    let victim = null;798    let hit = -Infinity;799    for (const ally of allies) {800      const gap = hex.distance(cell, ally.hex);801      if (gap > unit.range) continue;802      let value = this.enemyAttackScore(unit, ally, cell);803      if (unit.range > 1) {804        // Kite toward the far edge of the range instead of trading in melee.805        value -= Math.abs(gap - unit.range) * ENEMY_TACTICS.kite;806        value -= exposed * ENEMY_TACTICS.meleeExposure;807      }808      if (value > hit) {809        hit = value;810        victim = ally;811      }812    }813    if (victim) {814      return {815        score: ENEMY_TACTICS.attack + hit - cost * ENEMY_TACTICS.moveCost,816        victim,817      };818    }819820    if (canWalk) {821      const walk = approachMap.get(hex.key(cell));822      // Do not step into a pocket the target cannot be reached from while a823      // real path exists; standing still is better than oscillating in a dead824      // end.825      if (walk === undefined) return { score: -Infinity, victim: null };826      return {827        score: -walk * ENEMY_TACTICS.approach - cost * ENEMY_TACTICS.moveCost,828        victim: null,829      };830    }831    return {832      score: -hex.distance(cell, approach.hex) * ENEMY_TACTICS.approach -833        cost * ENEMY_TACTICS.moveCost,834      victim: null,835    };836  }837838  /**839   * Pick the best cell this enemy can reach and the heroine it should hit from840   * there. Ranged attackers prefer the far edge of their range, melee units841   * close along a walkable path, and a small hysteresis keeps an enemy from842   * shuffling between cells that are effectively equivalent.843   */844  chooseEnemyStep(unit, costs) {845    const approach = this.chooseEnemyTarget(unit, costs);846    const stay = { cell: { ...unit.hex }, cost: 0 };847    if (!approach) return { ...stay, victim: null };848849    const approachMap = this.distanceMap(approach.hex, unit.id);850    const canWalk = approachMap.has(hex.key(unit.hex));851    const stayScore = this.enemyStepScore(unit, stay.cell, 0, approach, approachMap, canWalk);852    let best = { ...stay, ...stayScore };853    for (const [key, cost] of costs) {854      const cell = hex.fromKey(key);855      if (hex.sameHex(cell, unit.hex)) continue;856      const scored = this.enemyStepScore(unit, cell, cost, approach, approachMap, canWalk);857      if (scored.score > best.score) best = { cell, cost, ...scored };858    }859860    if (best.cost > 0 && best.score - stayScore.score <= ENEMY_TACTICS.hysteresis) {861      return { ...stay, ...stayScore };862    }863    return best;864  }865866  runEnemyTurn() {867    if (this.outcome) return [];868    const unit = this.currentUnit();869    if (!unit || unit.team === 'allies') return [];870871    const costs = this.reachable(unit);872    const step = this.chooseEnemyStep(unit, costs);873    if (step.cost > 0) {874      const from = { ...unit.hex };875      unit.hex = { ...step.cell };876      unit.movementLeft -= step.cost;877      this.emit({ type: 'move', unit: unit.id, from, to: { ...unit.hex } });878      this.log(`${unit.name} takes position.`);879    }880    if (step.victim) {881      unit.hasActed = true;882      this.resolveAttack(unit, step.victim);883    }884    if (!this.outcome) this.endTurn();885    return this.drainEvents();886  }887888  // --------------------------------------------------------------- snapshot889890  snapshot() {891    const current = this.currentUnit();892    const player = current && current.team === 'allies' ? current : null;893    const reachable = player && !player.hasActed ? this.reachableHexes(player) : [];894    const attackable = player ? this.attackTargets(player).map((unit) => unit.id) : [];895    const hand = player896      ? player.hand.map((cardId, index) => {897          const card = cardById(cardId);898          const targets = this.targetHexes(player, card);899          return {900            index,901            id: card.id,902            name: card.name,903            cost: card.cost,904            text: card.text,905            icon: card.icon,906            playable:907              player.fervor >= card.cost &&908              (card.rule.kind === 'self' || targets.length > 0),909            needsTarget: card.rule.kind !== 'self',910          };911        })912      : [];913914    return {915      encounter: this.encounter,916      name: this.encounterName,917      round: this.round,918      version: this.version,919      outcome: this.outcome,920      current: this.current,921      currentName: current?.name ?? null,922      isPlayerTurn: this.isPlayerTurn(),923      turnOrder: this.order.map((id) => {924        const unit = this.unit(id);925        return unit926          ? {927              id,928              name: unit.name,929              character: unit.character,930              team: unit.team,931              health: unit.health,932              maxHealth: unit.maxHealth,933              initiative: unit.initiative,934            }935          : null;936      }).filter(Boolean),937      units: this.units.map((unit) => ({938        id: unit.id,939        character: unit.character,940        name: unit.name,941        title: unit.title,942        team: unit.team,943        color: unit.color,944        shape: unit.shape,945        hex: { ...unit.hex },946        health: unit.health,947        maxHealth: unit.maxHealth,948        damage: unit.damage,949        armor: unit.armor,950        initiative: unit.initiative,951        movement: unit.movement,952        range: unit.range,953        ward: unit.ward,954        wardRounds: unit.wardRounds,955        poison: unit.poison,956        poisonRounds: unit.poisonRounds,957        marked: unit.marked,958        markedRounds: unit.markedRounds,959        rooted: unit.rooted,960        movementLeft: unit.movementLeft,961        hasActed: unit.hasActed,962        fervor: unit.fervor,963        handSize: unit.hand.length,964        deckSize: unit.deck.length,965      })),966      hand,967      fervor: player?.fervor ?? 0,968      maxFervor: FERVOR_MAX,969      movementLeft: player?.movementLeft ?? 0,970      reachable,971      attackable,972      log: this.logLines.slice(-9),973    };974  }975}976977/** Convenience factory used by tests and the session. */978export function createBattle(spec, seed = 1) {979  return new Battle(spec, seed);980}