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())
+82
View File
@@ -0,0 +1,82 @@
"""Passive mitmproxy addon for manually played battles; never modifies flows.
Run from the project root using mitmdump -s tools/capture_battle_proxy.py.
Only the listed game service paths on dydab.com are recorded. The original
HTTP exchange is forwarded by mitmproxy; this addon does not issue requests.
"""
import json
import os
from pathlib import Path
import sys
from urllib.parse import urlparse
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from ranch_assistant.api import DEFAULT_KEY, decode
from ranch_assistant.debug import TraceLog
OPERATIONS = frozenset(("stageService/stageStart", "battleService/battleStart",
"battleService/battleEnd", "battleService/recordBattleResult",
"taskService/taskCompleteStep", "masterService/masterQueryDetail"))
DIAGNOSTIC_OPERATIONS = frozenset(("heartBeatService/keepAlive", "stackService/stackCheckProcess"))
class BattleCapture:
def __init__(self, folder=None, key=None):
self.trace = TraceLog(folder or ROOT / "local_state/battle_capture")
self.key = key if key is not None else os.environ.get("MYRZX_BATTLE_CAPTURE_KEY", DEFAULT_KEY)
self.trace.secrets.add(self.key)
def operation(self, flow):
parsed = urlparse(flow.request.pretty_url)
host = (parsed.hostname or "").lower()
if host != "dydab.com" and not host.endswith(".dydab.com"):
return None
if self.trace.path.with_name("capture.paused").exists():
return None
operation = parsed.path.strip("/")
return operation if operation in OPERATIONS | DIAGNOSTIC_OPERATIONS else None
def payload(self, message):
raw = message.get_content()
try:
result = json.loads(raw)
except (ValueError, TypeError, UnicodeError):
result = decode(raw, self.key)
if not isinstance(result, dict):
raise ValueError("Game payload is not a JSON object")
return result
def request(self, flow):
operation = self.operation(flow)
if operation is None:
return
self.record("request", operation, flow, flow.request)
def response(self, flow):
operation = self.operation(flow)
if operation is None or flow.response is None:
return
self.record("response", operation, flow, flow.response)
def record(self, kind, operation, flow, message):
details = {"request_id": str(flow.id), "capture_origin": "phone_proxy",
"url": flow.request.pretty_url.split("?", 1)[0]}
if kind == "response":
details["http_status"] = flow.response.status_code
try:
body = self.payload(message)
except Exception as error:
# Never write undecoded content, keys or exception text containing data.
self.trace.emit("error", operation, **details, decoded=False,
exception_type=type(error).__name__, message="Payload decoding failed; no raw body retained")
else:
if operation in DIAGNOSTIC_OPERATIONS:
# Verify passive decoding before a battle without retaining unrelated data.
self.trace.emit("diagnostic", operation, **details, direction=kind, decoded=True,
resCode=body.get("resCode") if type(body.get("resCode")) is int else None)
else:
self.trace.emit(kind, operation, **details, decoded=True, body=body)
addons = [BattleCapture()]
+158
View File
@@ -0,0 +1,158 @@
"""Compare local battle predictions with passively captured settlement requests.
Input and output are local files. No requests are sent or replayed.
"""
from collections import Counter
import argparse
import json
import math
from pathlib import Path
import statistics
OUTCOMES = frozenset(("battleService/battleEnd", "taskService/taskCompleteStep"))
CLIENT_VARIANTS = ("unknown", "original", "modified")
def observations(events):
pending, replies, notes, seen = {}, {}, Counter(), set()
for event in events:
operation = event.get("operation")
if operation not in OUTCOMES:
continue
key = (operation, str(event.get("request_id") or ""))
body = event.get("body")
if event.get("kind") == "request" and isinstance(body, dict) and isinstance(body.get("battleData"), dict):
if not key[1]:
notes["request_without_id"] += 1
continue
if key in pending:
notes["duplicate_request"] += 1
continue
pending[key] = event
elif event.get("kind") == "response" and isinstance(body, dict):
replies[key] = event
elif event.get("kind") == "error":
notes["capture_error"] += 1
samples = []
fields = ("win", "leftTime", "aliveNum", "apLeft", "killMonster", "killNum", "totalDamage", "deadNum", "bossDamage", "cheatNum")
for key, request in pending.items():
reply = replies.get(key)
if reply is None:
notes["settlement_response_missing"] += 1
continue
body = reply["body"]
if type(body.get("resCode")) is not int or body["resCode"] != 0:
notes["settlement_not_successful"] += 1
continue
battle = request["body"]["battleData"]
if (battle.get("win") is True and not battle.get("killMonster")
and all(battle.get(k, 0) == 0 for k in ("leftTime", "aliveNum", "apLeft", "killNum", "totalDamage", "deadNum", "bossDamage"))):
notes["sweep_or_ambiguous_empty_result"] += 1
continue
ids = battle.get("battleMonIds")
if not isinstance(ids, list) or any(type(mid) is not int or mid <= 0 for mid in ids):
notes["invalid_roster"] += 1
continue
position = battle.get("battlePosition")
if not isinstance(position, dict):
notes["position_missing"] += 1
continue
identity = (key[0], request["request_id"])
if identity in seen:
continue
seen.add(identity)
samples.append({"sample_id": request["request_id"], "operation": key[0], "time": request.get("time"),
"capture_origin": request.get("capture_origin", "unspecified"),
"position": {k: position.get(k) for k in ("battleType", "stageId", "stageLevel", "taskTypeId", "taskStep")},
"roster_instance_ids": ids,
"reported": {k: battle.get(k) for k in fields},
"response": {k: body.get(k) for k in ("costTi", "resCode")}})
for key in replies.keys() - pending.keys():
notes["response_without_settlement_request"] += 1
return samples, dict(notes)
def compare(estimate, sample, *, client_variant="unknown"):
if estimate.get("format") != "myrzx-offline-basic-attack-estimate":
raise ValueError("Not a supported estimate report")
if client_variant not in CLIENT_VARIANTS:
raise ValueError("Unknown client variant")
if client_variant == "modified":
return {"sample_id": sample["sample_id"], "status": "modified_client_not_calibratable"}
position, stage = sample["position"], estimate["stage"]
if position.get("battleType") != "stage":
return {"sample_id": sample["sample_id"], "status": "task_context_requires_separate_mapping"}
if str(position.get("stageId")) != str(stage["id"]) or str(position.get("stageLevel")) != str(stage["difficulty"]):
return {"sample_id": sample["sample_id"], "status": "different_stage_or_difficulty"}
supplied = [p.get("instance_id") for p in estimate.get("players", [])]
roster_matches = supplied == sample["roster_instance_ids"] if supplied and all(mid is not None for mid in supplied) else None
if roster_matches is False:
return {"sample_id": sample["sample_id"], "status": "different_roster"}
reported = sample["reported"]
limit, remaining = estimate.get("configured_time_limit_seconds"), reported.get("leftTime")
if (type(limit) not in (int, float) or type(remaining) not in (int, float)
or not math.isfinite(limit) or not math.isfinite(remaining)
or limit <= 0 or not 0 <= remaining <= limit * 1000 or type(reported.get("win")) is not bool):
return {"sample_id": sample["sample_id"], "status": "invalid_or_missing_timing"}
elapsed = limit - remaining / 1000
outcome = "win" if reported["win"] else "loss"
prediction = estimate.get("duration_seconds_by_predicted_outcome", {}).get(outcome)
status = ("exploratory_client_unverified" if client_variant == "unknown" else
"compared" if roster_matches else "exploratory_roster_unverified")
result = {"sample_id": sample["sample_id"], "status": status,
"observed_outcome": outcome, "observed_clock_elapsed_seconds": elapsed,
"roster_matches": roster_matches,
"same_attributes_and_resource_version_verified": False,
"model_has_samples_for_observed_outcome": prediction is not None}
if prediction:
delta = prediction["median"] - elapsed
result.update(model_median_seconds=prediction["median"], signed_time_error_seconds=delta,
absolute_time_error_seconds=abs(delta), relative_time_error=abs(delta) / elapsed if elapsed else None,
within_model_p10_p90=prediction["p10"] <= elapsed <= prediction["p90"])
return result
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--capture", type=Path, required=True, nargs="+")
parser.add_argument("--estimate", type=Path, help="Optional model report; omit to summarize protocol samples only")
parser.add_argument("--client-variant", choices=CLIENT_VARIANTS, default="unknown",
help="Operator-reported capture client, not independently verified")
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args(argv)
try:
events = []
for file in args.capture:
for line in file.read_text(encoding="utf-8").splitlines():
if line.strip():
event = json.loads(line)
if isinstance(event, dict):
events.append(event)
samples, diagnostics = observations(events)
estimate = json.loads(args.estimate.read_text(encoding="utf-8")) if args.estimate else None
comparisons = ([compare(estimate, sample, client_variant=args.client_variant) for sample in samples]
if estimate else [{"sample_id": sample["sample_id"], "status": "model_not_provided"} for sample in samples])
aligned = [row for row in comparisons if row["status"] == "compared"]
errors = [row["relative_time_error"] for row in aligned if row.get("relative_time_error") is not None]
report = {"format": "myrzx-local-battle-comparison", "version": 1,
"capture_client_variant": args.client_variant, "client_variant_source": "operator_report",
"accepted_settlement_sample_count": len(samples), "aligned_roster_comparison_count": len(aligned),
"median_relative_time_error": statistics.median(errors) if errors else None,
"diagnostics": diagnostics, "observations": samples, "comparisons": comparisons,
"limitations": ["Captured success validates that captured request, not a future simulated result.",
"Modified-client observations are protocol evidence, not original-damage calibration data.",
"Matching instance IDs do not verify identical attributes, equipment or hot-update resources.",
"Time uses configured battle limit minus reported leftTime in milliseconds, not HTTP wall time.",
"Samples and model intervals do not establish server verification rules."]}
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(json.dumps({k: report[k] for k in ("accepted_settlement_sample_count", "aligned_roster_comparison_count",
"median_relative_time_error", "diagnostics")}, ensure_ascii=True))
return 0
except (ValueError, TypeError, KeyError, OSError) as error:
print(json.dumps({"error": type(error).__name__, "message": str(error)}))
return 2
if __name__ == "__main__":
raise SystemExit(main())