"""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 DEFAULT_DAMAGE_PROFILE = "original_1x" DESKTOP_DAMAGE_PROFILE = "client_v4_x10" 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.", "Attack knockback, cosmetic equipment animations and special equipment words are omitted.", "Python seeded RNG is not the original Random helper or Math.random stream.", "Mining supports destroy-all/protect-all objectives, fixed hurt, target locks and timed joins; other controllers and triggers 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 DAMAGE_PROFILES = _freeze({ DEFAULT_DAMAGE_PROFILE: {"multiplier": 1, "cap": None}, DESKTOP_DAMAGE_PROFILE: {"multiplier": 10, "cap": 50000}, }) DAMAGE_PROFILE_DIGESTS = _freeze({name: hashlib.sha256(json.dumps( {"name": name, **config}, sort_keys=True, separators=(",", ":")).encode("ascii")).hexdigest() for name, config in DAMAGE_PROFILES.items()}) 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 _damage_profile(request): name = _get(request, "damage_profile", DEFAULT_DAMAGE_PROFILE) if not isinstance(name, str) or name not in DAMAGE_PROFILES: raise SimulationInputError("Unknown damage profile") return name, DAMAGE_PROFILES[name] def _damage_profile_report(name, config): return {"damage_profile": name, "damage_multiplier": config["multiplier"], "damage_cap": config["cap"], "damage_profile_digest": DAMAGE_PROFILE_DIGESTS[name], "damage_profile_scope": "team1 attacker to team2 target, after hurt controllers and before HP deduction" if name == DESKTOP_DAMAGE_PROFILE else "unchanged original final damage"} 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 = "" protect_target: bool = False destroy_target: bool = False pow_defense: float = 0 hurt_types: Mapping = field(default_factory=dict) hurt_elements: Mapping = field(default_factory=dict) lock_target: 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 force_join: bool = False vx: float = 0 vy: float = 0 locked_target: str = "" 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") hurt_types, hurt_elements = {}, {} for controller in mon.get("controller", ()) or (): if _get(controller, "type") == "fixHurt": para = _get(controller, "para", {}) hurt_types = {str(k): _number(v) for k, v in para.get("type", {}).items()} hurt_elements = {str(k): _number(v) for k, v in para.get("element", {}).items()} 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", "")), protect_target=mon.get("protectTarget") is True, destroy_target=mon.get("destroyTarget") is True, pow_defense=_number(mon.get("powDefPercent", 0)), hurt_types=_freeze(hurt_types), hurt_elements=_freeze(hurt_elements), lock_target=next((str(_get(c, "para", {}).get("mid", "")) for c in mon.get("controller", ()) or () if _get(c, "type") == "lockTarget"), "")) def _mining_trigger(entry, unit_mids): """Return an immutable trigger, or a precise unsupported reason.""" kind = _get(entry, "type", "unknown") para = _get(entry, "para", {}) if not isinstance(para, Mapping) or not isinstance(_get(entry, "effects"), list): return None, "Malformed mining battle trigger" if kind == "monDead": if _int(para.get("mid", -1)) not in unit_mids: return None, "Mining monDead trigger references an unknown unit" if any(_get(effect, "type") != "showFace" for effect in entry["effects"]): return None, "Only visual showFace effects are supported for mining monDead" elif kind == "time": if _int(para.get("time", -1)) <= 0 or para.get("loop") is True: return None, "Mining time trigger requires a positive non-looping time" for effect in entry["effects"]: if _get(effect, "type") == "showFace": continue effect_para = _get(effect, "para", {}) if (_get(effect, "type") != "monJoin" or not isinstance(effect_para, Mapping) or _int(effect_para.get("mid", -1)) not in unit_mids): return None, "Only showFace and configured monJoin are supported for mining time" else: return None, "Unsupported mining battle trigger: " + str(kind) return _freeze({"id": str(_get(entry, "id", "")), "type": kind, "para": para, "effects": entry["effects"]}), None @dataclass class Scenario: units: list teams: dict points: dict areas: dict duration_ms: int seed: int trace_limit: int position: object roster_ids: tuple win_types: tuple = (1,) lose_types: tuple = (1, 2) triggers: tuple = () def _prepare(request, tables, *, quick=False): report = _envelope() report.update(supported=False, reasons=[], implemented_skills=sorted(KNOWN_SKILLS)) def diagnostic(code, message, *, ignored=False, blocking=False): if quick and code in ("objective", "controller", "triggers", "unit_controller", "unit_objective", "field_effect", "cosmetic_controller"): record = {"code": "aggregate_approximation", "mechanic": code, "message": message} if record not in report["diagnostics"]: report["diagnostics"].append(record) return 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: profile_name, profile_config = _damage_profile(request) report.update(_damage_profile_report(profile_name, profile_config)) 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") win_types = tuple(map(_int, battle.get("winType", (1,)))) lose_types = tuple(map(_int, battle.get("loseType", (1, 2)))) mining = win_types == (4,) if not mining and (win_types != (1,) or any(x not in (1, 2) for x in lose_types)): diagnostic("objective", "Non-elimination win/loss objective is unsupported", blocking=True) if mining and lose_types != (4, 2): diagnostic("objective", "Mining requires exact winType=[4] and loseType=[4,2]", blocking=True) for entry in battle.get("controller", ()) or (): diagnostic("controller", f"Unsupported battle controller: {_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. configured_mons = [(team, mon) for team in battle.get("teams", ()) for mon in team.get("mons", ()) if mon is not None] # AS3 int('') is zero for an authored default mid; keep stat parsing strict. unit_mids = {_int(0 if mon.get("mid") == "" else mon.get("mid", -1)) for _, mon in configured_mons} triggers = [] for entry in battle.get("triggers", ()) or (): if mining: parsed, reason = _mining_trigger(entry, unit_mids) if reason: diagnostic("triggers", reason, blocking=True) else: triggers.append(parsed) else: diagnostic("triggers", f"Unsupported battle triggers: {_get(entry, 'type', 'unknown')}", blocking=True) 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) elif mining and kind in ("fixHurt", "lockTarget"): if not isinstance(para, Mapping): diagnostic("unit_controller", f"Malformed mining controller: {kind}", blocking=True) elif kind == "lockTarget": if _int(para.get("mid", -1)) not in unit_mids: diagnostic("unit_controller", "Mining lockTarget references an unknown unit", blocking=True) if para.get("interval") is not None and _number(para["interval"]) <= 0: diagnostic("unit_controller", "Mining lockTarget interval must be positive", blocking=True) else: diagnostic("unit_controller", f"Unsupported monster controller: {kind}", blocking=True) if mon.get("protectTarget") or mon.get("destroyTarget"): if not mining: diagnostic("unit_objective", "Protected/destroy objective units are unsupported", blocking=True) elif mon.get("protectTarget") and mon.get("destroyTarget"): diagnostic("unit_objective", "Mining target cannot be both protected and destroyed", 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 mining: if not any(u.destroy_target for u in units) or not any(u.protect_target for u in units): diagnostic("unit_objective", "Mining requires actual destroy and protect target units", blocking=True) elif not quick and 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 if quick else team["capacity"] <= 0) or team["initial"] < 0: raise SimulationInputError("Original team capacity/AP is invalid") field_config = battle.get("battleField") if quick and not isinstance(field_config, Mapping): field_config = {} 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 and not quick: raise SimulationInputError("Unknown original default battlefield") field_config = dict(original_field or {}, mapObjects=field_config.get("mapObjects", ()), mapAreas=tuple((original_field or {}).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 not quick and ("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") not in (("none", "pow") if mining else ("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 not quick and u.attack_area and u.attack_area not in areas: raise SimulationInputError("Configured attackArea is absent from original battlefield") if not quick and 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 quick and 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"] report["objective"] = "destroy_all_protect_until_none" if mining else "elimination" 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 (), win_types, lose_types, tuple(triggers)), 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, "auto_target": unit.auto_target, "source_id": unit.source_id, "protect_target": unit.protect_target, "destroy_target": unit.destroy_target, "lock_target": unit.lock_target} def _snapshot_anomalies(mon, unit, tables): """Check source input bounds, using the cultivation potential cap. 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)) 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) # PotentialPanel.as:102,245 uses cultivation, not TP level. The old # BattlePanel.cheatCheck bound can reject normally cultivated values. max_potential = potential.get(stat, 0) + potential.get(stat + "TpAdd", 0) * (potential_level - 1) 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.damage_profile = report["damage_profile"] self.damage_config = DAMAGE_PROFILES[self.damage_profile] 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.unlocked_waves = {team: {0, 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 self.pending_triggers = list(scenario.triggers) self.by_source_id = {a.unit.source_id: a for a in self.actors if a.unit.source_id} self.next_area = 0 self.area_due = {key: 0 for key in scenario.areas} def event(self, kind, **fields): record = {"at_ms": self.now, "type": kind, **fields} if kind == "damage": record.update(damage_profile=self.damage_profile, damage_cap=self.damage_config["cap"]) 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 check_objectives(self): """BattleGround.checkGameOver's original winner precedence.""" if self.now >= self.s.duration_ms: return "win" if 2 in self.s.win_types else "loss" mining = self.s.win_types == (4,) team_one_alive = sum(a.unit.team == 1 and a.state != "dead" for a in self.actors) if mining else self.terminal_team_size(1) if not team_one_alive: return "loss" if not mining and not any(self.terminal_team_size(team) for team in self.s.teams if team != 1): return "win" protected = [a for a in self.actors if a.unit.protect_target] if 4 in self.s.lose_types and protected and all(a.state == "dead" for a in protected): return "loss" destroyed = [a for a in self.actors if a.unit.destroy_target] if 4 in self.s.win_types and destroyed and all(a.state == "dead" for a in destroyed): return "win" return None 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 not actor.force_join and u.wave not in self.unlocked_waves[u.team] or not actor.force_join and 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) if actor.unit.lock_target: actor.locked_target = actor.unit.lock_target @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 if actor.locked_target: locked = self.by_source_id.get(actor.locked_target) if locked is not None and locked.state == "active" and locked.hp > 0: return locked actor.locked_target = "" 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, real_attack=False): if actor.state != "active": return 0 # beHurt passes the attack value (its atk argument) to onHurt at line # 902, despite onHurt naming that parameter damage. For real attacks # there is no GameMath.damage call before this controller. element = str(attacker.unit.stats.element) if attacker else "" if element in actor.unit.hurt_types and element in actor.unit.hurt_elements: amount = int(amount * actor.unit.hurt_elements[element]) elif attacker and str(attacker.unit.species) in actor.unit.hurt_types: amount = int(amount * actor.unit.hurt_types[str(attacker.unit.species)]) if real_attack: amount = max(0, int(amount * (1 - actor.unit.stats.damage_reduction))) amount = self.final_damage(amount, attacker, actor) 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: 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: self.finish_death(actor) return amount amount = max(0, int(int(amount) * (1 - actor.unit.stats.damage_reduction))) amount = self.final_damage(amount, attacker, actor) 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: self.finish_death(actor) return amount def final_damage(self, amount, attacker, actor): """V4's insertion: after every existing modifier, immediately before HP loss.""" if (self.damage_profile == DESKTOP_DAMAGE_PROFILE and attacker is not None and attacker.unit.team == 1 and actor.unit.team == 2): return int(min(amount * self.damage_config["multiplier"], self.damage_config["cap"])) return amount def finish_death(self, actor): 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)) remaining = [] for trigger in self.pending_triggers: if trigger["type"] == "monDead" and _int(trigger["para"]["mid"]) == _int(actor.unit.source_id): self.event("trigger", trigger_kind="monDead", trigger=trigger["id"], actor=actor.unit.key, effects="visual_only") else: remaining.append(trigger) self.pending_triggers = remaining self.complete_at = self.now + 1000 # Original delayed checkGameOver. 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]: current = self.wave[team] waves = [a.unit.wave for a in self.actors if a.unit.team == team and a.state != "dead" and not a.unit.is_object and a.unit.wave > current] self.wave[team] = min(waves) if waves else current + 1 self.unlocked_waves[team].update(range(current + 1, 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" and not a.unit.is_object] if any(a.unit.wave == current for a in relevant): continue next_waves = [a.unit.wave for a in relevant if a.unit.wave > current] if next_waves: next_wave = min(next_waves) self.wave_due[team] = self.now + 700 self.event("wave_wait", team=team, next_wave=next_wave, until_ms=self.now + 700) def advance_triggers(self): """SecondDriver checks elapsed seconds once; trigger removal prevents repeats.""" if self.now % 1000: return remaining = [] for trigger in self.pending_triggers: if trigger["type"] == "time" and _int(trigger["para"]["time"]) * 1000 <= self.now: for effect in trigger["effects"]: if effect.get("type") == "monJoin": target = self.by_source_id.get(str(_int(effect["para"]["mid"]))) if target is not None and target.state != "dead": target.force_join = True self.event("trigger", trigger_kind="time", trigger=trigger["id"], effect="monJoin", actor=target.unit.key) self.event("trigger", trigger_kind="time", trigger=trigger["id"]) else: remaining.append(trigger) self.pending_triggers = remaining def advance_areas(self): if self.now < self.next_area: return self.next_area = self.now + 125 for key, area in self.s.areas.items(): if area.get("type") != "pow" or self.now < self.area_due[key]: continue self.area_due[key] = self.now + _int(area["para"].get("interval", 0)) for actor in self.active(): if not (area["x"] <= actor.x <= area["x"] + area["w"] and area["y"] <= actor.y <= area["y"] + area["h"]): continue if actor.unit.move_immune: continue # BattleMon.givePow returns before changing velocity. para = area["para"] power = _number(para["pow"]) * .8 * (1 - actor.unit.pow_defense) dx, dy = actor.x - _number(para.get("fromX", actor.x)), actor.y - _number(para.get("fromY", actor.y)) length = math.hypot(dx, dy) if length: actor.vx, actor.vy = power * dx / length, power * dy / length self.event("area_pow", actor=actor.unit.key, area=key, vx=actor.vx, vy=actor.vy) 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 self.advance_triggers() self.advance_areas() 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 not u.move_immune and (actor.vx or actor.vy): # Engine2D's existing damping is retained as a trajectory # approximation; movement resumes once inertia has decayed. actor.x += actor.vx actor.y += actor.vy actor.vx *= .91 actor.vy *= .91 if abs(actor.vx) + abs(actor.vy) < .01: actor.vx = actor.vy = 0 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 and not (actor.vx or actor.vy): 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: outcome = battle.check_objectives() battle.event("complete", outcome=outcome, reason="battle_time_limit") result = battle.result(outcome) 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: outcome = battle.check_objectives() if outcome: reason = "battle_time_limit" if battle.now >= scenario.duration_ms else ( "elimination" if 1 in scenario.win_types else "objective") battle.event("complete", outcome=outcome, reason=reason) result = battle.result(outcome) result["terminal_reason"] = reason return result 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"), "damage_profile": _damage_profile(request)[0], "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: """Fast aggregate adapter. run always executes a fixed offline 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: from .battle_quick import prepare _, 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): import tempfile 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: # POSIX communicate(None) retries do not resume a partial stdin write. # A bounded, rewound file gives the child all input and EOF once; # its inherited handle remains valid after the parent closes its copy. with tempfile.TemporaryFile(mode="w+b") as input_stream: input_stream.write(wire) input_stream.seek(0) process = subprocess.Popen( [sys.executable, "-m", "ranch_assistant.battle_simulator", "--worker"], cwd=str(Path(__file__).resolve().parent.parent), stdin=input_stream, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), ) 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(timeout=min(.05, left)) break except subprocess.TimeoutExpired: pass 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) from .battle_quick import simulate_quick result = simulate_quick(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())