Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ jobs:
run: npm run test:run

- name: Audit production dependencies
run: npm audit --audit-level=high
run: npm run audit:high

- name: Build production Activity
run: npm run build
Expand Down
22 changes: 16 additions & 6 deletions README.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"discord-py>=2.7.1",
"aiohttp>=3.14.3",
"aiohttp>=3.14.4",
"feedparser>=6.0.12",
"httpx>=0.28.1",
"beautifulsoup4>=4.12.3",
Expand Down
31 changes: 28 additions & 3 deletions scripts/hands_balance.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,12 +36,13 @@

from intelstream.hands.cpu import CpuBrain, CpuLevel, cpu_style
from intelstream.hands.engine import AttackState, BoxingEngine, EngineConfig, FighterState
from intelstream.hands.rules import GUARD_REARM, TICKS_PER_SECOND
from intelstream.hands.rules import GUARD_REARM, TICKS_PER_SECOND, injury_kind
from intelstream.hands.types import (
ActionKind,
DefensivePose,
FighterStyle,
Hand,
Injury,
InputCommand,
MatchPhase,
MovementAction,
Expand Down Expand Up @@ -164,7 +165,7 @@ def decide(self, engine: BoxingEngine) -> InputCommand | None:
return InputCommand(self._sequence, tick)
if engine.phase is MatchPhase.REST:
return InputCommand(self._sequence, tick, actions=_corner_pick(me))
if engine.phase is not MatchPhase.FIGHT:
if engine.phase not in (MatchPhase.FIGHT, MatchPhase.FINISH):
return InputCommand(self._sequence, tick)
dx, dy = them.x - me.x, them.y - me.y
distance = max(1.0, hypot(dx, dy))
Expand Down Expand Up @@ -279,7 +280,7 @@ def decide(self, engine: BoxingEngine) -> InputCommand | None:
return self._command(tick)
if engine.phase is MatchPhase.REST and self.kind == "counter":
return self._command(tick, actions=_corner_pick(me))
if engine.phase is not MatchPhase.FIGHT:
if engine.phase not in (MatchPhase.FIGHT, MatchPhase.FINISH):
return self._command(tick)
dx, dy = them.x - me.x, them.y - me.y
distance = max(1.0, hypot(dx, dy))
Expand Down Expand Up @@ -372,6 +373,11 @@ class BoutStats:
corner_picks: Counter[str] = field(default_factory=Counter)
landed_by_round: list[list[int]] = field(default_factory=list)
"""Each seat's clean punches in each round fought."""
injuries: Counter[str] = field(default_factory=Counter)
"""How many injuries of each kind the two fighters took between them."""
deaths: Counter[str] = field(default_factory=Counter)
least_blood: int = 0
"""The blood the fighter who had bled the most had left at the end."""


def make_player(
Expand Down Expand Up @@ -425,6 +431,8 @@ def play(
landed_by_round = [[0] * config.rounds, [0] * config.rounds]
stunned_ticks = fight_ticks = stuns = chained = stunned_knockdowns = 0
corner_picks: Counter[str] = Counter()
injuries: Counter[str] = Counter()
deaths: Counter[str] = Counter()
while engine.result is None:
for player_id, player in players:
command = player.decide(engine)
Expand Down Expand Up @@ -458,6 +466,10 @@ def play(
stunned_knockdowns += 1
elif event.kind == "corner" and event.detail:
corner_picks[event.detail] += 1
elif event.kind == "injury":
injuries[injury_kind(Injury(event.detail))] += 1
elif event.kind == "death":
deaths[event.detail] += 1
result = engine.result
winner = None if result.winner_id is None else ids.index(result.winner_id)
return BoutStats(
Expand All @@ -475,6 +487,9 @@ def play(
stunned_knockdowns=stunned_knockdowns,
corner_picks=corner_picks,
landed_by_round=[seat[: result.round_number] for seat in landed_by_round],
injuries=injuries,
deaths=deaths,
least_blood=min(engine.fighter(player_id).blood_volume for player_id in ids),
)


Expand Down Expand Up @@ -505,8 +520,14 @@ def summarise(one: str, two: str, bouts: list[BoutStats], elapsed: float) -> str
chained = sum(bout.chained_stuns for bout in bouts)
stunned_knockdowns = sum(bout.stunned_knockdowns for bout in bouts)
picks: Counter[str] = Counter()
injuries: Counter[str] = Counter()
deaths: Counter[str] = Counter()
for bout in bouts:
picks.update(bout.corner_picks)
injuries.update(bout.injuries)
deaths.update(bout.deaths)
wounds = ", ".join(f"{kind} {times / count:.2f}" for kind, times in injuries.most_common())
least_blood = sum(bout.least_blood for bout in bouts)
blank = [
sum(punches == 0 for bout in bouts for punches in bout.landed_by_round[seat])
for seat in (0, 1)
Expand All @@ -531,6 +552,10 @@ def summarise(one: str, two: str, bouts: list[BoutStats], elapsed: float) -> str
f", two {per_round[1][0]:.0f}/{per_round[1][1]:.0f}"
f" | rounds landing nothing: one {blank[0]}/{rounds}, two {blank[1]}/{rounds}"
+ (f" | corner picks {dict(picks)}" if picks else ""),
f" injuries {sum(injuries.values()) / count:.2f}/bout"
+ (f": {wounds}" if wounds else "")
+ (f" | deaths: {dict(deaths)}" if deaths else "")
+ f" | blood left: least {least_blood / count:.0f}",
]
return "\n".join(lines)

Expand Down
31 changes: 18 additions & 13 deletions scripts/hands_e2e_scenarios.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@
* direction, through a TCP proxy, times how long the room takes to pause the other player, and checks
* both resume once the link is back.
* The cpu scenario is one player against the computer (E2E_CPU_LEVEL, default contender) through to the
* result card. The tko scenario gets the floored player up twice, so the bout ends on the punch of the
* third knockdown, and fails unless the knockout replay still plays. The styles scenario has one fighter pick a style with the keyboard and the other by
* result card. The finish scenario gets the floored player up twice, so the knockdown that would be his
* third leaves him out on his feet: it fails unless FINISH HIM is called, the bout ends in his death or
* his collapse, and a punch that killed him is replayed. The styles scenario has one fighter pick a style with the keyboard and the other by
* touch while a spectator watches; every other scenario settles on the offered style at once. E2E_PORT
* moves the server off 8091.
*
* node scripts/hands_e2e_scenarios.js ko|tko|reconnect|rest|spectator|touch|mash|latency|soak|background|rematch|rematchloop|clinch|response|cpu|styles
* node scripts/hands_e2e_scenarios.js ko|finish|reconnect|rest|spectator|touch|mash|latency|soak|background|rematch|rematchloop|clinch|response|cpu|styles
*/
const { chromium, devices } = require('playwright');
const { spawn, spawnSync } = require('node:child_process');
Expand Down Expand Up @@ -251,7 +252,7 @@ async function main() {

const serverArgs = {
ko: ['--rounds', '3', '--round-seconds', '90', '--rest-seconds', '5'],
tko: ['--rounds', '3', '--round-seconds', '90', '--rest-seconds', '5'],
finish: ['--rounds', '3', '--round-seconds', '90', '--rest-seconds', '5'],
reconnect: ['--rounds', '1', '--round-seconds', '70', '--rest-seconds', '5'],
rest: ['--rounds', '2', '--round-seconds', '14', '--rest-seconds', '9'],
spectator: ['--rounds', '1', '--round-seconds', '30', '--rest-seconds', '5'],
Expand Down Expand Up @@ -287,7 +288,7 @@ async function main() {
// Approach: A right, B left.
await A.page.keyboard.down('d'); await B.page.keyboard.down('a'); await wait(1600); await A.page.keyboard.up('d'); await B.page.keyboard.up('a');

if (scenario === 'tko') {
if (scenario === 'finish') {
// Presses each get-up prompt once, in the middle of its window, from inside the page.
await B.page.evaluate(() => {
let answered = -1;
Expand All @@ -307,7 +308,7 @@ async function main() {
});
}

if (scenario === 'ko' || scenario === 'tko') {
if (scenario === 'ko' || scenario === 'finish') {
// Records every fighter's punch phase while the knockout replay plays, to catch a stuttering replay.
await A.page.evaluate(() => {
const state = { frames: 0, jumps: 0, worst: 0 };
Expand All @@ -328,17 +329,18 @@ async function main() {
};
requestAnimationFrame(tick);
});
let downSeen = false; let promptsPressed = 0; let final = null; let lastCount = -1;
let downSeen = false; let finishSeen = false; let promptsPressed = 0; let final = null; let lastCount = -1;
const started = Date.now();
await A.page.keyboard.down('Alt');
while (Date.now() - started < 240000) {
const sB = await status(B.page);
if (sB.final) { final = sB; break; }
const live = sB.live ?? '';
if (!finishSeen && /\. finish\./.test(sB.summary ?? '')) { finishSeen = true; note('FINISH HIM seen at', ((Date.now() - started) / 1000).toFixed(1), 's'); await A.page.screenshot({ path: `${out}/e2e-finish-A.png` }); await B.page.screenshot({ path: `${out}/e2e-finish-B.png` }); }
if (/^Knockdown/.test(live) || /\. knockdown\./.test(sB.summary ?? '')) {
if (!downSeen) { downSeen = true; note('KNOCKDOWN seen at', ((Date.now() - started) / 1000).toFixed(1), 's:', live); await A.page.screenshot({ path: `${out}/e2e-ko-A-down.png` }); await B.page.screenshot({ path: `${out}/e2e-ko-B-down.png` }); }
const count = /Count (\d+)/.exec(live); if (count && Number(count[1]) !== lastCount) { lastCount = Number(count[1]); note('count', lastCount, '|', live); }
if (scenario === 'tko') { /* the page answers its own prompts */ }
if (scenario === 'finish') { /* the page answers its own prompts */ }
else if (/Press left now/.test(live)) { await B.page.keyboard.press('ArrowLeft'); promptsPressed += 1; }
else if (/Press right now/.test(live)) { await B.page.keyboard.press('ArrowRight'); promptsPressed += 1; }
await wait(60);
Expand Down Expand Up @@ -373,14 +375,17 @@ async function main() {
await A.page.screenshot({ path: `${out}/e2e-ko-A-result.png` });
const replay = await A.page.evaluate(() => window.__replayProbe);
note('knockout replay:', JSON.stringify(replay));
if (scenario === 'tko') {
if (scenario === 'finish') {
const ending = await A.page.evaluate(() => {
const renderer = window.__handsApp?.renderer;
return { lastRecordedTick: renderer?.history?.at(-1)?.tick ?? null, knockdownTick: renderer?.lastKnockdown?.knockdown?.tick ?? null };
return { lastRecordedTick: renderer?.history?.at(-1)?.tick ?? null, knockdownTick: renderer?.lastKnockdown?.knockdown?.tick ?? null, deaths: renderer?.deaths ?? null, finishTarget: renderer?.finishTargetId ?? null };
});
note('recording ends at tick', ending.lastRecordedTick, '| last knockdown at tick', ending.knockdownTick);
if (!/^tko\b/i.test(final?.final ?? '')) report.errors.push(`expected a TKO on the third knockdown, got: ${final?.final ?? 'no result'}`);
else if (!(replay?.frames > 0)) report.errors.push('no knockout replay after a TKO that ended on its punch');
note('recording ends at tick', ending.lastRecordedTick, '| last knockdown at tick', ending.knockdownTick, '| deaths', JSON.stringify(ending.deaths));
const killed = ending.deaths?.some((death) => typeof death === 'string' && death.startsWith('fatality:')) === true;
// The phase can pass between two polls of the page; the renderer keeps who was stood up for it.
if (!finishSeen && ending.finishTarget === null) report.errors.push(`the bout ended before a third knockdown stood him up to be finished (${final?.final ?? 'no result'}): run it again`);
else if (!/^(death|tko)\b/i.test(final?.final ?? '')) report.errors.push(`expected a death or a collapse after FINISH HIM, got: ${final?.final ?? 'no result'}`);
else if (killed && !(replay?.frames > 0)) report.errors.push('no replay of the punch that killed him');
}
}

Expand Down
76 changes: 73 additions & 3 deletions scripts/hands_parity_fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
- style-timing-table.json: the same, with the stamina price, for every other style;
- movement-traces.json: what the engine sent, tick by tick, while a fighter holding a direction
was parried, flinched mid-punch, finished a punch, pressed a punch during another's recovery or late in
a flinch, slipped, or slipped out of a punch's recovery.
a flinch, slipped, slipped out of a punch's recovery, or walked on injured legs;
- injury-table.json: the injury ids in the engine's order, and the hand, startup and recovery of
every punch for each state a fighter's arms can be in.

uv run python scripts/hands_parity_fixtures.py # rewrite the files
uv run python scripts/hands_parity_fixtures.py --check # fail if they are out of date
Expand All @@ -32,6 +34,7 @@
DefensivePose,
FighterStyle,
Hand,
Injury,
InputCommand,
MovementAction,
Power,
Expand Down Expand Up @@ -122,15 +125,22 @@ def _trace(
records = []
for sequence in range(1, 46):
inputs = script(engine.tick + 1)
inputs.setdefault("one", InputCommand(sequence, sequence, held.move_x, held.move_y))
inputs.setdefault(
"one",
InputCommand(sequence, sequence, held.move_x, held.move_y, defense=held.defense),
)
snapshot = engine.step(inputs)
payload = json.loads(encode_snapshot(snapshot, viewer_id="one"))["payload"]
records.append(
{
"tick": snapshot.tick,
"fighter": payload["fighters"][0],
"events": payload["events"],
"held": {"moveX": held.move_x, "moveY": held.move_y, "defense": "none"},
"held": {
"moveX": held.move_x,
"moveY": held.move_y,
"defense": held.defense.value,
},
}
)
return records
Expand Down Expand Up @@ -219,6 +229,16 @@ def slip_out_early(tick: int) -> dict[str, InputCommand]:
return {}
return {"one": InputCommand(tick, tick, back.move_x, back.move_y, actions=(action,))}

limping = _engine((FighterStyle.BALANCED, FighterStyle.BALANCED), 300, centre)
limping.fighter("one").injuries |= {Injury.KNEE_LEFT_BLOWN, Injury.DISEMBOWELED}
limping_jab = _engine((FighterStyle.BALANCED, FighterStyle.BALANCED), 300, centre)
limping_jab.fighter("one").injuries |= {Injury.KNEE_LEFT_BLOWN, Injury.KNEE_RIGHT_BLOWN}
# A guard slows the feet of a man who has arms to hold it with.
guarding_back = InputCommand(0, 0, -1000, 0, defense=DefensivePose.GUARD_HIGH)
guarded = _engine((FighterStyle.BALANCED, FighterStyle.BALANCED), 300, centre)
armless = _engine((FighterStyle.BALANCED, FighterStyle.BALANCED), 300, centre)
armless.fighter("one").injuries |= {Injury.ARM_LEFT_TORN, Injury.ARM_RIGHT_TORN}

return {
"parried while holding back": _trace(parried, back, parry),
"flinched mid-hook while holding back": _trace(flinched, back, counter),
Expand All @@ -234,9 +254,55 @@ def slip_out_early(tick: int) -> dict[str, InputCommand]:
"slipped out of a power uppercut's recovery while holding back": _trace(
long_cut, back, slip_out_early
),
"holding back on a blown knee with his gut open": _trace(limping, back, lambda _tick: {}),
"a jab thrown holding back on two blown knees": _trace(limping_jab, back, alone),
"holding back behind a guard": _trace(guarded, guarding_back, lambda _tick: {}),
"holding back and a guard with no arms left": _trace(
armless, guarding_back, lambda _tick: {}
),
}


# The states an arm can be in, on either arm and on both, that change which hand throws a punch
# or how soon it lands.
INJURED_ARMS: tuple[tuple[Injury, ...], ...] = (
(Injury.SHOULDER_LEFT_DISLOCATED,),
(Injury.SHOULDER_RIGHT_DISLOCATED,),
(Injury.ARM_LEFT_BROKEN,),
(Injury.ARM_RIGHT_BROKEN,),
(Injury.FOREARM_LEFT_SEVERED,),
(Injury.FOREARM_RIGHT_SEVERED,),
(Injury.ARM_LEFT_TORN,),
(Injury.ARM_RIGHT_TORN,),
(Injury.SHOULDER_LEFT_DISLOCATED, Injury.ARM_LEFT_BROKEN),
(Injury.SHOULDER_LEFT_DISLOCATED, Injury.FOREARM_LEFT_SEVERED),
(Injury.ARM_LEFT_TORN, Injury.ARM_RIGHT_BROKEN),
(Injury.SHOULDER_LEFT_DISLOCATED, Injury.ARM_RIGHT_TORN),
(Injury.ARM_LEFT_TORN, Injury.ARM_RIGHT_TORN),
)


def injury_table() -> dict[str, list[str]]:
"""The engine's injury ids in its order, and for a fresh fighter with each state of his arms,
the hand every punch is thrown with (none with no arms left) and its startup and recovery."""
rows = []
for injuries in INJURED_ARMS:
for key, action in _punches():
engine = _engine((FighterStyle.BALANCED, FighterStyle.BALANCED), 360)
fighter = engine.fighter("one")
fighter.stance = Stance.ORTHODOX
fighter.injuries |= set(injuries)
engine.step({"one": InputCommand(1, 1, actions=(action,))})
attack = fighter.attack
thrown = (
"none,0,0"
if attack is None
else f"{attack.action.hand.value},{attack.rule.startup},{attack.rule.recovery}"
)
rows.append(f"{'+'.join(injury.value for injury in injuries)},{key},{thrown}")
return {"ids": [injury.value for injury in Injury], "punches": rows}


def documents() -> dict[Path, str]:
return {
FIXTURES / "punch-timing-table.json": json.dumps(punch_timing_rows(), separators=(",", ":"))
Expand All @@ -246,6 +312,10 @@ def documents() -> dict[Path, str]:
movement_traces(), separators=(",", ":"), sort_keys=True
)
+ "\n",
FIXTURES / "injury-table.json": json.dumps(
injury_table(), separators=(",", ":"), sort_keys=True
)
+ "\n",
}


Expand Down
Loading
Loading