LINE1 10 20 30 40 50 60 70 80 90 100 1101import { test } from 'bun:test';2import assert from 'node:assert/strict';34import { Battle, BattleError, FERVOR_MAX } from '../src/battle.js';5import {6 ENCOUNTERS,7 HEROINE_IDS,8 RECRUIT_HONOR,9 STARTING_CARDS,10 battleSpec,11 cardById,12 cardPrice,13 heroineDeck,14} from '../src/catalog.js';15import { GOLD_PER_KILL, GOLD_PER_VICTORY, HONOR_PER_KILL } from '../src/profile.js';16import { distance as hexDistance, fromKey } from '../src/hex.js';17import { Session } from '../src/session.js';1819function battleWith(allies, enemies, seed = 7) {20 return new Battle({ encounter: 0, name: 'Test battle', allies, enemies }, seed);21}2223function unitSpec(character, column, row) {24 return { character, hex: { column, row } };25}2627function duel(heroine, enemy, heroineHex, enemyHex, seed = 7) {28 return battleWith([unitSpec(heroine, heroineHex.column, heroineHex.row)], [29 unitSpec(enemy, enemyHex.column, enemyHex.row),30 ], seed);31}3233function give(battle, cardId) {34 const unit = battle.currentUnit();35 unit.hand = [cardId];36 unit.fervor = FERVOR_MAX;37 return unit;38}3940function current(battle) {41 return battle.currentUnit();42}4344function enemyOf(battle) {45 return battle.units.find((unit) => unit.team === 'torment');46}47484950test('the round order follows initiative, highest first', () => {51 const battle = battleWith(52 [53 unitSpec('aislinn', 2, 8),54 unitSpec('finella', 4, 8),55 unitSpec('atlanta', 6, 8),56 ],57 [unitSpec('silencer', 4, 1)],58 );59 assert.deepEqual(60 battle.snapshot().turnOrder.map((entry) => entry.name),61 ['Finella', 'Atlanta', 'Aislinn', 'Silencer'],62 );63 assert.equal(current(battle).name, 'Finella');64 assert.equal(battle.snapshot().round, 1);65});6667test('movement spends points, avoids occupied hexes, and respects the budget', () => {68 const battle = battleWith(69 [unitSpec('finella', 4, 8), unitSpec('aislinn', 4, 7)],70 [unitSpec('silencer', 4, 1)],71 );72 const finella = current(battle);73 const reachable = battle.reachableHexes(finella);74 const keys = new Set(reachable.map((cell) => `${cell.column},${cell.row}`));75 assert.ok(keys.has('3,8'));76 assert.ok(keys.has('4,7') === false, 'an occupied hex is not reachable');77 assert.ok(keys.has('4,5'), 'four movement points reach four rows down');7879 battle.receive({ type: 'move', to: { column: 3, row: 8 } });80 assert.equal(finella.movementLeft, 3);81 assert.throws(82 () => battle.receive({ type: 'move', to: { column: 3, row: 4 } }),83 BattleError,84 );85});8687test('a melee attack damages the target and provokes a single retaliation', () => {88 const battle = duel('finella', 'silencer', { column: 4, row: 8 }, { column: 4, row: 7 });89 const finella = current(battle);90 const silencer = enemyOf(battle);91 const events = battle.receive({ type: 'attack', target: silencer.id });9293 assert.equal(silencer.health, 69, '18 damage minus 2 armour');94 assert.equal(finella.health, 163, 'half of 12 damage minus 4 armour');95 assert.ok(events.some((event) => event.type === 'retaliate'));96 assert.equal(current(battle).team, 'torment', 'attacking ends the turn');97});9899test('attack events carry the attacker range for melee and ranged visuals', () => {100 const ranged = duel('atlanta', 'silencer', { column: 2, row: 8 }, { column: 2, row: 5 });101 const shot = ranged.receive({ type: 'attack', target: enemyOf(ranged).id });102 assert.equal(shot.find((event) => event.type === 'attack').range, 4);103104 const melee = duel('finella', 'silencer', { column: 4, row: 8 }, { column: 4, row: 7 });105 const blow = melee.receive({ type: 'attack', target: enemyOf(melee).id });106 assert.equal(blow.find((event) => event.type === 'attack').range, 1);107 assert.equal(blow.find((event) => event.type === 'retaliate').range, 1);108});109110test('out-of-range attacks and enemy orders are rejected', () => {111 const battle = duel('finella', 'silencer', { column: 4, row: 8 }, { column: 4, row: 6 });112 const silencer = enemyOf(battle);113 assert.throws(() => battle.receive({ type: 'attack', target: silencer.id }), BattleError);114 battle.receive({ type: 'endTurn' });115 assert.equal(current(battle).team, 'torment');116 assert.throws(117 () => battle.receive({ type: 'endTurn', unit: silencer.id }),118 BattleError,119 );120 assert.equal(battle.needsEnemyTurn(), true);121});122123test('the player cannot move after ending the turn', () => {124 const battle = duel('finella', 'silencer', { column: 4, row: 8 }, { column: 4, row: 1 });125 battle.receive({ type: 'endTurn' });126 assert.throws(127 () => battle.receive({ type: 'move', unit: 1, to: { column: 3, row: 8 } }),128 BattleError,129 );130});131132133134test('Mist Lance ignores armour and costs one fervor', () => {135 const battle = duel('aislinn', 'silencer', { column: 2, row: 8 }, { column: 2, row: 5 });136 const aislinn = give(battle, 'mist-lance');137 const silencer = enemyOf(battle);138 const events = battle.receive({ type: 'playCard', handIndex: 0, target: silencer.hex });139140 assert.equal(silencer.health, 69);141 assert.equal(aislinn.fervor, FERVOR_MAX - 1);142 assert.equal(aislinn.hand.length, 0);143 assert.equal(aislinn.discard.length, 1);144 assert.ok(events.some((event) => event.type === 'damage' && event.amount === 16));145});146147test('Veil of Bran wards an ally and dream snare roots and damages', () => {148 const battle = duel('aislinn', 'silencer', { column: 2, row: 8 }, { column: 2, row: 6 });149 const aislinn = give(battle, 'veil-of-bran');150 battle.receive({ type: 'playCard', handIndex: 0, target: aislinn.hex });151 assert.equal(aislinn.ward, 9);152 assert.ok(aislinn.wardRounds >= 1);153154 const snareBattle = duel('aislinn', 'silencer', { column: 2, row: 8 }, { column: 2, row: 6 });155 give(snareBattle, 'dream-snare');156 const silencer = enemyOf(snareBattle);157 snareBattle.receive({ type: 'playCard', handIndex: 0, target: silencer.hex });158 assert.equal(silencer.health, 81, '6 damage minus 2 armour');159 assert.equal(silencer.rooted, 1);160161 snareBattle.runEnemyTurn();162 assert.deepEqual(silencer.hex, { column: 2, row: 6 }, 'a rooted unit cannot advance');163 assert.equal(silencer.rooted, 0, 'root expires after the rooted turn');164});165166test('poison ticks at the start of the victim turn and ignores armour', () => {167 const battle = duel('finella', 'brute', { column: 4, row: 8 }, { column: 4, row: 7 });168 give(battle, 'venom-kiss');169 const brute = enemyOf(battle);170 const events = battle.receive({ type: 'playCard', handIndex: 0, target: brute.hex });171 assert.equal(brute.health, 140, '8 damage minus 4 armour, then a 6-point poison tick');172 assert.ok(173 events.some((event) => event.type === 'damage' && event.amount === 6 && event.source === 'poison'),174 );175 assert.equal(brute.poison, 6);176177 battle.runEnemyTurn();178 assert.equal(brute.health, 135, 'Finella retaliates for half her damage');179});180181test('Hunter’s Mark increases all damage taken while it lasts', () => {182 const battle = duel('atlanta', 'silencer', { column: 2, row: 8 }, { column: 2, row: 5 });183 give(battle, 'hunters-mark');184 const silencer = enemyOf(battle);185 battle.receive({ type: 'playCard', handIndex: 0, target: silencer.hex });186 assert.equal(silencer.marked, 6);187 battle.damageUnit(silencer, 10);188 assert.equal(silencer.health, 71, '10 - 2 armour + 6 mark');189});190191test('Step Between teleports without a path', () => {192 const battle = duel('finella', 'silencer', { column: 4, row: 8 }, { column: 4, row: 1 });193 const finella = give(battle, 'step-between');194 battle.receive({ type: 'playCard', handIndex: 0, target: { column: 4, row: 5 } });195 assert.deepEqual(finella.hex, { column: 4, row: 5 });196 assert.equal(finella.hand.length, 0);197});198199test('Piercing Shot hits every enemy on the line', () => {200 const battle = battleWith(201 [unitSpec('atlanta', 2, 8)],202 [unitSpec('silencer', 2, 6), unitSpec('silencer', 2, 5)],203 );204 give(battle, 'piercing-shot');205 battle.receive({ type: 'playCard', handIndex: 0, target: { column: 2, row: 5 } });206 for (const enemy of battle.livingUnits('torment')) {207 assert.equal(enemy.health, 71, '14 piercing damage ignores armour');208 }209});210211test('Volley splashes onto enemies beside the target', () => {212 const battle = battleWith(213 [unitSpec('aislinn', 2, 8)],214 [unitSpec('silencer', 2, 5), unitSpec('silencer', 3, 5)],215 );216 give(battle, 'lullaby');217 battle.receive({ type: 'playCard', handIndex: 0, target: { column: 2, row: 5 } });218 for (const enemy of battle.livingUnits('torment')) {219 assert.equal(enemy.health, 75, '12 damage minus 2 armour');220 }221});222223test("Widow's Due punishes wounded targets", () => {224 const battle = duel('finella', 'silencer', { column: 4, row: 8 }, { column: 4, row: 7 });225 give(battle, 'widows-due');226 const silencer = enemyOf(battle);227 silencer.health = 30;228 battle.receive({ type: 'playCard', handIndex: 0, target: silencer.hex });229 assert.equal(silencer.health, 2, '30 damage minus 2 armour');230231 const healthyBattle = duel('finella', 'silencer', { column: 4, row: 8 }, { column: 4, row: 7 });232 give(healthyBattle, 'widows-due');233 const healthy = enemyOf(healthyBattle);234 healthyBattle.receive({ type: 'playCard', handIndex: 0, target: healthy.hex });235 assert.equal(healthy.health, 73, '14 damage minus 2 armour');236});237238test('Blood for Blood heals its caster and wards them', () => {239 const battle = duel('finella', 'silencer', { column: 4, row: 8 }, { column: 4, row: 1 });240 const finella = give(battle, 'blood-for-blood');241 finella.health = 100;242 battle.receive({ type: 'playCard', handIndex: 0 });243 assert.equal(finella.health, 125);244 assert.equal(finella.ward, 5);245});246247test('Wind Tales grants movement to an ally at the start of their turn', () => {248 const battle = battleWith(249 [unitSpec('finella', 4, 8), unitSpec('aislinn', 2, 8)],250 [unitSpec('silencer', 4, 1)],251 );252 battle.receive({ type: 'endTurn' });253 assert.equal(current(battle).name, 'Aislinn');254 const finella = battle.units.find((unit) => unit.name === 'Finella');255 give(battle, 'wind-tales');256 battle.receive({ type: 'playCard', handIndex: 0, target: finella.hex });257 assert.equal(finella.haste, 2);258259 battle.runEnemyTurn();260 assert.equal(current(battle).name, 'Finella');261 assert.equal(finella.movementLeft, 6, '4 base movement plus 2 from the card');262});263264test('cards cannot be played without fervor or a legal target', () => {265 const battle = duel('aislinn', 'silencer', { column: 2, row: 8 }, { column: 2, row: 1 });266 const aislinn = give(battle, 'mist-lance');267 aislinn.fervor = 0;268 assert.throws(269 () => battle.receive({ type: 'playCard', handIndex: 0, target: { column: 2, row: 5 } }),270 BattleError,271 );272 aislinn.fervor = 6;273 assert.throws(274 () => battle.receive({ type: 'playCard', handIndex: 0, target: { column: 2, row: 5 } }),275 BattleError,276 'range 6 is outside Mist Lance',277 );278});279280test('the deck reshuffles its discard pile when empty', () => {281 const battle = duel('aislinn', 'silencer', { column: 2, row: 8 }, { column: 2, row: 1 });282 const aislinn = current(battle);283 aislinn.hand = [];284 aislinn.deck = [];285 aislinn.discard = ['mist-lance'];286 battle.drawCards(aislinn, 1);287 assert.deepEqual(aislinn.hand, ['mist-lance']);288 assert.equal(aislinn.deck.length, 0);289 assert.equal(aislinn.discard.length, 0);290});291292test('cardTargets only lists legal targets', () => {293 const battle = battleWith(294 [unitSpec('aislinn', 2, 8)],295 [unitSpec('silencer', 2, 5), unitSpec('silencer', 2, 1)],296 );297 const aislinn = give(battle, 'mist-lance');298 const targets = battle.cardTargets(0);299 assert.ok(targets.some((cell) => cell.column === 2 && cell.row === 5));300 assert.ok(!targets.some((cell) => cell.column === 2 && cell.row === 1));301 assert.ok(aislinn.fervor >= cardById('mist-lance').cost);302});303304305306test('victory is declared when the last enemy falls', () => {307 const battle = duel('finella', 'silencer', { column: 4, row: 8 }, { column: 4, row: 7 });308 const silencer = enemyOf(battle);309 silencer.health = 1;310 battle.receive({ type: 'attack', target: silencer.id });311 assert.equal(battle.outcome, 'victory');312 assert.equal(battle.current, null);313});314315test('defeat is declared when the last heroine falls', () => {316 const battle = duel('finella', 'silencer', { column: 4, row: 8 }, { column: 4, row: 7 });317 const finella = current(battle);318 battle.damageUnit(finella, 999);319 battle.checkOutcome();320 assert.equal(battle.outcome, 'defeat');321});322323function skipToEnemyTurn(battle) {324 for (let guard = 0; guard < 10 && !battle.needsEnemyTurn(); guard += 1) {325 battle.receive({ type: 'endTurn' });326 }327 assert.equal(battle.needsEnemyTurn(), true, 'the enemy should be acting');328}329330test('an enemy advances toward the nearest heroine and attacks in range', () => {331 const battle = duel('aislinn', 'brute', { column: 2, row: 8 }, { column: 2, row: 5 });332 battle.receive({ type: 'endTurn' });333 assert.equal(battle.needsEnemyTurn(), true);334 battle.runEnemyTurn();335 const brute = battle.units.find((unit) => unit.team === 'torment');336 const aislinn = battle.units.find((unit) => unit.team === 'allies');337 assert.equal(brute.hex.row, 7, 'two movement points carry the brute to the front row');338 assert.equal(hexDistance(brute.hex, aislinn.hex), 1);339 assert.equal(aislinn.health, 132, '20 damage minus 2 armour');340});341342test('enemies focus the wounded heroine they can reach', () => {343 const battle = battleWith(344 [unitSpec('aislinn', 2, 8), unitSpec('finella', 6, 8)],345 [unitSpec('silencer', 4, 6)],346 );347 const aislinn = battle.units.find((unit) => unit.name === 'Aislinn');348 const finella = battle.units.find((unit) => unit.name === 'Finella');349 aislinn.health = 20;350351 skipToEnemyTurn(battle);352 battle.runEnemyTurn();353354 assert.ok(aislinn.health < 20, 'the wounded heroine is the preferred target');355 assert.equal(finella.health, finella.maxHealth, 'the healthy heroine is ignored');356});357358test('ranged enemies back off to the far edge of their range', () => {359 const battle = duel('finella', 'spitebound', { column: 4, row: 8 }, { column: 4, row: 7 });360 const finella = battle.units.find((unit) => unit.name === 'Finella');361 const spitebound = battle.units.find((unit) => unit.team === 'torment');362363 skipToEnemyTurn(battle);364 battle.runEnemyTurn();365366 assert.equal(367 hexDistance(spitebound.hex, finella.hex),368 spitebound.range,369 'the archer retreats to the far edge of its range instead of staying in melee',370 );371 assert.ok(finella.health < finella.maxHealth, 'the archer still attacks after repositioning');372});373374test('enemies finish a heroine when one blow would break her', () => {375 const battle = battleWith(376 [unitSpec('aislinn', 4, 8), unitSpec('finella', 4, 6)],377 [unitSpec('brute', 4, 7)],378 );379 const aislinn = battle.units.find((unit) => unit.name === 'Aislinn');380 const finella = battle.units.find((unit) => unit.name === 'Finella');381 aislinn.health = 18; 382 finella.health = 17; 383384 skipToEnemyTurn(battle);385 battle.runEnemyTurn();386387 assert.equal(aislinn.health, 0, 'the killable heroine is finished');388 assert.equal(finella.health, 17, 'the blow is not wasted on a survivor');389});390391test('an enemy strikes from reach instead of chasing a distant wounded heroine', () => {392 const battle = battleWith(393 [unitSpec('aislinn', 4, 7), unitSpec('finella', 4, 1)],394 [unitSpec('silencer', 4, 6)],395 );396 const aislinn = battle.units.find((unit) => unit.name === 'Aislinn');397 const finella = battle.units.find((unit) => unit.name === 'Finella');398 finella.health = 20;399400 skipToEnemyTurn(battle);401 const silencer = battle.currentUnit();402 const position = { ...silencer.hex };403 battle.runEnemyTurn();404405 assert.deepEqual(silencer.hex, position, 'the enemy does not walk away from a free hit');406 assert.ok(aislinn.health < aislinn.maxHealth, 'the reachable heroine is attacked');407 assert.equal(finella.health, 20, 'the distant wounded heroine is ignored this turn');408});409410test('a ranged enemy holds the edge of its range instead of shuffling', () => {411 const battle = duel('finella', 'spitebound', { column: 4, row: 8 }, { column: 4, row: 5 });412 const spitebound = battle.units.find((unit) => unit.team === 'torment');413 const position = { ...spitebound.hex };414415 for (let turn = 0; turn < 3; turn += 1) {416 skipToEnemyTurn(battle);417 battle.runEnemyTurn();418 assert.deepEqual(spitebound.hex, position, 'a firing position at maximum range is kept');419 }420});421422test('a ranged enemy leaves melee reach without losing its target', () => {423 const battle = battleWith(424 [unitSpec('aislinn', 4, 9), unitSpec('finella', 5, 6)],425 [unitSpec('spitebound', 4, 6)],426 );427 const aislinn = battle.units.find((unit) => unit.name === 'Aislinn');428 const finella = battle.units.find((unit) => unit.name === 'Finella');429 const spitebound = battle.units.find((unit) => unit.team === 'torment');430431 skipToEnemyTurn(battle);432 battle.runEnemyTurn();433434 assert.equal(435 hexDistance(spitebound.hex, aislinn.hex),436 spitebound.range,437 'the archer stays at the far edge of its range',438 );439 assert.ok(hexDistance(spitebound.hex, finella.hex) > 1, 'and out of the assassin’s melee reach');440 assert.ok(aislinn.health < aislinn.maxHealth, 'the repositioned archer still fires');441});442443test('an enemy paths around a blocking unit instead of stalling', () => {444 const battle = battleWith(445 [unitSpec('aislinn', 4, 5)],446 [unitSpec('brute', 4, 8), unitSpec('brute', 4, 7)],447 );448 const aislinn = battle.units.find((unit) => unit.name === 'Aislinn');449 const acting = battle.unitAt({ column: 4, row: 8 });450 const blocker = battle.unitAt({ column: 4, row: 7 });451452 skipToEnemyTurn(battle);453 assert.equal(battle.currentUnit().id, acting.id, 'the unblocked brute acts first');454 battle.runEnemyTurn();455456 assert.equal(hexDistance(acting.hex, aislinn.hex), 1, 'the brute routes around its ally');457 assert.deepEqual(blocker.hex, { column: 4, row: 7 }, 'the blocker stays put');458 assert.ok(aislinn.health < aislinn.maxHealth, 'the detour still ends in an attack');459});460461462463464function winBattle(session) {465 for (const unit of session.battle.units) {466 if (unit.team === 'torment') unit.health = 0;467 }468 session.battle.checkOutcome();469 session.settle();470}471472test('a new game starts in the village with the chosen heroine and her starting cards', () => {473 const session = new Session(42);474 assert.equal(session.screen, 'title');475 session.receive({ type: 'newGame', starter: 'finella' });476 assert.equal(session.screen, 'village');477 assert.deepEqual(session.profile.party, ['finella']);478 assert.deepEqual(session.profile.cards.finella, STARTING_CARDS.finella);479 assert.equal(session.profile.honor, 0);480 assert.equal(session.profile.gold, 0);481});482483test('starting cards are a strict subset of a heroine’s deck', () => {484 for (const id of HEROINE_IDS) {485 const deck = heroineDeck(id);486 assert.ok(STARTING_CARDS[id].length < deck.length, `${id} starts with fewer cards`);487 for (const cardId of STARTING_CARDS[id]) assert.ok(deck.includes(cardId));488 }489});490491test('battles fight with the owned cards, and kills plus victory pay out', () => {492 const session = new Session(42);493 session.receive({ type: 'newGame', starter: 'aislinn' });494 session.start(0);495 assert.equal(session.screen, 'battle');496 assert.equal(session.battle.units.filter((unit) => unit.team === 'allies').length, 1);497 const hero = session.battle.units.find((unit) => unit.team === 'allies');498 assert.deepEqual(499 [...hero.hand, ...hero.deck].sort(),500 [...STARTING_CARDS.aislinn].sort(),501 );502503 winBattle(session);504 const kills = ENCOUNTERS[0].enemies.length;505 assert.equal(session.screen, 'result');506 assert.equal(session.outcome, 'victory');507 assert.equal(session.rewards.kills, kills);508 assert.equal(session.profile.honor, kills * HONOR_PER_KILL);509 assert.equal(session.profile.gold, kills * GOLD_PER_KILL + GOLD_PER_VICTORY);510});511512test('kills pay honor even when the battle is lost', () => {513 const session = new Session(7);514 session.receive({ type: 'newGame', starter: 'atlanta' });515 session.start(0);516 const enemy = session.battle.units.find((unit) => unit.team === 'torment');517 enemy.health = 0;518 session.battle.finish('defeat');519 session.settle();520 assert.equal(session.outcome, 'defeat');521 assert.equal(session.profile.honor, HONOR_PER_KILL);522 assert.equal(session.profile.gold, GOLD_PER_KILL, 'a defeat pays no victory gold');523});524525test('retry rebuilds the same encounter with the same party', () => {526 const session = new Session(7);527 session.receive({ type: 'newGame', starter: 'aislinn' });528 session.start(0);529 const firstSerial = session.serial;530 session.battle.finish('defeat');531 session.settle();532 session.receive({ type: 'retry' });533 assert.equal(session.screen, 'battle');534 assert.equal(session.encounterIndex, 0);535 assert.equal(session.serial, firstSerial + 1);536 assert.equal(session.battle.units.filter((unit) => unit.team === 'allies').length, 1);537});538539test('recruiting spends honor and the new heroine joins with her starting cards', () => {540 const session = new Session(5);541 session.receive({ type: 'newGame', starter: 'aislinn' });542 assert.throws(() => session.receive({ type: 'recruit', heroine: 'finella' }), /honor/);543544 session.profile.honor = RECRUIT_HONOR.finella;545 session.receive({ type: 'recruit', heroine: 'finella' });546 assert.equal(session.profile.honor, 0);547 assert.deepEqual(session.profile.party, ['aislinn', 'finella']);548 assert.deepEqual(session.profile.cards.finella, STARTING_CARDS.finella);549 assert.throws(() => session.receive({ type: 'recruit', heroine: 'finella' }), /already/);550551 session.start(0);552 assert.equal(session.battle.units.filter((unit) => unit.team === 'allies').length, 2);553});554555test('the market sells only unowned cards of recruited heroines, for gold', () => {556 const session = new Session(5);557 session.receive({ type: 'newGame', starter: 'aislinn' });558 assert.throws(559 () => session.receive({ type: 'buy', card: 'widows-due' }),560 /Recruit finella/,561 );562563 session.profile.gold = 1000;564 assert.throws(565 () => session.receive({ type: 'buy', card: 'mist-lance' }),566 /already owned/,567 );568569 session.receive({ type: 'buy', card: 'wind-tales' });570 assert.ok(session.profile.cards.aislinn.includes('wind-tales'));571 assert.equal(session.profile.gold, 1000 - cardPrice(cardById('wind-tales')));572573 session.profile.gold = 0;574 assert.throws(() => session.receive({ type: 'buy', card: 'lullaby' }), /costs/);575});576577test('a battle saved mid-fight resumes exactly where it stopped', () => {578 const session = new Session(21);579 session.receive({ type: 'newGame', starter: 'atlanta' });580 session.start(0);581 session.receive({ type: 'battle', command: { type: 'endTurn' } });582 while (session.needsEnemyTurn()) session.enemyAct();583584 const saved = JSON.parse(JSON.stringify(session.serialize()));585 const resumed = new Session(1);586 resumed.load(saved);587 assert.equal(resumed.screen, 'battle');588 assert.deepEqual(resumed.battle.snapshot(), session.battle.snapshot());589590 591 const playOn = (target) => {592 const events = [];593 for (let step = 0; step < 60 && !target.battle.outcome; step += 1) {594 if (target.needsEnemyTurn()) {595 events.push(...target.enemyAct());596 } else {597 target.receive({ type: 'battle', command: { type: 'endTurn' } });598 }599 }600 return events.map((event) => event.type).join(',');601 };602 assert.equal(playOn(resumed), playOn(session));603});604605test('only the village and a battle can be saved', () => {606 const session = new Session(3);607 assert.equal(session.canSave(), false, 'no save on the title screen');608 session.receive({ type: 'newGame', starter: 'finella' });609 assert.equal(session.canSave(), true);610 session.start(0);611 winBattle(session);612 assert.equal(session.canSave(), false, 'no save on the result screen');613});614615test('loading rejects saves from another version and damaged battles', () => {616 const session = new Session(3);617 session.receive({ type: 'newGame', starter: 'finella' });618 const state = session.serialize();619 assert.throws(() => new Session().load({ ...state, version: 99 }), /different version/);620 assert.throws(621 () => new Session().load({ ...state, screen: 'battle', battle: null }),622 /damaged/,623 );624 assert.throws(625 () => new Session().load({ ...state, profile: { ...state.profile, party: ['nobody'] } }),626 /damaged/,627 );628});629630test('battle snapshots expose the active hand and reachable hexes', () => {631 const session = new Session(9);632 session.receive({ type: 'newGame', starter: 'finella' });633 session.start(0);634 const snapshot = session.snapshot();635 assert.equal(snapshot.screen, 'battle');636 assert.equal(snapshot.battle.hand.length, STARTING_CARDS.finella.length, 'the starting cards fill the hand');637 assert.ok(snapshot.battle.reachable.length > 0);638 assert.equal(snapshot.battle.fervor, 4, 'starts at 2 and gains 2 on the first turn');639 assert.ok(snapshot.battle.log.length > 0);640});641642643644test('the encounter builds a legal battle for every heroine who can take the field', () => {645 for (const heroine of HEROINE_IDS) {646 const battle = new Battle(battleSpec(0, [heroine]), 11);647 assert.equal(battle.encounter, 0);648 assert.equal(battle.livingUnits('allies').length, 1);649 assert.ok(battle.livingUnits('torment').length >= 2);650 assert.ok(battle.snapshot().turnOrder.length >= 3);651 }652 const full = new Battle(battleSpec(0), 11);653 assert.equal(full.livingUnits('allies').length, 3);654});655656function playSimpleTurn(battle) {657 const unit = battle.currentUnit();658 const targets = battle.attackTargets(unit);659 if (targets.length > 0) {660 battle.receive({ type: 'attack', target: targets[0].id });661 return;662 }663 const enemies = battle.livingUnits('torment');664 const nearest = enemies.reduce((best, enemy) =>665 hexDistance(unit.hex, enemy.hex) < hexDistance(unit.hex, best.hex) ? enemy : best,666 );667 const reachable = battle.reachable(unit);668 let destination = null;669 let bestDistance = hexDistance(unit.hex, nearest.hex);670 for (const key of reachable.keys()) {671 const cell = fromKey(key);672 const gap = hexDistance(cell, nearest.hex);673 if (gap < bestDistance) {674 bestDistance = gap;675 destination = cell;676 }677 }678 if (destination) battle.receive({ type: 'move', to: destination });679 else battle.receive({ type: 'endTurn' });680}681682test('a whole encounter can be played to a result without stalling', () => {683 const battle = new Battle(battleSpec(0), 3);684 for (let step = 0; step < 400 && !battle.outcome; step += 1) {685 if (battle.needsEnemyTurn()) {686 battle.runEnemyTurn();687 continue;688 }689 playSimpleTurn(battle);690 }691 assert.ok(battle.outcome, 'the battle should settle within the round limit');692});693694test('enemy turns always take an available attack across many seeds', () => {695 for (let encounter = 0; encounter < ENCOUNTERS.length; encounter += 1) {696 for (let seed = 1; seed <= 12; seed += 1) {697 const battle = new Battle(battleSpec(encounter), seed);698 let enemyTurns = 0;699 for (let step = 0; step < 600 && !battle.outcome; step += 1) {700 if (!battle.needsEnemyTurn()) {701 playSimpleTurn(battle);702 continue;703 }704 const unit = battle.currentUnit();705 const couldAttack = battle.attackTargets(unit).length > 0;706 const before = { ...unit.hex };707 const events = battle.runEnemyTurn();708 enemyTurns += 1;709 const attacked = events.some((event) => event.type === 'attack');710 const moved = events.some((event) => event.type === 'move');711 if (couldAttack) {712 assert.equal(713 attacked,714 true,715 `${unit.name} passed up an attack (encounter ${encounter}, seed ${seed})`,716 );717 }718 if (moved) {719 assert.ok(720 hexDistance(before, unit.hex) > 0,721 `${unit.name} spent a turn moving in place (encounter ${encounter}, seed ${seed})`,722 );723 }724 }725 assert.ok(726 battle.outcome,727 `encounter ${encounter} seed ${seed} did not settle`,728 );729 assert.ok(enemyTurns > 0, 'the Torment should get a turn');730 }731 }732});733734test('simultaneous elimination is a draw, not a victory', () => {735 const battle = duel('finella', 'silencer', { column: 4, row: 8 }, { column: 4, row: 7 });736 battle.damageUnit(current(battle), 999);737 battle.damageUnit(enemyOf(battle), 999);738 battle.checkOutcome();739 assert.equal(battle.outcome, 'draw');740});