health items

This commit is contained in:
Forrest 2026-09-29 12:07:31 -04:00
parent cb3513bd99
commit 62b2b9feca
17 changed files with 611 additions and 141 deletions

View file

@ -1,7 +1,7 @@
/** Scoring helpers the greedy bot shares: board values, combat odds and what a combat is worth. */
import { isStart, levelFor, type LocId } from '../map.ts';
import { winChance } from '../odds.ts';
import { bugImmune, coresOf, fighterOf, hardwareActive, sources } from '../query.ts';
import { bugImmune, coresOf, fighterOf, hardwareActive, healthLeft, sources } from '../query.ts';
import { scriptOf } from '../scripts.ts';
import { avatar, defOf, defendersAt, fightersOf, hardwareOf, refKey } from '../state.ts';
import type { AvatarRef, GameState, PlayerId } from '../types.ts';
@ -69,6 +69,57 @@ function beats(fa: number, ka: number, fb: number, kb: number, tie: number): num
return win + draw * tie;
}
/** Probability of each margin (a − b) where a = fa + ka d6 and b = fb + kb d6. */
export function marginDist(fa: number, ka: number, fb: number, kb: number): Map<number, number> {
const da = diceSum(ka);
const db = diceSum(kb);
const out = new Map<number, number>();
da.forEach((pa, a) => {
if (!pa) return;
db.forEach((pb, b) => {
if (!pb) return;
const m = fa + a - fb - b;
out.set(m, (out.get(m) ?? 0) + pa * pb);
});
});
return out;
}
/** Averages margin distributions, for a combat whose bonus is decided by a coin flip (Race Condition). */
function mixDist(...dists: Map<number, number>[]): Map<number, number> {
const out = new Map<number, number>();
for (const d of dists) for (const [m, p] of d) out.set(m, (out.get(m) ?? 0) + p / dists.length);
return out;
}
/** The dice each side of the current combat still has to roll (or has rolled), for the odds. */
function combatDice(v: GameState, reroll?: { ref: AvatarRef; k: number }): { fa: number; ka: number; fd: number; kd: number } {
const c = v.combat!;
let fa = 0;
let ka = 0;
let fd = 0;
let kd = 0;
for (const r of fightersOf(c)) {
const want = coresOf(v, fighterOf(v, r));
let dice = c.rolled ? [...(c.dice[refKey(r)] ?? [])].sort((a, b) => a - b) : [];
if (dice.length > want) dice = dice.slice(0, want);
let extra = want - dice.length;
if (reroll && refKey(reroll.ref) === refKey(r)) {
extra += dice.filter((d) => d <= reroll.k).length;
dice = dice.filter((d) => d > reroll.k);
}
const fixed = dice.reduce((a, b) => a + b, 0);
if (r === c.attacker) {
fa += fixed;
ka += extra;
} else {
fd += fixed;
kd += extra;
}
}
return { fa, ka, fd, kd };
}
/**
* Chance the attacker wins the current combat. Before the roll that's the Core odds. After it,
* the dice on the table count: Core changes add dice or drop the highest ones, and `reroll` lets a
@ -85,36 +136,22 @@ export function combatOdds(v: GameState, reroll?: { ref: AvatarRef; k: number })
}
const tie = winChance(atk, def);
if (!c.rolled) return tie;
let fa = 0;
let ka = 0;
let fd = 0;
let kd = 0;
for (const r of fightersOf(c)) {
const want = coresOf(v, fighterOf(v, r));
let dice = [...(c.dice[refKey(r)] ?? [])].sort((a, b) => a - b);
if (dice.length > want) dice = dice.slice(0, want);
let extra = want - dice.length;
if (reroll && refKey(reroll.ref) === refKey(r)) {
extra += dice.filter((d) => d <= reroll.k).length;
dice = dice.filter((d) => d > reroll.k);
}
const fixed = dice.reduce((a, b) => a + b, 0);
if (r === c.attacker) {
fa += fixed;
ka += extra;
} else {
fd += fixed;
kd += extra;
}
}
const { fa, ka, fd, kd } = combatDice(v, reroll);
return beats(fa, ka, fd, kd, tie);
}
/** Health rule: the margin distribution of the current combat, given the dice on the table. */
export function combatDist(v: GameState, reroll?: { ref: AvatarRef; k: number }): Map<number, number> {
const { fa, ka, fd, kd } = combatDice(v, reroll);
return marginDist(fa, ka, fd, kd);
}
/**
* Chance an attack would win if declared now, counting what the target's Programs do when a
* combat starts there (Memory Leak, Visual Artifact, Race Condition, Memory Parasite).
* Cores each side would have if `ref` attacked `target` from `origin` now, counting what the
* target's Programs do when a combat starts there (Memory Leak, Visual Artifact, Memory Parasite),
* and whether Race Condition may add +2 to the defence.
*/
export function attackOdds(v: GameState, ref: AvatarRef, origin: LocId, target: LocId, bonus = 0): number {
function attackCores(v: GameState, ref: AvatarRef, origin: LocId, target: LocId, bonus: number): { atk: number; def: number; race: boolean } {
let atk = coresOf(v, { ref, role: 'attack', at: origin, loc: target, combat: null }) + bonus;
const defs = defendersAt(v, target);
let def = defs.reduce((t, d) => t + coresOf(v, { ref: d, role: 'defend', at: target, loc: target, combat: null }), 0);
@ -130,11 +167,69 @@ export function attackOdds(v: GameState, ref: AvatarRef, origin: LocId, target:
if (bonuses.length) atk -= Math.min(...bonuses);
}
}
atk = Math.max(1, atk);
def = Math.max(1, def);
return { atk: Math.max(1, atk), def: Math.max(1, def), race };
}
/** Chance an attack would win the roll if declared now. */
export function attackOdds(v: GameState, ref: AvatarRef, origin: LocId, target: LocId, bonus = 0): number {
const { atk, def, race } = attackCores(v, ref, origin, target, bonus);
return race ? (winChance(atk, def) + winChance(atk, def + 2)) / 2 : winChance(atk, def);
}
/** Health rule: margin distribution of an attack declared now. */
export function attackDist(v: GameState, ref: AvatarRef, origin: LocId, target: LocId, bonus = 0): Map<number, number> {
const { atk, def, race } = attackCores(v, ref, origin, target, bonus);
const plain = marginDist(0, atk, 0, def);
return race ? mixDist(plain, marginDist(0, atk, 0, def + 2)) : plain;
}
/**
* Health rule: expected points for `me` from a combat with the given margin distribution.
* Destroying every defender wins the location and their stakes. Damage short of that is worth a
* share of those stakes plus half the location, since the defender can still recall and heal.
* Damage to the attacker is worth the same share of its own stake.
*/
export function damageValue(
v: GameState,
me: PlayerId,
attacker: AvatarRef,
defenders: AvatarRef[],
dist: Map<number, number>,
locValue: number,
): number {
const sumLeft = Math.max(1, defenders.reduce((t, d) => t + healthLeft(v, d), 0));
const stakeD = defenders.reduce((t, d) => t + avatarStake(v, d), 0);
const stakeA = avatarStake(v, attacker);
const leftA = Math.max(1, healthLeft(v, attacker));
let total = 0;
for (const [m, p] of dist) {
if (m > 0) total += p * (m >= sumLeft ? locValue + stakeD : (m * (stakeD + locValue / 2)) / sumLeft);
else if (m < 0) total -= p * (-m >= leftA ? stakeA : (-m * stakeA) / leftA);
}
return attacker.player === me ? total : -total;
}
/**
* Points for the attacking player from declaring an attack now: under the health rule the expected
* damage value, otherwise the odds of taking the location against losing the Avatar.
*/
export function attackValue(v: GameState, ref: AvatarRef, origin: LocId, target: LocId, locValue: number, bonus = 0): number {
if (!v.rules.health.on) {
const chance = attackOdds(v, ref, origin, target, bonus);
return chance * locValue - (1 - chance) * avatarStake(v, ref);
}
return damageValue(v, ref.player, ref, defendersAt(v, target), attackDist(v, ref, origin, target, bonus), locValue);
}
/** Chance `target` falls to this attack: the win odds, or under the health rule the odds of destroying every defender. */
export function fallChance(v: GameState, ref: AvatarRef, origin: LocId, target: LocId, bonus = 0): number {
if (!v.rules.health.on) return attackOdds(v, ref, origin, target, bonus);
const need = defendersAt(v, target).reduce((t, d) => t + healthLeft(v, d), 0);
let p = 0;
for (const [m, pr] of attackDist(v, ref, origin, target, bonus)) if (m >= need) p += pr;
return p;
}
/** Rough Cores a Hardware card adds in combat. */
export function hardwareCores(v: GameState, hw: number): number {
const name = v.cards[hw].name;
@ -155,8 +250,11 @@ export function stakes(v: GameState, me: PlayerId): { win: number; lose: number
: { win: atk / 2, lose: -(loc + def) };
}
/** Expected points for `me` from the current combat, or from how it ended. */
export function combatValue(v: GameState, me: PlayerId): number {
/**
* Expected points for `me` from the current combat, or from how it ended. `reroll` values a Bit
* Flip of one fighter's dice showing k or less.
*/
export function combatValue(v: GameState, me: PlayerId, reroll?: { ref: AvatarRef; k: number }): number {
const c = v.combat;
if (!c) return 0;
const iAttack = c.attacker.player === me;
@ -166,8 +264,11 @@ export function combatValue(v: GameState, me: PlayerId): number {
if (!taken) return 0;
return iAttack ? locationValue(v, me, c.loc) : -locationValue(v, c.attacker.player, c.loc);
}
if (v.rules.health.on) {
return damageValue(v, me, c.attacker, c.defenders, combatDist(v, reroll), locationValue(v, c.attacker.player, c.loc));
}
const s = stakes(v, me);
const pAtk = combatOdds(v);
const pAtk = combatOdds(v, reroll);
const p = iAttack ? pAtk : 1 - pAtk;
return p * s.win + (1 - p) * s.lose;
}

View file

@ -13,7 +13,7 @@ import {
recruitSlots,
} from '../engine.ts';
import { GRID, LINES_AT, LOCATIONS, otherEnd, type LocId } from '../map.ts';
import { avatarRoom, coresOf, hardwareActive, hasRoom, portsFree, programSlots, sources } from '../query.ts';
import { avatarRoom, coresOf, hardwareActive, hasRoom, healthLeft, healthOf, portsFree, programSlots, sources } from '../query.ts';
import { scriptOf } from '../scripts.ts';
import {
avatar,
@ -36,14 +36,13 @@ import {
CARD_POINTS,
RAM_POINTS,
attackOdds,
avatarStake,
attackValue,
cardName,
combatOdds,
combatValue,
fallChance,
hardwareCores,
locationValue,
printedRam,
stakes,
unlocksAt,
} from './eval.ts';
@ -279,7 +278,7 @@ function planTurn(v: GameState, me: PlayerId, params: GreedyParams): TurnPlan {
if (holder !== undefined && holder !== slot) continue;
const chance = attackOdds(v, ref, from, to);
if (chance < params.minWinChance) continue;
const score = chance * value - (1 - chance) * avatarStake(v, ref) - clearCost * RAM_POINTS;
const score = attackValue(v, ref, from, to, value) - clearCost * RAM_POINTS;
options.push({ kind: 'attack', slot, to, origin: from, clear, score });
}
}
@ -347,8 +346,22 @@ function planTurn(v: GameState, me: PlayerId, params: GreedyParams): TurnPlan {
}
}
}
// Everyone else guards the most threatened free location.
const busy = new Set(final.map((o) => o.slot));
// Health rule: a badly hurt Avatar with nothing to do goes back to its slot to heal.
if (v.rules.health.on && v.rules.health.recall) {
for (const { slot } of ready) {
const cur = pos.get(slot) ?? null;
if (busy.has(slot) || cur === null || slot > 4) continue;
const ref = { player: me, slot };
if (healthLeft(v, ref) > Math.max(2, Math.ceil(healthOf(v, ref) * 0.3))) continue;
if (busy.has(slot + 4)) continue; // recalling would remove its copy, which has a job
busy.add(slot);
occupied.delete(cur);
pos.set(slot, null);
deploy.push({ type: 'recall', slot });
}
}
// Everyone else guards the most threatened free location.
for (const { slot } of ready) {
if (busy.has(slot)) continue;
const cur = pos.get(slot) ?? null;
@ -541,6 +554,7 @@ function clearTheWay(v: GameState, me: PlayerId, plan: TurnPlan | null): Action[
for (const a of plan.attacks) {
if (a.type !== 'attack') continue;
const ref = { player: me, slot: a.slot };
if (avatar(v, ref).at === null) continue; // the planned attacker left play (a copy removed by a recall)
const origin = [...plan.deploy].reverse().find((d) => d.type === 'place' && d.slot === a.slot);
const from = origin?.type === 'place' ? origin.to : avatar(v, ref).at;
if (!from) continue;
@ -580,8 +594,10 @@ function preAttackPlays(v: GameState, me: PlayerId, plan: TurnPlan | null): Acti
if (threatened(v, me).includes(av.at!) && defendersAt(v, av.at!).length < 2) continue;
if (v.declarations.some((d) => d.to === t)) continue;
const value = locationValue(v, me, t);
const chance = defendersAt(v, t).length ? attackOdds(v, ref, av.at!, t, 1 + executionPower(v, me, a.from)) : 1;
const score = chance * value - (1 - chance) * avatarStake(v, ref) - 5 * RAM_POINTS - CARD_POINTS;
const bonus = 1 + executionPower(v, me, a.from);
const defended = defendersAt(v, t).length > 0;
const chance = defended ? attackOdds(v, ref, av.at!, t, bonus) : 1;
const score = (defended ? attackValue(v, ref, av.at!, t, value, bonus) : value) - 5 * RAM_POINTS - CARD_POINTS;
if (chance >= 0.6 && score > 0 && (!best || score > best.score)) best = { a, score };
}
if (best) out.push(best.a);
@ -750,10 +766,7 @@ function combatTrick(v: GameState, me: PlayerId): Action | null {
if (!touchesCombat(v, a)) continue;
if (a.type === 'activate' && a.name === 'Broken Bits') {
const ref = refsInPlay(v, me).find((r) => avatar(v, r).card === a.card && !isCopy(r))!;
const pAtk = combatOdds(v, { ref, k: a.args.k! });
const s = stakes(v, me);
const p = c.attacker.player === me ? pAtk : 1 - pAtk;
consider(a, p * s.win + (1 - p) * s.lose);
consider(a, combatValue(v, me, { ref, k: a.args.k! }));
continue;
}
const after = simulate(v, me, a);
@ -769,7 +782,7 @@ function stopDeclaration(v: GameState, me: PlayerId): Action | null {
const at = avatar(v, d.ref).at;
if (at === null) return null;
const defended = defendersAt(v, d.to).length > 0;
const risk = defended ? attackOdds(v, d.ref, d.from, d.to) : 1;
const risk = defended ? fallChance(v, d.ref, d.from, d.to) : 1;
const stake = risk * locationValue(v, d.ref.player, d.to);
// Root the Avatar that declared, so it can't move.
const flood = findPlay(v, me, 'Execute: Packet Flood', (a) => (a.args.to ?? a.target) === at);

View file

@ -10,6 +10,8 @@ export interface CardDef {
/** Printed RAM: play cost and salvage value. Avatars and Servers print none. */
ram: number;
cores: number;
/** Avatar Health: the damage that destroys it (health rule). 0 when not printed. */
health: number;
/** Expansion Slots (Hardware ports). */
slots: number;
/** V / B / G / P, when printed. */
@ -51,6 +53,7 @@ export function loadCards(path = DEFAULT_CARDS_CSV): CardPool {
kind,
ram: num(row['RAM']),
cores: num(row['Cores']),
health: num(row['Health']),
slots: num(row['Expansion Slots']),
type: row['Type'],
text: row['Description'],

View file

@ -39,7 +39,9 @@ const USAGE = `Files TCG simulator
buyAvatars.on=true (buy Avatars 2-4 instead of unlocking; buyAvatars.prices=8,12,16),
copies.waitATurn=true, copies.needAvatar2=true, copies.allowed=false,
commands.on=false (whole turns instead of rounds of commands),
commands.perPlayer=3, commands.leads=F|FS|FFSS|thue, commands.snake=false
commands.perPlayer=3, commands.leads=F|FS|FFSS|thue, commands.snake=false,
health.on=false (one roll decides a combat, as before v0.9),
health.override=8 (every Avatar has this Health), health.recall=false
--log play one game and print the play-by-play
--check check rule invariants after every action (slow)
--json FILE also write the summary and every game's result as JSON

View file

@ -14,6 +14,7 @@ import {
defeat,
drawNow,
drawTask,
recallAvatar,
resolveDeclaration,
retireAvatar,
} from './flow.ts';
@ -154,6 +155,7 @@ function newAvatar(card: number, faceUp: boolean, copyOf: number | null): Avatar
faceUp,
at: null,
hardware: [],
damage: 0,
placed: false,
advanced: false,
attacks: 0,
@ -561,6 +563,7 @@ export function legalActions(s: GameState): Action[] {
if (av.at !== null && !canAct(s, ref)) return;
if (placementOpen && !av.placed && !waitsForRound(s, av)) {
for (const to of LOCATIONS) if (to !== av.at && hasRoom(s, p, to)) out.push({ type: 'place', slot: i + 1, to });
if (s.rules.health.on && s.rules.health.recall && av.at !== null && !isCopy(ref)) out.push({ type: 'recall', slot: i + 1 });
}
if (av.at !== null && !freshCopy(s, ref) && !commandSpent(s)) for (const to of targets) out.push({ type: 'advance', slot: i + 1, to });
});
@ -651,6 +654,8 @@ export function actionKey(a: Action): string {
case 'advance':
case 'attack':
return `${a.type}:${a.slot}:${a.to}`;
case 'recall':
return `recall:${a.slot}`;
case 'clearFirewall':
return `clear:${a.line}`;
case 'firewall':
@ -761,6 +766,9 @@ export function applyAction(s: GameState, a: Action, legal: Action[] = legalActi
av.placed = true;
break;
}
case 'recall':
recallAvatar(s, ref(a.slot));
break;
case 'advance':
case 'attack': {
const r = ref(a.slot);

View file

@ -5,7 +5,7 @@
*/
import { isStart, levelFor, type LocId } from './map.ts';
import { scriptOf } from './scripts.ts';
import { coresOf, emit, fighterOf, hardwareActive, sideCores } from './query.ts';
import { coresOf, emit, fighterOf, hardwareActive, healthLeft, healthOf, sideCores } from './query.ts';
import {
adjacent,
avatar,
@ -68,6 +68,7 @@ function clearStatus(av: AvatarState): void {
av.mods = [];
av.disabledUntil = 0;
av.rootedUntil = 0;
av.damage = 0;
}
/** A copy leaves play. It has no Hardware of its own. */
@ -115,9 +116,27 @@ export function knockOut(s: GameState, ref: AvatarRef, loc: LocId, role: 'attack
say(s, `${avatarName(s, ref)} returns to its slot.`);
removeCopy(s, copyOf(ref));
}
stat(s, 'avatarsDestroyed', ref.player);
emit(s, 'onDefeat', { ref, loc, role });
}
/**
* Health rule: an Avatar returns to its slot by its owner's choice, as its placement for the
* round. It heals fully and keeps its Hardware; like a defeat, its counters and effects come off
* (Persistent Infection's stay) and its copy leaves play.
*/
export function recallAvatar(s: GameState, ref: AvatarRef): void {
const av = avatar(s, ref);
if (av.at === null) return;
const healed = av.damage;
say(s, `${playerName(ref.player)} recalls ${avatarName(s, ref)} from ${av.at} to its slot${healed ? `, healing ${healed} damage` : ''}.`);
clearStatus(av);
av.at = null;
av.placed = true;
removeCopy(s, copyOf(ref));
stat(s, 'recalls', ref.player);
}
/** Places a copy of `original` on `to`. */
export function createCopy(s: GameState, original: AvatarRef, to: LocId): void {
const ref = copyOf(original);
@ -127,6 +146,7 @@ export function createCopy(s: GameState, original: AvatarRef, to: LocId): void {
faceUp: true,
at: to,
hardware: [],
damage: 0,
placed: false,
advanced: false,
attacks: 0,
@ -201,17 +221,83 @@ function diceText(s: GameState, c: Combat): string {
return `${one(c.attacker)}=${t.atk} vs ${c.defenders.map(one).join(' + ')}=${t.def}`;
}
/** Rolls every fighter's dice, rerolling all of them on a tie. */
/** Rolls every fighter's dice, rerolling all of them on a tie (under the health rule a tie stands). */
function rollAll(s: GameState, c: Combat): void {
do {
for (const r of fightersOf(c)) c.dice[refKey(r)] = roll(s, coresOf(s, fighterOf(s, r)));
const t = sideTotals(c);
if (t.atk !== t.def) break;
if (t.atk !== t.def || s.rules.health.on) break;
c.ties++;
} while (true);
c.rolled = true;
}
// ---------------------------------------------------------------------------------------------
// Damage (health rule)
/** Health text for the combat log, e.g. "7/10 Health". */
export const healthText = (s: GameState, r: AvatarRef): string => `${healthLeft(s, r)}/${healthOf(s, r)} Health`;
/** Deals `n` damage to an Avatar. Returns true if that destroys it (its damage reaches its Health). */
export function damageAvatar(s: GameState, ref: AvatarRef, n: number): boolean {
const av = avatar(s, ref);
if (av.at === null || n <= 0) return false;
av.damage += n;
const dead = av.damage >= healthOf(s, ref);
say(s, `${avatarName(s, ref)} takes ${n} damage${dead ? ' and is destroyed' : ` (${healthText(s, ref)})`}.`);
return dead;
}
/**
* The attacker splits `n` damage among the defenders. The engine picks the split that destroys the
* most defenders, weakest first, and puts what's left on the weakest survivor. Returns the
* destroyed defenders.
*/
function allocateDamage(s: GameState, defenders: AvatarRef[], n: number): AvatarRef[] {
const order = [...defenders].sort((a, b) => healthLeft(s, a) - healthLeft(s, b));
const destroyed: AvatarRef[] = [];
for (const [i, d] of order.entries()) {
if (n <= 0) break;
const left = healthLeft(s, d);
const hit = n >= left ? left : i === order.length - 1 ? n : 0;
if (hit === 0) {
// Can't destroy this one: dump the rest on the weakest.
damageAvatar(s, order[0], n);
break;
}
n -= hit;
if (damageAvatar(s, d, hit)) destroyed.push(d);
}
return destroyed;
}
/** Health rule: the loser of the roll takes the difference as damage; destroyed Avatars are defeated. */
function resolveDamage(s: GameState, c: Combat, t: { atk: number; def: number }): void {
if (t.atk === t.def) {
c.ties++;
stat(s, 'combatsTied', c.attacker.player);
say(s, `Tie, ${t.atk} to ${t.def}: a stalemate. Nobody takes damage.`);
return;
}
const margin = Math.abs(t.atk - t.def);
const attackerWins = t.atk > t.def;
const defender = s.locations[c.loc].owner!;
const winner = attackerWins ? c.attacker.player : defender;
say(s, `${playerName(winner)} wins the roll, ${t.atk} to ${t.def}: ${margin} damage.`);
stat(s, 'damageDealt', winner, margin);
if (attackerWins) {
stat(s, 'attacksWon', c.attacker.player);
const destroyed = allocateDamage(s, c.defenders, margin);
const tasks: Task[] = destroyed.map((ref): Task => ({ t: 'defeat', ref, loc: c.loc, role: 'defend' }));
if (destroyed.length === c.defenders.length) {
tasks.push({ t: 'capture', ref: c.attacker, loc: c.loc, stage: 'hooks', how: 'capturesInCombat' });
} else say(s, `${c.loc} holds.`);
pushTasks(s, ...tasks);
} else if (damageAvatar(s, c.attacker, margin)) {
pushTasks(s, { t: 'defeat', ref: c.attacker, loc: c.loc, role: 'attack' });
}
}
/**
* Cores that change after the roll change the dice: each Core gained rolls one more die, and each
* Core lost removes that Avatar's highest die.
@ -288,8 +374,9 @@ export function combatStage(s: GameState, stage: 'start' | 'roll' | 'result' | '
if (stage === 'start') {
stat(s, 'attacks', c.attacker.player);
const { atk, def } = sideCores(s);
const defs = c.defenders.map((d) => avatarName(s, d)).join(' and ');
say(s, `Combat at ${c.loc}: ${avatarName(s, c.attacker)} (${atk} Cores, from ${c.origin}) vs ${defs} (${def} Cores).`);
const hp = (r: AvatarRef) => (s.rules.health.on ? `, ${healthText(s, r)}` : '');
const defs = c.defenders.map((d) => `${avatarName(s, d)}${hp(d)}`).join(' and ');
say(s, `Combat at ${c.loc}: ${avatarName(s, c.attacker)} (${atk} Cores, from ${c.origin}${hp(c.attacker)}) vs ${defs} (${def} Cores).`);
emit(s, 'onCombatStart', null);
return;
}
@ -310,6 +397,7 @@ export function combatStage(s: GameState, stage: 'start' | 'roll' | 'result' | '
}
// result
const t = combatTotals(s);
if (s.rules.health.on) return resolveDamage(s, c, t);
if (t.atk === t.def) {
c.ties++;
rollAll(s, c);

View file

@ -1,5 +1,5 @@
import { LOCATIONS } from './map.ts';
import { capacity, portsTotal } from './query.ts';
import { capacity, healthOf, portsTotal } from './query.ts';
import { scriptOf } from './scripts.ts';
import { controls } from './state.ts';
import type { GameState } from './types.ts';
@ -41,8 +41,15 @@ export function checkInvariants(s: GameState): string[] {
if (av.at !== null && pl.avatars[i - 4].at === null) errors.push(`p${p} copy ${slot - 4} is in play without its original`);
if (av.card !== pl.avatars[i - 4].card) errors.push(`p${p} copy ${slot - 4} doesn't match its original`);
}
if (av.at === null) return;
if (av.damage < 0) errors.push(`p${p} Avatar ${slot} has negative damage`);
if (av.at === null) {
if (av.damage !== 0) errors.push(`p${p} Avatar ${slot} is in its slot with ${av.damage} damage`);
return;
}
if (!av.faceUp) errors.push(`p${p} Avatar ${slot} is in play face down`);
// A destroyed Avatar may still stand there while its defeat is being resolved (RAID Array's choice).
const dying = s.choice !== null || s.tasks.some((t) => t.t === 'defeat' && t.ref.player === p && t.ref.slot === slot);
if (s.rules.health.on && !dying && av.damage >= healthOf(s, { player: p as 0 | 1, slot })) errors.push(`p${p} Avatar ${slot} is in play with no Health left`);
if (!controls(s, p as 0 | 1, av.at)) errors.push(`p${p} Avatar ${slot} is on ${av.at}, which it doesn't control`);
count.set(av.at, (count.get(av.at) ?? 0) + 1);
});

View file

@ -188,6 +188,26 @@ export function desynced(s: GameState, ref: AvatarRef): boolean {
return enemyFlagAt(s, c.loc, ref.player, (sc) => sc.blocksHardwareAbilities).length > 0;
}
// ---------------------------------------------------------------------------------------------
// Health (health rule)
/** Health when no value is printed and no override is set. */
export const FALLBACK_HEALTH = 10;
/**
* Health rule: the damage that destroys an Avatar. Printed Health (or the rules' override), plus
* active Hardware that adds Health. A copy has its original's Health.
*/
export function healthOf(s: GameState, r: AvatarRef): number {
const av = avatar(s, r);
let n = s.rules.health.override || (av.card < 0 ? 0 : defOf(s, av.card).health) || FALLBACK_HEALTH;
for (const hw of hardwareOf(s, r)) if (hardwareActive(s, hw)) n += scriptOf(s.cards[hw].name)?.health ?? 0;
return Math.max(1, n);
}
/** Health rule: Health an Avatar has left. */
export const healthLeft = (s: GameState, r: AvatarRef): number => healthOf(s, r) - avatar(s, r).damage;
/**
* Combat Cores for a fighter. `credit` is told about every card that changed the total, so the
* card report can count static effects (Stack Overflow, Server bonuses) as firing.

View file

@ -67,6 +67,16 @@ export interface RulesConfig {
* a round's commands A B B A instead of A B A B.
*/
commands: { on: boolean; perPlayer: number; leads: string; snake: boolean };
/**
* Health and damage (the rules since v0.9; off = one roll decides the combat and the loser is
* knocked out). Each Avatar has printed Health; `override` (when not 0) gives every Avatar that
* Health instead, for A/B tests. The roll is unchanged, but the loser takes damage equal to the
* difference in totals, a tie is a stalemate (no reroll, no damage), and an Avatar is destroyed
* (knocked out as before) only when its damage reaches its Health. A location is captured only
* when its last defender is destroyed. `recall` allows returning an Avatar to its slot in the
* Deploy step (as its placement for the round) to heal it fully; it keeps its Hardware.
*/
health: { on: boolean; override: number; recall: boolean };
}
export const DEFAULT_RULES: RulesConfig = {
@ -86,6 +96,7 @@ export const DEFAULT_RULES: RulesConfig = {
buyAvatars: { on: false, prices: [8, 12, 16] },
copies: { allowed: true, waitATurn: false, needAvatar2: false },
commands: { on: true, perPlayer: 2, leads: 'FS', snake: true },
health: { on: true, override: 0, recall: true },
};
/** Avatars kept outside the main deck: all of them, or just the starting one when recruiting. */

View file

@ -77,6 +77,8 @@ export interface Script {
noPort?: boolean;
/** Hardware: Expansion Slots it adds to its wearer (Network Interface Upgrade). */
extraSlots?: number;
/** Hardware: Health it adds to its wearer (health rule). No card does yet. */
health?: number;
/** Program: extra attacks for its controller's Avatars attacking from this location (Infinite Loop). */
extraAttacks?: number;
/** Program: no Hardware Core bonuses in combats here (Stock Rice). */

View file

@ -90,6 +90,10 @@ export function formatSummary(sum: BatchSummary, labels: [string, string]): stri
both('Captures: won in combat', 'capturesInCombat'),
both('Attacks', 'attacks'),
row('Attack win rate', pct(g.attacksWon[0], g.attacks[0]), pct(g.attacksWon[1], g.attacks[1])),
both('Combats tied (health rule: stalemates)', 'combatsTied'),
both('Damage dealt (health rule)', 'damageDealt'),
both('Avatars destroyed', 'avatarsDestroyed'),
both('Recalls (health rule)', 'recalls'),
both('Firewalls placed', 'firewallsPlaced'),
both('Firewalls upgraded', 'firewallsUpgraded'),
both('Firewalls cleared', 'firewallsCleared'),

View file

@ -63,6 +63,8 @@ export interface AvatarState {
/** null while the Avatar is in its slot (or, for a copy, doesn't exist). */
at: LocId | null;
hardware: number[];
/** Health rule: damage taken so far. Cleared when the Avatar leaves play. */
damage: number;
/** Placed (entered play or repositioned) this turn. */
placed: boolean;
advanced: boolean;
@ -250,6 +252,8 @@ export type Action =
| { type: 'pass' }
| { type: 'choose'; index: number }
| { type: 'place'; slot: number; to: LocId }
/** Health rule: return an Avatar in play to its slot as its placement for the round; it heals. */
| { type: 'recall'; slot: number }
| { type: 'advance'; slot: number; to: LocId }
| { type: 'attack'; slot: number; to: LocId }
| { type: 'clearFirewall'; line: string }
@ -270,6 +274,10 @@ export const STAT_KEYS = [
'capturesInCombat',
'attacks',
'attacksWon',
'combatsTied',
'damageDealt',
'avatarsDestroyed',
'recalls',
'combatsEnded',
'firewallsPlaced',
'firewallsUpgraded',

View file

@ -55,6 +55,24 @@ test('bots play the copy-rule variants without breaking a rule', () => {
}
});
test('bots play with the health rule off (one-roll combats) without breaking a rule', () => {
const rules = withRule(DEFAULT_RULES, 'health.on=false');
for (let seed = 1; seed <= 25; seed++) {
assert.ok(playGame({ pool, bots: [randomBot, randomBot], seed, rules, check: true }).over);
assert.ok(playGame({ pool, bots: [() => greedyBot(), () => greedyBot()], seed, rules, check: true }).over);
}
});
test('bots play the health rule without recall, and with Health 8, without breaking a rule', () => {
for (const spec of ['health.recall=false', 'health.override=8']) {
const rules = withRule(DEFAULT_RULES, spec);
for (let seed = 1; seed <= 15; seed++) {
assert.ok(playGame({ pool, bots: [randomBot, randomBot], seed, rules, check: true }).over);
assert.ok(playGame({ pool, bots: [() => greedyBot(), () => greedyBot()], seed, rules, check: true }).over);
}
}
});
test('bots play the command rule without breaking a rule', () => {
const rules = withRule(DEFAULT_RULES, 'commands.on=true');
for (let seed = 1; seed <= 25; seed++) {

182
sim/test/health.test.ts Normal file
View file

@ -0,0 +1,182 @@
/** The health rule (rules v0.9): the loser of the roll takes damage; destruction at 0 Health; recall. */
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { healthLeft, healthOf } from '../src/query.ts';
import { withRule } from '../src/rules.ts';
import { FOREVER } from '../src/types.ts';
import { Table } from './table.ts';
/** Ends steps until player `p` is in their Deploy step. */
function turnOf(t: Table, p: 0 | 1): Table {
for (let i = 0; i < 12 && !(t.decider === p && t.s.step === 'deploy'); i++) t.end();
assert.equal(t.decider, p);
assert.equal(t.s.step, 'deploy');
return t;
}
/** South's Avatar 1 (Broken Bits, 4 Cores, 9 Health) on B1 facing North's Avatar 1 on C1. */
function standoff(o: { northMain?: string[] } = {}): Table {
const t = new Table({ health: true, north: { main: o.northMain } });
t.own(0, 'B1');
t.own(1, 'C1');
t.place(0, 1, 'B1');
t.place(1, 1, 'C1');
return t;
}
test('health: printed Health, and the override rule', () => {
const t = standoff();
assert.equal(healthOf(t.s, { player: 0, slot: 1 }), 9, 'Broken Bits: 4 Cores, 9 Health');
assert.equal(healthOf(t.s, { player: 0, slot: 2 }), 10, 'Pixelated Picture: 3 Cores, 10 Health');
t.s.rules = withRule(t.s.rules, 'health.override=8');
assert.equal(healthOf(t.s, { player: 0, slot: 1 }), 8);
});
test('health: the loser takes the margin as damage, and nobody moves', () => {
const t = standoff();
t.to('attack').go({ type: 'attack', slot: 1, to: 'C1' });
t.rig(6, 6, 6, 6, 5, 5, 5, 4); // 24 to 19
t.end();
assert.equal(t.s.locations.C1.owner, 1, 'C1 holds');
assert.equal(t.avatar(0, 1).at, 'B1', 'the attacker stays where it attacked from');
assert.equal(t.avatar(1, 1).at, 'C1');
assert.equal(t.avatar(1, 1).damage, 5);
assert.equal(healthLeft(t.s, { player: 1, slot: 1 }), 4);
assert.equal(t.s.stats.attacksWon[0], 1);
assert.equal(t.s.stats.damageDealt[0], 5);
assert.equal(t.s.stats.capturesInCombat[0], 0);
assert.equal(t.s.combat, null);
});
test('health: damage adds up; the Avatar is destroyed at 0 Health, loses its Hardware, and the location falls', () => {
const t = standoff({ northMain: ['Additional Core'] });
const hw = t.hardware(1, 1, 'Additional Core');
t.avatar(1, 1).damage = 6;
t.to('attack').go({ type: 'attack', slot: 1, to: 'C1' });
t.rig(6, 6, 6, 6, 3, 3, 3, 3, 3); // 24 to 15: 9 damage, 3 was enough
t.end();
assert.equal(t.avatar(1, 1).at, null, 'destroyed: back in its slot');
assert.equal(t.avatar(1, 1).damage, 0, 'a destroyed Avatar comes back at full Health');
assert.deepEqual(t.avatar(1, 1).hardware, []);
assert.ok(t.s.players[1].discard.includes(hw));
assert.equal(t.s.locations.C1.owner, 0);
assert.equal(t.avatar(0, 1).at, 'C1');
assert.equal(t.s.stats.capturesInCombat[0], 1);
assert.equal(t.s.stats.avatarsDestroyed[1], 1);
assert.equal(t.s.stats.damageDealt[0], 9, 'the whole margin counts as dealt');
});
test('health: a losing attacker takes damage and stays put, or is destroyed by a big enough loss', () => {
const t = standoff();
t.to('attack').go({ type: 'attack', slot: 1, to: 'C1' });
t.rig(3, 3, 3, 3, 4, 4, 4, 4); // 12 to 16
t.end();
assert.equal(t.avatar(0, 1).at, 'B1');
assert.equal(t.avatar(0, 1).damage, 4);
assert.equal(t.avatar(1, 1).damage, 0, 'the winner takes no damage');
assert.equal(t.s.stats.damageDealt[1], 4);
const u = standoff();
u.avatar(0, 1).damage = 5;
u.to('attack').go({ type: 'attack', slot: 1, to: 'C1' });
u.rig(1, 1, 1, 1, 2, 2, 2, 2); // 4 to 8: 4 damage, 4 left
u.end();
assert.equal(u.avatar(0, 1).at, null, 'destroyed');
assert.equal(u.avatar(0, 1).damage, 0);
assert.equal(u.s.locations.B1.owner, 0, 'losing an attack never loses the origin');
});
test('health: a tie is a stalemate, with no reroll and no damage', () => {
const t = standoff();
t.to('attack').go({ type: 'attack', slot: 1, to: 'C1' });
t.rig(3, 3, 3, 3, 4, 4, 2, 2);
t.end();
assert.equal(t.avatar(0, 1).damage, 0);
assert.equal(t.avatar(1, 1).damage, 0);
assert.equal(t.avatar(0, 1).at, 'B1');
assert.equal(t.avatar(1, 1).at, 'C1');
assert.deepEqual(t.s.rigged, [], 'no dice were rerolled');
assert.match(t.logText(), /stalemate/);
assert.equal(t.s.stats.combatsTied[0], 1);
assert.equal(t.s.stats.attacksWon[0], 0);
});
test('health: recall heals fully, keeps Hardware, counts as the placement, and leaves the location undefended', () => {
const t = standoff({ northMain: ['Additional Core'] });
const hw = t.hardware(1, 1, 'Additional Core');
t.avatar(1, 1).damage = 7;
t.avatar(1, 1).infection = 2;
turnOf(t, 1); // South's turn passes without acting
assert.ok(t.can({ type: 'recall', slot: 1 }));
assert.ok(!t.can({ type: 'recall', slot: 2 }), 'only Avatars in play can be recalled');
t.go({ type: 'recall', slot: 1 });
const av = t.avatar(1, 1);
assert.equal(av.at, null);
assert.equal(av.damage, 0);
assert.equal(av.infection, 0, 'leaving play removes counters');
assert.deepEqual(av.hardware, [hw], 'Hardware stays on it');
assert.ok(av.placed, 'the recall was its placement');
assert.ok(!t.can({ type: 'place', slot: 1, to: 'C1' }), "it can't come back this turn");
assert.equal(t.s.stats.recalls[1], 1);
assert.equal(t.s.locations.C1.owner, 1, 'C1 is still North\'s, just undefended');
// South can now walk in.
turnOf(t, 0);
assert.ok(t.can({ type: 'advance', slot: 1, to: 'C1' }));
});
test('health: a rooted Avatar can\'t be recalled, and the rule can be switched off', () => {
const t = standoff();
t.avatar(0, 1).rootedUntil = FOREVER;
assert.ok(!t.can({ type: 'recall', slot: 1 }), 'Packet Flood: no retreat');
t.avatar(0, 1).rootedUntil = 0;
assert.ok(t.can({ type: 'recall', slot: 1 }));
t.s.rules = withRule(t.s.rules, 'health.recall=false');
assert.ok(!t.can({ type: 'recall', slot: 1 }));
});
test('health: Redundant Power Supply still saves the Hardware of a destroyed Avatar', () => {
const t = standoff({ northMain: ['Redundant Power Supply', 'Additional Core'] });
const rps = t.hardware(1, 1, 'Redundant Power Supply');
const core = t.hardware(1, 1, 'Additional Core');
t.avatar(1, 1).damage = 8;
t.to('attack').go({ type: 'attack', slot: 1, to: 'C1' });
t.rig(6, 6, 6, 6, 1, 1, 1, 1, 1); // 24 to 5
t.end();
assert.equal(t.avatar(1, 1).at, null);
assert.deepEqual([...t.avatar(1, 1).hardware].sort(), [rps, core].sort());
assert.equal(t.s.locations.C1.owner, 0);
});
test('health: with two defenders the damage destroys the weakest first, and the location falls only when both are gone', () => {
const t = new Table({ health: true, north: { servers: ['Cluster Server'] } });
t.own(0, 'B1');
t.own(1, 'C1', 'Cluster Server');
t.place(0, 1, 'B1');
t.place(1, 1, 'C1'); // Broken Bits, 4 Cores, 9 Health
t.place(1, 2, 'C1'); // Pixelated Picture, 3 Cores, 10 Health
t.avatar(1, 2).damage = 7; // 3 left
t.to('attack').go({ type: 'attack', slot: 1, to: 'C1' });
t.rig(6, 6, 6, 6, 1, 1, 1, 1, 5, 5, 5); // 24 to 4 + 15 = 19: 5 damage
t.end();
assert.equal(t.avatar(1, 2).at, null, 'the weak one is destroyed with 3 of the damage');
assert.equal(t.avatar(1, 1).damage, 2, 'the other 2 land on the survivor');
assert.equal(t.s.locations.C1.owner, 1, 'C1 holds with a defender left');
assert.equal(t.avatar(0, 1).at, 'B1');
// Enough damage for both takes the location.
const u = new Table({ health: true, north: { servers: ['Cluster Server'] } });
u.own(0, 'B1');
u.own(1, 'C1', 'Cluster Server');
u.place(0, 1, 'B1');
u.place(1, 1, 'C1');
u.place(1, 2, 'C1');
u.avatar(1, 1).damage = 8;
u.avatar(1, 2).damage = 8;
u.to('attack').go({ type: 'attack', slot: 1, to: 'C1' });
u.rig(6, 6, 6, 6, 1, 1, 1, 1, 1, 1, 1); // 24 to 7: 17 damage for 1 + 2 left
u.end();
assert.equal(u.avatar(1, 1).at, null);
assert.equal(u.avatar(1, 2).at, null);
assert.equal(u.s.locations.C1.owner, 0);
assert.equal(u.avatar(0, 1).at, 'C1');
});

View file

@ -29,18 +29,20 @@ export interface Side {
export class Table {
s: GameState;
constructor(o: { south?: Side; north?: Side; first?: PlayerId; seed?: number } = {}) {
constructor(o: { south?: Side; north?: Side; first?: PlayerId; seed?: number; health?: boolean } = {}) {
const side = (x: Side = {}) => ({
avatars: x.avatars ?? DEFAULT_AVATARS,
servers: [...(x.servers ?? []), ...Array(12).fill(PLAIN_SERVER)],
main: [...(x.main ?? []), ...Array(12).fill(FILLER)],
});
const decks = [side(o.south), side(o.north)] as const;
// Classic turns (one turn each, every Avatar acts), which the card tests are written for. The
// command rule has its own tests in engine.test.ts.
// Classic turns (one turn each, every Avatar acts) and one-roll combats, which the card tests
// are written for. The command rule has its own tests in engine.test.ts, the health rule in
// health.test.ts (`health: true`).
const rules: RulesConfig = {
...DEFAULT_RULES,
commands: { ...DEFAULT_RULES.commands, on: false },
health: { ...DEFAULT_RULES.health, on: o.health ?? false },
openingHand: 0,
deck: { avatars: 4, servers: decks[0].servers.length, main: decks[0].main.length, maxCopies: 99 },
};