Add offline battle estimates and passive phone sample analysis

This commit is contained in:
AttilaNet
2026-11-08 16:50:14 +08:00
parent 45a7f2dfa4
commit 79b7672471
10 changed files with 1142 additions and 5 deletions
+285
View File
@@ -0,0 +1,285 @@
"""Offline basic-attack estimates from the original APK, without game API access.
This is an explicitly approximate predictor, not an implementation of the
original battle runtime or a producer of server settlement payloads.
"""
from collections import defaultdict
from dataclasses import asdict, dataclass
import argparse
import json
import math
from pathlib import Path
import random
import statistics
import sys
import zipfile
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from tools.research_battle_v12 import recover_table
LIMITATIONS = [
"Skills, summons, buffs, healing, shields and equipment effects are not simulated.",
"Movement, range, collision, projectile travel and animation callbacks are not simulated.",
"Units attack the first living enemy; same-time hits resolve simultaneously.",
"The selected player roster starts deployed; AP and player deployment limits are not simulated.",
"First hits and reinforcements use the attack interval as their initial delay.",
"Random.number ranges are sampled uniformly; the original RNG helper has not been replayed.",
"Only elimination battles with explicit enemy stats and no controllers/triggers are admitted.",
"Durations and win fractions describe this model; they have not been calibrated against gameplay.",
]
class UnsupportedScenario(ValueError):
pass
@dataclass(frozen=True)
class Fighter:
species: int
name: str
hp: int
atk: int
defense: int
dex: int
attack_ms: int
element: int = 5
crit: float = 0
wave: int = 1
instance_id: int | None = None
def __post_init__(self):
for field in ("species", "hp", "atk", "defense", "dex", "attack_ms", "element", "wave"):
value = getattr(self, field)
if type(value) is not int or value < (1 if field in ("species", "hp", "attack_ms", "wave") else 0):
raise ValueError(f"Invalid fighter {field}: {value!r}")
if not isinstance(self.crit, (int, float)) or not math.isfinite(self.crit):
raise ValueError("Invalid crit")
if self.instance_id is not None and (type(self.instance_id) is not int or self.instance_id <= 0):
raise ValueError("Invalid instance_id")
@dataclass(frozen=True)
class Rules:
damage_per_atk: float
guard_per_def: float
crit_add: float
counter_add: float
counters: dict
def hit_damage(attacker, defender, rules, rng):
"""Port the ordinary GameMath roll, retaining int coercion and Math.round."""
dex_quarters = int((attacker.dex - defender.dex) / 4)
critical_chance = .02 + attacker.crit / 100
if dex_quarters >= 0:
critical_chance += dex_quarters / (dex_quarters + 120)
attack = attacker.atk
if rng.random() < critical_chance:
attack = int(attack * rules.crit_add)
if rules.counters.get(attacker.element) == defender.element:
attack = int(attack * rules.counter_add)
delta = min(80, max(-80, attacker.dex - defender.dex))
low = .8 + .3 * max(0, delta) / 80
high = 1.2 + .3 * min(0, delta) / 80
value = attack * rules.damage_per_atk * rng.uniform(low, high)
value -= defender.defense * (rules.guard_per_def * .75 + rng.uniform(0, rules.guard_per_def * .25))
return max(1, math.floor(value + .5))
def simulate(players, enemies, rules, *, seed, timeout_ms, enemy_capacity):
"""Resolve basic attacks across enemy waves; never mutates its input roster."""
if not players or not enemies:
raise ValueError("Both teams must contain units")
if type(timeout_ms) is not int or timeout_ms <= 0 or type(enemy_capacity) is not int or enemy_capacity <= 0:
raise ValueError("Invalid timeout or enemy deployment capacity")
rng = random.Random(seed)
player_hp = [p.hp for p in players]
now, hits, damage, enemy_kills = 0, 0, 0, 0
waves = sorted({e.wave for e in enemies})
def result(outcome):
return {"predicted_outcome": outcome, "model_duration_seconds": now / 1000,
"player_survivors": sum(hp > 0 for hp in player_hp), "enemy_kills": enemy_kills,
"player_damage": damage, "resolved_hits": hits}
for wave_index, wave in enumerate(waves):
if wave_index:
now = min(timeout_ms, now + 700)
if now >= timeout_ms:
return result("timeout")
waiting = [i for i, e in enumerate(enemies) if e.wave == wave]
enemy_hp = {i: enemies[i].hp for i in waiting}
active, enemy_ready = [], {}
player_ready = {i: now + p.attack_ms for i, p in enumerate(players) if player_hp[i] > 0}
def fill_enemy_slots():
while waiting and len(active) < enemy_capacity:
i = waiting.pop(0)
active.append(i)
enemy_ready[i] = now + enemies[i].attack_ms
fill_enemy_slots()
while active:
living = [i for i, hp in enumerate(player_hp) if hp > 0]
if not living:
return result("loss")
next_hit = min([player_ready[i] for i in living] + [enemy_ready[i] for i in active])
if next_hit >= timeout_ms:
now = timeout_ms
return result("timeout")
now = next_hit
to_enemy, to_player = defaultdict(int), defaultdict(int)
for i in living:
if player_ready[i] == now:
target = active[0]
to_enemy[target] += hit_damage(players[i], enemies[target], rules, rng)
player_ready[i] += players[i].attack_ms
hits += 1
for i in active:
if enemy_ready[i] == now:
target = living[0]
to_player[target] += hit_damage(enemies[i], players[target], rules, rng)
enemy_ready[i] += enemies[i].attack_ms
hits += 1
for i, hurt in to_enemy.items():
damage += min(enemy_hp[i], hurt)
enemy_hp[i] = max(0, enemy_hp[i] - hurt)
if enemy_hp[i] == 0:
enemy_kills += 1
for i, hurt in to_player.items():
player_hp[i] = max(0, player_hp[i] - hurt)
active[:] = [i for i in active if enemy_hp[i] > 0]
if not any(player_hp):
return result("loss")
fill_enemy_slots()
return result("win")
def demo_player(row, level):
"""A synthetic example at mean growth, not the user's account monster."""
if type(level) is not int or level < 1:
raise ValueError("Invalid example level")
stats = {stat: int(float(row[stat]) + (float(row[stat + "_grow_min"]) + float(row[stat + "_grow_max"])) / 2 * (level - 1))
for stat in ("atk", "def", "hp", "dex")}
return Fighter(int(row["type"]), row["name"], stats["hp"], stats["atk"], stats["def"], stats["dex"],
int(float(row["spd_atk"]) + int(-stats["dex"] * 3 / 4)), element=int(row["element"]))
def load_scenario(apk, stage_id, difficulty):
tables, fingerprints = {}, {}
with zipfile.ZipFile(apk) as archive:
for name in ("stage_info", "monster_info", "monster_setting", "game_setting"):
value, fingerprints[name] = recover_table(archive, name)
tables[name] = value.get("datas", value) if isinstance(value, dict) else value
stage = next((s for s in tables["stage_info"] if str(s["id"]) == stage_id), None)
if stage is None or difficulty not in stage.get("level", {}):
raise ValueError("Unknown stage or difficulty")
battle = stage["level"][difficulty].get("battle") or {}
if not battle:
raise UnsupportedScenario("No nonempty battle configuration")
if battle.get("hideTeamMon") or battle.get("controller") or battle.get("triggers"):
raise UnsupportedScenario("This scenario requires hidden teams, controllers or triggers")
if {int(x) for x in battle.get("winType", [])} != {1} or set(map(int, battle.get("loseType", []))) - {1, 2}:
raise UnsupportedScenario("This predictor supports elimination battles only")
if len(battle.get("teams", [])) != 1:
raise UnsupportedScenario("This predictor supports one enemy faction only")
enemy_team = battle["teams"][0]
ability_scale = float(battle.get("scaleAbility", 1))
hp_scale = float(battle.get("scaleHp", 1))
enemies, skills = [], set()
for mon in enemy_team["mons"]:
if (mon.get("autoValue") or mon.get("controller") or mon.get("isObject") or mon.get("protectTarget")
or mon.get("destroyTarget") or float(mon.get("joinTime", -1)) >= 0):
raise UnsupportedScenario("An enemy requires generated stats, timed spawning or a special mechanic")
row = tables["monster_info"][str(mon["type"])]
for slot in (1, 2):
skill = int(mon.get(f"skill_{slot}", -1))
skills.add(int(row.get(f"skill_{slot}", 0)) if skill < 0 else skill)
enemies.append(Fighter(int(mon["type"]), row["name"], int(float(mon["hp"]) * hp_scale),
int(float(mon["atk"]) * ability_scale), int(float(mon["def"]) * ability_scale),
int(float(mon["dex"]) * ability_scale), int(float(mon["spd_atk"])),
element=int(row["element"]), crit=float(mon.get("crit", 0)), wave=int(mon.get("wave", 1))))
game = tables["game_setting"]
rules = Rules(float(game["countDamagePerAtk"]), float(game["countGuardPerDef"]),
float(game["critAdd"]), float(game["counterAdd"]),
{int(k): int(v["counter"]) for k, v in tables["monster_setting"]["element"].items()})
seconds = int(battle.get("time", -1))
timeout = int(game["normalBattleTime"]) if seconds < 0 else seconds
return tables, fingerprints, stage, enemies, rules, timeout * 1000, int(enemy_team["numMax"]), skills - {0}
def describe(values):
values = sorted(values)
return {"count": len(values), "min": values[0], "median": statistics.median(values),
"p10": values[round((len(values) - 1) * .1)], "p90": values[round((len(values) - 1) * .9)], "max": values[-1]}
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--apk", type=Path)
parser.add_argument("--stage", default="0101")
parser.add_argument("--difficulty", choices=("1", "2", "3"), default="1")
parser.add_argument("--team", type=Path, help="Local JSON array of already calculated Fighter combat attributes")
parser.add_argument("--players", type=int, choices=range(1, 7), default=3)
parser.add_argument("--species", default="1001010")
parser.add_argument("--level", type=int, default=1, help="Level of synthetic catalog examples only")
parser.add_argument("--trials", type=int, default=100)
parser.add_argument("--seed", type=int, default=1)
parser.add_argument("--output", type=Path)
args = parser.parse_args(argv)
if not 1 <= args.trials <= 10000:
parser.error("trials must be between 1 and 10000")
try:
if args.apk is None:
candidates = list(ROOT.glob("*_1.9.68.apk"))
if len(candidates) != 1:
raise ValueError("Expected exactly one original APK, or pass --apk")
args.apk = candidates[0]
tables, fingerprints, stage, enemies, rules, timeout, capacity, skills = load_scenario(args.apk, args.stage, args.difficulty)
if args.team:
players = [Fighter(**row) for row in json.loads(args.team.read_text(encoding="utf-8"))]
if not 1 <= len(players) <= 6:
raise ValueError("team must contain 1 to 6 fighters")
source = "local_combat_attributes_not_independently_verified"
else:
row = tables["monster_info"][args.species]
players = [demo_player(row, args.level) for _ in range(args.players)]
source = "synthetic_catalog_examples_with_mean_growth_no_equipment_or_bonuses"
for player in players:
row = tables["monster_info"].get(str(player.species), {})
skills.update(int(row.get(f"skill_{slot}", 0)) for slot in (1, 2))
skills.discard(0)
results = [simulate(players, enemies, rules, seed=args.seed + n, timeout_ms=timeout, enemy_capacity=capacity)
for n in range(args.trials)]
durations = defaultdict(list)
for result in results:
durations[result["predicted_outcome"]].append(result["model_duration_seconds"])
report = {"format": "myrzx-offline-basic-attack-estimate", "version": 1,
"approximate": True, "calibrated_against_original_runtime": False,
"stage": {"id": args.stage, "difficulty": args.difficulty, "name": stage["name"]},
"team_source": source, "players": [asdict(p) for p in players],
"enemy_count": len(enemies), "enemy_waves": sorted({e.wave for e in enemies}),
"configured_time_limit_seconds": timeout / 1000,
"trials": args.trials, "first_seed": args.seed,
"model_win_fraction": sum(r["predicted_outcome"] == "win" for r in results) / len(results),
"duration_seconds_by_predicted_outcome": {k: describe(v) for k, v in durations.items()},
"first_trial": results[0], "ignored_skill_ids_from_catalog": sorted(skills),
"limitations": LIMITATIONS,
"sources": {"damage_and_crit": "analysis/as3/scripts/net/pixvi/myr/GameMath.as:212",
"attack_interval": "analysis/as3/scripts/net/pixvi/myr/element/battle/BattleMonVo.as:303",
"tables": fingerprints}}
text = json.dumps(report, ensure_ascii=False, indent=2) + "\n"
if args.output:
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(text, encoding="utf-8")
print(json.dumps({k: report[k] for k in ("format", "approximate", "stage", "team_source", "trials",
"model_win_fraction", "duration_seconds_by_predicted_outcome", "ignored_skill_ids_from_catalog")}, ensure_ascii=True))
return 0
except (ValueError, KeyError, TypeError, OSError, zipfile.BadZipFile) as error:
print(json.dumps({"error": type(error).__name__, "message": str(error), "approximate": True}), file=sys.stderr)
return 2
if __name__ == "__main__":
raise SystemExit(main())