Files
myrzx_bot/ranch_assistant/battle_simulator.py
T

1181 lines
61 KiB
Python

"""Experimental fixed-clock offline combat; never an original-engine replay.
The public runtime runs CPU work in a disposable module subprocess. No game
API, production engine, GUI, estimator, or AIR runtime is imported here.
``simulate`` is the direct deterministic test/research entrypoint.
"""
from __future__ import annotations
from collections import Counter
from collections.abc import Mapping
from dataclasses import asdict, dataclass, field, replace
from functools import lru_cache
import gzip
import hashlib
import heapq
import json
import math
from pathlib import Path
import random
import subprocess
import sys
import time
from types import MappingProxyType
ORIGINAL_APK_SHA256 = "01678ee3a8465d818d32cbbd94baa0d8253b04b4c57b70ebc5544ed341f1015d"
DATA_DIR = Path(__file__).with_name("data")
CONTEXTS = frozenset(("ordinary_stage", "task_battle", "task_pass_stage"))
KNOWN_SKILLS = frozenset((3, 5, 7, 9, 38))
FPS = 50 # Original MYRMain.app SWF header: 50 fps.
MAX_TRACE = 10000
MAX_UNITS = 1024
MAX_WIRE_BYTES = 16 * 1024 * 1024
LIMITATIONS = (
"Experimental fixed clock: not validated against original AIR battle trajectories.",
"Straight-line ground movement; collision, inertia, flight height and animation joins are approximated.",
"Nearest spatial targeting with source range box; target-search jump cadence is approximated.",
"Original hit callbacks and projectile speed inform delays; visual offsets, easing and rocket paths are omitted.",
"Skills 3, 5, 7, 9, 38 have partial source ports; all other skills are omitted and individually reported.",
"Skill presentation callbacks are replaced with immediate model activation; AI checks use modeled cadence.",
"Knockback, cosmetic equipment animations and special equipment words are omitted.",
"Python seeded RNG is not the original Random helper or Math.random stream.",
"Only elimination objectives are supported; authored combat controllers, triggers and active field areas are rejected.",
"Original cheat-check execution is incomplete; detected model anomalies are preserved, not a clean-engine verdict.",
)
class SimulationInputError(ValueError):
"""The model cannot interpret the supplied original inputs."""
def _get(obj, key, default=None):
return obj.get(key, default) if isinstance(obj, Mapping) else getattr(obj, key, default)
def _number(value, name="number"):
try:
result = float(value)
if isinstance(value, bool) or not math.isfinite(result):
raise ValueError
return result
except (TypeError, ValueError, OverflowError) as exc:
# Do not echo arbitrary input (potentially account material) in errors.
raise SimulationInputError(f"Invalid numeric field: {name}") from exc
def _int(value, name="integer"):
return int(_number(value, name)) # AS3 int coercion truncates toward zero.
def _freeze(value):
if isinstance(value, dict):
return MappingProxyType({k: _freeze(v) for k, v in value.items()})
if isinstance(value, list):
return tuple(_freeze(v) for v in value)
return value
def _plain(value):
if isinstance(value, Mapping):
return {str(k): _plain(v) for k, v in value.items()}
if isinstance(value, (tuple, list)):
return [_plain(v) for v in value]
return value
def _position(value):
if value is None:
return None
# Original BattlePosition fields only; never serialize arbitrary account
# envelope fields from a caller-provided object.
return {key: _get(value, key) for key in ("battleType", "stageId", "stageLevel", "taskTypeId", "taskStep")
if _get(value, key) is not None}
@lru_cache(maxsize=4)
def _combat_artifact(name, directory):
try:
directory = Path(directory)
manifest = json.loads((directory / "combat_manifest.json").read_text(encoding="utf-8"))
if manifest["schema_version"] != 1 or manifest["source"]["apk_sha256"] != ORIGINAL_APK_SHA256:
raise SimulationInputError("Combat data source identity mismatch")
meta = manifest["artifacts"][name]
artifact = (directory / name).read_bytes()
if hashlib.sha256(artifact).hexdigest() != meta["sha256"]:
raise SimulationInputError("Combat artifact hash mismatch")
decoded = gzip.decompress(artifact)
if hashlib.sha256(decoded).hexdigest() != meta["decoded_sha256"]:
raise SimulationInputError("Decoded combat artifact hash mismatch")
data = json.loads(decoded)
if data["schema_version"] != 1:
raise SimulationInputError("Unsupported combat data schema")
if name == "combat_tables.json.gz" and data.get("clock", {}).get("fps") != FPS:
raise SimulationInputError("Original combat frame rate does not match this model")
return _freeze(data)
except (OSError, KeyError, ValueError, EOFError) as exc:
if isinstance(exc, SimulationInputError):
raise
raise SimulationInputError("Cannot load bundled original combat tables") from exc
def combat_tables(directory=DATA_DIR):
"""Independent, immutable numeric/skill cache. Never opens an APK."""
return _combat_artifact("combat_tables.json.gz", directory)
def combat_battles(directory=DATA_DIR):
"""Lazy public research corpus; run/inspect never need the full corpus."""
return _combat_artifact("combat_battles.json.gz", directory)
def _envelope():
return {"execution_mode": "experimental", "approximate": True, "faithful": False,
"settlement_eligible": False, "requires_realtime_wait": True,
"experimental_settlement_eligible": False,
"experimental_eligibility_reasons": ["No completed supported model trajectory"],
"source_identity": ORIGINAL_APK_SHA256, "model": "v1.2-fixed-clock-1",
"diagnostics": [], "ignored_mechanics": list(LIMITATIONS),
"anomalies": [], "battle_data": None}
@dataclass(frozen=True)
class Stats:
hp: int
atk: int
defense: int
dex: int
attack_ms: float
move_speed: float
attack_range: float
element: int
crit: float = 0
damage_reduction: float = 0
@dataclass(frozen=True)
class Skill:
id: int
level: int
cost: int
cooldown_ms: int
para: Mapping
@dataclass(frozen=True)
class Unit:
key: str
species: int
team: int
stats: Stats
skills: tuple
attack_type: int
mode: int = 2
position: int = 1
join_time: int = -1
wave: int = 1
join_point: str = ""
count_unit: bool = True
is_object: bool = False
auto_target: bool = True
move_immune: bool = False
ai: int = 0
ai_search: int = 2
ap_recovery: bool = False
ap_cost: int = 0
boss_point: int = 0
effects: Mapping = field(default_factory=dict)
source_id: str = ""
attack_area: str = ""
@dataclass
class Actor:
unit: Unit
hp: int
x: float = 0
y: float = 0
state: str = "waiting"
joined_ms: int | None = None
died_ms: int | None = None
next_attack: int = 0
busy_until: int = 0
next_ai: int = 0
cooldowns: dict = field(default_factory=dict)
summon_of: str | None = None
total_hurt: int = 0
damage_dealt: int = 0
healed: int = 0
stunned_until: int = 0
poison_until: int = 0
poison_at: int = 0
poison_damage: int = 0
area_hit: bool = False
combo_hits: int = 0
def _skills(species_row, mon, tables, diagnostic, *, player):
tp = min(4, _int(mon.get("tpLevel", 0)))
ids = [int(species_row.get("skill_1", 0)), int(species_row.get("skill_2", 0))]
if player and _int(mon.get("upStar", 0)) > 0:
change = tables["upstar_info"].get(str(mon["typeId"]), {}).get("skill", {})
ids = [int(change.get(str(i + 1), v)) for i, v in enumerate(ids)]
if not player:
ids = [_int(mon.get(f"skill_{i + 1}", -1)) if _int(mon.get(f"skill_{i + 1}", -1)) != -1
else v for i, v in enumerate(ids)]
levels = [tp + 1 if ids[1] <= 0 else (1 if tp == 0 else 2 if tp <= 2 else 3),
1 if tp <= 1 else 2 if tp <= 3 else 3]
result = []
for i, skill_id in enumerate(ids):
if skill_id <= 0:
continue
level = levels[i]
if not player and _int(mon.get(f"skill_{i + 1}_lv", -1)) != -1:
level = _int(mon[f"skill_{i + 1}_lv"])
row = tables["monster_skill"].get(str(skill_id), {}).get(f"lv{level}")
if skill_id not in KNOWN_SKILLS or row is None:
diagnostic("unsupported_skill", f"Skill {skill_id} level {level} is omitted", ignored=True)
continue
result.append(Skill(skill_id, level, _int(row["cost"]), _int(row["cd"]), row["para"]))
return tuple(result)
def _player(mon, attributes, master, tables, key, position, diagnostic):
for name in ("id", "typeId", "level", "gAtk", "gDef", "gHp", "gDex"):
if name not in mon:
raise SimulationInputError(f"Full roster is missing monster field {name}")
species = _int(mon["typeId"])
row = tables["monster_info"].get(str(species))
if row is None:
raise SimulationInputError("Unknown original player species")
level = _int(mon["level"])
tp = min(4, _int(mon.get("tpLevel", 0)))
feel = min(200, max(0, _int(mon.get("feel", 0)))) / 2000
feel += _int(mon.get("upStar", 0)) * tables["game_setting"].get("upStarAdd", 0)
values = {}
for stat, suffix in (("hp", "Hp"), ("atk", "Atk"), ("def", "Def"), ("dex", "Dex")):
base = _number(row[stat]) + _number(mon["g" + suffix]) * (level + tp - 1)
base += _int(attributes.get(stat, 0)) + _int(mon.get("p" + suffix, 0))
base += _int(master.get("global" + suffix, 0))
values[stat] = int((1 + feel) * base)
stats = Stats(values["hp"], values["atk"], values["def"], values["dex"],
_number(row["spd_atk"]) + int(-values["dex"] * 3 / 4)
- 1600 * _int(attributes.get("atkSpd", 0)) / 100,
_number(row["spd_move"]) + math.floor(values["dex"] / 200 * 100 + .5) / 100,
_number(row["atk_dis"]), _int(row["element"]), _int(attributes.get("crit", 0)))
mode = _int(mon.get("mode", 2))
if level < 1 or mode not in (1, 2):
raise SimulationInputError("Only hatched, positive-level roster monsters can fight")
skills = _skills(row, mon, tables, diagnostic, player=True)
ap_costs = tables["game_setting"]["apCostByStar"]
ap_cost = max(0, _int(ap_costs[_int(row["star"]) - 1]) - _int(attributes.get("apCostSave", 0)))
return Unit(key, species, 1, stats, skills, _int(row[f"atk_type{mode}"]), mode=mode,
position=position, ai=1, ap_recovery=True, ap_cost=ap_cost,
effects=_freeze({k: _int(v, k) for k, v in attributes.items() if k != "monsterId"}),
source_id=str(mon["id"]))
def _enemy(mon, team, tables, key, battle, diagnostic, master):
species = _int(mon.get("type"))
row = tables["monster_info"].get(str(species))
if row is None:
raise SimulationInputError("Unknown original configured species")
mode = _int(mon.get("mode", 2))
auto = mon.get("autoValue") is True
level = _int(mon.get("level", 1))
stats = {}
for stat in ("hp", "atk", "def", "dex"):
if auto:
stats[stat] = int(_number(row[stat]) + (_number(row[stat + "_grow_min"])
+ _number(row[stat + "_grow_max"])) / 2 * (level - 1)
+ _int(master.get("global" + stat.capitalize(), 0)))
else:
if stat not in mon:
raise SimulationInputError(f"Configured enemy is missing {stat}")
stats[stat] = _int(mon[stat], stat)
ability = 1 if mon.get("abilityScaled") else _number(battle.get("scaleAbility", 1))
hp_scale = 1 if mon.get("abilityScaled") else _number(battle.get("scaleHp", 1))
# Authored battle scales are original configuration, never an invented boost.
hp = int(stats["hp"] * hp_scale)
move = _number(mon.get("spd_mov", -1))
attack = _number(mon.get("spd_atk", -1))
distance = _number(mon.get("atk_dis", -1))
if auto:
if move == -1:
move = _number(row["spd_move"]) + math.floor(stats["dex"] / 2 + .5) / 100
if attack == -1:
attack = _number(row["spd_atk"]) + int(-stats["dex"] * 3 / 4)
if distance == -1:
distance = _number(row["atk_dis"])
if min(move, distance) < 0 or attack <= 0:
raise SimulationInputError("Configured enemy movement/range/attack interval is incomplete")
effect_keys = ("atkVim", "atkStun", "defStun", "atkStunTime", "defStunTime", "atkPoi",
"atkPoiDmg", "thorns", "selfCure", "skillCooldown", "sunFire", "moonHeal", "deadBoom")
return Unit(key, species, _int(mon.get("team", team["team"])),
Stats(hp, int(stats["atk"] * ability), int(stats["def"] * ability),
int(stats["dex"] * ability), attack, move, distance, _int(row["element"]),
_number(mon.get("crit", 0)), _number(mon.get("defDama", 0))),
_skills(row, mon, tables, diagnostic, player=False),
_int(row.get(f"atk_type{mode}", row["atk_type1"])), mode=mode,
position=_int(mon.get("teamPos", 0)), join_time=_int(mon.get("joinTime", -1)),
wave=_int(mon.get("wave", 1)), join_point=str(mon.get("joinPoint", "")),
count_unit=mon.get("countUnit", True) is not False, is_object=bool(mon.get("isObject")),
auto_target=mon.get("autoTarget", True) is not False, move_immune=bool(mon.get("moveImmune")),
ai=_int(mon.get("ai", 0)) if _int(mon.get("ai", 0)) != -1 else _int(team.get("ai", 0)),
ai_search=_int(mon.get("ai_search", 2)) if _int(mon.get("ai_search", 2)) != -1 else _int(team.get("ai_search", 2)),
ap_recovery=bool(mon.get("apRecovery")), boss_point=_int(mon.get("bossPoint", 0)),
effects=_freeze({k: _number(mon[k], k) * (ability if k in ("deadBoom", "sunFire", "moonHeal", "selfCure") else 1)
for k in effect_keys if k in mon}),
source_id=str(mon.get("mid", "")), attack_area=str(mon.get("attackArea", "")))
@dataclass
class Scenario:
units: list
teams: dict
points: dict
areas: dict
duration_ms: int
seed: int
trace_limit: int
position: object
roster_ids: tuple
def _prepare(request, tables):
report = _envelope()
report.update(supported=False, reasons=[], implemented_skills=sorted(KNOWN_SKILLS))
def diagnostic(code, message, *, ignored=False, blocking=False):
record = {"code": code, "message": message}
if record not in report["diagnostics"]:
report["diagnostics"].append(record)
if ignored and message not in report["ignored_mechanics"]:
report["ignored_mechanics"].append(message)
if blocking and message not in report["reasons"]:
report["reasons"].append(message)
try:
if _get(request, "context") not in CONTEXTS:
raise SimulationInputError("Context must be ordinary_stage, task_battle or task_pass_stage")
original = _get(request, "original_data", {})
battle = _get(original, "battle")
if not isinstance(battle, Mapping) or not battle:
raise SimulationInputError("original_data.battle must contain the full original configuration")
if list(map(_int, battle.get("winType", (1,)))) != [1] or any(
_int(x) not in (1, 2) for x in battle.get("loseType", (1, 2))):
diagnostic("objective", "Non-elimination win/loss objective is unsupported", blocking=True)
for key in ("controller", "triggers"):
for entry in battle.get(key, ()) or ():
diagnostic(key, f"Unsupported battle {key}: {_get(entry, 'type', 'unknown')}", blocking=True)
raw = _get(request, "roster", _get(request, "snapshot"))
raw = _get(raw, "raw", raw)
if not isinstance(raw, Mapping) or not isinstance(raw.get("master"), Mapping):
raise SimulationInputError("roster must be a full raw snapshot including master")
team_name = _get(request, "team", "teamA")
if not isinstance(team_name, str):
raise SimulationInputError("team must be the original team name or an ordered comma-separated id string")
team = next((t for t in raw.get("teams", ()) if t.get("teamName") == team_name), None)
if team is None:
if not team_name or any(not part.strip().isdigit() for part in team_name.split(",")):
raise SimulationInputError("Selected team is absent from the raw snapshot")
ids = [part.strip() for part in team_name.split(",")]
else:
ids = team["monsters"]
ids = [str(i) for i in ids]
selected = [i for i in ids if _int(i) > 0]
if not selected or len(selected) != len(set(selected)):
raise SimulationInputError("Team must contain distinct original roster monsters")
roster = {str(m["id"]): m for m in raw.get("monsters", ())}
attributes = {str(m["monsterId"]): m for m in raw.get("monsterAttributes", ()) or ()}
master = raw["master"]
level = _int(master.get("level", 0), "master.level")
if level < 1:
raise SimulationInputError("Raw master.level must be positive")
slots = tables["team_info"]["battleTeam"]
capacity = min(4, sum(_int(s["level"]) <= level for s in slots.values()))
game = tables["game_setting"]
player_ap = _int(game["startAp"]) + (level - 1) * _int(game["addApByLevel"])
teams = {1: {"capacity": capacity, "initial": player_ap, "max": player_ap}}
units = []
positions = (1, 4, 2, 5, 6, 7, 8, 9)
for slot, mid in enumerate(ids):
if _int(mid) <= 0:
continue
if mid not in roster or slot >= len(positions):
raise SimulationInputError("Team references a missing monster or unsupported slot")
if str(slot) not in slots or level < _int(slots[str(slot)]["level"]):
raise SimulationInputError("Selected team uses a locked original team slot")
mon = roster[mid]
effects = attributes.get(mid, {})
units.append(_player(mon, effects, master, tables, f"player-{slot + 1}", positions[slot], diagnostic))
report["anomalies"].extend(_snapshot_anomalies(mon, units[-1], tables))
if any(mon.get(f"equip{i}", 0) for i in range(1, 6)) or mon.get("skin"):
diagnostic("equipment_words", "Equipment/skin numeric bonuses use monsterAttributes; special words and skin attack overrides are omitted", ignored=True)
if battle.get("hideTeamMon"):
units = [] # BattleCenter empties the master team before adding authored allies.
for ti, team in enumerate(battle.get("teams", ())):
team_id = _int(team.get("team", 2))
initial_ap = _int(team.get("ap", 0))
config = {"capacity": _int(team.get("numMax", 0)), "initial": initial_ap, "max": initial_ap * 2}
teams.setdefault(team_id, config)
for mi, mon in enumerate(team.get("mons", ())):
if mon is None:
continue
if not isinstance(mon, Mapping):
raise SimulationInputError("Enemy configuration contains a non-object monster")
for controller in mon.get("controller", ()) or ():
kind = _get(controller, "type", "unknown")
para = _get(controller, "para")
# MonControllerBuffMovie.start -> BattleMonBuff.addBuffMov:
# a standalone aura only draws a clip; stopMove pauses the
# monster's legs. Other buff slots may share status visuals.
if (kind == "buffMovie" and isinstance(para, Mapping)
and para.get("type") == "none" and not para.get("stopMove", False)):
diagnostic("cosmetic_controller", "Cosmetic monster buffMovie animation is omitted", ignored=True)
else:
diagnostic("unit_controller", f"Unsupported monster controller: {kind}", blocking=True)
if mon.get("protectTarget") or mon.get("destroyTarget"):
diagnostic("unit_objective", "Protected/destroy objective units are unsupported", blocking=True)
unit = _enemy(mon, dict(team, team=team_id), tables, f"configured-{ti + 1}-{mi + 1}", battle, diagnostic, master)
teams.setdefault(unit.team, config.copy())
units.append(unit)
if not any(u.team != 1 and not u.is_object for u in units):
raise SimulationInputError("Elimination battle must contain configured enemies")
for team in teams.values():
if team["capacity"] <= 0 or team["initial"] < 0:
raise SimulationInputError("Original team capacity/AP is invalid")
field_config = battle.get("battleField")
if not isinstance(field_config, Mapping):
raise SimulationInputError("Full original battleField configuration is required")
if field_config.get("fieldMode"):
name = field_config.get("fieldName", "default")
original_field = tables["setting"]["defaultField"].get(name)
if original_field is None:
raise SimulationInputError("Unknown original default battlefield")
field_config = dict(original_field, mapObjects=field_config.get("mapObjects", ()),
mapAreas=tuple(original_field.get("mapAreas", ())) + tuple(field_config.get("mapAreas", ())))
points = {p["id"]: p for p in field_config.get("mapPoints", ())}
areas = {a["id"]: a for a in field_config.get("mapAreas", ())}
if "area_battlefield" not in areas or not points:
raise SimulationInputError("Battlefield needs original points and area_battlefield")
for area in areas.values():
if area.get("type", "none") != "none":
diagnostic("field_effect", f"Unsupported active field area: {area.get('type')}", blocking=True)
if field_config.get("mapObjects"):
diagnostic("ground_objects", "Battlefield ground object collision/decoration is omitted", ignored=True)
for u in units:
if u.stats.hp <= 0 or u.stats.atk < 0 or u.stats.defense < 0 or u.stats.dex < 0:
raise SimulationInputError("Original computed combat stats must be nonnegative with positive HP")
if u.stats.attack_ms <= 0:
raise SimulationInputError("Original computed attack interval is nonpositive; no clamping is applied")
if u.attack_type and str(u.attack_type) not in tables["attack_profiles"]:
diagnostic("attack_profile", f"Attack {u.attack_type} has no bundled source profile; original default AttackType1 is approximated", ignored=True)
if u.effects.get("sunFire") or u.effects.get("moonHeal") or u.effects.get("deadBoom"):
diagnostic("unimplemented_effect", "sunFire, moonHeal and deadBoom effects are omitted where present", ignored=True)
if u.attack_area and u.attack_area not in areas:
raise SimulationInputError("Configured attackArea is absent from original battlefield")
if u.join_point and not u.join_point.startswith("mon_") and u.join_point not in points:
raise SimulationInputError("Configured joinPoint is absent from original battlefield")
if not u.join_point:
default_point = f"point_team{u.team}_{'fore' if u.position < 3 else 'back'}{u.position + 1 if u.position < 3 else u.position - 2}"
if (u.position >= 6 or default_point not in points) and not any(
p.startswith(f"point_team{u.team}_wait") for p in points):
raise SimulationInputError("Original battlefield lacks a required team spawn point")
duration = _int(battle.get("time", -1))
duration = _int(game["normalBattleTime"]) if duration == -1 else duration
if duration <= 0:
raise SimulationInputError("Original battle clock must be positive")
seed = _int(_get(request, "seed", 0), "seed")
trace_limit = _int(_get(request, "trace_limit", 2000), "trace_limit")
if trace_limit < 0 or trace_limit > MAX_TRACE:
raise SimulationInputError(f"trace_limit must be in 0..{MAX_TRACE}")
if len(units) > MAX_UNITS:
diagnostic("resource_limit", "Initial configured unit count exceeds the model resource limit", blocking=True)
report["units"] = [_unit_preview(u) for u in units]
report["teams"] = _plain(teams)
report["duration_ms"] = duration * 1000
report["supported"] = not report["reasons"]
return Scenario(units, teams, points, areas, duration * 1000, seed, trace_limit,
_position(_get(request, "battle_position")),
tuple(_int(mid) for mid in selected) if not battle.get("hideTeamMon") else ()), report
except (SimulationInputError, KeyError, TypeError, AttributeError, IndexError) as exc:
message = str(exc) if isinstance(exc, SimulationInputError) else "Malformed original combat input"
diagnostic("input", message, blocking=True)
return None, report
def _unit_preview(unit):
return {"id": unit.key, "species": unit.species, "team": unit.team,
"stats": asdict(unit.stats), "attack_type": unit.attack_type, "mode": unit.mode,
"skills": [{"id": s.id, "level": s.level, "cost": s.cost,
"cooldown_ms": s.cooldown_ms, "para": _plain(s.para)} for s in unit.skills],
"wave": unit.wave, "join_time_seconds": unit.join_time, "position": unit.position,
"count_unit": unit.count_unit, "is_object": unit.is_object, "ap_cost": unit.ap_cost}
def _snapshot_anomalies(mon, unit, tables):
"""Port the observable input checks from BattlePanel.cheatCheck.
These are a subset of the final original checks, not a claim to have run
them all. Keep raw input values; never repair them to make checks pass.
"""
if _number(mon["id"]) < 99999: # Source exempts temporary/NPC ids.
return []
records = []
def add(code, points, **fields):
records.append({"at_ms": 0, "code": code, "source_cheat_points": points,
"target": unit.key, **fields})
row = tables["monster_info"][str(unit.species)]
potential_level = _int(mon.get("potentialLevel", 1))
tp = min(4, _int(mon.get("tpLevel", 0)))
if _number(mon.get("feel", 0)) > 200:
add("+15overfeel", 50, feel=mon["feel"])
potential = tables["potential_info"]["potential"].get(str(row["job"]), {}).get(str(row["star"]), {})
for stat, value in (("atk", unit.stats.atk), ("def", unit.stats.defense),
("hp", unit.stats.hp), ("dex", unit.stats.dex)):
maximum = row[stat] + row[stat + "_grow_max"] * (_int(mon["level"]) + potential_level) * 4
if value > maximum:
add("+15overgrow", 25, stat=stat, value=value, source_maximum=maximum)
max_potential = potential.get(stat, 0) + potential.get(stat + "TpAdd", 0) * tp
value_potential = _number(mon.get("p" + stat.capitalize(), 0))
if potential and value_potential > max_potential * 1.5:
add("+15overpoten", 30, stat=stat, value=value_potential, source_maximum=max_potential * 1.5)
maximum_level = potential_level * tables["potential_info"]["potentialLevelMaxAdd"]
if _int(mon["level"]) > maximum_level:
add("+50overlv", 50, level=mon["level"], source_maximum=maximum_level)
return records
def damage_roll(attack, attacker_dex, defender, game, rng):
"""GameMath.damage, including int stages and positive Math.round semantics."""
difference = min(80, max(-80, attacker_dex - defender.dex))
low = .8 + .3 * max(0, difference) / 80
high = 1.2 + .3 * min(0, difference) / 80
raw = attack * game["countDamagePerAtk"] * rng.uniform(low, high)
raw -= defender.defense * (game["countGuardPerDef"] * .75
+ rng.uniform(0, game["countGuardPerDef"] * .25))
return max(1, math.floor(raw + .5))
class _Battle:
def __init__(self, scenario, report, tables):
self.s = scenario
self.report = report
self.tables = tables
self.game = tables["game_setting"]
self.rng = random.Random(scenario.seed)
self.actors = [Actor(u, u.stats.hp) for u in scenario.units]
self.by_key = {a.unit.key: a for a in self.actors}
self.ap = {team: dict(initial=v["initial"], current=v["initial"], max=v["max"], spent=0, recovered=0)
for team, v in scenario.teams.items()}
self.wave = {team: 1 for team in scenario.teams}
self.wave_due = {}
self.queue = []
self.sequence = 0
self.now = 0
self.events = []
self.omitted_events = 0
self.anomalies = list(report["anomalies"])
self.kill_monster = Counter()
self.all_kills = Counter()
self.deaths = Counter()
self.hp_lost = Counter()
self.boss_points = 0
self.next_ap = _int(self.game["apCD"])
self.next_deploy = 0
self.complete_at = None
self.resource_limited = False
self.skill_used = False
def event(self, kind, **fields):
record = {"at_ms": self.now, "type": kind, **fields}
if len(self.events) < self.s.trace_limit:
self.events.append(record)
else:
self.omitted_events += 1
def anomaly(self, code, points=0, **fields):
# No score normalization, record removal, or threshold avoidance.
self.anomalies.append({"at_ms": self.now, "code": code, "source_cheat_points": points, **fields})
if len(self.anomalies) >= 10000:
self.resource_limited = True
def schedule(self, delay, kind, **fields):
self.sequence += 1
heapq.heappush(self.queue, (self.now + max(0, delay), self.sequence, kind, fields))
def active(self):
return [a for a in self.actors if a.state == "active" and a.hp > 0]
def living(self, team):
return [a for a in self.actors if a.unit.team == team and a.state != "dead" and not a.unit.is_object]
def terminal_team_size(self, team):
# BattleGround.checkGameOver counts objects differently from getAliveNum.
return sum(a.unit.team == team and a.state != "dead"
and (team == 1 or a.state == "active" or not a.unit.is_object) for a in self.actors)
def add_ap(self, team, amount, reason):
ap = self.ap[team]
before = ap["current"]
ap["current"] = min(ap["max"], int(ap["current"] + amount))
ap["recovered"] += ap["current"] - before
self.event("ap", team=team, amount=ap["current"] - before, current=ap["current"], reason=reason)
def spend_ap(self, team, amount, actor, skill):
ap = self.ap[team]
if ap["current"] < amount:
return False
ap["current"] -= amount
ap["spent"] += amount
self.event("ap", team=team, amount=-amount, current=ap["current"], reason="skill", actor=actor, skill=skill)
return True
def spawn_point(self, actor):
unit = actor.unit
point = unit.join_point
if point.startswith("mon_"):
original_id = point[4:]
target = next((a for a in self.actors if a.unit.source_id == original_id and a.joined_ms is not None), None)
if target:
return target.x, target.y
point = f"point_team{unit.team}_wait1"
if not point:
pos = unit.position
point = f"point_team{unit.team}_{'fore' if pos < 3 else 'back'}{pos + 1 if pos < 3 else pos - 2}"
if point not in self.s.points or pos >= 6:
names = sorted(p for p in self.s.points if p.startswith(f"point_team{unit.team}_wait"))
point = self.rng.choice(names) if names else ""
location = self.s.points.get(point)
if location is None:
raise SimulationInputError("Original battlefield lacks a required team spawn point")
return (_number(location["x"]) + self.rng.random() * _number(location.get("w", 0)),
_number(location["y"]) + self.rng.random() * _number(location.get("h", 0)))
def deploy(self):
for actor in self.actors:
u = actor.unit
if actor.state != "waiting" or u.wave > self.wave[u.team] or u.join_time * 1000 > self.now:
continue
count = sum(a.state == "active" and a.unit.team == u.team and a.unit.count_unit for a in self.actors)
if u.count_unit and count >= self.s.teams[u.team]["capacity"]:
continue
actor.x, actor.y = self.spawn_point(actor)
actor.state = "active"
actor.joined_ms = self.now
# Initial Cooldowner readiness is approximated as ready at deployment.
actor.next_attack = self.now
actor.next_ai = self.now + self.ai_interval(u)
for slot, skill in enumerate(u.skills):
actor.cooldowns[slot] = self.now + (2000 if u.team == 2 else 0)
if self.now > 1 and u.ap_recovery:
self.add_ap(u.team, self.ap[u.team]["max"] * self.game["addApByJoinMon"], "join")
self.event("deploy", actor=u.key, team=u.team, wave=u.wave, x=actor.x, y=actor.y,
count_unit=u.count_unit, ap_charged=0)
@staticmethod
def ai_interval(unit):
# BattleMon.setAutoSkill explicitly changes the player Jumper to 30.
frames = 30 if unit.team == 1 and unit.ai == 1 else 20 if unit.ai == 4 else 60 if unit.ai == 3 else 100
return frames * 1000 // FPS
def target(self, actor):
u = actor.unit
choices = [b for b in self.active() if b.unit.team != u.team]
if u.attack_area:
area = self.s.areas[u.attack_area]
choices = [b for b in choices if area["x"] <= b.x <= area["x"] + area["w"]
and area["y"] <= b.y <= area["y"] + area["h"]]
auto = [b for b in choices if b.unit.auto_target]
choices = auto or choices
if not choices:
return None
chosen = min(choices, key=lambda b: (math.hypot(b.x - actor.x, b.y - actor.y), b.unit.key))
if u.ai_search >= 3:
near = [b for b in choices if math.hypot(b.x - actor.x, b.y - actor.y) < u.stats.attack_range * 1.2]
if near:
chosen = max(near, key=lambda b: b.unit.stats.atk)
wounded = [b for b in near if b.hp / b.unit.stats.hp < .2]
if u.ai_search >= 4 and wounded:
chosen = min(wounded, key=lambda b: b.hp / b.unit.stats.hp)
return chosen
def in_range(self, actor, target):
distance = actor.unit.stats.attack_range
return abs(target.x - actor.x) < distance and abs(target.y - actor.y) < distance * .5
def profile(self, actor):
attack_type = 28 if actor.combo_hits else actor.unit.attack_type
return self.tables["attack_profiles"].get(str(attack_type), self.tables["attack_profiles"]["1"])
def cast(self, actor, target):
if self.skill_used or actor.summon_of or actor.next_ai > self.now or actor.unit.ai_search == 0:
return False
if actor.unit.team != 1 and actor.unit.ai < 1:
return False
actor.next_ai = self.now + self.ai_interval(actor.unit)
for slot, skill in enumerate(actor.unit.skills):
if actor.cooldowns[slot] > self.now:
continue
if skill.id == 5:
willing = target is not None and math.hypot(target.x - actor.x, target.y - actor.y) > actor.unit.stats.attack_range * 2
else:
willing = self.rng.random() < {3: .15, 7: .2, 9: .2, 38: .25}[skill.id]
if not willing or not self.spend_ap(actor.unit.team, skill.cost, actor.unit.key, skill.id):
continue
reduction = actor.unit.effects.get("skillCooldown", 0)
actor.cooldowns[slot] = self.now + max(0, int(skill.cooldown_ms / (1 + reduction / 100)))
self.event("skill", actor=actor.unit.key, skill=skill.id, level=skill.level)
self.skill_used = True
if skill.id in (3, 7):
self.summon(actor, skill)
elif skill.id == 5 and target is not None:
# Source impulse is one initial speed; approximate the impulse
# with a single displacement. No damage/stat adjustment.
dx, dy = target.x - actor.x, target.y - actor.y
distance = math.hypot(dx, dy)
step = min(distance, _number(skill.para["speed"]))
if distance:
actor.x += step * dx / distance
actor.y += step * dy / distance
removed = [e for e in self.queue if e[2] == "impact" and e[3].get("target") == actor.unit.key and e[3].get("projectile")]
self.queue = [e for e in self.queue if e not in removed]
heapq.heapify(self.queue)
for item in removed:
self.event("projectile_lost", actor=item[3]["attacker"], target=actor.unit.key, reason="skill5")
self.event("dash", actor=actor.unit.key, x=actor.x, y=actor.y, lost_projectiles=len(removed))
elif skill.id == 9:
actor.area_hit = True
actor.next_attack = self.now
elif skill.id == 38:
actor.combo_hits = 4
actor.next_attack = self.now
return True
return False
def summon(self, parent, skill):
for index in range(3 if skill.id == 7 else 1):
if len(self.actors) >= MAX_UNITS:
self.resource_limited = True
self.anomaly("unit_resource_limit", parent=parent.unit.key)
return
ability = _number(skill.para["ability"])
base = parent.unit.stats
# Skill3 uses current HP, Skill7 scaleAbility resets scaled max HP.
hp = max(1, int((parent.hp if skill.id == 3 else base.hp) * ability))
# BattleMonVo.clone rebuilds speed from the original MonsterVo,
# then overwrites only atk/def/dex/range/crit from the battle copy.
new_stats = replace(base, hp=hp, atk=int(base.atk * ability),
defense=int(base.defense * ability), dex=int(base.dex * ability))
key = f"summon-{len(self.actors) + 1}"
unit = replace(parent.unit, key=key, stats=new_stats, skills=(), count_unit=False,
ap_recovery=False, position=100, ap_cost=1 if skill.id == 7 else parent.unit.ap_cost,
effects=_freeze({"deadBoom": parent.unit.effects.get("deadBoom", 0)}))
actor = Actor(unit, hp, parent.x, parent.y + (index - 1) * 4, "active", self.now,
summon_of=parent.unit.key, next_ai=self.now + 2000)
self.actors.append(actor)
self.by_key[key] = actor
self.event("summon", actor=key, parent=parent.unit.key, skill=skill.id, hp=hp,
atk=new_stats.atk, defense=new_stats.defense, dex=new_stats.dex, count_unit=False)
def heal(self, actor, amount, reason):
if actor.state != "active":
return
if actor.unit.team == 1 and int(amount) > 20000:
self.anomaly("+15overcure", points=19, actor=actor.unit.key, cure=int(amount), reason=reason)
amount = max(0, min(int(amount), actor.unit.stats.hp - actor.hp))
actor.hp += amount
actor.healed += amount
if amount:
self.event("heal", actor=actor.unit.key, amount=amount, hp=actor.hp, reason=reason)
def hurt(self, actor, amount, attacker, reason):
if actor.state != "active":
return 0
amount = max(0, int(int(amount) * (1 - actor.unit.stats.damage_reduction)))
lost = min(actor.hp, amount)
actor.hp -= lost
actor.total_hurt += amount
self.hp_lost[actor.unit.team] += lost
if actor.unit.boss_point == -1:
self.boss_points += lost
if attacker:
attacker.damage_dealt += lost
self.event("damage", actor=attacker.unit.key if attacker else None, target=actor.unit.key,
damage=amount, hp_lost=lost, hp=actor.hp, reason=reason)
if amount > 80000: # BattleMon.beHurt original threshold, no cap.
self.anomaly("+10overdamage", points=10, damage=amount, hurt_team=actor.unit.team,
actor=attacker.unit.key if attacker else None, target=actor.unit.key)
if actor.hp == 0:
actor.state = "dead"
actor.died_ms = self.now
if actor.unit.boss_point > 0:
self.boss_points += actor.unit.boss_point
if not actor.unit.is_object:
self.deaths[actor.unit.team] += 1
if actor.unit.team != 1 and not actor.unit.is_object:
self.all_kills[str(actor.unit.species)] += 1
if actor.unit.mode == 2:
self.kill_monster[str(actor.unit.species)] += 1
if actor.total_hurt == 0:
self.anomaly("+1k_cheatDead", points=1000, target=actor.unit.key)
self.event("death", actor=actor.unit.key, team=actor.unit.team, summon=bool(actor.summon_of))
self.complete_at = self.now + 1000 # Original delayed checkGameOver.
return amount
def impact(self, fields):
attacker = self.by_key[fields["attacker"]]
target = self.by_key[fields["target"]]
if target.state != "active" or (attacker.state != "active" and not fields.get("projectile")):
self.event("miss", actor=attacker.unit.key, target=target.unit.key, reason="dead_target_or_attacker")
return
attack = fields["atk"]
dex = attacker.unit.stats.dex
quarters = int((dex - target.unit.stats.dex) / 4)
crit = .02 + attacker.unit.stats.crit / 100 + (quarters / (quarters + 120) if quarters >= 0 else 0)
critical = self.rng.random() < crit
if critical:
attack = int(attack * self.game["critAdd"])
if attacker.combo_hits > 0 and attacker.state == "active":
skill = next(s for s in attacker.unit.skills if s.id == 38)
attack = int(attack * self.rng.uniform(skill.para["min"], skill.para["max"]))
attacker.combo_hits -= 1
if attacker.combo_hits:
attacker.next_attack = self.now + 50
if attacker.area_hit:
attacker.area_hit = False
skill = next(s for s in attacker.unit.skills if s.id == 9)
for other in list(self.active()):
if other is target or other.unit.team == attacker.unit.team:
continue
# findMonsByMonNear expands +/- w,h into a 2w by 2h box.
if abs(other.x - target.x) <= 150 and abs(other.y - target.y) <= 91:
self.apply_damage(attacker, other, int(attacker.unit.stats.atk * skill.para["areahurt"]), "skill9_area")
self.apply_damage(attacker, target, attack, "attack", critical=critical)
def apply_damage(self, attacker, target, attack, reason, critical=False):
stats = attacker.unit.stats
counter = self.tables["monster_setting"]["element"].get(str(stats.element), {}).get("counter")
if counter == target.unit.stats.element:
attack = int(attack * self.game["counterAdd"])
amount = damage_roll(attack, stats.dex, target.unit.stats, self.game, self.rng)
amount = self.hurt(target, amount, attacker, reason)
if reason != "attack":
return
effects = attacker.unit.effects
if target.state == "active" and self.rng.random() < effects.get("atkStun", 0) / 100:
target.stunned_until = self.now + int(effects.get("atkStunTime", 2) * 1000)
self.event("stun", actor=target.unit.key, until_ms=target.stunned_until)
if target.state == "active" and self.rng.random() < effects.get("atkPoi", 0) / 100:
target.poison_until = self.now + 5000
target.poison_at = self.now + 1000
target.poison_damage = int(effects.get("atkPoiDmg", 0))
self.event("poison", actor=target.unit.key, until_ms=target.poison_until, damage=target.poison_damage)
if self.rng.random() < target.unit.effects.get("defStun", 0) / 100:
attacker.stunned_until = self.now + int(target.unit.effects.get("defStunTime", 2) * 1000)
self.event("stun", actor=attacker.unit.key, until_ms=attacker.stunned_until)
thorn = target.unit.effects.get("thorns", 0)
if thorn > 0:
self.hurt(attacker, max(1, int(amount * thorn / 100)), None, "thorns")
if effects.get("atkVim", 0) > 0:
self.heal(attacker, amount * effects["atkVim"] / 100, "lifesteal")
def advance_waves(self):
for team in self.s.teams:
if team in self.wave_due:
if self.now >= self.wave_due[team]:
self.wave[team] += 1
del self.wave_due[team]
self.event("wave", team=team, wave=self.wave[team])
continue
current = self.wave[team]
relevant = [a for a in self.actors if a.unit.team == team and a.state != "dead"]
if any(a.unit.wave == current for a in relevant):
continue
if any(a.unit.wave == current + 1 for a in relevant):
self.wave_due[team] = self.now + 700
self.event("wave_wait", team=team, next_wave=current + 1, until_ms=self.now + 700)
def tick(self):
self.skill_used = False
if self.now >= self.next_ap:
for team in self.ap:
if self.ap[team]["current"] < self.ap[team]["max"]:
self.add_ap(team, 1, "clock")
self.next_ap += _int(self.game["apCD"])
self.advance_waves()
if self.now >= self.next_deploy:
self.deploy()
self.next_deploy = (self.now // 1000 + 1) * 1000
while self.queue and self.queue[0][0] <= self.now:
_, _, kind, fields = heapq.heappop(self.queue)
if kind == "impact":
self.impact(fields)
elif kind == "launch":
actor, target = self.by_key[fields["attacker"]], self.by_key[fields["target"]]
if actor.state != "active" or target.state != "active":
continue
if fields["projectile"]:
distance = math.hypot(target.x - actor.x, target.y - actor.y)
travel = max(0, int((distance - 30) / fields.pop("speed") * 1000 / FPS))
self.event("projectile", actor=actor.unit.key, target=target.unit.key, travel_ms=travel)
self.schedule(travel, "impact", **fields)
else:
self.impact(fields)
for actor in list(self.active()):
u = actor.unit
if actor.poison_until >= self.now and actor.poison_at and actor.poison_at <= self.now:
self.hurt(actor, actor.poison_damage, None, "poison")
actor.poison_at += 1000
if actor.state != "active":
continue
if u.effects.get("selfCure", 0) > 0 and self.now > actor.joined_ms and (self.now - actor.joined_ms) % 5000 == 0:
self.heal(actor, u.effects["selfCure"], "selfCure")
if u.is_object or u.ai_search == 0 or self.now < actor.busy_until or self.now < actor.stunned_until:
continue
target = self.target(actor)
if self.cast(actor, target):
continue
if target is None:
continue
if self.in_range(actor, target):
if self.now < actor.next_attack:
continue
profile = self.profile(actor)
recovery = 150 if actor.combo_hits else 300
delay = profile["hit_delay_ms"]
actor.next_attack = self.now + max(1, int(u.stats.attack_ms))
actor.busy_until = self.now + delay + recovery
self.event("attack", actor=u.key, target=target.unit.key, hit_delay_ms=delay)
self.schedule(delay, "launch", attacker=u.key, target=target.unit.key,
atk=u.stats.atk, projectile=profile["projectile"], speed=profile["projectile_speed"])
elif not u.move_immune:
dx, dy = target.x - actor.x, target.y - actor.y
distance = math.hypot(dx, dy)
# Source Pointer.Point2Point uses spd_mov per frame.
step = min(distance, u.stats.move_speed)
if distance:
actor.x += step * dx / distance
actor.y += step * dy / distance
if self.now % 1000 == 0:
self.event("move", actor=u.key, target=target.unit.key, x=actor.x, y=actor.y)
def result(self, outcome, timeout_kind=None):
result = dict(self.report)
completed = outcome in ("win", "loss")
result.update(outcome=outcome, elapsed_ms=self.now, elapsed_seconds=self.now / 1000,
execution_status="completed" if completed else "cancelled" if outcome == "cancelled" else "error" if outcome == "error" else "timed_out",
terminal=completed, terminal_reason="elimination" if completed else timeout_kind or outcome,
units=[dict(_unit_preview(a.unit), hp=a.hp, x=a.x, y=a.y, state=a.state,
joined_ms=a.joined_ms, died_ms=a.died_ms, summon_of=a.summon_of,
damage_dealt=a.damage_dealt, total_hurt=a.total_hurt, healed=a.healed)
for a in self.actors],
events=self.events, trace_truncated=bool(self.omitted_events), omitted_events=self.omitted_events,
ap={str(k): v for k, v in self.ap.items()}, kills=sum(self.all_kills.values()),
all_kills=dict(self.all_kills), kill_monster=dict(self.kill_monster),
deaths={str(k): v for k, v in self.deaths.items()},
damage_hp_lost={str(k): v for k, v in self.hp_lost.items()},
anomalies=self.anomalies,
alive_num=len(self.living(1)), timeout_kind=timeout_kind,
source_field_notes={"killMonster": "non-player, non-object, mode==2 deaths (including summons)",
"aliveNum": "waiting plus active non-object player units, including summons",
"totalDamage": "declared AS3 int default 0; no source updates located",
"killNum": "declared AS3 int default 0; no source updates located",
"deadNum": "declared AS3 int default 0; no source updates located"})
if outcome in ("win", "loss"):
result["battle_data"] = {"win": outcome == "win", "leftTime": max(0, self.s.duration_ms - self.now),
"aliveNum": result["alive_num"], "apLeft": self.ap[1]["current"],
"battleMonIds": list(self.s.roster_ids),
"killMonster": dict(self.kill_monster), "killNum": 0, "deadNum": 0, "totalDamage": 0,
"bossDamage": self.boss_points,
"cheatNum": sum(r["source_cheat_points"] for r in self.anomalies),
"cheatRecords": _plain(self.anomalies)}
if self.s.position is not None:
result["battle_data"]["battlePosition"] = self.s.position
result["experimental_eligibility_reasons"] = []
if self.anomalies:
result["experimental_eligibility_reasons"].append("Detected model anomalies must be reviewed")
if not result["supported"] or result.get("reasons"):
result["experimental_eligibility_reasons"].append("Unresolved original combat inputs")
result["experimental_settlement_eligible"] = not result["experimental_eligibility_reasons"]
return result
def simulate(request, *, cancel_event=None, timeout=30.0, tables=None):
"""Execute a seeded offline model directly. Runtime.run isolates CPU work.
``timeout`` is wall-clock seconds; original ``battle.time`` independently
controls modeled battle expiry. Neither path synthesizes a win.
"""
started = time.monotonic()
timeout = _number(timeout, "timeout")
if timeout < 0:
raise SimulationInputError("timeout must be nonnegative")
tables = tables if tables is not None else combat_tables()
scenario, report = _prepare(request, tables)
if not report["supported"]:
return dict(report, outcome="unsupported", elapsed_ms=0, elapsed_seconds=0,
execution_status="unsupported", terminal=False, terminal_reason="unsupported_scenario",
events=[], units=report.get("units", []))
battle = _Battle(scenario, report, tables)
for tick in range(min(scenario.duration_ms // (1000 // FPS) + 1, 180001)):
battle.now = tick * 1000 // FPS
if cancel_event is not None and cancel_event.is_set():
return battle.result("cancelled")
if time.monotonic() - started >= timeout:
return battle.result("timeout", "wall_clock")
if battle.now >= scenario.duration_ms:
battle.event("complete", outcome="loss", reason="battle_time_limit")
result = battle.result("loss")
result["terminal_reason"] = "battle_time_limit"
return result
try:
battle.tick()
except Exception as exc:
result = battle.result("error")
result["terminal_reason"] = "model_execution_failure"
result["diagnostics"] = list(result["diagnostics"]) + [{"code": "execution", "message": type(exc).__name__}]
return result # Keep every anomaly and partial trajectory already observed.
if battle.resource_limited:
return battle.result("timeout", "resource_limit")
if battle.complete_at is not None and battle.now >= battle.complete_at:
if not battle.terminal_team_size(1):
battle.event("complete", outcome="loss")
return battle.result("loss")
if not any(battle.terminal_team_size(team) for team in scenario.teams if team != 1):
battle.event("complete", outcome="win")
return battle.result("win")
return battle.result("timeout", "resource_limit")
def _transport_request(request):
"""Send combat inputs only, not login credentials or the account envelope."""
raw = _get(request, "roster", _get(request, "snapshot"))
raw = _get(raw, "raw", raw)
if isinstance(raw, Mapping):
raw = {k: _plain(raw[k]) for k in ("master", "monsters", "teams", "monsterAttributes") if k in raw}
if isinstance(raw.get("master"), dict):
raw["master"] = {k: v for k, v in raw["master"].items()
if k in ("level", "globalAtk", "globalDef", "globalHp", "globalDex")}
original = _get(request, "original_data", {})
return {"context": _get(request, "context"), "original_data": {"battle": _plain(_get(original, "battle"))},
"roster": raw, "team": _get(request, "team", "teamA"),
"seed": _get(request, "seed", 0), "trace_limit": _get(request, "trace_limit", 2000),
"battle_position": _position(_get(request, "battle_position"))}
def _execution_failure(outcome, reason, *, supported=True):
return dict(_envelope(), supported=supported, outcome=outcome,
execution_status="cancelled" if outcome == "cancelled" else "timed_out" if outcome == "timeout" else "error",
terminal=False, terminal_reason=reason, timeout_kind="wall_clock" if outcome == "timeout" else None,
elapsed_ms=None, elapsed_seconds=None, events=[], units=[],
diagnostics=[{"code": "execution", "message": reason}])
class ExperimentalBattleRuntime:
"""Offline experimental adapter. run always executes a fixed worker module.
supported means this approximate model is runnable, not server settlement
eligibility. Calls do not mutate the request, cache, or input snapshot.
"""
def inspect(self, request):
try:
_, report = _prepare(request, combat_tables())
return report
except SimulationInputError as exc:
result = _envelope()
return dict(result, supported=False, reasons=[str(exc)],
diagnostics=[{"code": "static_data", "message": str(exc)}])
def run(self, request, *, cancel_event=None, timeout=30.0):
timeout = _number(timeout, "timeout")
if timeout < 0:
raise SimulationInputError("timeout must be nonnegative")
if cancel_event is not None and cancel_event.is_set():
return _execution_failure("cancelled", "cancelled_before_worker")
if timeout == 0:
return _execution_failure("timeout", "worker_wall_clock_limit")
try:
wire = json.dumps({"request": _transport_request(request), "timeout": timeout},
ensure_ascii=True, allow_nan=False, separators=(",", ":")).encode("utf-8")
except (TypeError, ValueError):
return _execution_failure("error", "request_is_not_serializable", supported=False)
if len(wire) > MAX_WIRE_BYTES:
return _execution_failure("error", "request_exceeds_worker_input_limit", supported=False)
started = time.monotonic()
process = None
try:
process = subprocess.Popen(
[sys.executable, "-m", "ranch_assistant.battle_simulator", "--worker"],
cwd=str(Path(__file__).resolve().parent.parent),
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
)
pending_input = wire
while True:
if cancel_event is not None and cancel_event.is_set():
return _execution_failure("cancelled", "worker_cancelled")
left = timeout - (time.monotonic() - started)
if left <= 0:
return _execution_failure("timeout", "worker_wall_clock_limit")
try:
stdout, stderr = process.communicate(input=pending_input, timeout=min(.05, left))
break
except subprocess.TimeoutExpired:
pending_input = None
if len(stdout) > MAX_WIRE_BYTES or len(stderr) > 65536:
return _execution_failure("error", "worker_output_exceeds_limit")
result = json.loads(stdout)
if not isinstance(result, dict) or result.get("execution_mode") != "experimental" or result.get("faithful") is not False:
return _execution_failure("error", "invalid_worker_result")
if process.returncode != 0 and result.get("outcome") != "error":
return _execution_failure("error", "worker_exited_unsuccessfully")
return result
except KeyboardInterrupt:
return _execution_failure("cancelled", "worker_interrupted")
except (OSError, ValueError):
return _execution_failure("error", "worker_transport_failure")
finally:
if process is not None:
if process.poll() is None:
process.kill()
# communicate drains/joins the killed child and closes all pipes.
process.communicate()
def _offline_audit(event, args):
if event.startswith("socket.") or event == "urllib.Request":
raise PermissionError("Network access is forbidden in the combat worker")
def _worker():
sys.addaudithook(_offline_audit)
try:
wire = sys.stdin.buffer.read(MAX_WIRE_BYTES + 1)
if len(wire) > MAX_WIRE_BYTES:
raise SimulationInputError("Worker input exceeds limit")
payload = json.loads(wire)
result = simulate(payload["request"], timeout=payload.get("timeout", 30.0))
if result.get("outcome") == "unsupported":
result.update(execution_status="unsupported", terminal=False, terminal_reason="unsupported_scenario")
encoded = json.dumps(result, ensure_ascii=True, allow_nan=False,
separators=(",", ":")).encode("utf-8")
if len(encoded) > MAX_WIRE_BYTES:
# Do not discard anomaly records to fit a successful result.
raise SimulationInputError("Worker result exceeds transport limit")
sys.stdout.buffer.write(encoded)
return 0
except Exception as exc:
result = _execution_failure("error", f"worker_failure:{type(exc).__name__}")
sys.stdout.buffer.write(json.dumps(result, ensure_ascii=True).encode("utf-8"))
return 1
if __name__ == "__main__":
if sys.argv[1:] != ["--worker"]:
raise SystemExit("Use ExperimentalBattleRuntime or --worker (one JSON stdin request)")
raise SystemExit(_worker())