Add offline battle estimates and passive phone sample analysis
This commit is contained in:
@@ -94,7 +94,7 @@ python -B -m unittest discover -s ranch_assistant/tests -v
|
|||||||
## v1.2 预研
|
## v1.2 预研
|
||||||
|
|
||||||
[主线任务、普通挑战与战斗委托方案](analysis/V1_2_PLAN.md)包含已核对的客户端调用链、完整资料恢复结果、战斗引擎路线和分阶段验收标准。
|
[主线任务、普通挑战与战斗委托方案](analysis/V1_2_PLAN.md)包含已核对的客户端调用链、完整资料恢复结果、战斗引擎路线和分阶段验收标准。
|
||||||
当前为预研资料,独立战斗引擎尚未跑通;离线实验直接推进,预研中的真实账号联网操作由用户手动执行。
|
已增加[离线普攻估算与实机样本对比工具](analysis/V1_2_OFFLINE_EXPERIMENT.md),可在本地计算有限机制下的胜负和耗时分布。忠实执行原始规则的独立战斗引擎尚未跑通;预研中的真实账号联网操作由用户手动执行。
|
||||||
|
|
||||||
## 免责声明
|
## 免责声明
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# v1.2 首组实机采样结论
|
||||||
|
|
||||||
|
日期:2026-11-08。场景:用户手动进入 1-1 / 难度 1。用户确认客户端为此前的伤害10倍包;该组用于协议分析,不用于原版伤害或耗时校准。离线模型继续使用原始1.9.68 APK参数,没有按该倍率修改。
|
||||||
|
|
||||||
|
## 实际观察到的流程
|
||||||
|
|
||||||
|
| 步骤 | 请求/响应 | 本组观察 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| 第一次进入 | `stageService/stageStart` | 成功;`triggerEvent=true`,返回 `stageEvent`,事件类型 `300002` |
|
||||||
|
| 事件奖励 | 包含在上述 `stageEvent.result` | 金币12、经验24;该次响应体力消耗6 |
|
||||||
|
| 第二次进入 | `stageService/stageStart` | 成功;`triggerEvent=false`、`stageEvent=null`,随后发生普通挑战 |
|
||||||
|
| 战斗结算 | `battleService/battleEnd` | 成功;`win=true`,关卡 `0101`、难度 `1`,返回奖励和体力消耗 |
|
||||||
|
| 通关记录 | `battleService/recordBattleResult` | 在结算后发送,成功 |
|
||||||
|
|
||||||
|
这一组与[此前静态调用链研究](V1_2_PLAN.md)相符:进入关卡可能先触发事件并直接返回事件结果;普通挑战则在本地战斗后提交结算,再记录通关。事件不能直接按“战斗完成”处理,两次进入需要分开计数。
|
||||||
|
|
||||||
|
本次只被动采集指定白名单接口,没有代理重放或程序代打;不能据此排除其他心跳或未采集路径。服务器内部实现和额外校验仍不可见。
|
||||||
|
|
||||||
|
## 结算字段的实际含义
|
||||||
|
|
||||||
|
开始请求携带 `stageTypeId/stageLevel` 以及会话、请求序号;开始响应没有提供逐帧战斗脚本。结算请求的 `battleData` 包含场景定位、上阵实例列表、胜负、剩余时间、AP、存活数、击杀/伤害等统计和异常记录字段。真实实例编号与认证信息只保留本地,本页不列出。
|
||||||
|
|
||||||
|
| 字段 | 本场值 | 可以说明什么 |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `battlePosition` | `stage / 0101 / 1` | 普通关卡结算上下文 |
|
||||||
|
| `battleMonIds` | 3个实例 | 上阵角色身份;不包含完整装备、技能和战斗加成 |
|
||||||
|
| `leftTime` | 291519毫秒 | 原APK该场限时300秒,按该上限得到战斗内用时约8.481秒 |
|
||||||
|
| `aliveNum` | 6 | 不能简单等同于上阵实例列表的存活数 |
|
||||||
|
| `apLeft` | 58 | 客户端结算时的队伍AP |
|
||||||
|
| `killMonster` | 空对象 | 不代表没有击败敌人 |
|
||||||
|
| `killNum/totalDamage/deadNum/bossDamage` | 本场均为0 | 本场记录没有提供可用于反推普攻伤害的非零统计 |
|
||||||
|
|
||||||
|
原代码的 [BattleTeamVo.getAliveNum](as3/scripts/net/pixvi/myr/element/battle/BattleTeamVo.as#L201) 会遍历 `stageMons` 和 `mons`,排除场景物件后计数。因此不能直接用上阵编号数量限制该字段;这一份结算本身不足以确定6个计数对象各自是什么。
|
||||||
|
|
||||||
|
[BattleGround.as](as3/scripts/net/pixvi/myr/battle/BattleGround.as#L1070) 只在敌方、非场景物件且 `mode==2` 时增加 `killMons`。它是有条件的统计,不是所有敌方死亡的无条件总数。[BattlePanel.as](as3/scripts/net/pixvi/myr/panel/battle/BattlePanel.as#L270) 再把当前计时、AP、队伍数量和这些记录填入结算。
|
||||||
|
|
||||||
|
普通挑战成功响应返回金币12、经验24、绿色粘液(物品类型30005)1个,体力消耗6。奖励由响应提供;不能只凭本地预测的胜利推定获得了什么。
|
||||||
|
|
||||||
|
## 对离线实现的影响
|
||||||
|
|
||||||
|
可以据此确定普通关卡与事件的分支、结算字段的类型以及奖励响应位置。`aliveNum` 和 `killMonster` 的含义需要遵循客户端实际集合与条件,不能把离线估算的“玩家存活数/敌人击杀总数”原样视为同名协议字段。
|
||||||
|
|
||||||
|
现有示例模型仍使用三只1级示例史莱姆,100次模型内胜利的中位用时22.148秒。它与本场真实阵容没有完成输入对齐,又缺少技能、移动和出场等机制,因此不计算二者的准确率或时间误差。也不能通过把实测时间乘除10来还原原版战斗:移动、动画、技能、波次等待和离散攻击次数不会与伤害倍率统一缩放。
|
||||||
|
|
||||||
|
本地已生成 `sample_context.json`、`protocol_analysis.json` 和 `comparison.json`,明确标记修改版来源,保留1场成功结算,原版对齐样本为0。它们及原始脱敏日志只在 `local_state/battle_capture/`,不纳入Git。
|
||||||
|
|
||||||
|
## 根据现有账号快照的原版参数估算
|
||||||
|
|
||||||
|
本地既有日志中找到了包含本场三只上阵实例的账号快照,距结算约17分5秒。这三只角色在快照里没有装备和皮肤,独立属性加成列表为空;据原代码计算了基础成长、等级与突破、潜能、全局加成、好感和升星加成,再按敏捷修正普攻间隔。没有应用10倍伤害。
|
||||||
|
|
||||||
|
使用这些入参运行100次有限普攻模型,模型内均获胜,用时中位数6.097秒,范围6.095~6.097秒。完整入参、计算脚本和报告只保存在本地 `local_state/battle_capture/` 的 `team.local.json`、`calculate_roster.local.py` 和 `estimate_real_roster_original_rules.json`,不公开账号阵容或实例编号。
|
||||||
|
|
||||||
|
**6.097秒是简化模型的结果,不是原版客户端实测。** 该模型尚未计算技能(本队伍原表包含的技能也已列入忽略清单)、移动、动画、玩家分批出场和AP约束;快照也不是开战当时的同步状态。因此不能因为这个数字比修改版实测更短,就判定模型更快或已经准确。
|
||||||
|
|
||||||
|
后续工作是验证开战时完整输入,再补齐并验证技能、移动、出场、时钟与统计语义。现有样本证明捕获和解码流程可用,尚未证明独立模型能够忠实运行原始战斗。
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
{
|
||||||
|
"format": "myrzx-offline-basic-attack-estimate",
|
||||||
|
"version": 1,
|
||||||
|
"approximate": true,
|
||||||
|
"calibrated_against_original_runtime": false,
|
||||||
|
"stage": {
|
||||||
|
"id": "0101",
|
||||||
|
"difficulty": "1",
|
||||||
|
"name": "莉莉托斯门外"
|
||||||
|
},
|
||||||
|
"team_source": "synthetic_catalog_examples_with_mean_growth_no_equipment_or_bonuses",
|
||||||
|
"players": [
|
||||||
|
{
|
||||||
|
"species": 1001010,
|
||||||
|
"name": "绿色史莱姆",
|
||||||
|
"hp": 335,
|
||||||
|
"atk": 28,
|
||||||
|
"defense": 24,
|
||||||
|
"dex": 6,
|
||||||
|
"attack_ms": 1596,
|
||||||
|
"element": 4,
|
||||||
|
"crit": 0,
|
||||||
|
"wave": 1,
|
||||||
|
"instance_id": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"species": 1001010,
|
||||||
|
"name": "绿色史莱姆",
|
||||||
|
"hp": 335,
|
||||||
|
"atk": 28,
|
||||||
|
"defense": 24,
|
||||||
|
"dex": 6,
|
||||||
|
"attack_ms": 1596,
|
||||||
|
"element": 4,
|
||||||
|
"crit": 0,
|
||||||
|
"wave": 1,
|
||||||
|
"instance_id": null
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"species": 1001010,
|
||||||
|
"name": "绿色史莱姆",
|
||||||
|
"hp": 335,
|
||||||
|
"atk": 28,
|
||||||
|
"defense": 24,
|
||||||
|
"dex": 6,
|
||||||
|
"attack_ms": 1596,
|
||||||
|
"element": 4,
|
||||||
|
"crit": 0,
|
||||||
|
"wave": 1,
|
||||||
|
"instance_id": null
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"enemy_count": 5,
|
||||||
|
"enemy_waves": [
|
||||||
|
1,
|
||||||
|
2,
|
||||||
|
3
|
||||||
|
],
|
||||||
|
"configured_time_limit_seconds": 300.0,
|
||||||
|
"trials": 100,
|
||||||
|
"first_seed": 1,
|
||||||
|
"model_win_fraction": 1.0,
|
||||||
|
"duration_seconds_by_predicted_outcome": {
|
||||||
|
"win": {
|
||||||
|
"count": 100,
|
||||||
|
"min": 20.552,
|
||||||
|
"median": 22.148,
|
||||||
|
"p10": 22.148,
|
||||||
|
"p90": 22.148,
|
||||||
|
"max": 23.744
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"first_trial": {
|
||||||
|
"predicted_outcome": "win",
|
||||||
|
"model_duration_seconds": 23.744,
|
||||||
|
"player_survivors": 3,
|
||||||
|
"enemy_kills": 5,
|
||||||
|
"player_damage": 738,
|
||||||
|
"resolved_hits": 60
|
||||||
|
},
|
||||||
|
"ignored_skill_ids_from_catalog": [
|
||||||
|
3
|
||||||
|
],
|
||||||
|
"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."
|
||||||
|
],
|
||||||
|
"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": {
|
||||||
|
"stage_info": {
|
||||||
|
"logical_path": "data/table/stage_info.json",
|
||||||
|
"member": "assets/codes/9484cfff9fb912e4791832375e771475",
|
||||||
|
"compressed_bytes": 1061791,
|
||||||
|
"decoded_bytes": 19703775,
|
||||||
|
"sha256": "47ccef41d460f4ef23732624cf302e863a22ca33148dc02629841d764c38b487"
|
||||||
|
},
|
||||||
|
"monster_info": {
|
||||||
|
"logical_path": "data/table/monster_info.json",
|
||||||
|
"member": "assets/codes/08b83182d2a7882bfe2bb0ed710d343f",
|
||||||
|
"compressed_bytes": 219398,
|
||||||
|
"decoded_bytes": 933486,
|
||||||
|
"sha256": "081747ddc5b7afba03f69e65f5eba6af815b9fbd3ea7e0821c7f8807d9486921"
|
||||||
|
},
|
||||||
|
"monster_setting": {
|
||||||
|
"logical_path": "data/table/monster_setting.json",
|
||||||
|
"member": "assets/codes/1d188dbf8ca7a253fb2e5bc2475b2669",
|
||||||
|
"compressed_bytes": 6687,
|
||||||
|
"decoded_bytes": 22488,
|
||||||
|
"sha256": "49388d221e3d4461fede3b176526d593ec0f1647a8b93a8d2b33a712761febab"
|
||||||
|
},
|
||||||
|
"game_setting": {
|
||||||
|
"logical_path": "data/table/game_setting.json",
|
||||||
|
"member": "assets/codes/f1c2e2603d6c82bbb8b5f94585273208",
|
||||||
|
"compressed_bytes": 3559,
|
||||||
|
"decoded_bytes": 5820,
|
||||||
|
"sha256": "8810981688414e3cef520976911d16e2847df0a435dccd792e2dd527695283e3"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
# v1.2 离线战斗估算与实机采样
|
||||||
|
|
||||||
|
## 当前交付
|
||||||
|
|
||||||
|
`tools/battle_estimate_v12.py` 可以从原始 1.9.68 APK 恢复关卡、敌人和伤害参数,在不连接游戏服务器的情况下模拟普攻,输出胜负、存活数、击杀数和耗时分布。`simulate()` 是可单独调用的函数,输入不会被修改,相同输入和种子可以复现结果。
|
||||||
|
|
||||||
|
这是有限机制的估算模型:尚未执行原始 AS3 引擎,也不生成或提交服务器战斗结算请求。界面中的自动主线功能仍未实现。
|
||||||
|
|
||||||
|
## 已运行的离线样例
|
||||||
|
|
||||||
|
场景为原 APK 的 `0101` / 难度 `1`,即 1-1 莉莉托斯门外;敌人为 3 波共 5 只。玩家是按原表平均成长生成的 1 级绿色史莱姆示例,没有装备和额外加成。每组 100 次,种子从 1 递增。
|
||||||
|
|
||||||
|
| 示例阵容 | 模型内结果 | 耗时中位数 | P10~P90 |
|
||||||
|
| --- | --- | --- | --- |
|
||||||
|
| 3 只示例绿色史莱姆 | 100 次胜利 | 22.148 秒 | 22.148~22.148 秒 |
|
||||||
|
| 1 只示例绿色史莱姆 | 100 次失败 | 29.420 秒 | 27.825~32.609 秒 |
|
||||||
|
|
||||||
|
三只阵容的完整报告见 [V1_2_ESTIMATE_SAMPLE.json](V1_2_ESTIMATE_SAMPLE.json)。这些数字只描述该模型,不能当作实机通关时间或服务器认可结果;同一档攻击间隔会使不同伤害随机数得到相同结束时间。
|
||||||
|
|
||||||
|
运行方式,在项目根目录执行:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -B tools/battle_estimate_v12.py --trials 100 --output local_state/battle_capture/estimate.json
|
||||||
|
python -B tools/battle_estimate_v12.py --players 1 --trials 100 --output local_state/battle_capture/one_player_estimate.json
|
||||||
|
```
|
||||||
|
|
||||||
|
也可以使用 `--stage 0101 --difficulty 1 --team <本地JSON路径>`。队伍文件是 `Fighter` 对象的数组,每项包含 `species/name/hp/atk/defense/dex/attack_ms`,可选 `element/crit/instance_id`。应提供已经按客户端规则计算完成的入场属性;工具不会把角色面板参考值认证为完整战斗属性。
|
||||||
|
|
||||||
|
## 覆盖范围
|
||||||
|
|
||||||
|
已实现普通伤害中的敏捷区间、暴击、元素克制、AS3整数转换和取整,以及攻击间隔、扣血死亡、敌方出场容量、700毫秒波间间隔和超时。结果会自然落到胜利、失败或超时。
|
||||||
|
|
||||||
|
尚未模拟技能、召唤、治疗、护盾、增减益、装备效果、移动、射程、碰撞、弹道和动画回调;玩家默认全部在场,未模拟AP和玩家出场约束。同一时刻的攻击同时结算,目标简化为首个存活敌人。随机区间暂用均匀分布,没有重放原始随机函数。
|
||||||
|
|
||||||
|
包含控制器、触发器、特殊目标、自动生成敌方数值或定时出场的场景会被拒绝。普通怪物携带的技能仍可能被忽略,报告会列出已从原表发现的技能编号;示例包含未执行的技能 `3`。外部队伍也会按物种列出原表技能,但没有皮肤、升级等完整技能元数据,不能据此判断队伍不存在其他技能。
|
||||||
|
|
||||||
|
公式和入场属性来源:
|
||||||
|
|
||||||
|
- [GameMath.as](as3/scripts/net/pixvi/myr/GameMath.as#L212):普攻伤害、敏捷和暴击。
|
||||||
|
- [BattleMonVo.as](as3/scripts/net/pixvi/myr/element/battle/BattleMonVo.as#L303):攻击间隔。
|
||||||
|
- [MasterCenter.as](as3/scripts/net/pixvi/myr/center/MasterCenter.as#L141):全局加成;角色的 `monsterAttributes` 会更新独立属性加成,不能只用基础成长代替。
|
||||||
|
- 原始表的摘要和恢复方法见 [资料清单](V1_2_BATTLE_INVENTORY.json)及 [research_battle_v12.py](../tools/research_battle_v12.py)。APK内资源与线上热更新是否相同,仍需另外核对。
|
||||||
|
|
||||||
|
## 手机被动采样
|
||||||
|
|
||||||
|
采样插件为 `tools/capture_battle_proxy.py`。用户在手机游戏里手动操作;插件不修改请求、不重放请求,也不主动调用游戏服务。
|
||||||
|
|
||||||
|
仅记录 `dydab.com` 及其子域下的 `stageStart`、`battleStart`、`battleEnd`、`recordBattleResult`、`taskCompleteStep` 和 `masterQueryDetail`。心跳、培育室成长检查只保留解码是否成功和返回码,用于确认采样链路,不保留其业务正文。其他路径、登录和支付正文不记录。白名单之外的通信没有被完整采集,不能由日志缺失推断它们没有发生。
|
||||||
|
|
||||||
|
实际记录保存在 `local_state/battle_capture/network_debug.jsonl`,认证字段会脱敏,解码失败时不保留原始正文。账号实例编号等业务信息仍只留本地,整个目录受 Git 忽略。代理环境、CA私钥和证书也都只放本地。
|
||||||
|
|
||||||
|
准备方法:使用独立环境安装 mitmproxy 和本项目导入所需依赖,将证书目录指向 `local_state/battle_capture/proxy_certs`。启动示例:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
mitmdump --listen-host 127.0.0.1 --listen-port 8086 --allow-hosts '(^|\.)dydab\.com(:\d+)?$' --set confdir=local_state/battle_capture/proxy_certs --set flow_detail=0 -s tools/capture_battle_proxy.py
|
||||||
|
adb -s <设备序列号> reverse tcp:8086 tcp:8086
|
||||||
|
```
|
||||||
|
|
||||||
|
手机手动安装该本地代理生成的公开CA证书,并把当前Wi-Fi手动代理设为 `127.0.0.1:8086`,保持USB连接。先确认普通请求和响应能够解码,再开始战斗。如果该客户端不接受用户CA,应先恢复正常联网;“游戏能联网”本身不等于HTTPS正文已经采集成功。
|
||||||
|
|
||||||
|
第一组建议采集同一队伍、同一关卡与难度的 3~5 场普通挑战,记录是否原版、有无伤害倍率、装备/技能/加成、资源版本和操作方式。倍率包的记录可用于研究协议结构,不能用于校准原版伤害。扫荡结果和任务专属结算不能混入普通关卡时间样本。
|
||||||
|
|
||||||
|
## 本地比较
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -B tools/compare_battle_v12.py --capture local_state/battle_capture/network_debug.jsonl --estimate local_state/battle_capture/estimate.json --output local_state/battle_capture/comparison.json
|
||||||
|
```
|
||||||
|
|
||||||
|
`--client-variant` 默认 `unknown`,因此默认不会把样本计入已匹配的原版对比;只有操作者明确标记 `original` 后才尝试归类。标记 `modified` 时保留协议观察,跳过时间误差计算。不同来源的客户端应分文件分析。省略 `--estimate` 可以只生成协议样本摘要,例如本轮采样:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python -B tools/compare_battle_v12.py --capture local_state/battle_capture/network_debug.jsonl --client-variant modified --output local_state/battle_capture/protocol_analysis.json
|
||||||
|
```
|
||||||
|
|
||||||
|
工具按请求编号配对结算请求和成功响应,排除缺响应、失败响应、重复流和具有扫荡特征的空统计。首先匹配关卡、难度和有序的角色实例编号;队伍编号不全时标为探索性对比,已知不一致时不比较。任务战斗暂不自动映射到普通关卡。
|
||||||
|
|
||||||
|
耗时来自配置时间上限减去 `leftTime / 1000`,不是HTTP请求耗时。输出包括模型中位数、时间绝对/相对误差以及实测时间是否位于模型P10~P90区间。
|
||||||
|
|
||||||
|
只有结算请求,不能恢复完整开战输入或逐帧轨迹。即使角色编号一致,也仍需核实属性、装备、技能和资源版本;自动重建这些完整输入尚未实现。捕获到某个原客户端请求成功,不证明模拟结果会被接受,也不证明服务端采用何种校验规则。
|
||||||
|
|
||||||
|
本轮已捕获一场事件和一场成功普通挑战,具体语义核对见[实机采样结论](V1_2_CAPTURE_FINDINGS.md)。用户确认使用伤害10倍包,因此按协议证据保留,离线模型继续使用原APK公式与参数。
|
||||||
|
|
||||||
|
## 结束采样
|
||||||
|
|
||||||
|
在采样目录创建 `capture.paused` 文件即可暂停插件记录,代理仍继续转发,手机无需立即改配置;移除此文件可以恢复记录。本轮样本分析结束后已使用该方式暂停。
|
||||||
|
|
||||||
|
先把手机当前Wi-Fi代理改回“无”,确认游戏正常联网,再删除本次USB转发并停止本次专用代理进程。可在手机系统证书设置里移除本次安装的CA。
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
adb -s <设备序列号> reverse --remove tcp:8086
|
||||||
|
```
|
||||||
|
|
||||||
|
保留脱敏采样文件用于本地对比即可;不要提交真实记录、账号快照、证书或私钥。
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
# v1.2 预研:主线任务、普通挑战与战斗委托
|
# v1.2 预研:主线任务、普通挑战与战斗委托
|
||||||
|
|
||||||
日期:2026-11-08。基线:辅助 v1.1.1、原始 Android APK 1.9.68。
|
日期:2026-11-08。基线:辅助 v1.1.1、原始 Android APK 1.9.68。
|
||||||
状态:已完成配置恢复和重点调用链研究,尚未运行独立战斗引擎、提交普通挑战或验证服务器接受结果。
|
状态:已完成配置恢复和重点调用链研究,并运行了离线普攻估算原型;忠实执行原始规则的独立战斗引擎尚未跑通,未提交模拟挑战或验证服务器接受结果。
|
||||||
|
|
||||||
实验安排:按用户本轮授权,离线解析、运行壳和战斗实验直接推进,无需再次确认。预研中的真实账号接任务、开战、结算与领奖由用户手动操作;本轮不自动进行联网游戏实验。
|
实验安排:按用户本轮授权,离线解析、运行壳和战斗实验直接推进,无需再次确认。预研中的真实账号接任务、开战、结算与领奖由用户手动操作;本轮不自动进行联网游戏实验。
|
||||||
|
|
||||||
|
新增的[离线实验与实机采样说明](V1_2_OFFLINE_EXPERIMENT.md)记录了可运行的函数、示例结果和本地对比流程。它是有限机制的估算实验,不能替代下面 P1/P2 要求的原引擎运行与对拍。
|
||||||
|
|
||||||
## 可行性结论
|
## 可行性结论
|
||||||
|
|
||||||
**有技术可行性,但需要恢复一个能够执行原始规则的战斗引擎。任务接取接口不是主要难点。**
|
**有技术可行性,但需要恢复一个能够执行原始规则的战斗引擎。任务接取接口不是主要难点。**
|
||||||
@@ -101,7 +103,7 @@ Ruffle官方兼容性页仍将AS3语言与API兼容性分别列为未全覆盖
|
|||||||
来源:[Ruffle兼容性说明](https://ruffle.rs/compatibility)。
|
来源:[Ruffle兼容性说明](https://ruffle.rs/compatibility)。
|
||||||
|
|
||||||
当前PATH可发现Java,但未发现ADL、mxmlc或FFDec命令;这只是PATH范围内的观察,不等同于整机没有安装。
|
当前PATH可发现Java,但未发现ADL、mxmlc或FFDec命令;这只是PATH范围内的观察,不等同于整机没有安装。
|
||||||
本次没有安装运行时、启动完整客户端或执行独立战斗。AS3运行壳是下一阶段的工程验证项。
|
AS3运行壳尚未执行。新增 Python 普攻估算实验只覆盖下文列明的有限机制;AS3运行壳仍是下一阶段的工程验证项。
|
||||||
|
|
||||||
## v1.2 分阶段实施方案
|
## v1.2 分阶段实施方案
|
||||||
|
|
||||||
@@ -155,9 +157,9 @@ flowchart TD
|
|||||||
## 本次预研的边界与待验证项
|
## 本次预研的边界与待验证项
|
||||||
|
|
||||||
- 已证实:原APK身份、配置可以恢复、本地战斗核心与统计采集入口、普通地图/任务分流,以及当前辅助资料被精简的事实。
|
- 已证实:原APK身份、配置可以恢复、本地战斗核心与统计采集入口、普通地图/任务分流,以及当前辅助资料被精简的事实。
|
||||||
- 工程推断:完整输入、时序、技能与依赖补齐后,独立执行原始规则有可行路径;目前没有可运行战斗原型来证明覆盖和速度。
|
- 工程推断:完整输入、时序、技能与依赖补齐后,独立执行原始规则有可行路径;普攻估算原型已经运行,尚不能证明原始战斗机制的覆盖、准确性和速度。
|
||||||
- 未验证:当前线上热更新与APK的差异、独立运行壳的兼容性、动画与时钟完整迁移、随机流复现、具体账号的所有加成是否完整可得、服务器接受真实独立战斗结果的条件。
|
- 未验证:当前线上热更新与APK的差异、独立运行壳的兼容性、动画与时钟完整迁移、随机流复现、具体账号的所有加成是否完整可得、服务器接受真实独立战斗结果的条件。
|
||||||
- 范围:当前方案先覆盖已验证普通关卡和任务战斗。PVP、排行榜/BOSS及特殊活动不纳入首批交付。
|
- 范围:当前方案先覆盖已验证普通关卡和任务战斗。PVP、排行榜/BOSS及特殊活动不纳入首批交付。
|
||||||
- 本次没有登录真实账号、发送任务/战斗写请求、操作手机或运行修改版APK,也没有改动1.1.1的辅助执行逻辑。
|
- 本轮工具不自动登录真实账号或发送任务/战斗写请求;用户手动运行手机游戏,电脑被动记录指定接口。采样准备包括本机代理、USB转发和公开CA证书传输;没有改动1.1.1的辅助执行逻辑。
|
||||||
|
|
||||||
下一步建议:完成“一场离线普通战斗的忠实运行与对拍”,再开展联网挑战和任务闭环。
|
下一步建议:完成“一场离线普通战斗的忠实运行与对拍”,再开展联网挑战和任务闭环。
|
||||||
|
|||||||
@@ -0,0 +1,205 @@
|
|||||||
|
import copy
|
||||||
|
from contextlib import redirect_stdout
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
from types import SimpleNamespace
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from ranch_assistant.api import DEFAULT_KEY, encode
|
||||||
|
from ranch_assistant.tests.test_core import workspace_temp
|
||||||
|
from tools.capture_battle_proxy import BattleCapture
|
||||||
|
from tools.compare_battle_v12 import compare, main, observations
|
||||||
|
|
||||||
|
END = "battleService/battleEnd"
|
||||||
|
|
||||||
|
|
||||||
|
def battle():
|
||||||
|
return {"battlePosition": {"battleType": "stage", "stageId": "0101", "stageLevel": "1"},
|
||||||
|
"battleMonIds": [11, 12], "win": True, "leftTime": 275000, "aliveNum": 2,
|
||||||
|
"apLeft": 5, "killMonster": {"1001010": 5}, "cheatNum": 0}
|
||||||
|
|
||||||
|
|
||||||
|
def events(value=None, code=0):
|
||||||
|
return [{"kind": "request", "operation": END, "request_id": "fixture-1", "capture_origin": "phone_proxy",
|
||||||
|
"body": {"battleData": battle() if value is None else value, "token": "sensitive-token"}},
|
||||||
|
{"kind": "response", "operation": END, "request_id": "fixture-1", "body": {"resCode": code, "costTi": 10}}]
|
||||||
|
|
||||||
|
|
||||||
|
def estimate(ids=(11, 12)):
|
||||||
|
return {"format": "myrzx-offline-basic-attack-estimate", "stage": {"id": "0101", "difficulty": "1"},
|
||||||
|
"players": [{"instance_id": mid} for mid in ids], "configured_time_limit_seconds": 300,
|
||||||
|
"duration_seconds_by_predicted_outcome": {"win": {"median": 20, "p10": 18, "p90": 23}}}
|
||||||
|
|
||||||
|
|
||||||
|
class Message:
|
||||||
|
def __init__(self, content):
|
||||||
|
self.content = content
|
||||||
|
|
||||||
|
def get_content(self):
|
||||||
|
return self.content
|
||||||
|
|
||||||
|
|
||||||
|
def flow(request, response, url="https://prod-dyd-1.dydab.com:9091/" + END):
|
||||||
|
req = Message(request)
|
||||||
|
req.pretty_url = url
|
||||||
|
res = Message(response)
|
||||||
|
res.status_code = 200
|
||||||
|
return SimpleNamespace(id="fixture-flow", request=req, response=res)
|
||||||
|
|
||||||
|
|
||||||
|
class BattleCaptureTests(unittest.TestCase):
|
||||||
|
def test_encrypted_capture_decodes_redacts_and_never_changes_or_sends_the_flow(self):
|
||||||
|
with workspace_temp() as folder, patch("socket.socket", side_effect=AssertionError("Unexpected network")):
|
||||||
|
capture = BattleCapture(folder, DEFAULT_KEY)
|
||||||
|
exchange = flow(encode({"token": "capture-private-token", "battleData": battle()}, DEFAULT_KEY),
|
||||||
|
encode({"resCode": 0, "reward": {}}, DEFAULT_KEY))
|
||||||
|
before = (exchange.request.content, exchange.response.content)
|
||||||
|
capture.request(exchange)
|
||||||
|
capture.response(exchange)
|
||||||
|
self.assertEqual((exchange.request.content, exchange.response.content), before)
|
||||||
|
text = capture.trace.path.read_text(encoding="utf-8")
|
||||||
|
self.assertNotIn("capture-private-token", text)
|
||||||
|
self.assertNotIn(DEFAULT_KEY, text)
|
||||||
|
rows = [json.loads(line) for line in text.splitlines()]
|
||||||
|
self.assertEqual(rows[0]["body"]["battleData"], battle())
|
||||||
|
samples, diagnostics = observations(rows)
|
||||||
|
self.assertEqual(len(samples), 1)
|
||||||
|
self.assertEqual(diagnostics, {})
|
||||||
|
|
||||||
|
def test_plain_json_is_supported_and_query_strings_are_not_saved(self):
|
||||||
|
with workspace_temp() as folder:
|
||||||
|
capture = BattleCapture(folder)
|
||||||
|
exchange = flow(json.dumps({"battleData": battle()}).encode(), b'{"resCode":0}',
|
||||||
|
url="https://prod-dyd-1.dydab.com:9091/" + END + "?token=query-secret")
|
||||||
|
capture.request(exchange)
|
||||||
|
self.assertNotIn("query-secret", capture.trace.path.read_text(encoding="utf-8"))
|
||||||
|
|
||||||
|
def test_other_hosts_login_and_payment_paths_are_ignored(self):
|
||||||
|
with workspace_temp() as folder:
|
||||||
|
capture = BattleCapture(folder)
|
||||||
|
for url in ("https://prod-dyd-1.dydab.com.evil.test/" + END,
|
||||||
|
"https://unrelated.test/" + END,
|
||||||
|
"https://prod-dyd-1.dydab.com:9091/userServerService/loginUser",
|
||||||
|
"https://prod-dyd-1.dydab.com:9091/paymentService/pay"):
|
||||||
|
exchange = flow(b'{"token":"secret"}', b'{}', url)
|
||||||
|
capture.request(exchange)
|
||||||
|
capture.response(exchange)
|
||||||
|
self.assertFalse(capture.trace.events)
|
||||||
|
self.assertFalse(capture.trace.path.exists())
|
||||||
|
|
||||||
|
def test_decode_failure_does_not_retain_raw_body(self):
|
||||||
|
with workspace_temp() as folder:
|
||||||
|
capture = BattleCapture(folder)
|
||||||
|
capture.request(flow(b"raw-private-body", b"{}"))
|
||||||
|
text = capture.trace.path.read_text(encoding="utf-8")
|
||||||
|
self.assertNotIn("raw-private-body", text)
|
||||||
|
self.assertEqual(capture.trace.events[0]["kind"], "error")
|
||||||
|
|
||||||
|
def test_pause_marker_stops_recording_without_modifying_the_flow(self):
|
||||||
|
with workspace_temp() as folder:
|
||||||
|
capture = BattleCapture(folder)
|
||||||
|
exchange = flow(b'{"battleData":{}}', b'{"resCode":0}')
|
||||||
|
capture.trace.path.with_name("capture.paused").touch()
|
||||||
|
capture.request(exchange)
|
||||||
|
capture.response(exchange)
|
||||||
|
self.assertFalse(capture.trace.events)
|
||||||
|
self.assertEqual(exchange.request.content, b'{"battleData":{}}')
|
||||||
|
|
||||||
|
def test_readiness_probe_decodes_but_retains_no_game_or_account_body(self):
|
||||||
|
with workspace_temp() as folder:
|
||||||
|
capture = BattleCapture(folder)
|
||||||
|
exchange = flow(encode({"token": "probe-token", "masterId": 1234567}, DEFAULT_KEY),
|
||||||
|
encode({"resCode": 0, "private": "probe-private-data"}, DEFAULT_KEY),
|
||||||
|
url="https://prod-dyd-1.dydab.com:9091/heartBeatService/keepAlive")
|
||||||
|
capture.request(exchange)
|
||||||
|
capture.response(exchange)
|
||||||
|
rows = list(capture.trace.events)
|
||||||
|
self.assertTrue(all(row["kind"] == "diagnostic" and row["decoded"] for row in rows))
|
||||||
|
self.assertEqual(rows[1]["resCode"], 0)
|
||||||
|
text = capture.trace.path.read_text(encoding="utf-8")
|
||||||
|
for value in ("probe-token", "1234567", "probe-private-data", '"body"'):
|
||||||
|
self.assertNotIn(value, text)
|
||||||
|
|
||||||
|
|
||||||
|
class BattleComparisonTests(unittest.TestCase):
|
||||||
|
def test_successful_request_and_response_are_paired_without_mutation_or_secrets(self):
|
||||||
|
source = events()
|
||||||
|
before = copy.deepcopy(source)
|
||||||
|
samples, diagnostics = observations(source)
|
||||||
|
self.assertEqual(source, before)
|
||||||
|
self.assertEqual(diagnostics, {})
|
||||||
|
self.assertEqual(len(samples), 1)
|
||||||
|
self.assertNotIn("sensitive-token", json.dumps(samples))
|
||||||
|
|
||||||
|
def test_missing_or_failed_response_is_not_a_confirmed_sample(self):
|
||||||
|
self.assertEqual(observations(events()[:1])[0], [])
|
||||||
|
self.assertEqual(observations(events(code=997))[0], [])
|
||||||
|
|
||||||
|
def test_sweep_shaped_data_cannot_be_used_as_a_real_battle_sample(self):
|
||||||
|
value = battle()
|
||||||
|
value.update(leftTime=0, aliveNum=0, apLeft=0, killMonster={})
|
||||||
|
samples, diagnostics = observations(events(value))
|
||||||
|
self.assertEqual(samples, [])
|
||||||
|
self.assertEqual(diagnostics["sweep_or_ambiguous_empty_result"], 1)
|
||||||
|
|
||||||
|
def test_duplicate_flow_is_not_counted_twice(self):
|
||||||
|
source = events()
|
||||||
|
samples, diagnostics = observations(source + source)
|
||||||
|
self.assertEqual(len(samples), 1)
|
||||||
|
self.assertEqual(diagnostics["duplicate_request"], 1)
|
||||||
|
|
||||||
|
def test_elapsed_time_is_derived_from_millisecond_combat_clock(self):
|
||||||
|
sample = observations(events())[0][0]
|
||||||
|
result = compare(estimate(), sample, client_variant="original")
|
||||||
|
self.assertEqual(result["status"], "compared")
|
||||||
|
self.assertEqual(result["observed_clock_elapsed_seconds"], 25)
|
||||||
|
self.assertEqual(result["absolute_time_error_seconds"], 5)
|
||||||
|
self.assertAlmostEqual(result["relative_time_error"], .2)
|
||||||
|
self.assertFalse(result["same_attributes_and_resource_version_verified"])
|
||||||
|
|
||||||
|
def test_other_rosters_stages_and_task_contexts_are_not_mixed(self):
|
||||||
|
sample = observations(events())[0][0]
|
||||||
|
self.assertEqual(compare(estimate((99,)), sample)["status"], "different_roster")
|
||||||
|
other = estimate()
|
||||||
|
other["stage"]["difficulty"] = "2"
|
||||||
|
self.assertEqual(compare(other, sample)["status"], "different_stage_or_difficulty")
|
||||||
|
sample["position"]["battleType"] = "task"
|
||||||
|
self.assertEqual(compare(estimate(), sample)["status"], "task_context_requires_separate_mapping")
|
||||||
|
|
||||||
|
def test_missing_roster_identity_is_only_an_exploratory_comparison(self):
|
||||||
|
result = compare(estimate((None, None)), observations(events())[0][0], client_variant="original")
|
||||||
|
self.assertEqual(result["status"], "exploratory_roster_unverified")
|
||||||
|
|
||||||
|
def test_missing_and_out_of_range_timing_is_rejected(self):
|
||||||
|
sample = observations(events())[0][0]
|
||||||
|
for remaining in (None, -1, 300001, float("nan")):
|
||||||
|
sample["reported"]["leftTime"] = remaining
|
||||||
|
self.assertEqual(compare(estimate(), sample)["status"], "invalid_or_missing_timing")
|
||||||
|
|
||||||
|
def test_modified_client_is_retained_as_protocol_evidence_without_timing_comparison(self):
|
||||||
|
sample = observations(events())[0][0]
|
||||||
|
result = compare(estimate(), sample, client_variant="modified")
|
||||||
|
self.assertEqual(result["status"], "modified_client_not_calibratable")
|
||||||
|
self.assertNotIn("relative_time_error", result)
|
||||||
|
|
||||||
|
def test_unverified_client_is_not_counted_as_an_aligned_comparison(self):
|
||||||
|
result = compare(estimate(), observations(events())[0][0])
|
||||||
|
self.assertEqual(result["status"], "exploratory_client_unverified")
|
||||||
|
|
||||||
|
def test_protocol_only_cli_keeps_variant_and_samples_without_network_or_model(self):
|
||||||
|
with workspace_temp() as folder, patch("socket.socket", side_effect=AssertionError("Unexpected network")):
|
||||||
|
capture, output = folder / "capture.jsonl", folder / "report.json"
|
||||||
|
capture.write_text("\n".join(json.dumps(row) for row in events()), encoding="utf-8")
|
||||||
|
with redirect_stdout(io.StringIO()):
|
||||||
|
code = main(["--capture", str(capture), "--client-variant", "modified", "--output", str(output)])
|
||||||
|
report = json.loads(output.read_text(encoding="utf-8"))
|
||||||
|
self.assertEqual(code, 0)
|
||||||
|
self.assertEqual(report["capture_client_variant"], "modified")
|
||||||
|
self.assertEqual(report["accepted_settlement_sample_count"], 1)
|
||||||
|
self.assertEqual(report["aligned_roster_comparison_count"], 0)
|
||||||
|
self.assertIsNone(report["median_relative_time_error"])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
from contextlib import redirect_stdout
|
||||||
|
from dataclasses import asdict, replace
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from tools.battle_estimate_v12 import Fighter, Rules, demo_player, hit_damage, main, simulate
|
||||||
|
from ranch_assistant.tests.test_core import workspace_temp
|
||||||
|
|
||||||
|
|
||||||
|
class MidpointRandom:
|
||||||
|
def __init__(self, critical=False):
|
||||||
|
self.critical = critical
|
||||||
|
|
||||||
|
def random(self):
|
||||||
|
return 0 if self.critical else .99
|
||||||
|
|
||||||
|
def uniform(self, low, high):
|
||||||
|
return (low + high) / 2
|
||||||
|
|
||||||
|
|
||||||
|
def fighter(**changes):
|
||||||
|
return replace(Fighter(1001010, "fixture", 100, 100, 20, 10, 1000), **changes)
|
||||||
|
|
||||||
|
|
||||||
|
RULES = Rules(.95, .25, 1.5, 1.15, {1: 2, 2: 4, 3: 1, 4: 3, 5: 0})
|
||||||
|
|
||||||
|
|
||||||
|
class BattleEstimateTests(unittest.TestCase):
|
||||||
|
def test_base_damage_matches_source_formula_at_midpoint(self):
|
||||||
|
# 100 * .95 - 20 * (.25 * .75 + .25 * .125) = 90.625.
|
||||||
|
self.assertEqual(hit_damage(fighter(), fighter(), RULES, MidpointRandom()), 91)
|
||||||
|
|
||||||
|
def test_critical_attack_is_applied_before_the_defense_roll(self):
|
||||||
|
self.assertEqual(hit_damage(fighter(), fighter(), RULES, MidpointRandom(True)), 138)
|
||||||
|
|
||||||
|
def test_dex_advantage_and_disadvantage_change_the_damage_range(self):
|
||||||
|
self.assertEqual(hit_damage(fighter(dex=50), fighter(), RULES, MidpointRandom()), 98)
|
||||||
|
self.assertEqual(hit_damage(fighter(dex=0), fighter(dex=40), RULES, MidpointRandom()), 84)
|
||||||
|
|
||||||
|
def test_extreme_dex_difference_is_capped(self):
|
||||||
|
rng = MidpointRandom()
|
||||||
|
self.assertEqual(hit_damage(fighter(dex=90), fighter(), RULES, rng),
|
||||||
|
hit_damage(fighter(dex=900), fighter(), RULES, rng))
|
||||||
|
|
||||||
|
def test_high_defense_cannot_reduce_base_damage_below_one(self):
|
||||||
|
self.assertEqual(hit_damage(fighter(atk=1), fighter(defense=100000), RULES, MidpointRandom()), 1)
|
||||||
|
|
||||||
|
def test_element_counter_uses_the_attacker_element(self):
|
||||||
|
attack = fighter(element=1)
|
||||||
|
self.assertGreater(hit_damage(attack, fighter(element=2), RULES, MidpointRandom()),
|
||||||
|
hit_damage(attack, fighter(element=3), RULES, MidpointRandom()))
|
||||||
|
|
||||||
|
def test_win_is_derived_from_kills_and_credits_only_actual_hp_lost(self):
|
||||||
|
strong = fighter(hp=10000, atk=10000, attack_ms=100)
|
||||||
|
result = simulate([strong], [fighter()], RULES, seed=1, timeout_ms=10000, enemy_capacity=1)
|
||||||
|
self.assertEqual(result["predicted_outcome"], "win")
|
||||||
|
self.assertEqual(result["enemy_kills"], 1)
|
||||||
|
self.assertEqual(result["player_damage"], 100)
|
||||||
|
self.assertEqual(result["model_duration_seconds"], .1)
|
||||||
|
|
||||||
|
def test_a_weak_roster_can_lose(self):
|
||||||
|
result = simulate([fighter(hp=1, atk=1)], [fighter(hp=10000)], RULES,
|
||||||
|
seed=1, timeout_ms=10000, enemy_capacity=1)
|
||||||
|
self.assertEqual(result["predicted_outcome"], "loss")
|
||||||
|
self.assertEqual(result["player_survivors"], 0)
|
||||||
|
|
||||||
|
def test_timeout_happens_before_an_attack_at_the_same_deadline(self):
|
||||||
|
result = simulate([fighter(atk=100000)], [fighter()], RULES,
|
||||||
|
seed=1, timeout_ms=1000, enemy_capacity=1)
|
||||||
|
self.assertEqual(result["predicted_outcome"], "timeout")
|
||||||
|
self.assertEqual(result["resolved_hits"], 0)
|
||||||
|
|
||||||
|
def test_wave_gap_and_enemy_capacity_are_respected(self):
|
||||||
|
result = simulate([fighter(hp=10000, atk=10000, attack_ms=100)],
|
||||||
|
[fighter(), fighter(), fighter(wave=2)], RULES, seed=1, timeout_ms=10000, enemy_capacity=1)
|
||||||
|
self.assertEqual(result["enemy_kills"], 3)
|
||||||
|
self.assertEqual(result["model_duration_seconds"], 1.0)
|
||||||
|
|
||||||
|
def test_fixed_seed_is_reproducible_and_does_not_mutate_roster(self):
|
||||||
|
team, enemies = [fighter()], [fighter()]
|
||||||
|
before = [asdict(x) for x in team + enemies]
|
||||||
|
first = simulate(team, enemies, RULES, seed=12, timeout_ms=10000, enemy_capacity=1)
|
||||||
|
self.assertEqual(first, simulate(team, enemies, RULES, seed=12, timeout_ms=10000, enemy_capacity=1))
|
||||||
|
self.assertEqual([asdict(x) for x in team + enemies], before)
|
||||||
|
|
||||||
|
def test_invalid_units_and_empty_teams_are_rejected(self):
|
||||||
|
for field, value in (("hp", 0), ("attack_ms", 0), ("atk", float("nan")), ("crit", float("inf"))):
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
fighter(**{field: value})
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
simulate([], [fighter()], RULES, seed=1, timeout_ms=1000, enemy_capacity=1)
|
||||||
|
|
||||||
|
def test_catalog_example_uses_mean_growth_without_changing_source(self):
|
||||||
|
row = {"type": 1, "name": "fixture", "element": 5, "spd_atk": 1600,
|
||||||
|
**{key: 10 for key in ("atk", "def", "hp", "dex")},
|
||||||
|
**{key + suffix: value for key in ("atk", "def", "hp", "dex")
|
||||||
|
for suffix, value in (("_grow_min", 2), ("_grow_max", 4))}}
|
||||||
|
before = dict(row)
|
||||||
|
unit = demo_player(row, 3)
|
||||||
|
self.assertEqual((unit.atk, unit.defense, unit.hp, unit.dex), (16, 16, 16, 16))
|
||||||
|
self.assertEqual(unit.attack_ms, 1588)
|
||||||
|
self.assertEqual(row, before)
|
||||||
|
|
||||||
|
def test_cli_cannot_call_network_and_labels_results_as_uncalibrated_estimates(self):
|
||||||
|
tables = {"monster_info": {"1": {"type": 1, "name": "fixture", "element": 5, "spd_atk": 1000, "skill_1": 3,
|
||||||
|
**{key: 100 for key in ("atk", "def", "hp", "dex")},
|
||||||
|
**{key + suffix: 1 for key in ("atk", "def", "hp", "dex") for suffix in ("_grow_min", "_grow_max")}}}}
|
||||||
|
scenario = (tables, {}, {"name": "fixture"}, [fighter()], RULES, 10000, 1, set())
|
||||||
|
with workspace_temp() as folder, patch("tools.battle_estimate_v12.load_scenario", return_value=scenario), \
|
||||||
|
patch("socket.socket", side_effect=AssertionError("Offline model attempted a socket")), redirect_stdout(io.StringIO()):
|
||||||
|
output = folder / "estimate.json"
|
||||||
|
self.assertEqual(main(["--apk", "fixture.apk", "--species", "1", "--trials", "2", "--output", str(output)]), 0)
|
||||||
|
report = json.loads(output.read_text(encoding="utf-8"))
|
||||||
|
self.assertTrue(report["approximate"])
|
||||||
|
self.assertFalse(report["calibrated_against_original_runtime"])
|
||||||
|
self.assertNotIn("battleData", report)
|
||||||
|
self.assertNotIn("token", report)
|
||||||
|
self.assertEqual(sum(v["count"] for v in report["duration_seconds_by_predicted_outcome"].values()), 2)
|
||||||
|
team = folder / "team.json"
|
||||||
|
team.write_text(json.dumps([asdict(fighter(species=1))]), encoding="utf-8")
|
||||||
|
self.assertEqual(main(["--apk", "fixture.apk", "--team", str(team), "--trials", "2", "--output", str(output)]), 0)
|
||||||
|
report = json.loads(output.read_text(encoding="utf-8"))
|
||||||
|
self.assertEqual(report["ignored_skill_ids_from_catalog"], [3])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -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())
|
||||||
@@ -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()]
|
||||||
@@ -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())
|
||||||
Reference in New Issue
Block a user