Add v1.2 development quest progression and experimental battle runtime
This commit is contained in:
@@ -38,6 +38,7 @@ logs/
|
||||
# Supplied binaries, dependencies and generated packages/previews.
|
||||
*.apk
|
||||
*.zip
|
||||
!/ranch_assistant/data/progression_battles.zip
|
||||
*.jar
|
||||
*.class
|
||||
*.dex
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# 牧羊人之心Bot
|
||||
|
||||
原生 PySide6 桌面辅助,当前版本 **1.1.1**,适配《牧羊人之心》Android **1.9.68**。
|
||||
支持多账号独立运行、牧场培养、每日事务、自动扫荡及本地掉落分析。
|
||||
原生 PySide6 桌面辅助,当前开发版本 **1.2.0.dev1**,适配资料基线为《牧羊人之心》Android **1.9.68**;最近正式版本为 **1.1.1**。
|
||||
支持多账号独立运行、牧场培养、每日事务、自动扫荡及本地掉落分析;v1.2 新增任务、对话与战斗调度,完整集成验证仍在进行。
|
||||
|
||||
## 运行指引
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
|
||||
## 当前功能
|
||||
|
||||
| 模块 | 1.1.1 已具备的功能 |
|
||||
| 模块 | 1.2.0.dev1 当前实现(战斗能力范围见下文) |
|
||||
| --- | --- |
|
||||
| 登录与多账号 | 第一弹渠道账号密码登录,选择官方返回的区服及角色;账号密码与会话在本机加密保存,支持恢复会话、多账号独立运行、退出登录及清除登录记录。关闭账号页签后重启不会重新打开,也可彻底移除该账号的本地记录。 |
|
||||
| 状态刷新与策略开关 | 登录后自动刷新角色、培育室、背包及牧场状态;每个账号只有一个“开启 / 停止”开关,菜单支持批量控制。关闭策略后仍同步状态和到期成长;手动刷新不触发消耗类自动操作。 |
|
||||
@@ -28,14 +28,27 @@
|
||||
| 资质保留与经验喂养 | 支持星级、综合资质、四项全S(4S)保护,另可保留资质严格高于牧场同种培养代表的新魔物。经验喂养按目标优先级批量提交素材,遵守当前突破上限与停止等级,保护锁定、在队和委托所需魔物。 |
|
||||
| 自动赠礼与好感培养 | 在背包选择物品、牧场选择目标后自动赠礼;跳过冷却目标,连续处理其他可送目标,在本地倒计时并到期核对状态。支持喜欢物品筛选、库存保留及当前好感上限。可在本地自动为每种魔物选择唯一培养代表,依次按等级、好感、成长资质比较,完全相同时随机选定并记住。 |
|
||||
| 每日事务 | 查看并领取每日签到礼包、七日签到、累计奖励、已有VIP日奖和邮件附件;支持手动领取及按勾选项目自动领取。 |
|
||||
| 自动委托 | 根据每日剩余次数、城市与库存接取委托,推进已满足条件的步骤并领奖;显示金币和氪金奖励,金币、道具及魔物提交可分别限制。需要实战的步骤等待用户在游戏内完成。 |
|
||||
| 自动主线 | 展示主线、支线、委托的状态、位置、NPC、需求、对话和阻塞原因;推进已支持的接取、线性对话、交付、领奖与任务补链。材料、蛋或击杀不足时,按已知来源规划普通地图收集;开图受前置、资源和战斗能力限制。 |
|
||||
| 自动委托 | 根据每日剩余次数、城市与库存接取委托,推进已支持的步骤并领奖;显示金币和氪金奖励,金币、道具及魔物提交可分别限制。实战委托已接入任务战斗调度,须开启对应选项并通过所选模式的能力检查;设置仍在“自动委托”。 |
|
||||
| 战斗模式与记录 | “自动主线 → 推进策略”显式选择原版运行时(默认)或实验模拟(近似);按普通地图、任务专属战斗、任务通关战斗分别编排。记录胜负、模式、地图奖励事件和待核对原因,支持停止与中断恢复;局部能力不代表全部关卡可用。 |
|
||||
| 自动扫荡 | 按地区折叠显示关卡、难度、通关星级及可能掉落;账号地图首次读取后本地缓存,仅手动刷新关卡时重新获取。逐关勾选、选择已解锁难度和本日次数上限,配置保留体力与战队;处理普通扫荡及探索奖励事件,记录实际奖励。 |
|
||||
| 掉落数据分析 | 按账号、关卡与难度在本地保存扫荡记录,分别统计普通扫荡、奖励事件或合计;展示样本数、出现次数、总数量、实测掉落率、平均数量和95%区间。支持掉落率/每点体力获得数量的条形图,不额外请求游戏服务器。 |
|
||||
| 收益资料与执行计划 | 内置749种魔物的培育时间、派遣金币、强化经验及每小时收益,支持名称/星级筛选和CSV/XLSX覆盖;执行计划显示下一步操作与等待原因。 |
|
||||
| 统一策略配置 | 规则修改后自动保存并应用;通过原生菜单保存、导入或导出当前账号的孵蛋、牧场、喂养、赠礼、委托、每日事务、扫荡、刷新间隔及自定义收益资料。跨账号按魔物种类匹配培养目标,导出文件不包含账号凭据。 |
|
||||
| 统一策略配置 | 规则修改后自动保存并应用;通过原生菜单保存、导入或导出当前账号的孵蛋、牧场、喂养、赠礼、委托、每日事务、扫荡、主线推进、战斗模式、刷新间隔及自定义收益资料。跨账号按魔物种类匹配培养目标,导出文件不包含账号凭据或服务器进度。 |
|
||||
| 界面与调试 | 原生Qt菜单、可调整和隐藏的日志区、各页右键刷新;数字与勾选项可排序,数字框获得焦点后才响应滚轮,下拉框按内容扩宽。独立调试窗口查看请求、响应、耗时与错误,支持复制、导出和本地脱敏日志。 |
|
||||
| 后台处理与离线演示 | 各账号后台线程独立处理网络与资料,单账号请求串行;只渲染当前查看页面,大列表分批更新并复用控件。支持随机30秒、60秒、2分钟或5分钟上限的刷新间隔,以及无需连接服务器的离线演示。 |
|
||||
|
||||
## 1.2 开发版使用要点
|
||||
|
||||
在“自动主线 → 任务状态”点击“刷新任务 / 预览”,查看下一步和阻塞原因;到“推进策略”选择任务范围、推进战斗队伍、保留体力和交付限制,再勾选“启用自动主线策略”,用顶部绿色“开启”运行、红色“停止”暂停。规则自动保存,重启、恢复会话或导入配置后仍需手动开启。委托接取、交付和“也接取需要实战的委托”继续在“自动委托”配置。
|
||||
|
||||
- **原版运行时(默认)**:原 AIR 引擎已通过原始战斗面板自然完成合成阵容的 1-1 离线实验,读取实际战场统计与检查结果,样例 `cheatNum=0`。任意实际阵容的输入桥接仍在完善,当前能力检查会阻止尚未验证的开战;该样例不代表全部原版战斗可用。
|
||||
- **实验模拟(需显式选择)**:使用原始数值资料,在独立进程中计算 AP、出场、移动、攻击和部分技能,记录实际模型轨迹。它包含机制近似与遗漏,可能和原版胜负不同;完整集成 QA、原引擎对拍及真实账号验证尚未完成。
|
||||
- **地图与扫荡**:普通地图可能直接发放探索奖励,此时记录为奖励事件;进入战斗的分支才调用所选运行时。扫荡仍要求普通关卡三个难度全部通关。任务专属战斗和任务通关目标按任务路线处理,击杀缺口不靠扫荡计数。
|
||||
- **中断恢复**:请求结果不明、开战后停止或运行超时时,保留本账号的待核对记录,暂停冲突操作。恢复后先刷新角色与任务;仅在新状态足以确认结果时继续,不重放未知写请求。
|
||||
|
||||
详细设置、能力限制与恢复方法见[辅助使用说明](ranch_assistant/README.md#v12-自动主线与战斗设置);阶段证据及待验收事项见[v1.2 实施与交接](analysis/V1_2_IMPLEMENTATION.md)。当前仍为开发版,尚未发布 v1.2 正式标签。
|
||||
|
||||
## 1.1.1 更新内容
|
||||
|
||||
- 顶部策略按钮改为绿色“开启”和红色“停止”,运行状态更醒目。
|
||||
@@ -55,14 +68,14 @@
|
||||
## 功能范围与数据
|
||||
|
||||
当前登录适配第一弹渠道;需要短信验证的登录流程尚未提供验证码界面。
|
||||
自动扫荡仅用于已满足游戏原有条件的普通关卡,首次通关、特殊关卡及委托战斗仍需在游戏内手动完成;不再提供手机截图配置或ADB自动战斗。
|
||||
自动扫荡仅用于已满足游戏原有条件的普通关卡;v1.2 的首次挑战、任务及委托战斗受所选运行时能力检查限制,未支持内容显示原因并等待处理。当前不提供手机截图配置或ADB自动战斗。
|
||||
|
||||
地图与可能掉落来自客户端静态配置,实际奖励以服务器响应为准;统计概率为本账号已确认样本的实测值。
|
||||
“每点体力数量”按已知消耗样本的物品总量除以实际扣除体力计算,未知消耗不参与。
|
||||
资料包含1178个关卡和2079种道具名称;客户端或接口更新后可能需要重新适配。
|
||||
资料包含1178个关卡和2079种道具名称;v1.2 的独立任务资料另含1165个任务、337个NPC和4269份剧情脚本,其中4239份属于已支持的线性类别,主线引用的720份中有718份属于该类别。脚本分类数量不代表任务或战斗全部通过;30份特殊选择等脚本、4类特殊接取入口及任务1001006的抽蛋钩子仍不支持。客户端热更新与当前账号资源是否一致尚未验证。
|
||||
|
||||
账号凭据、策略、地图缓存、购蛋/扫荡记录及统计数据库均保存在本机 `local_state/ranch_helper/`,按账号和角色隔离。
|
||||
当前代码通过 **209项本地测试**,覆盖会话隔离、策略开关、培养流程、奖励处理、统计与界面响应;测试使用模拟数据和模拟服务,不代表所有功能均已通过真实账号验证。
|
||||
v1.2 常规回归检查497项,493项首轮通过,4项旧界面测试补齐异步等待后复测通过;14项原AIR长时间试跑不纳入常规回归。原版适配器最终集成仍待完成,自动原版开战准入保持关闭。各组准确数量及验证条件见[实施验证记录](analysis/V1_2_IMPLEMENTATION.md#验证记录)。本地模拟结果不代表真实账号通关、服务器接受结算或全部关卡支持。本轮开发验证未执行真实游戏请求,真实账号联网验收由用户手动进行;软件在用户开启策略后,可按配置和能力检查自动执行已支持操作。
|
||||
详细配置与实现范围见[辅助使用说明](ranch_assistant/README.md)。
|
||||
|
||||
## 项目目录与测试
|
||||
@@ -85,16 +98,17 @@ python -B -m unittest discover -s ranch_assistant/tests -v
|
||||
|
||||
| 辅助版本 | 《牧羊人之心》Android 客户端版本 | 状态 |
|
||||
| --- | --- | --- |
|
||||
| 1.2.0.dev1(开发分支 `develop/v1.2.0`) | 1.9.68 静态资料基线 | 开发中;任务与战斗调度已实现,运行时覆盖、实际阵容桥接及完整集成 QA 待完成;未发布正式标签 |
|
||||
| 1.1.1(`v1.1.1`) | 1.9.68 | 当前正式版本,1.1系列修复与界面更新 |
|
||||
| 1.1.0(`v1.1.0`) | 1.9.68 | 已发布版本 |
|
||||
| 1.0.0(`v1.0.0`) | 1.9.68 | 已发布版本 |
|
||||
|
||||
本表仅记录已经分析、测试的版本对应关系,不代表对其他客户端版本的兼容承诺。
|
||||
|
||||
## v1.2 预研
|
||||
## v1.2 开发进展
|
||||
|
||||
[主线任务、普通挑战与战斗委托方案](analysis/V1_2_PLAN.md)包含已核对的客户端调用链、完整资料恢复结果、战斗引擎路线和分阶段验收标准。
|
||||
已增加[离线普攻估算与实机样本对比工具](analysis/V1_2_OFFLINE_EXPERIMENT.md),可在本地计算有限机制下的胜负和耗时分布。忠实执行原始规则的独立战斗引擎尚未跑通;预研中的真实账号联网操作由用户手动执行。
|
||||
[实施与阶段交接](analysis/V1_2_IMPLEMENTATION.md)汇总当前能力、测试证据与后续验收;[方案与阶段状态](analysis/V1_2_PLAN.md)保留客户端调用链研究和实施标准。
|
||||
早期[离线普攻估算工具](analysis/V1_2_OFFLINE_EXPERIMENT.md)、[原 AIR 运行实验](analysis/V1_2_RUNTIME_IMPLEMENTATION.md)和[独立实验模型](analysis/V1_2_SIMULATION_IMPLEMENTATION.md)是三条不同路径,覆盖范围分别记录。本轮真实账号的任务、开战、结算及领奖验证由用户手动进行。
|
||||
|
||||
## 免责声明
|
||||
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
# v1.2 实施记录与阶段交接
|
||||
|
||||
状态日期:2026-11-08。开发分支:`develop/v1.2.0`。当前版本:**1.2.0.dev1**;原始资料基线:Android **1.9.68**。
|
||||
|
||||
任务资料、状态规划器、普通地图/任务/委托战斗编排和界面已经实现,当前进入独立 QA 与运行时集成阶段。原 AIR 已自然完成合成 1-1 离线实验,独立 Python 实验模型也已运行;任意实际阵容的原引擎输入桥接仍在完善,完整集成 QA 正在进行。当前没有全部主线、全部战斗或服务器接受结算的验证结论,也未发布 v1.2 正式标签。
|
||||
|
||||
用户操作见[辅助使用说明](../ranch_assistant/README.md#v12-自动主线与战斗设置)。研究依据和原验收标准见[实施方案](V1_2_PLAN.md)、[任务调用链研究](V1_2_TASK_RESEARCH.md)。本页汇总交接时已收到的阶段证据;最终集成结果尚待回填。
|
||||
|
||||
## 当前实施范围
|
||||
|
||||
| 模块 | 已实现内容 | 代码与证据 |
|
||||
| --- | --- | --- |
|
||||
| 完整任务与地图资料 | 独立资料包保留 1165 个任务、1178 个关卡、337 个 NPC、4269 份脚本,以及任务/地图/收集来源索引。4239 份脚本归入已支持线性类别,主线引用中为 718/720;这些是分类数量,不是任务完成率。 | [资料读取](../ranch_assistant/game_data.py)、[构建工具](../tools/build_progression_data.py)、[资料清单](../ranch_assistant/data/progression_manifest.json)、[支持范围](../ranch_assistant/data/progression_support.json) |
|
||||
| 数据加载 | 任务与索引使用 `progression.json.gz`,地图战斗使用独立 `progression_battles.zip`,按所需关卡延迟读取并校验摘要。保留现有精简 `Catalog`,应用启动不解析 APK,也不一次展开全部地图战斗配置。 | [ProgressionData](../ranch_assistant/game_data.py)、[资料测试](../ranch_assistant/tests/test_progression.py) |
|
||||
| 有状态任务规划 | 接取、前后剧情、本地位置、服务器步骤确认、本地收尾、领奖后继与补链分别建模;保存每个角色的检查点,防止旧快照、重复确认和跨角色状态污染。 | [ProgressionPlanner](../ranch_assistant/progression.py)、[任务研究](V1_2_TASK_RESEARCH.md) |
|
||||
| 任务缺口收集 | 已识别的成年目标击杀、物品及蛋缺口可选择普通地图来源;物品可按条件选择扫荡。检查解锁、位置截获、体力、金币、道具保留和所选战斗能力,结算后重新核对真实库存/击杀。 | [规划器](../ranch_assistant/progression.py)、[引擎集成](../ranch_assistant/engine.py) |
|
||||
| 委托调度 | 全量规划器负责已支持的委托步骤,既有 `QuestPolicy` 继续拥有启用、城市、接取、实战许可和交付保护。候选委托检查整份已知需求,支持日切刷新;旧委托规划器不会同时重复执行。 | [QuestPolicy](../ranch_assistant/quests.py)、[规划器](../ranch_assistant/progression.py)、[Engine](../ranch_assistant/engine.py) |
|
||||
| 战斗与事件编排 | 普通地图、任务内嵌战斗、任务通关战斗分别开始和结算;地图奖励事件独立完成,隐藏战斗重新检查能力。包含战败、取消、模型时钟等待、未知结果与恢复保护。 | [BattleOrchestrator / BattleJournal](../ranch_assistant/battles.py)、[编排测试](../ranch_assistant/tests/test_battle_orchestration.py) |
|
||||
| 用户界面与配置 | “自动主线”的任务状态、推进策略、模式选择和“战斗记录”已接入后台引擎。规则自动保存、按账号/角色隔离,并纳入统一策略导入/导出;顶部绿色“开启”/红色“停止”统一执行。 | [任务界面](../ranch_assistant/progression_gui.py)、[主界面](../ranch_assistant/gui.py)、[策略导入导出](../ranch_assistant/policy_io.py)、[界面测试](../ranch_assistant/tests/test_progression_gui.py) |
|
||||
|
||||
## 三条战斗路径
|
||||
|
||||
| 路径 | 当前用途和证据 | 边界 |
|
||||
| --- | --- | --- |
|
||||
| 早期普攻估算 | 使用简化战斗单位和有限公式做离线胜负/耗时估计,保留为研究工具。 | 不负责应用中的普通挑战或任务结算,不代表原引擎执行。见[估算实验](V1_2_OFFLINE_EXPERIMENT.md)、[估算工具](../tools/battle_estimate_v12.py)。 |
|
||||
| 原始 AS3/AIR 内核 | 已通过原始 `BattlePanel` 自然完成合成阵容的 1-1 离线战斗,取得实际战场统计与原检查,样例 `cheatNum=0`。原版模式是应用默认选择。 | 已证明的范围仅限该离线样例;任意实际阵容的数据桥接、任务路线、资源匹配和广泛覆盖仍待集成验证。当前原版适配器尚未验证支持线上开战/结算,尚未验证的请求会被能力检查阻止。见[适配器](../ranch_assistant/battle_runtime.py)、[原引擎实验说明](V1_2_RUNTIME_IMPLEMENTATION.md)。 |
|
||||
| 独立实验模型 | `ExperimentalBattleRuntime` 在单独 Python 进程中执行 AP、出场、移动、攻击、已知技能及自然终局,输出实际模型轨迹和统计,已经接入应用编排。 | 使用原始数值资料,仍包含机制近似与遗漏;必须显式选择实验模式,不能自动降级混入原版模式。完整集成、原引擎对拍和真实账号验证待完成。见[模型实现](../ranch_assistant/battle_simulator.py)、[机制与测试说明](V1_2_SIMULATION_IMPLEMENTATION.md)。 |
|
||||
|
||||
实验模型已实现技能 **3、5、7、9、38 的部分机制**,以及实际模型轨迹中的击杀、存活、AP、剩余时间、伤害与异常记录。出场、移动、攻击与技能会改变战场状态,胜负由模型运行产生;没有保证胜利、修改原始伤害或清空异常来构造结算。配置自带的缩放按其原有含义处理。
|
||||
|
||||
当前结构准入统计:地图战斗配置 **941/2512**,任务内嵌战斗配置 **106/199**。另有 **12 场合成阵容地图执行自然胜利**。准入数表示近似模型能接收这些配置;既不是原版机制覆盖率,也不是实际账号通关率。不能把 1178 个地图条目、各难度战斗配置数和可执行场次数混为一谈。
|
||||
|
||||
技术契约中,原版路线要求运行时支持且结果具备原版结算资格;实验结果始终标记 `execution_mode='experimental'`、`approximate=True`、`faithful=False`、`settlement_eligible=False`。编排仅在显式实验模式、自然完成、定位匹配、无异常且 `experimental_settlement_eligible=True` 等条件成立后,才允许进入对应的实验结算分支。该标志是本地集成条件,不证明服务器接受或原版完整校验通过。诊断、遗漏和异常随记录保存,原版样例的零检查分也不替代实际阵容验证。
|
||||
|
||||
## 调度与恢复约定
|
||||
|
||||
| 场景 | 当前路线 | 关键约束 |
|
||||
| --- | --- | --- |
|
||||
| 普通地图战斗 | 能力及资源预检 → `stageService/stageStart` → 事件分流 → 运行时 → 成功时 `battleService/battleEnd` → 对应战绩记录 → 刷新核对 | 当前位置关联任务时优先交给任务路线;不能直接当普通地图或扫荡。 |
|
||||
| 普通地图奖励事件 | 开始响应中的已发奖励 → 本地奖励/事件记录 → 刷新 | 不运行战斗,不额外调用普通战斗结算,不把奖励事件记成战斗胜利。 |
|
||||
| 任务 `battle` | `battleService/battleStart` 的任务分支 → 本步骤内嵌配置 → 实际运行 → `taskService/taskCompleteStep` 携带 `battleData` | 主线、支线与委托使用同一类任务路线;接取/交付仍受所属策略限制。 |
|
||||
| 任务 `passStage` | 同一任务开始分支 → 引用地图/难度的战斗配置 → 任务步骤结算 → 已确认的本地通关/解锁收尾 | 不额外调用普通 `battleEnd`,也不用扫荡替代该任务专属战斗。 |
|
||||
| 任务缺口收集 | 已识别来源 → 普通地图战斗或合规扫荡 → 刷新目标计数/库存 → 重新规划任务 | 来源任务信息只用于诊断;收集动作不能直接确认任务步骤。扫荡不提供击杀信用。 |
|
||||
| 扫荡 | 既有 `SweepRunner` 处理三个难度已通关的普通关卡,奖励事件仍单独分流 | 检查特殊关卡、任务位置、开放状态、资源与队伍;逐关规则和本日次数继续由“自动扫荡”管理。 |
|
||||
| 战败或自然战斗时间耗尽 | 保留实际失败结果,走对应失败/战绩路径并累计停止条件 | 不提交胜利结算或本地提前推进任务;工作进程超时、取消、未知结果另归待核对。 |
|
||||
|
||||
代码入口:[编排](../ranch_assistant/battles.py)、[引擎请求构建](../ranch_assistant/engine.py)、[扫荡](../ranch_assistant/sweeping.py)。客户端证据:[任务研究](V1_2_TASK_RESEARCH.md)、[地图分支](STAGES_DAILY.md)、[方案调用链](V1_2_PLAN.md#请求流程必须按战斗类型区分)。
|
||||
|
||||
规划器拥有任务客户端游标与普通剧情检查点。`none` 步骤也先取得服务器步骤确认,再执行后续剧情和本地收尾;不能因为没有资源需求就跳过确认。服务器使用的一基任务步骤和战斗定位中的零基步骤分别转换。领奖响应中的已接取后继与仅解锁任务分开处理,补链按已知图和条件核对,不按任务编号递增猜测后继。
|
||||
|
||||
同账号的请求与战斗串行,战斗计算在独立工作进程中执行。发送写请求前持久化 `BattleJournal`,任务状态和剧情检查点按账号/角色保存;战斗或任务存在未核对状态时,暂停可能改变阵容、资源的牧场、赠礼及任务等冲突写操作,其他账号独立运行。实际目录由账号工作区提供,策略导出不携带凭据、执行日志、待核对状态或服务器进度。
|
||||
|
||||
超时、开战后停止、结算响应未知、进程中断或未支持的隐藏事件都会保留 pending 记录。恢复后只用新取得且角色匹配的服务器快照核对;充分证据可解除阻塞并继续已保存的剧情收尾。旧通关记录、体力变化、未变化的步骤或单独的本地胜利不能证明未知请求已完成。核对过程不重放未知的接取、开战、提交、结算、领奖或战绩写请求;证据不足就继续阻塞,不能靠导入策略、重启或删除日志假装成功。
|
||||
|
||||
### 离线时钟与实际经过时间
|
||||
|
||||
独立离线模拟按模型时钟计算,可比战斗逻辑耗时更快返回,不为模拟时长休眠。实验结果声明需要真实时钟等待;应用编排从开战确认后开始计时,只补足尚未经过的战斗时长,等待可取消,取消后保留待核对状态。该等待不能证明网络结算已获服务器认可。
|
||||
|
||||
模型中的自然时间上限到期属于已完成的战败;工作进程墙钟超时或资源上限属于未完成执行,不携带可结算战果。原 AIR 样例仍按原生时钟运行;加速离线研究不能用于假定线上时序可省略。相关覆盖见[编排测试](../ranch_assistant/tests/test_battle_orchestration.py)和[模型测试](../ranch_assistant/tests/test_battle_simulator.py)。
|
||||
|
||||
## 尚不支持与待验证内容
|
||||
|
||||
- **剧情与入口:**30 份特殊选择等脚本(含 2 份主线引用)、4 类特殊接取入口和任务1001006第4步的 `task1` 抽蛋钩子尚不支持。活动、羁绊、未知任务类别及未验证引导按原因阻塞。线性脚本支持包含已识别的展示与布尔答案事件,不代表完整脚本解释器。具体分类见[支持清单](../ranch_assistant/data/progression_support.json)。
|
||||
- **场地机制:**实验模型拒绝未支持的战斗/魔物控制器、触发器、非歼灭目标、保护/破坏单位及活动场地区域;动态控制器/技能生成目标也不是收集索引的完整来源。
|
||||
- **技能和运动:**技能 3、5、7、9、38 仍是部分移植,其他技能逐项列为遗漏。直线移动、碰撞、惯性、击退、弹道、初始冷却、皮肤动作及随机流存在近似;部分装备效果与 `sunFire`、`moonHeal`、`deadBoom` 等属性机制未实现。可运行的模型仍须披露遗漏,不承诺原版胜负一致。
|
||||
- **原始数值与资源事实:**资料来自原始 APK,实际阵容需完整成长、突破、潜能、装备/聚合属性、好感、升星及队伍等输入,不能用界面参考属性替代。资料摘要验证不等于线上热更新匹配;任意实际阵容的原 AIR 桥接和与原引擎相同时钟/操作/随机流的对拍仍待完成。
|
||||
- **实际游戏:**本轮开发验证未执行真实游戏 API,真实账号的任务、开战、失败、结算、奖励、进度和服务器接受条件仍待用户手动验证。软件在用户开启策略后,可按配置和能力检查自动执行已支持操作;PVP、排行榜/BOSS及特殊活动不属于当前交付承诺。
|
||||
|
||||
## 验证记录
|
||||
|
||||
收尾常规回归检查 **497 项**:首轮 **493 项通过、4 项错误**;4 项均为旧界面测试在切换页面后立即访问尚未完成的后台魔物表格,补齐异步等待后,原 4 项复测全部通过。此结论来自一次全量常规运行及定向复测,并非修正后再次全量运行。常规回归不包含 **14 项原 AIR 长时间试跑**;真实游戏请求未执行。账号回归另有 **13 项通过**,86 份 Python 文件语法检查及暂存内容空白检查通过,未出现 Qt 表格所有权告警。
|
||||
|
||||
原版运行时已用本地缓存阵容离线完成三条战斗路线,原回调样例 `cheatNum=0`;Engine 到原版适配器的最终集成及完整装备/皮肤场景仍未验收,自动原版开战准入保持关闭。实验模式可对明确支持的配置执行,不代表全部主线可用。以下表格保留各阶段的定向验证记录,不能将各组数量相加。
|
||||
|
||||
以下是交接时收到的实现阶段记录,非本文编辑时重新执行的测试。测试组可能相互重叠,不相加为全量总数;常规回归结果见上文,原版运行时与真实账号集成仍待完成。
|
||||
|
||||
| 验证组 | 已报告证据 | 适用边界与复查入口 |
|
||||
| --- | --- | --- |
|
||||
| 数据与规划 | **145 项定向测试通过**;禁用 socket 后检查 **6 份本地日志中的 514 个快照,规划器异常 0 次** | 只读快照和离线规划,不证明写请求或战斗成功。[数据/规划测试](../ranch_assistant/tests/test_progression.py);不公开日志原文及账号资料。 |
|
||||
| 战斗编排 | **66 项编排测试通过** | 模拟服务/运行时下的路线、资源、事件、时钟、取消、异常和恢复保护。[编排测试](../ranch_assistant/tests/test_battle_orchestration.py)。 |
|
||||
| 选定集成回归 | **212 项选定回归通过** | 为实现阶段选定集合,包含重叠测试;不能视作最终全量 QA。[测试目录](../ranch_assistant/tests)。 |
|
||||
| 界面定向验证 | **30 项界面目标测试通过** | 任务/记录界面、模式、配置和交互的目标验证,非真实账号实战。[任务界面测试](../ranch_assistant/tests/test_progression_gui.py)、[规则管理测试](../ranch_assistant/tests/test_rules_management.py)、[策略配置测试](../ranch_assistant/tests/test_policy_config.py)。 |
|
||||
| 独立实验模型 | **38 项测试通过**;结构准入 **941/2512** 地图配置、**106/199** 任务内嵌配置;**12 场合成地图执行自然胜利** | 模型证据,不是原 AIR 对拍、全部关卡或真实账号验收。[模型测试](../ranch_assistant/tests/test_battle_simulator.py)、[模型说明](V1_2_SIMULATION_IMPLEMENTATION.md)。 |
|
||||
| 原 AIR 实验 | 合成 1-1 自然完成,实际原始 `BattlePanel` 统计与检查,样例 **`cheatNum=0`** | 仅该合成离线场景;实际阵容桥接和广泛覆盖待验证。[原版适配器测试](../ranch_assistant/tests/test_battle_runtime.py)、[原引擎说明](V1_2_RUNTIME_IMPLEMENTATION.md)。 |
|
||||
| 完整集成与真实账号 | 独立 QA 正在运行;原版/模型最终集成结论待回填;本轮开发验证未执行真实游戏请求 | 不能据局部结果标记全量通过、服务器接受或发布就绪。 |
|
||||
|
||||
从仓库根目录运行相应离线回归,使用 `-B` 避免生成字节码缓存;界面测试需要已安装的项目依赖。下列是复查命令,不表示本文已执行或这些命令对应所有历史测试组。
|
||||
|
||||
```console
|
||||
python -B -m unittest discover -s ranch_assistant/tests -p "test_progression.py" -v
|
||||
python -B -m unittest discover -s ranch_assistant/tests -p "test_battle_orchestration.py" -v
|
||||
python -B -m unittest discover -s ranch_assistant/tests -p "test_progression_gui.py" -v
|
||||
python -B -m unittest discover -s ranch_assistant/tests -p "test_battle_simulator.py" -v
|
||||
python -B -m unittest discover -s ranch_assistant/tests -v
|
||||
```
|
||||
|
||||
原 AIR 准备与运行涉及单独的本地运行时资源,依赖说明留在[原引擎技术文档](V1_2_RUNTIME_IMPLEMENTATION.md),不作为用户启动辅助的额外配置步骤。
|
||||
|
||||
## 阶段交接与后续验收
|
||||
|
||||
| 后续工作 | 完成判据 | 当前状态 |
|
||||
| --- | --- | --- |
|
||||
| 独立集成 QA | 对当前整合代码核对回归输出、失败/跳过原因、任务服务确认与本地收尾、路线分流、取消/时钟、配置和多账号隔离,记录准确命令与测试数量。 | 进行中;最终结果待回填。 |
|
||||
| 原版输入桥接 | 任意受支持实际阵容快照能按原始规则构建输入,保持属性、站位、技能、检查与输出语义;能力检查只放行已验证场景。 | 完善中;合成 1-1 已证明原内核能够自然完成。 |
|
||||
| 模型最终集成 | 真实模型进程在普通地图、任务 `battle`、`passStage` 和委托路线产生可追踪结果;保留近似、遗漏、异常、资格标志,并验证真实时钟等待与停止恢复。 | 编排已接入;独立集成与原引擎对拍待完成。 |
|
||||
| 用户手动实际验证 | 本轮由用户操作真实账号,分别核对奖励事件、胜负、体力与物品、经验、任务/地图进度和未知响应恢复;写请求不重复。 | 尚无本阶段服务器验收结论;开发验证继续使用离线资料和模拟服务。 |
|
||||
| 扩展覆盖 | 每次增加脚本、技能或控制器,都有明确支持清单、可复现轨迹与对应回归,覆盖不足继续显示原因。 | 按明确场景逐步增加,不承诺全关卡。 |
|
||||
| 正式发布 | 完成最终验证与遗留问题评审,文档和版本一致。 | 验证完成前保持开发版;尚未创建稳定标签或合入main。 |
|
||||
|
||||
接续工作先读取各运行时的最新技术记录和独立 QA 结果,再更新本页、[方案阶段状态](V1_2_PLAN.md)及两份 README。不得沿用早期“只完成静态资料”的描述,也不能把局部原引擎成功或模型准入解释成全主线完成。保持原数值基线的离线近似实验继续推进;本轮真实账号联网验证由用户手动进行,软件在用户开启策略后可自动执行已支持操作。
|
||||
+31
-22
@@ -1,21 +1,31 @@
|
||||
# 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;当前实现为 `develop/v1.2.0` 的 **1.2.0.dev1**。
|
||||
状态:完整任务资料、有状态任务/对话/补链/收集规划、普通地图与任务/委托战斗编排、界面及策略保存已经实现。原 AIR 已通过原始战斗面板自然完成合成 1-1 离线实验,取得实际统计与检查,样例 `cheatNum=0`;任意实际阵容桥接仍在完善。独立实验模型已接入编排,完整集成 QA 正在运行,服务器接受结果仍未验证。验证完成前保持开发版;尚未创建稳定标签或合入main。
|
||||
|
||||
实验安排:按用户本轮授权,离线解析、运行壳和战斗实验直接推进,无需再次确认。预研中的真实账号接任务、开战、结算与领奖由用户手动操作;本轮不自动进行联网游戏实验。
|
||||
实验安排:继续推进离线解析、运行壳和战斗实验。本轮真实账号接任务、开战、结算与领奖验证由用户手动操作;软件在用户开启策略后,可按配置和能力检查自动执行已支持操作。
|
||||
|
||||
新增的[离线实验与实机采样说明](V1_2_OFFLINE_EXPERIMENT.md)记录了可运行的函数、示例结果和本地对比流程。它是有限机制的估算实验,不能替代下面 P1/P2 要求的原引擎运行与对拍。
|
||||
当前交接与准确验证记录见[V1_2_IMPLEMENTATION.md](V1_2_IMPLEMENTATION.md)。下文保留研究证据与验收标准;[早期普攻估算](V1_2_OFFLINE_EXPERIMENT.md)、[原 AIR 运行实验](V1_2_RUNTIME_IMPLEMENTATION.md)、[独立实验模型](V1_2_SIMULATION_IMPLEMENTATION.md)是不同路径,不能互相替代覆盖或对拍证据。
|
||||
|
||||
## 当前阶段状态
|
||||
|
||||
| 范围 | 当前实现与验证状态 |
|
||||
| --- | --- |
|
||||
| 数据和规划 | 独立索引资料包包含1165任务、1178关卡、337 NPC、4269脚本;4239份线性脚本支持,主线引用718/720。145项定向测试通过;禁用socket检查6份本地日志中的514个快照,规划器异常0次。30份特殊选择等脚本(含2份主线)、4类接取入口和任务1001006抽蛋钩子仍不支持。 |
|
||||
| 调度和界面 | 已实现服务器步骤确认后再执行本地剧情收尾、补链、缺口收集、QuestPolicy拥有的委托调度、普通地图奖励事件/战斗分流、三难度全通后扫荡及任务专属战斗路线;编排66项、选定回归212项、界面目标30项为阶段记录,集合有重叠,不相加为全量总数。 |
|
||||
| 原 AIR | 合成1-1已自然完成,使用实际原始BattlePanel统计与检查;当前只是局部离线能力证明,任意实际阵容桥接和广泛支持仍待验证,默认原版模式不放行未验证开战。 |
|
||||
| 实验模型 | 独立进程模型已有38项测试;结构准入941/2512地图战斗配置、106/199任务内嵌配置,12场合成地图执行自然胜利。AP、出场、移动、攻击及技能3/5/7/9/38部分实现,仍有近似与遗漏;已接入应用,须显式选择实验模式。 |
|
||||
| 集成与发布 | 独立完整QA和原版/模型最终集成结论待回填;本轮开发验证未执行真实游戏请求,实际账号验收由用户手动进行。维持开发版,不承诺全部主线或服务器接受结算。 |
|
||||
|
||||
## 可行性结论
|
||||
|
||||
**有技术可行性,但需要恢复一个能够执行原始规则的战斗引擎。任务接取接口不是主要难点。**
|
||||
**原始战斗内核已有单场合成离线成功证据,任务与战斗调度已实现;实际阵容桥接、机制覆盖与完整集成仍需验证。**
|
||||
|
||||
手机可以不启动游戏;电脑辅助仍需登录并与服务器通信。电脑侧可以负责选择任务、准备阵容、运行战斗、提交实际结果、核对任务进度,再继续下一步。
|
||||
战斗必须能够自然得到胜利、失败或超时;强度不够时应停下或等待培养。按原始规则运行不代表任何阵容都能推过主线。
|
||||
|
||||
本次确认了客户端会在本地创建战场、执行AI与技能,再从战场状态生成结算数据。
|
||||
但源码只能说明客户端行为,不能证明服务器不做额外校验,也不能证明一个尚未实现的替代引擎会被服务器接受。
|
||||
但源码和局部离线执行只能说明对应客户端行为,不能证明服务器不做额外校验,也不能证明现有实验模型的结果会被服务器接受。
|
||||
这是后续联调需要验证的条件,不能用扫荡的简化数据代替普通挑战数据。
|
||||
|
||||
## 本次已经确认的证据
|
||||
@@ -25,7 +35,7 @@
|
||||
| 原始APK身份 | SHA-256为 `01678ee3a8465d818d32cbbd94baa0d8253b04b4c57b70ebc5544ed341f1015d`,与原始分析对象一致;未使用伤害修改包 | REA `open_binary` 与本次静态归档检查 |
|
||||
| 主程序 | `assets/MYRMain.app` 为4,196,806字节的FWS/SWF,版本字节为50,SHA-256为 `c6838331a198a22ffa486cbf61cc74c97619e011bc3364c8bb8dc99e269036cf` | [配置与文件清单](V1_2_BATTLE_INVENTORY.json) |
|
||||
| 完整资料可恢复 | 1,178条关卡记录、3,534条难度记录,其中2,512个非空战斗字典;1,165条任务、199个非空任务步骤战斗字典、749种魔物、266组技能配置 | 从原APK中解压并用AMF解析,非空字典不等同于已验证可挑战关卡 |
|
||||
| 当前辅助资料不完整 | 当前目录只保留83条每日委托任务,没有完整技能表/场地表,关卡难度里的战斗字典已被提取脚本剔除 | [提取脚本](../tools/extract_ranch_catalog.py#L70)、[本次清单](V1_2_BATTLE_INVENTORY.json) |
|
||||
| 预研起点的辅助资料不完整 | 既有精简catalog只保留83条每日委托任务,关卡战斗字典被剔除;现已保留原catalog并新增完整任务索引、延迟读取的战斗资料和实验战斗表 | [提取脚本](../tools/extract_ranch_catalog.py#L70)、[原清单](V1_2_BATTLE_INVENTORY.json)、[当前实施](V1_2_IMPLEMENTATION.md) |
|
||||
| 战场在客户端生成 | 关卡配置构造成 `BattleVo`,加入所选玩家队伍,再创建 `BattlePanel` | [BattleCenter.as:36](as3/scripts/net/pixvi/myr/center/BattleCenter.as#L36) |
|
||||
| 战斗有实际循环 | 每帧处理控制器、场地区域、触发器、AI、碰撞、子弹;另有按秒触发的逻辑 | [BattleGround.as:1718](as3/scripts/net/pixvi/myr/battle/BattleGround.as#L1718)、[1844](as3/scripts/net/pixvi/myr/battle/BattleGround.as#L1844) |
|
||||
| 胜负不只有消灭敌人 | 有时间条件、我方全灭、保护/破坏目标、波次和主动撤退等判断 | [BattleGround.as:1141](as3/scripts/net/pixvi/myr/battle/BattleGround.as#L1141) |
|
||||
@@ -83,15 +93,15 @@ REA归档检查的父证据为 `ev_3bb779224b3b2f1754b820542d4efc08d829f6da1e106
|
||||
证据:[BattlePanel.as:262](as3/scripts/net/pixvi/myr/panel/battle/BattlePanel.as#L262)、[314](as3/scripts/net/pixvi/myr/panel/battle/BattlePanel.as#L314)。
|
||||
|
||||
资源还必须与实际服务版本匹配。APK内配置是本次离线基线,不等同于该账号当前热更新资源。
|
||||
后续建立资料包时要带版本、文件摘要和必要的热更新来源记录,避免把旧敌人/技能参数混进新版本战斗。
|
||||
现有资料包已携带原APK版本、来源及文件摘要;线上热更新匹配仍待验证,不能把静态摘要通过解释为实际服务资源一致。
|
||||
|
||||
## 推荐的引擎路线
|
||||
|
||||
| 路线 | 用途与可行性 | 本次结论 |
|
||||
| --- | --- | --- |
|
||||
| Python按公式简单估算 | 可用于阵容强度预览;无法覆盖帧序、弹道、复杂技能和场景触发 | 不作为实际挑战的结算引擎 |
|
||||
| 原始AS3/AIR战斗内核加独立运行壳 | 更适合保持原有逻辑和数值语义,也可作为其他实现的对照基准;需补依赖并切开登录、平台SDK、资源和展示入口 | 优先验证;还没有成功运行的原型 |
|
||||
| 将战斗逻辑逐步移植到独立工作进程 | 能满足长期无需手机、无需完整游戏客户端的目标;需要覆盖度管理和严格对拍 | 运行壳验证后再确定范围;不可承诺一次覆盖全部技能 |
|
||||
| 原始AS3/AIR战斗内核加独立运行壳 | 更适合保持原有逻辑和数值语义,也可作为其他实现的对照基准;需补依赖并切开登录、平台SDK、资源和展示入口 | 原始BattlePanel已自然完成合成1-1;实际阵容桥接及广泛能力仍待验证,尚不能据此认定支持全部原版战斗 |
|
||||
| 将战斗逻辑逐步移植到独立工作进程 | 能满足长期无需手机、无需完整游戏客户端的目标;需要覆盖度管理和严格对拍 | 独立Python实验模型已实现并接入编排,38项模型测试;近似与遗漏明确披露,完整集成和原引擎对拍待完成 |
|
||||
| 直接把完整游戏SWF交给替代播放器 | 依赖AIR接口、显示列表、资源和原生扩展的兼容性 | 本次不能认定可用,也不作为交付前提 |
|
||||
|
||||
AIR官方ADL文档支持开发期运行SWF,并提供命令行模式;但命令行模式的 `stage` 为null、没有显示列表。
|
||||
@@ -102,8 +112,7 @@ AIR官方ADL文档支持开发期运行SWF,并提供命令行模式;但命
|
||||
Ruffle官方兼容性页仍将AS3语言与API兼容性分别列为未全覆盖;这也不能直接推出本游戏可运行或一定不可运行,必须做本游戏的兼容性验证。
|
||||
来源:[Ruffle兼容性说明](https://ruffle.rs/compatibility)。
|
||||
|
||||
当前PATH可发现Java,但未发现ADL、mxmlc或FFDec命令;这只是PATH范围内的观察,不等同于整机没有安装。
|
||||
AS3运行壳尚未执行。新增 Python 普攻估算实验只覆盖下文列明的有限机制;AS3运行壳仍是下一阶段的工程验证项。
|
||||
预研初期的PATH检查只发现Java;后续已准备本地AIR运行资源并执行合成离线战斗,最新依赖与运行证据见[原引擎技术记录](V1_2_RUNTIME_IMPLEMENTATION.md)。早期Python普攻估算仍是独立研究工具,不是当前应用的实验战斗模型。
|
||||
|
||||
## v1.2 分阶段实施方案
|
||||
|
||||
@@ -116,8 +125,8 @@ AS3运行壳尚未执行。新增 Python 普攻估算实验只覆盖下文列明
|
||||
| P4 主线和委托调度 | 主线接取、步骤推进、地图挑战、任务专属战斗、提交与领奖;恢复未完成步骤 | 覆盖一个包含非战斗和战斗步骤的任务链;战斗完成后再核对任务状态,不凭本地胜利预先推进 |
|
||||
| P5 扩大覆盖与多账号 | 扩充技能、场景和事件覆盖;独立工作进程、配置导出、诊断与任务界面 | 大列表和战斗不阻塞Qt;角色互不串数据;遇不支持内容、实际战败或资源不足时按策略停止 |
|
||||
|
||||
推荐先交付P0的任务可视化和P1的离线战斗验证,再评估P2/P3的工作量。
|
||||
若独立运行壳与原引擎对拍尚未通过,v1.2就不应宣称已经支持完整自动推主线。
|
||||
当前进度:P0资料和任务可视化已实现;P1取得原AIR合成单场自然完成证据,实际阵容输入仍待完成;P2已有有限机制实验模型,原引擎严格对拍待完成;P3/P4的普通地图、任务和委托编排及模拟测试已实现,真实账号闭环未验收;P5的进程、配置和界面已接入,完整QA及覆盖扩展继续进行。各阶段具体交接见[实施记录](V1_2_IMPLEMENTATION.md#阶段交接与后续验收)。
|
||||
当前局部运行与测试不构成完整自动推主线的验收。
|
||||
大量特殊机制的覆盖成本只有验证具体阵容、敌人、技能与关卡后才能估算,现在给出全部完成日期没有依据。
|
||||
|
||||
## 程序结构与调度
|
||||
@@ -136,7 +145,7 @@ flowchart TD
|
||||
C --> Q
|
||||
```
|
||||
|
||||
建议的模块边界:
|
||||
原方案的模块边界如下;当前实现映射为 `game_data.py`、`progression.py`、`engine.py`、`battles.py` 和两个独立运行时,具体状态见[实施范围](V1_2_IMPLEMENTATION.md#当前实施范围):
|
||||
|
||||
- `game_data`:完整资料包、配置摘要、版本匹配与能力查询;不持有账号Token。
|
||||
- `progression`:任务图、主线/委托步骤分类、地图定位、剧情触发和下一步解释。
|
||||
@@ -150,16 +159,16 @@ flowchart TD
|
||||
关卡开始、任务步骤或结算请求结果不明确时,先记录待核对并查询现状,不自动重发,也不随意重新开始同一场。
|
||||
本地尝试ID用于防止本程序重复执行,不代表服务器提供幂等接口。
|
||||
|
||||
界面增加“自动主线”页,展示已完成/进行中/可接取/条件不足/不支持的任务和下一步;“战斗记录”展示本场队伍、胜负、耗时和阻塞原因。
|
||||
界面已增加“自动主线”页,展示任务状态、位置、需求、对话、下一步与支持原因;“战斗记录”展示上下文、队伍、结果、模式和原因,耗时等执行证据保存在本地日志中。
|
||||
仍复用顶部绿色“开启”与红色“停止”,不再增加“仅监控/执行”两套开关。
|
||||
配置只包含任务范围、可用战队、保留体力、失败停止次数与是否包含委托等偏好,并纳入现有统一导入/导出;服务器通关进度不能靠配置文件设置。
|
||||
|
||||
## 本次预研的边界与待验证项
|
||||
|
||||
- 已证实:原APK身份、配置可以恢复、本地战斗核心与统计采集入口、普通地图/任务分流,以及当前辅助资料被精简的事实。
|
||||
- 工程推断:完整输入、时序、技能与依赖补齐后,独立执行原始规则有可行路径;普攻估算原型已经运行,尚不能证明原始战斗机制的覆盖、准确性和速度。
|
||||
- 未验证:当前线上热更新与APK的差异、独立运行壳的兼容性、动画与时钟完整迁移、随机流复现、具体账号的所有加成是否完整可得、服务器接受真实独立战斗结果的条件。
|
||||
- 已证实:完整静态资料已经进入独立资料包;任务、剧情检查点、补链、收集、委托、编排与界面已实现。原始战斗内核自然完成合成1-1并取得实际统计与检查;实验模型有局部结构准入和合成执行证据。
|
||||
- 工程边界:原AIR单场成功、实验模型执行与早期普攻估算分别评价;原版能力检查和显式实验模式分开,有限技能及场地支持不能解释为全关卡完成。
|
||||
- 未验证:完整集成QA、任意实际阵容的原引擎桥接、线上热更新匹配、完整动画/时钟/随机流对拍、实际角色全部加成与服务器接受结算条件。
|
||||
- 范围:当前方案先覆盖已验证普通关卡和任务战斗。PVP、排行榜/BOSS及特殊活动不纳入首批交付。
|
||||
- 本轮工具不自动登录真实账号或发送任务/战斗写请求;用户手动运行手机游戏,电脑被动记录指定接口。采样准备包括本机代理、USB转发和公开CA证书传输;没有改动1.1.1的辅助执行逻辑。
|
||||
- 本轮开发验证未执行真实游戏请求;真实账号接取、开战、结算和领奖验证由用户手动进行。开发分支已加入v1.2自动策略执行编排;未知写请求保持待核对,不自动重放。
|
||||
|
||||
下一步建议:完成“一场离线普通战斗的忠实运行与对拍”,再开展联网挑战和任务闭环。
|
||||
下一步:完成实际阵容桥接与原版/模型集成,回填独立QA准确结果,再由用户手动核对本轮实际游戏闭环。验证完成前保持开发版;尚未创建稳定标签或合入main。
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# v1.2 privacy audit
|
||||
|
||||
Date: 2026-11-08. Scope: known personal workstation paths and device identifiers in current tracked text, with edits limited to the two legacy tools below and SDK decompiler path comments.
|
||||
|
||||
- Initial scan: 18 occurrences across 17 files (16 local profile paths, one device identifier, one workstation ADB executable path). No matching files outside the authorized edit scope.
|
||||
- Final scan: 1,464 tracked text files checked; zero remaining occurrences of the known identifiers. One binary file was excluded from the text scan. The new audit was checked separately. Results contain filenames and counts only, without the identifier values.
|
||||
- `read_device_battle_assets.py` now accepts `--adb` (otherwise uses PATH) and `--serial`. Actual invocation checks ADB authorization; automatic selection requires exactly one authorized connected device. Import and `--help` perform no discovery, device operations, or writes. Packaged-asset extraction and matching remain available.
|
||||
- `build_battle_v3.py` now requires `--build-tools`, or the explicit `build_tools` keyword argument when called from Python. APK modification, repacking, signing, cache options, and verification logic are preserved.
|
||||
- Removed only the source-local-path JADX comment in each of the 15 Java files listed below. Vendor namespaces, public endpoints, protocol information, and Java logic remain unchanged. Author and contributor attribution was not edited; AttilaNet <zbolink@foxmail.com> remains permitted.
|
||||
|
||||
Validation passed: in-memory Python syntax compilation for both tools; inert imports and both `--help` entrypoints with subprocesses, tool discovery, and file writes forbidden; nine mocked device-selection cases; missing-ADB rejection; static equality of APK build function bodies apart from the configured tool-directory name; Java comparison against the index after Git newline normalization and removal of the permitted comments only; whitespace checks. No ADB process, device/game operation, APK modification, or signing was executed.
|
||||
|
||||
Changed files:
|
||||
|
||||
- `tools/read_device_battle_assets.py`
|
||||
- `tools/build_battle_v3.py`
|
||||
- `analysis/sdk_login/com.diyidan.game.api.DydGameApi.java`
|
||||
- `analysis/sdk_login/com.diyidan.game.common.Constants.java`
|
||||
- `analysis/sdk_login/com.diyidan.game.dialog.LoginDialog.java`
|
||||
- `analysis/sdk_login/com.diyidan.game.entity.impl.DydPlayerModel.java`
|
||||
- `analysis/sdk_login/com.diyidan.game.network.BaseNetwork2.java`
|
||||
- `analysis/sdk_login/com.diyidan.game.network.SuccessListener.java`
|
||||
- `analysis/sdk_login/com.diyidan.game.network.UserNetwork2.java`
|
||||
- `analysis/sdk_login/com.diyidan.game.network.model.JsonData.java`
|
||||
- `analysis/sdk_login/com.diyidan.game.network.model.ListJsonDataModel.java`
|
||||
- `analysis/sdk_login/com.diyidan.game.network.util.AESTools.java`
|
||||
- `analysis/sdk_login/com.diyidan.game.network.util.DydOkHttpNetwork.java`
|
||||
- `analysis/sdk_login/com.diyidan.game.network.util.DydStringRequest.java`
|
||||
- `analysis/sdk_login/com.diyidan.game.util.JsonUtils.java`
|
||||
- `analysis/sdk_login/com.diyidan.game.util.Utils.java`
|
||||
- `analysis/sdk_login/net.pixvi.ane.dydsdk.functions.LoginFunction.java`
|
||||
- `analysis/V1_2_PRIVACY_AUDIT.md`
|
||||
|
||||
This finding applies to current tracked working-tree text and the new audit, for the exact known identifiers (including ordinary and escaped path separators). It is not an exhaustive search for unrelated personal information, secrets, ignored/untracked files, or publication artifacts. Git history and the index were not changed; older revisions may still contain the removed values. The cleaned files need to be included in the published revision. No feature files, game data, logs, commits, or remote state were changed by this task.
|
||||
@@ -0,0 +1,281 @@
|
||||
# v1.2 original offline battle runtime — development build
|
||||
|
||||
Updated 2026-11-08. The original compiled engine now completes actual offline
|
||||
scenes through `BattleCenter → BattleGround → BattlePanel.battleCompleteHandler`.
|
||||
Ordinary stage, embedded task battle, and task `passStage` each have a completed
|
||||
snapshot-driven native scene with original statistics and original checks.
|
||||
This is executable development functionality; complete game coverage, matching
|
||||
the current live resources, and server acceptance have not been established.
|
||||
No game API actions were performed for this validation.
|
||||
|
||||
**Frozen development checkpoint:** scope stopped at the user's quota request.
|
||||
The fixed bridge completed the cached roster in all three contexts with
|
||||
`cheatNum=0` and two retained player checks per scene. Its actual cached team has
|
||||
two occupied slots. The final identity comparison accepts original decimal-string
|
||||
audit IDs without modifying either output. Revalidation of all three existing
|
||||
executed callback bodies passes; no additional native trial was launched.
|
||||
Automatic native admission is deliberately disabled by
|
||||
`NATIVE_ADMISSION_ENABLED=False` pending final Engine/native/fake-client integration
|
||||
QA. Offline execution remains available. This is an integration checkpoint,
|
||||
not a restriction based solely on untested server acceptance.
|
||||
|
||||
## Public integration contract
|
||||
|
||||
The runtime accepts `BattleRequest` or the equivalent dictionary:
|
||||
|
||||
```python
|
||||
request = BattleRequest(
|
||||
context="ordinary_stage", stage_id="0101", difficulty=1,
|
||||
original_data={"battle": canonical_original_battle},
|
||||
roster=raw_master_snapshot, team="teamB",
|
||||
battle_position={"battleType": "stage", "stageId": "0101",
|
||||
"stageLevel": "1", "taskTypeId": None, "taskStep": 0},
|
||||
)
|
||||
runtime = BattleRuntime() # optional config: {"backend": "original_air"}
|
||||
capability = runtime.inspect(request)
|
||||
result = runtime.run(request, cancel_event=event, timeout=None)
|
||||
```
|
||||
|
||||
`roster={"snapshot": raw_master_snapshot, "team_name": "teamB"}` is also
|
||||
accepted for CLI callers. Both forms normalize to the same native input.
|
||||
An explicit team is required. Conflicting selectors refuse; no default changes
|
||||
`teamB` to `teamA`. Requests are copied once before inspection and execution.
|
||||
`original_data` optionally accepts `source="original_apk"` and the exact pinned
|
||||
`resource_identity`; it never accepts executable commands, replacement tables,
|
||||
an estimated result, or a manifest claiming verification.
|
||||
|
||||
| Context | Original config selected | Native BattlePosition |
|
||||
| --- | --- | --- |
|
||||
| `ordinary_stage` | `stage_info[stage_id].level[difficulty].battle` | `battleType=stage`, string stage ID/level |
|
||||
| `task_battle` | `task_info[type_id].steps[step_index].battle`, status `battle` | `battleType=task`, task type and zero-based step |
|
||||
| `task_pass_stage` | stage/level from the original step's `statusValue`, status `passStage` | Same task position; no ordinary-stage result substitution |
|
||||
|
||||
With canonical orchestration requests, `battle_position.taskTypeId` identifies
|
||||
the original task definition; `task_id` may retain the account task-instance ID.
|
||||
Without `battle_position`, legacy CLI task requests use `task_id` for the original
|
||||
task type. Task step conflicts and wrong supplied positions refuse. The supplied
|
||||
battle must equal the independently decoded original config for that context.
|
||||
The engine-side `runtime_request` must retain `battle`, `team`, and
|
||||
`battle_position`; an identity-only request cannot reconstruct the selected team.
|
||||
|
||||
`inspect` returns `supported`, `offline_supported`, specific `reasons`, original
|
||||
resource identity, input coverage, native position, original battle duration, and
|
||||
derived watchdog. Support refers to offline execution of those supplied inputs,
|
||||
not to every stage or skill having an observed test. The complete original SWF
|
||||
contains the combat implementations; this adapter does not handport skill math.
|
||||
Unknown controllers, effects, formations, data shapes, and required missing images
|
||||
refuse. The native bridge additionally validates and constructs the snapshot.
|
||||
An unseen dynamic dependency can still fail execution and produce no outcome.
|
||||
|
||||
Validated snapshot execution reports original-code fidelity (`faithful=True`,
|
||||
`approximate=False`); diagnostic fixtures and invalid inputs do not qualify.
|
||||
`settlement_eligible=False` remains enforced at this frozen checkpoint pending
|
||||
final integration QA. `server_acceptance_verified=False` and the compatibility
|
||||
alias `server_validated=False` are independent of original-code fidelity.
|
||||
The implemented eligibility path requires original input/resource validation,
|
||||
natural completion, zero original check points, callback/roster/route binding,
|
||||
complete original statistics, and a valid asset audit. Strict synchronized trace
|
||||
parity and current server resource matching remain unverified. Online orchestration
|
||||
must gate before starting a battle.
|
||||
|
||||
Successful `run` results contain `status="completed"`, `battle_executed=True`,
|
||||
`battle_completed=True`, `outcome`, and `offline_result` with the actual original
|
||||
`battle_data`, `anomaly_records`, per-unit original records, timing, and terminal
|
||||
reason. Positive original `cheatNum` yields `status="anomaly"`, preserves the
|
||||
completed native evidence, and keeps eligibility false. Unsupported, cancelled,
|
||||
technical timeout, or failed jobs do not return an outcome or BattleData.
|
||||
Interrupted worker execution is `battle_executed=None` when progress is unknown;
|
||||
pre-start refusal/cancellation is `False`.
|
||||
|
||||
## Native execution and artifact identity
|
||||
|
||||
REA inspected the shipped original APK; retained AS3 was used for focused call
|
||||
inspection, not rebuilt as a replacement engine. The shipped identities are:
|
||||
|
||||
| Resource | Identity |
|
||||
| --- | --- |
|
||||
| APK 1.9.68 SHA-256 | `01678ee3a8465d818d32cbbd94baa0d8253b04b4c57b70ebc5544ed341f1015d` |
|
||||
| `assets/MYRMain.app` SHA-256 | `c6838331a198a22ffa486cbf61cc74c97619e011bc3364c8bb8dc99e269036cf` |
|
||||
| Main SWF header | Version 50, **50 FPS**, 640×960 RECT; FPS was decoded separately from the version byte |
|
||||
| Local SDK | Official AIR SDK 51.5.1.1, Windows x64; executable/JAR/SWC pins in `trusted.py` |
|
||||
|
||||
`swf_library.py` removes document-class binding ID 0 and makes DoABC blocks lazy.
|
||||
All 1,641 main ABC payloads remain byte-identical; 1,324 eager flags change.
|
||||
Executable/import tags are refused. Neither the original game document class nor
|
||||
the loader's login/update startup executes. Framework, main, UI, and movieclip
|
||||
library copies load into one child ApplicationDomain. No native extension, phone,
|
||||
rooting, protection bypass, rebuilt APK, or modified battle code is required.
|
||||
|
||||
`OriginalProbe.as` is a small compiled bootstrap. It injects original compressed
|
||||
AMF tables using native `ByteArray.readObject`, initializes the generic display
|
||||
framework, invokes `SnapshotBridge.build`, and starts the stock BattleCenter.
|
||||
Stock movement, AP, AI, skills, collisions, animation callbacks, timers, result
|
||||
statistics, and cheat checks execute. Only local win/loss observers are installed;
|
||||
the harness never forces a winner. Component probes are a separate action, so they
|
||||
do not consume random values or temporary unit IDs before a scene.
|
||||
|
||||
All original NetCenter service bases are replaced with a nonexistent local file
|
||||
URI before snapshot/scene construction. The image hook refuses URL/colon/path
|
||||
traversal inputs; sounds are disabled through original settings. Completion checks
|
||||
the original NetCenter request counter is zero. Python execution imports no game
|
||||
transport. This is deliberate transport isolation and neutralized startup,
|
||||
not a claim of an OS network sandbox around arbitrary AIR code.
|
||||
|
||||
The correct launcher is `adl64.exe -runtime ... -nodebug -profile
|
||||
extendedDesktop descriptor.xml -- ...`. The x86 launcher returned exit 4;
|
||||
misordered `-runtime` arguments were rejected. ADL uses the SDK runtime without a
|
||||
global installation. `-cmd` is unsuitable because its stage is null; the game uses
|
||||
display objects and frame callbacks. See [official ADL documentation](https://airsdk.dev/docs/building/air-debug-launcher).
|
||||
|
||||
## Assets, callbacks, and timing
|
||||
|
||||
Normal preparation builds a ZIP-entry index directly from the pinned APK:
|
||||
original hashed resource key, local-header data offset, compressed size, size,
|
||||
method, and CRC32. It verifies local/central metadata and entry bounds. Native
|
||||
FileStream reads the original packed bytes, decompresses ZIP deflate, verifies
|
||||
size/CRC, and passes those bytes to the original image decoder. Reading a new
|
||||
unit's assets does not require extracting the 1.4 GB resource tree. Existing
|
||||
earlier extracts remain ignored. Post-run audit compares every observed resource
|
||||
with the APK ZIP metadata. The native compression API is documented in the
|
||||
[official ByteArray reference](https://airsdk.dev/reference/actionscript/3.0/flash/utils/ByteArray.html).
|
||||
|
||||
An absent required image refuses. Empty optional frame declarations that are
|
||||
also absent from the original APK retain the original local IO-error callback;
|
||||
their paths remain in evidence. No replacement pixels or fabricated completion
|
||||
callbacks are supplied. The base slime's original `1001010_q_2s.png` absence is one
|
||||
such observed fallback. Native skill effects and additional spawned-unit assets
|
||||
are audited when read; an unapproved missing dependency stops the scene.
|
||||
|
||||
The stage runs hidden, 640×960, at the original 50 FPS. The harness records a
|
||||
separate ENTER_FRAME/100 ms Timer sample and full-scene frames/wall time, plus
|
||||
original frame-driver callback/delta observations. Initial short cold samples
|
||||
were about 42.7 FPS; full 1-1 scenes were about 49 FPS. New measurements include a
|
||||
300 ms warm-up and 2.5-second observation window. The subsequent three hidden
|
||||
samples measured 48.26–48.30 FPS and 22 Timer ticks over 2.505–2.527 seconds;
|
||||
the repeated task scene measured 47.45 FPS over 7.566 seconds. Requested FPS is
|
||||
never presented as measured FPS. Hidden-window execution is demonstrated on this workstation;
|
||||
timing under another host's background throttling remains an environment limit.
|
||||
|
||||
A critical bootstrap error was fixed: original EnterFrameDriver's constructor
|
||||
already calls `startup()`. Calling it again created a second ENTER_FRAME source,
|
||||
corrupted delta timing, and froze a skill pause. The harness now only registers
|
||||
its observer. Earlier 30-FPS and stalled 50-FPS evidence remains retained, and is
|
||||
not counted as correct original-timing validation.
|
||||
|
||||
The default technical watchdog is `2 × original battle seconds + 90` (690 s for
|
||||
the original 300-second normal limit). An explicit caller deadline is preserved,
|
||||
including source inspection and bootstrap. Cold APK hashing checks cancellation
|
||||
and the deadline between chunks; a 0.1-second cold deadline returned in 0.103 s
|
||||
without launching combat. Natural native clock completion is a completed native
|
||||
result with `terminal_reason="time_limit"`; winner still comes from original
|
||||
rules, including survival scenes that win on time. A technical watchdog supplies
|
||||
no BattleData and never changes the battle's original time limit.
|
||||
|
||||
## Observed completed native scenes
|
||||
|
||||
The following runs use unchanged original battle configs. Synthetic selected IDs
|
||||
exceed the NPC/player-check exemption threshold. Every row has retained original
|
||||
player check records; callback data is original `BattleData.getObj()`.
|
||||
|
||||
| Input and route | Outcome | Original clock used | Scene wall time / frames | Original checks |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Three level-1 adult green slimes, mean original growth, master level 1, ordinary `0101/1` | Win | 37.127 s | 41.112 s / 2,020 = 49.13 FPS | `cheatNum=0`, 3 player records |
|
||||
| Complete synthetic snapshot, original levels 1/2/3, ordinary `0101/1` | Win | 38.883 s | 44.299 s / 2,190 = 49.44 FPS | `cheatNum=0`, 3 player records |
|
||||
| Same snapshot, original task `2002014`, zero-based step 2 | Natural loss | 5.133 s of 60 s | 8.701 s / 405 = 46.55 FPS | `cheatNum=0`, 3 player records |
|
||||
| Same snapshot, task `1001004`, step 0 (`passStage` 0101/1) | Win | 30.943 s | 35.473 s / 1,750 = 49.33 FPS | `cheatNum=0`, 3 player records |
|
||||
|
||||
The first row read 12 distinct asset members with one genuine original optional
|
||||
absence and zero CRC/size mismatches. It retained 11 original unit records:
|
||||
player-side damage 784; enemy-side damage 371; five enemies dead. Native final
|
||||
AP was 13 and `aliveNum` was 5. These are actual engine outputs, not expected
|
||||
values filled by the harness. Randomness is native and unseeded, so subsequent
|
||||
valid fights need not reproduce those numbers.
|
||||
|
||||
Legacy `killNum`, `totalDamage`, `deadNum`, and `bossDamage` remained zero as in the
|
||||
retained original code path. `killMonster={}` in 1-1 follows the original mode-2
|
||||
enemy counting condition; its five enemies are juvenile mode 1. No counters are
|
||||
repaired. `anomaly_records` has four fields, not four anomalies: the count is
|
||||
`battle_data.cheatNum`, and even a zero count may retain `+0uneqmon` audit text.
|
||||
|
||||
Additional bounded experiments: an authored 30-second survival/spawn-controller
|
||||
scene completed in a natural loss before time expired, `cheatNum=0`. An invalid
|
||||
synthetic level-90/potential-1 roster triggered three original `+50overlv` records:
|
||||
`cheatNum=150`, adapter status `anomaly`, all records retained. That attempt is
|
||||
negative validation, not a successful timing or valid-roster proof.
|
||||
|
||||
## Snapshot bridge status and resolved bootstrap blockers
|
||||
|
||||
The independently owned `SnapshotBridge.as` compiles with the native harness.
|
||||
It uses original History/Monster/Bag/Team/global/addition builders and original
|
||||
AP getters, preserves input, and restores prior master on construction failure.
|
||||
The complete synthetic snapshots above passed the real bridge and full scenes.
|
||||
|
||||
The first authorized cached-snapshot attempt stopped before combat at:
|
||||
|
||||
```text
|
||||
phase: original_snapshot_bridge
|
||||
SnapshotBridge[missing_attributes] monsterAttributes:
|
||||
a complete attribute row is required for every selected monster instance
|
||||
```
|
||||
|
||||
Original MasterCenter allows a complete empty independent-addition list; the
|
||||
earlier bridge instead required every selected row. It also indexed
|
||||
`Table.skin_info.skins`, whereas original
|
||||
Table startup and this harness expose the flat `Table.skin_info` dictionary.
|
||||
The helper owner fixed both issues. No zero rows or nested table wrappers were
|
||||
fabricated. Cached-roster scenes now complete in all three contexts with zero
|
||||
original check points; their callback bodies pass the corrected binding validator.
|
||||
The original audit IDs may be strings while BattleData IDs are numbers; comparison
|
||||
normalizes identity only and retains original output types. A full skin/equipment
|
||||
scene and final Engine/native/fake-client integration remain pending at freeze.
|
||||
Private roster content,
|
||||
account identifiers, paths, statistics, and logs are omitted from this document.
|
||||
|
||||
## Process isolation and validation
|
||||
|
||||
Every worker has a fresh cwd/log directory, input/result nonce, captured compiler
|
||||
sources and their hashes, unique AIR application ID, and distinct native storage
|
||||
directory. Fixed Python → Java → ADL commands run without a shell. The Windows
|
||||
Job Object kills the worker and descendants on cancellation, deadline, or parent
|
||||
close. A process-tree test confirms the descendant is terminated. Imported runtime
|
||||
commands/paths/env/support manifests and unsigned verification claims are refused.
|
||||
SDK and prepared libraries use bundled reviewed hashes; native result verification
|
||||
also checks APK/main identity, input digest, nonce, route, outcome, anomaly count,
|
||||
actual execution/completion, and resource audit.
|
||||
|
||||
Two simultaneous native component probes passed with different native app IDs,
|
||||
storage directories, and nonces. The first concurrent trial exposed Windows
|
||||
`WinError 5` replacing a shared asset index during a read. Preparation now reuses
|
||||
identical immutable verified bytes and safely accepts a competing identical write;
|
||||
the repeated simultaneous trial passed. No cross-account invoke forwarding or
|
||||
shared application storage was observed.
|
||||
|
||||
Focused validation: **46 no-network unit tests pass**. They cover data/route/team
|
||||
contracts, unknown mechanics/assets, native result binding, anomaly preservation,
|
||||
time-limit result semantics versus watchdogs, default/explicit deadlines, arbitrary
|
||||
command rejection, SWF document neutralization/ABC preservation, ZIP offsets/CRC,
|
||||
resource preparation races, cancellation, and process-tree termination. Native
|
||||
execution is explicit opt-in and is not part of routine unit tests.
|
||||
The same 46 tests also passed with Python socket connection methods blocked.
|
||||
Combined runtime/orchestration validation passed **130 tests**. The latest
|
||||
explicit native task/concurrency validator exited 0, and no ADL worker remained
|
||||
after completion.
|
||||
|
||||
```powershell
|
||||
python -B -m unittest ranch_assistant.tests.test_battle_runtime -v
|
||||
python -B -m tools.battle_runtime.prepare
|
||||
python -B -m tools.battle_runtime.probe --compile-only
|
||||
python -B -m tools.battle_runtime.validate_native
|
||||
python -B -m tools.battle_runtime.validate_native --contexts task_battle --concurrent
|
||||
```
|
||||
|
||||
`validate_native --request <local JSON>` runs the public API against a data-only
|
||||
request, writes full evidence under ignored local_state, and prints aggregate
|
||||
results. `--rich` selects synthetic gear/skin inputs; their full-scene validation
|
||||
remains pending at freeze. The opt-in `acquire_air` tool downloads pinned
|
||||
51.5.1.1 dependencies into ignored local_state using official ZIP ranges; normal
|
||||
runtime/test execution never downloads anything or alters PATH/global config.
|
||||
|
||||
This owner changed only `battle_runtime.py`, its runtime tools/tests, and this
|
||||
document. Engine/UI/progression/AMF fixes belong to their respective owners.
|
||||
No commit, push, game request, battle submission, or reward action was performed.
|
||||
@@ -0,0 +1,280 @@
|
||||
# v1.2 experimental offline simulation
|
||||
|
||||
Implemented as a separate experimental Python model, parallel to original AIR
|
||||
runtime research. This is useful approximate combat, not an AIR engine replay.
|
||||
|
||||
## Public request/result contract
|
||||
|
||||
`ranch_assistant.battle_simulator.ExperimentalBattleRuntime` implements
|
||||
`inspect(request)` and `run(request, cancel_event=None, timeout=30.0)`.
|
||||
Both accept dicts or objects with the same attributes. Request fields are
|
||||
`context` (`ordinary_stage`, `task_battle`, `task_pass_stage`),
|
||||
`original_data` containing the original `battle` dictionary, `roster` containing
|
||||
the full raw snapshot (or `snapshot.raw`), `team` (original ordered team string),
|
||||
and `battle_position`. Optional `seed` defaults to zero. No game API is called.
|
||||
|
||||
Every response carries `execution_mode='experimental'`, `approximate=True`,
|
||||
`faithful=False`, `settlement_eligible=False`, `diagnostics`, and
|
||||
`ignored_mechanics`. `supported` means this approximate model can execute;
|
||||
it is never a claim of original engine fidelity or permission to settle.
|
||||
Unsupported objectives/controllers/triggers return `outcome='unsupported'`.
|
||||
An executed result includes natural `win`/`loss`, or technical `timeout`/`cancelled`,
|
||||
`units`, `events`, `elapsed_ms`, AP history, kill counters, and detected
|
||||
anomalies. Any `battle_data` will be explicitly model-derived evidence,
|
||||
never a fabricated victory or an authorization to submit.
|
||||
|
||||
### Worker contract
|
||||
|
||||
```python
|
||||
request = {
|
||||
"context": "ordinary_stage", # also task_battle / task_pass_stage
|
||||
"original_data": {"battle": original_battle_config},
|
||||
"roster": snapshot.raw, # full monsters/master/teams/monsterAttributes
|
||||
"team": "teamA", # team name, preserves its ordered monster slots
|
||||
"battle_position": original_battle_position,
|
||||
"seed": 0,
|
||||
}
|
||||
capability = ExperimentalBattleRuntime().inspect(request)
|
||||
result = ExperimentalBattleRuntime().run(request, cancel_event=event, timeout=30.0)
|
||||
# result:
|
||||
# execution_mode: 'experimental'; approximate: True; faithful: False
|
||||
# settlement_eligible: False (offline evidence only, explicit future review required)
|
||||
# requires_realtime_wait: True
|
||||
# supported: bool; outcome: win/loss/timeout/cancelled/unsupported/error
|
||||
# elapsed_ms: modeled game clock; elapsed_seconds: elapsed_ms / 1000
|
||||
# timeout_kind: wall_clock / resource_limit for technical timeouts
|
||||
# units: per-unit initial stats, hp, position, waiting/active/dead, summon origin
|
||||
# events: bounded deterministic trajectory; trace_truncated / omitted_events explicit
|
||||
# ap: team -> {initial, current, max, spent, recovered}; kills: all enemy deaths
|
||||
# kill_monster: source-selective non-player, non-object, mode==2 death map
|
||||
# anomalies: every anomaly detected, unfiltered; diagnostics; ignored_mechanics
|
||||
# battle_data: trajectory-derived source fields for completed win/loss only;
|
||||
# never treat these as authorized live settlement, never discard anomalies.
|
||||
# battle_data.battleMonIds: original ordered roster instance IDs from selected
|
||||
# team; includes waiting originals, excludes summons, empty for hideTeamMon
|
||||
# execution_status: completed / timed_out / cancelled / unsupported / error
|
||||
# terminal: True only for completed model win/loss
|
||||
# terminal_reason: elimination / battle_time_limit for completed models
|
||||
```
|
||||
|
||||
Natural expiry of `battle.time` is **completed loss**, with
|
||||
`terminal_reason='battle_time_limit'`, `battle_data.win=False`, `leftTime=0`,
|
||||
and the full configured modeled elapsed time. Technical worker timeout is
|
||||
`outcome='timeout'`, `execution_status='timed_out'`, `terminal=False`, and
|
||||
`battle_data=None`. Cancellation also has no battle data. This distinction
|
||||
separates incomplete execution from a completed natural loss.
|
||||
|
||||
`run` uses `Popen([sys.executable, '-m', 'ranch_assistant.battle_simulator',
|
||||
'--worker'], CREATE_NO_WINDOW on Windows)` with pipes and bounded output.
|
||||
CPU simulation does not run in the GUI process. The worker cannot use sockets;
|
||||
it reads only bundled combat artifacts and one JSON request on stdin. It has
|
||||
no imports of engine, GUI, battle_runtime, or battles. `simulate(request)` is
|
||||
the direct deterministic entrypoint for offline tests. Results return as soon
|
||||
as computation ends, without sleeping for the modeled battle duration.
|
||||
Orchestration owns any cancellable wait before a future reviewed live route.
|
||||
|
||||
### Explicit experimental eligibility (latest integration contract)
|
||||
|
||||
`settlement_eligible=False` and `faithful=False` always refer to original
|
||||
engine fidelity. After an actual supported model completes (including a
|
||||
natural loss), `experimental_settlement_eligible=True` only when `battle_data`
|
||||
was computed and there are no unresolved inputs or detected anomalies.
|
||||
Otherwise `experimental_eligibility_reasons` gives the reason and the flag is
|
||||
false. Inspection and technical timeout/cancel/error never assert experimental
|
||||
eligibility. Known approximate mechanics remain disclosed even when eligible;
|
||||
this does **not** claim that original cheat checks ran or were complete.
|
||||
|
||||
Integration must use the experimental flag only under the explicitly selected
|
||||
`policy.battle_mode='experimental'`, never the native route. Production
|
||||
integration and the real-time wait remain owned by orchestration; this module
|
||||
does not start or settle any live battle.
|
||||
|
||||
## Original inputs and reproducible static data
|
||||
|
||||
The builder uses `tools.research_battle_v12.recover_table` with the repaired
|
||||
AMF Reader (empty arrays remain `[]`). It rejects any APK whose SHA-256 is not
|
||||
`01678ee3a8465d818d32cbbd94baa0d8253b04b4c57b70ebc5544ed341f1015d`.
|
||||
The retained main SWF SHA-256 is
|
||||
`c6838331a198a22ffa486cbf61cc74c97619e011bc3364c8bb8dc99e269036cf`.
|
||||
The SWF header independently decodes to **50.0 fps**; the fixed model clock
|
||||
therefore advances 20 ms per tick.
|
||||
|
||||
```powershell
|
||||
python tools/build_battle_simulation_data.py
|
||||
python tools/build_battle_simulation_data.py --output local_state/battle_simulator/rebuild
|
||||
```
|
||||
|
||||
Both builds were run; the two gzip artifacts and manifest matched byte for
|
||||
byte. Gzip has a fixed zero timestamp, JSON is sorted and compact, and the
|
||||
manifest retains per-table original compressed-member digests, logical names,
|
||||
decoded sizes, APK identity, and 196 attack profiles' retained AS3 source hashes.
|
||||
No personal path or account data enters these artifacts.
|
||||
|
||||
| Artifact | Bytes | Contents |
|
||||
| --- | ---: | --- |
|
||||
| `combat_tables.json.gz` | 242,430 | 749 species, 266 skill definitions, original numeric/settings/team/potential/entangle/upstar/item tables, default fields, 196 attack profiles |
|
||||
| `combat_battles.json.gz` | 1,465,404 | All 1,178 original stage records' level configs and 1,165 tasks' combat/status steps |
|
||||
| `combat_manifest.json` | manifest | Original source and artifact digests and retained-source fingerprints |
|
||||
|
||||
The runtime validates identity and compressed/decoded artifact hashes, then
|
||||
freezes dictionaries and arrays recursively. The independent cache does not
|
||||
use Catalog. Normal workers never decode the roughly 62 MB full battle corpus;
|
||||
they receive one original battle config and read the small combat bundle.
|
||||
`combat_battles()` is a lazy public-static research helper. Neither runtime
|
||||
method imports the builder, opens the APK, or contacts the network.
|
||||
|
||||
## Implemented trajectory
|
||||
|
||||
Player HP/ATK/DEF/DEX follow `MonsterVo`:
|
||||
|
||||
```text
|
||||
int((base + actualGrowth * (level + min(tpLevel, 4) - 1)
|
||||
+ monsterAttributes[stat] + pStat + master.globalStat)
|
||||
* (1 + clamp(feel, 0, 200) / 2000 + game_setting.upStarAdd * upStar))
|
||||
```
|
||||
|
||||
Growth comes from the raw monster, never a generic Fighter or midpoint player.
|
||||
Potential uses actual `pAtk/pDef/pHp/pDex`. Server `monsterAttributes` supplies
|
||||
the aggregate bonuses once; equipment is not added again. Attack interval is
|
||||
the species interval plus source integer dex adjustment and `atkSpd`; movement
|
||||
uses species speed plus the source two-decimal dex adjustment. Crit and AP cost
|
||||
saving come from the same server attributes. Upstar skill replacements and
|
||||
breakthrough-derived skill levels use the original tables. Missing growth or a
|
||||
nonpositive computed attack interval is rejected, not replaced or clamped.
|
||||
|
||||
Configured enemies retain their individual authored values. `autoValue` uses
|
||||
the source species midpoint construction, level and global additions. Only
|
||||
authored `scaleAbility`/`scaleHp` fields change configured enemy numbers; they
|
||||
are not user-selectable damage cheats. Normal stage/task combat does not apply
|
||||
the unrelated PvP `pveHpScale` or `pveApStartScale`.
|
||||
|
||||
Teams preserve the selected snapshot team order and original position mapping
|
||||
`1,4,2,5,6,7,8`. Player field capacity follows unlocked `team_info.battleTeam`
|
||||
slots, capped at four. Enemy capacity comes from original `numMax`. Deployment
|
||||
uses original spawn rectangles, `joinTime` in seconds, and per-team waves.
|
||||
Wave unlock waits 700 ms; scheduled reinforcements are admitted on the source
|
||||
one-second deployment cadence. `hideTeamMon` removes roster combatants and
|
||||
allows authored allies. Summons do not consume field capacity.
|
||||
|
||||
Player AP starts at `startAp + (master.level-1)*addApByLevel`. Enemy AP starts
|
||||
at authored `ap` with max `2*ap`. The clock recovers one AP per original
|
||||
`apCD=2000` ms; delayed roster joins restore the original fraction of max AP.
|
||||
Automatic deployment has **no invented AP charge**: source
|
||||
`prepareTimeMonster` checks time/wave/capacity, not cost. AP is spent on actual
|
||||
skill casts. Position-command AP spending is outside this automatic model.
|
||||
|
||||
The model selects spatial targets, moves toward them, tests the source attack
|
||||
box (`abs(dx)<range`, `abs(dy)<range*0.5`), schedules original attack action
|
||||
hit delays, and adds projectile travel using recovered projectile speed and
|
||||
`(distance-30)/speed*(1000/50)`. Target death and skill-5 projectile loss cause
|
||||
real misses. Damage uses original critical chance, critical and elemental
|
||||
factors, integer stages, dex-dependent random range, defense and reduction.
|
||||
HP loss, healing, poison, stun, reflection and lifesteal change the trajectory.
|
||||
The model waits the source one-second delayed game-over check after deaths.
|
||||
|
||||
| Skill | Source mechanics implemented | Remaining approximation |
|
||||
| --- | --- | --- |
|
||||
| 3 `Skill3Copy` | One summon; original level ability factor; scaled ATK/DEF/DEX; HP from current parent HP; no inherited skills or capacity cost | Physical split impulse, visual/equipment callbacks and exact clone motion |
|
||||
| 5 `Skill5FlashMove` | Source distance AI and AP/CD; movement displacement using original speed; loses incoming model projectiles | Impulse is one displacement; inertia and temporary knockback resistance are omitted |
|
||||
| 7 `Skill7Copy3` | Exactly three summons; original factor; scaled max HP; child AP-cost metadata 1; no capacity cost | Physical spreading impulses and clone animation |
|
||||
| 9 `Skill9AreaHit` | Next attack is ready; original attack factor damages nearby enemies in source +/-150 by +/-91 box; primary hit preserved | Knockback, visual shake and exact projectile-versus-activation timestamp edge cases |
|
||||
| 38 `Skill38Miohit` | Four hits; original random attack factor; attack type 28/100 ms windup, 150 ms recovery, 50 ms quick-CD scheduling | Rush motion, final knockback, temporary resistance and skin-specific motions |
|
||||
|
||||
Known skills use the original random AI probabilities. Player auto-skill checks
|
||||
use the source 30-frame cadence, enemy AI 20/60/100 frames by mode, and at most
|
||||
one cast per model tick. Missing framework `Cooldowner` initialization and
|
||||
callback timing are approximated; the model assumes initial attacks are ready.
|
||||
Enemy initial skill readiness is approximated at two seconds.
|
||||
|
||||
`atkStun`, `defStun`, five-second poison with one-second ticks, thorns,
|
||||
`atkVim`, and five-second `selfCure` have trajectory effects. `sunFire`,
|
||||
`moonHeal`, and `deadBoom` are not implemented and are explicitly reported when
|
||||
present. All other skill IDs are individually listed as omitted by inspection;
|
||||
the five implemented skill families are partial, not full-fidelity ports.
|
||||
|
||||
## Counters, evidence and anomaly retention
|
||||
|
||||
| Output | Exact model meaning |
|
||||
| --- | --- |
|
||||
| `kills` / `all_kills` | All modeled non-player, non-object deaths, regardless of adult/juvenile mode; includes summons |
|
||||
| `kill_monster` / `battle_data.killMonster` | Source `deadHandler` selection only: non-player, non-object, **mode 2** deaths; includes adult summons |
|
||||
| `alive_num` / `battle_data.aliveNum` | Active plus waiting non-object player units, including summons; not just deployed original survivors |
|
||||
| `battle_data.battleMonIds` | Selected team order of original roster **instance IDs**, including waiting originals; excludes clones/summons and species IDs; empty when the source hides the roster |
|
||||
| `damage_hp_lost`, unit `damage_dealt` | Measured HP actually removed by this model |
|
||||
| `battle_data.totalDamage`, `killNum`, `deadNum` | Source-declared integer defaults **0**; no assignments found in retained combat source; never filled from invented counters |
|
||||
| `bossDamage` | Source marker `bossPoint=-1` credits actual HP loss; positive markers credit actual deaths |
|
||||
|
||||
`battle_data` exists for completed model win/loss only. It also carries actual
|
||||
model AP, left time and filtered original BattlePosition fields. It is local
|
||||
evidence; no callback or game route is invoked here. Unknown/cancelled/timed-out
|
||||
execution has no battle data. Internal model errors retain partial traces and
|
||||
every anomaly already recorded, while keeping eligibility false.
|
||||
|
||||
Original observed thresholds are not softened: damage over 80,000 records
|
||||
`+10overdamage`/10 points; player requested healing over 20,000 records the
|
||||
source's `+15overcure`/**19** points even if effective healing is small.
|
||||
The observable snapshot subset of `BattlePanel.cheatCheck` records excess
|
||||
affection, growth-derived totals, potential and level with original scores and
|
||||
the original temporary/NPC-id exemption. Original full character equivalence,
|
||||
runtime memory/table comparison and all skill-specific checks are **not fully
|
||||
replayed**. Artifact integrity checks and these partial checks are not a claim
|
||||
of a clean original engine execution.
|
||||
|
||||
Anomalies are retained separately from the bounded event trace and copied
|
||||
unchanged into model evidence; they prevent experimental eligibility. Event
|
||||
truncation reports `trace_truncated` and `omitted_events`. Default trace limit
|
||||
is 2,000 events, maximum 10,000. Input/output are bounded to 16 MiB; 1,024 total
|
||||
created units, 10,000 detected anomalies or 180,000 logical ticks stop work as
|
||||
a technical resource limit. Recorded anomalies are never removed to manufacture
|
||||
an acceptable result. This code does not normalize cheat scores or clear records.
|
||||
|
||||
## Completeness and offline validation
|
||||
|
||||
Inspection of the entire original corpus with a synthetic four-unit roster:
|
||||
|
||||
| Original configurations | Inspected | Admitted by this approximate model |
|
||||
| --- | ---: | ---: |
|
||||
| Stage level battle configs | 2,512 | 941 |
|
||||
| Inline task battle configs | 199 | 106 |
|
||||
|
||||
Admission is structural model support, not a fidelity or gameplay-success rate.
|
||||
Non-elimination objectives, authored battle/monster controllers, triggers,
|
||||
protected/destroyed units, and active field areas are rejected with reasons.
|
||||
Twelve admitted original stage configs were also executed with a synthetic
|
||||
level-20 roster using species 1001010, 1030010, 2004010, 3010010; all twelve
|
||||
completed model wins. They were not account replays and were not calibrated
|
||||
against recorded AIR fights.
|
||||
|
||||
Remaining limitations include straight-line movement, no collision/inertia or
|
||||
flight height, simplified retargeting/retreat, visual object collision omitted,
|
||||
projectile paths/easing/offsets omitted, skill presentation replaced with model
|
||||
activation, no full physics/knockback, omitted equipment special words and skin
|
||||
attack overrides, and Python RNG rather than original Math.random/Random.
|
||||
These limitations accompany every inspection/result even when the model admits
|
||||
the battle. No percentage of original engine fidelity is claimed.
|
||||
|
||||
```powershell
|
||||
python -m unittest ranch_assistant.tests.test_battle_simulator -v
|
||||
```
|
||||
|
||||
**38 simulator tests passed**, and **59 tests passed** when combined with the
|
||||
estimator and AMF suites: immutable original artifacts and constants; all three
|
||||
contexts; snapshot growth/tp/potential/global/feel/upstar/attributes; normal wins,
|
||||
natural elimination losses and completed clock-expiry losses; order, capacity,
|
||||
waves and join delays; each of skills 3/5/7/9/38; projectiles, statuses/healing;
|
||||
waiting/summon alive counts and selective kills; source default counters; hidden
|
||||
teams and boss markers; anomaly retention through truncation and model failure;
|
||||
explicit unsupported mechanics; identical seeded direct/worker trajectories;
|
||||
object/dict requests; all three original route fields and ordered instance-ID
|
||||
lists (including waiting/excluding summons); fixed Windows worker command and no GUI imports;
|
||||
socket audit rejection; child cancellation, wall timeout and interrupt cleanup.
|
||||
|
||||
A sample worker completed in approximately 0.16 wall seconds with 2.7 modeled
|
||||
seconds. This is an observation, not a performance guarantee. There is no
|
||||
offline real-time sleep; `requires_realtime_wait=True` delegates the cancellable
|
||||
elapsed-clock wait to orchestration before any separately reviewed live route.
|
||||
|
||||
Only public original configs and synthetic fixtures were used. No actual
|
||||
account input, log, personal identifier, credential, real game request,
|
||||
production integration, commit or push was made by this workstream. The
|
||||
experimental module is independent of the native original-engine runtime.
|
||||
@@ -63,7 +63,6 @@ import com.diyidan.game.util.Utils;
|
||||
import com.diyidan.game.widget.DydToast;
|
||||
import com.diyidan.game.widget.FloatView;
|
||||
|
||||
/* JADX INFO: loaded from: C:\Users\11789\Documents\Projects\Codex_ws\myrzx_fang\analysis\base_classes.dex */
|
||||
public class DydGameApi {
|
||||
public static final String LOGIN_TYPE_QQ = "QQ";
|
||||
public static final String LOGIN_TYPE_WEIBO = "WEIBO";
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
package com.diyidan.game.common;
|
||||
|
||||
/* JADX INFO: loaded from: C:\Users\11789\Documents\Projects\Codex_ws\myrzx_fang\analysis\base_classes.dex */
|
||||
public class Constants {
|
||||
public static final String ACTION_RECEIVER_FINISH_PAYMENT_PAGE = "action.dydgame.close.payment.page";
|
||||
public static final String ACTION_RECEIVER_PAYMENT_CALLBACK = "action.dydgame.payment.callback";
|
||||
|
||||
@@ -17,7 +17,6 @@ import com.diyidan.game.util.PrivacyUtils;
|
||||
import com.diyidan.game.util.Utils;
|
||||
import com.diyidan.game.widget.DydToast;
|
||||
|
||||
/* JADX INFO: loaded from: C:\Users\11789\Documents\Projects\Codex_ws\myrzx_fang\analysis\base_classes.dex */
|
||||
public class LoginDialog extends Dialog implements View.OnClickListener {
|
||||
private BaseDialog dialog;
|
||||
private CheckBox mCbPrivacy;
|
||||
|
||||
@@ -3,7 +3,6 @@ package com.diyidan.game.entity.impl;
|
||||
import com.diyidan.game.entity.DydPlayer;
|
||||
import java.io.Serializable;
|
||||
|
||||
/* JADX INFO: loaded from: C:\Users\11789\Documents\Projects\Codex_ws\myrzx_fang\analysis\base_classes.dex */
|
||||
public class DydPlayerModel implements DydPlayer, Serializable {
|
||||
private static final int USER_TYPE_ADMIN = 200;
|
||||
private static final int USER_TYPE_MOBILE_PASS = 111;
|
||||
|
||||
@@ -10,7 +10,6 @@ import com.diyidan.game.util.Utils;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
/* JADX INFO: loaded from: C:\Users\11789\Documents\Projects\Codex_ws\myrzx_fang\analysis\base_classes.dex */
|
||||
public class BaseNetwork2<T> {
|
||||
protected INetworkHandler callbackHandler;
|
||||
protected Context mContext;
|
||||
|
||||
@@ -5,7 +5,6 @@ import com.diyidan.game.network.model.JsonData;
|
||||
import com.diyidan.game.util.JsonUtils;
|
||||
import org.apache.http.HttpStatus;
|
||||
|
||||
/* JADX INFO: loaded from: C:\Users\11789\Documents\Projects\Codex_ws\myrzx_fang\analysis\base_classes.dex */
|
||||
public class SuccessListener implements Response.Listener<String> {
|
||||
private INetworkHandler callbackHandler;
|
||||
private Class clazz;
|
||||
|
||||
@@ -6,7 +6,6 @@ import com.diyidan.game.network.model.ListJsonDataModel;
|
||||
import com.diyidan.game.util.Utils;
|
||||
import java.util.HashMap;
|
||||
|
||||
/* JADX INFO: loaded from: C:\Users\11789\Documents\Projects\Codex_ws\myrzx_fang\analysis\base_classes.dex */
|
||||
public class UserNetwork2 extends BaseNetwork2<ListJsonDataModel> {
|
||||
public UserNetwork2(Context context, INetworkHandler iNetworkHandler, int i) {
|
||||
super(context, iNetworkHandler, i);
|
||||
|
||||
@@ -2,7 +2,6 @@ package com.diyidan.game.network.model;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
/* JADX INFO: loaded from: C:\Users\11789\Documents\Projects\Codex_ws\myrzx_fang\analysis\base_classes.dex */
|
||||
public class JsonData<T> implements Serializable {
|
||||
private static final long serialVersionUID = 1183879419184262397L;
|
||||
private String apiVersion;
|
||||
|
||||
@@ -4,7 +4,6 @@ import com.diyidan.game.entity.impl.DydPlayerModel;
|
||||
import com.diyidan.game.util.Utils;
|
||||
import java.util.List;
|
||||
|
||||
/* JADX INFO: loaded from: C:\Users\11789\Documents\Projects\Codex_ws\myrzx_fang\analysis\base_classes.dex */
|
||||
public class ListJsonDataModel extends BaseModel {
|
||||
private static final long serialVersionUID = 4037399126099105967L;
|
||||
private List<FriendModel> friendList;
|
||||
|
||||
@@ -6,7 +6,6 @@ import javax.crypto.SecretKeyFactory;
|
||||
import javax.crypto.spec.DESedeKeySpec;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
|
||||
/* JADX INFO: loaded from: C:\Users\11789\Documents\Projects\Codex_ws\myrzx_fang\analysis\base_classes.dex */
|
||||
public class AESTools {
|
||||
private static final String encoding = "utf-8";
|
||||
private static final String iv = "01234567";
|
||||
|
||||
@@ -8,7 +8,6 @@ import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/* JADX INFO: loaded from: C:\Users\11789\Documents\Projects\Codex_ws\myrzx_fang\analysis\base_classes.dex */
|
||||
public class DydOkHttpNetwork implements Dns {
|
||||
@Override // com.squareup.okhttp.Dns
|
||||
public List<InetAddress> lookup(String str) throws UnknownHostException {
|
||||
|
||||
@@ -17,7 +17,6 @@ import javax.crypto.spec.SecretKeySpec;
|
||||
import org.apache.http.auth.AUTH;
|
||||
import org.apache.http.cookie.SM;
|
||||
|
||||
/* JADX INFO: loaded from: C:\Users\11789\Documents\Projects\Codex_ws\myrzx_fang\analysis\base_classes.dex */
|
||||
public class DydStringRequest extends StringRequest {
|
||||
private static long APP_ID;
|
||||
private static String AUTH_RESULT;
|
||||
|
||||
@@ -9,7 +9,6 @@ import java.lang.reflect.Type;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/* JADX INFO: loaded from: C:\Users\11789\Documents\Projects\Codex_ws\myrzx_fang\analysis\base_classes.dex */
|
||||
public class JsonUtils {
|
||||
public static <T> JsonData<T> parseNetworkResponse(String str, TypeReference<JsonData<T>> typeReference) {
|
||||
return (JsonData) JSON.parseObject(str, typeReference, new Feature[0]);
|
||||
|
||||
@@ -39,7 +39,6 @@ import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipFile;
|
||||
import org.zengrong.ane.funs.pref.PreferenceType;
|
||||
|
||||
/* JADX INFO: loaded from: C:\Users\11789\Documents\Projects\Codex_ws\myrzx_fang\analysis\base_classes.dex */
|
||||
public class Utils {
|
||||
private static final String[] strSplits = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM".split("");
|
||||
private static final Random random = new Random();
|
||||
|
||||
@@ -14,7 +14,6 @@ import net.pixvi.ane.dydsdk.DydSdkContext;
|
||||
import net.pixvi.ane.dydsdk.DydSdkEvent;
|
||||
import net.pixvi.ane.dydsdk.DydSdkEventStatus;
|
||||
|
||||
/* JADX INFO: loaded from: C:\Users\11789\Documents\Projects\Codex_ws\myrzx_fang\analysis\base_classes.dex */
|
||||
public class LoginFunction implements FREFunction {
|
||||
private DydGameApi.ExitCallback mFloatViewExitCallback;
|
||||
private OnAccountUpgradeListener mFloatViewUpgradeListener;
|
||||
|
||||
+45
-16
@@ -1,7 +1,7 @@
|
||||
# 牧羊人之心牧场辅助
|
||||
|
||||
原生 PySide6 窗口,使用 Qt 默认控件。双击项目根目录的
|
||||
`Start_Ranch_Helper.cmd` 启动。当前辅助版本为 **1.1.1**,适配游戏 **1.9.68**。
|
||||
`Start_Ranch_Helper.cmd` 启动。当前开发版本为 **1.2.0.dev1**,资料基线为游戏 **1.9.68**;最近正式版本为 **1.1.1**。497项常规回归已检查并完成失败项复测,原版运行时最终集成与真实账号验证仍待完成,自动原版开战准入保持关闭。
|
||||
首次运行请先执行 `python -m pip install -r ranch_assistant/requirements.txt`。
|
||||
完整功能与版本摘要见[项目README](../README.md)。
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
“牧场策略”新增独立开关“保留资质高于牧场同种培养代表的新魔物”,与S/A/B/C、4S及星级保护分别生效。
|
||||
同种培养代表优先选等级最高者,再依次比较好感、综合成长资质;新魔物的四项成长按各自范围归一化后取平均,严格更高才算提升。
|
||||
同分不算提升;牧场尚无同种时保留首只,代表资质未同步完整时暂留。已有锁定、队伍及保留种类保护继续生效。
|
||||
- 统一策略配置:通过主窗口菜单“策略配置”,保存、导入或导出当前账号的全部孵蛋、牧场、喂养、赠礼、委托、每日事务、扫荡及监控间隔设置,包含自定义收益资料。
|
||||
- 统一策略配置:通过主窗口菜单“策略配置”,保存、导入或导出当前账号的全部孵蛋、牧场、喂养、赠礼、委托、每日事务、扫荡、主线推进、战斗模式及监控间隔设置,包含自定义收益资料。
|
||||
跨账号按魔物种类匹配喂养和赠礼目标;牧场实例编号不跨账号复制,默认使用有空位的牧场。兼容旧版培养策略文件。
|
||||
导入保留功能勾选和规则,策略开关保持关闭,核对后手动开启;文件不包含账号、密码、Token、会话或本机路径。
|
||||
- 自动赠礼:独立页签,在背包勾选可用物品,在牧场勾选目标并设置优先级,再到“自动赠礼”启用。
|
||||
@@ -64,12 +64,14 @@
|
||||
密码使用当前 Windows 账户的 DPAPI 加密;可取消勾选移除保存内容。
|
||||
- 调试窗口:逐条查看请求地址、参数、HTTP 状态、耗时、解密响应和错误阶段,
|
||||
支持复制/导出,自动保存本地脱敏日志。
|
||||
- 自动委托:按每日剩余接取次数、解锁城市和库存,接取、推进已满足条件的步骤、
|
||||
领取奖励;列表显示奖励金币和氪金数量。提交金币、道具、魔物分别受策略限制。战斗步骤等待游戏实际完成。
|
||||
- 自动主线:查看任务、NPC、位置、需求、对话和下一步,推进已支持的任务链;材料、蛋和击杀缺口可按已知普通地图来源自动收集,能力或条件不足时显示原因。详见下方设置。
|
||||
- 自动委托:按每日剩余接取次数、解锁城市和库存,接取、推进已支持的步骤、
|
||||
领取奖励;列表显示奖励金币和氪金数量。提交金币、道具、魔物分别受策略限制。实战步骤已接入任务战斗编排,仍须通过能力检查。
|
||||
- 自动扫荡:按地区分组,默认折叠显示关卡、难度、掉落及账号解锁/通关记录。
|
||||
首次读取后按账号/角色保存本地地图缓存,重启、切换页面或普通监控刷新均复用缓存,仅“刷新关卡”(或本页右键刷新)更新列表。
|
||||
每关可勾选、选择已解锁难度和本日上限;满足游戏原有条件的普通关卡可接口扫荡,
|
||||
其余请在游戏内手动战斗。
|
||||
首次挑战由任务与战斗调度按能力检查处理;未支持内容等待用户在游戏内处理。
|
||||
- 战斗记录:按上下文筛选普通地图、主线、任务与委托战斗、扫荡和地图奖励事件;实验模型结果标明“实验近似”,未知结果保留待核对原因。
|
||||
- 扫荡奖励:普通扫荡读取 `battleEnd.reward`,奖励事件读取 `stageEvent.result`,日志列出本次实际获得的物品、魔物蛋、金币和经验。
|
||||
- 数据分析:紧邻“自动扫荡”的独立页签。左侧按地区选择关卡和难度,右侧显示条形图与掉落明细;关卡和可能掉落来自本地静态配置。
|
||||
可分别查看普通扫荡、奖励事件或合计,显示样本数、出现次数、获得总数量、实测掉落率、每次平均数量及95%区间。
|
||||
@@ -83,6 +85,36 @@
|
||||
- 等级与体力:经验达到下一等级门槛时自动请求官方升级结算;按客户端150秒恢复周期请求体力结算并显示服务器返回值。
|
||||
到期检查独立于随机刷新间隔,在账号后台线程串行执行;未开启消耗类策略时也会同步,退出登录或连接出错后停止。
|
||||
|
||||
## v1.2 自动主线与战斗设置
|
||||
|
||||
本节对应 **1.2.0.dev1 开发版**。任务调度和界面已实现,原版与实验模式均有局部能力限制;完整集成 QA、实际阵容的原 AIR 输入桥接和真实账号验收尚未完成。
|
||||
|
||||
1. 登录或恢复当前角色后,进入“自动主线”,点击“刷新任务 / 预览”。“任务状态”显示类别、步骤、目标位置、需求、下一步和支持状态;选择一行可查看 NPC、对话与阻塞原因。刷新用于同步与预览,不执行任务交付或开战。
|
||||
2. 打开“推进策略”,选择主线或支线、自动接取、已支持对话和补链选项。需要补齐材料、蛋或击杀时,勾选“自动收集任务材料 / 击杀目标”;来源必须符合当前位置、地图解锁、资源保护及运行时能力。
|
||||
3. 在“战斗模式(任务 / 委托)”明确选择模式,默认是“原版运行时(以能力检查为准)”。“实验模拟(近似,未完整验证)”需要手动选择;任务和委托共用此模式。选择推进战斗队伍,设置保留体力、单次交付金币上限、物品保留量和连续失败停止次数。物品、魔物交付默认关闭,金币上限默认 0。
|
||||
4. 委托仍在“自动委托”单独配置启用、接取、城市、交付限制及“也接取需要实战的委托”。“自动主线”中的“委托(仅诊断)”用于查看状态;委托执行遵循“自动委托”的规则。接取前会检查已知后续条件与战斗能力,避免接下当前无法处理的委托。
|
||||
5. 勾选“启用自动主线策略”,再点击顶部绿色“开启”。修改规则会自动保存并应用;菜单“策略配置”可立即保存、导入或导出当前账号规则,包含任务策略与战斗模式。重启、恢复会话和导入后,顶部策略开关保持关闭,核对后再开启。
|
||||
6. 在“战斗记录”查看上下文、队伍、胜负和原因;“刷新本地记录”只读取本机记录。点击顶部红色“停止”可取消后续推进和可取消的运行/时钟等待;已经发出的请求仍须等待确认,开战后的未知状态会保留待核对记录。
|
||||
|
||||
| 能力 | 当前开发版行为与边界 |
|
||||
| --- | --- |
|
||||
| 任务与对话 | 已实现接取、已支持线性对话、满足条件后的交付、领奖、后继接取与任务补链。服务器确认步骤后,才完成后续剧情和本地步骤收尾;本地检查点按账号/角色保存。 |
|
||||
| 开图与收集 | 随任务目标和地图前置推进,缺少材料、蛋或已识别的成年目标击杀时规划普通地图;可能掉落只用于选择来源,实际库存与击杀仍需结算后刷新。扫荡不计作击杀来源。 |
|
||||
| 扫荡 | 普通、非特殊、无当前任务截获的关卡,三个难度全部通关后才可扫荡。“允许用扫荡完成已通关目标”受此条件限制;任务专属战斗和任务通关战斗仍走各自任务路线。逐关次数与难度在“自动扫荡”配置。 |
|
||||
| 地图奖励事件 | 普通地图开始时若已经发放探索奖励,单独记录奖励并刷新;该分支不运行战斗,也不重复提交战斗奖励。隐藏战斗重新检查能力,未知事件保留待处理。 |
|
||||
| 原版运行时(默认) | 原 AIR 的合成 1-1 已通过原始战斗面板自然完成,读取实际统计与检查,样例 `cheatNum=0`。任意实际阵容桥接仍在完善;当前只允许能力检查确认的范围,尚未验证的开战会被阻止。 |
|
||||
| 实验模拟(显式选择) | 独立进程使用原始数值资料计算 AP、出场、移动、攻击及技能 3、5、7、9、38 的部分机制,保留轨迹、胜负和异常。物理、随机、时序、装备及其他技能存在近似或遗漏,结果可能与原版不同。 |
|
||||
|
||||
任务资料包含 1165 个任务、1178 个关卡、337 个 NPC 和 4269 份脚本;4239 份属于已支持的线性脚本,主线引用中为 718/720。这些是资料与脚本分类数量,不是整条主线通关率。30 份特殊选择等脚本(含 2 份主线)、4 类特殊接取入口、任务1001006第4步的特殊抽蛋钩子尚不支持;活动、羁绊和未知任务类别也不承诺自动推进。
|
||||
|
||||
实验模型当前拒绝未支持的控制器、触发器、保护/破坏目标及活动场地区域;未实现的技能与属性效果会在诊断中列出。941/2512 份地图战斗配置和 106/199 份任务内嵌战斗配置通过结构准入,12 场合成阵容地图实验自然胜利;这些数量不证明全部关卡可过、完整原版机制或真实账号验证。原 APK 资料与线上热更新资源的一致性、全部实际角色加成仍需核对。详细机制与遗漏见[实验模型说明](../analysis/V1_2_SIMULATION_IMPLEMENTATION.md),原引擎实验见[运行时说明](../analysis/V1_2_RUNTIME_IMPLEMENTATION.md)。
|
||||
|
||||
离线演示和独立实验可以加速计算模型时钟,不预测服务器奖励或任务进度。已接入的实验战斗编排在开战确认后,以真实经过时间补足模型战斗耗时,等待可取消;自然战斗时间耗尽与工作进程超时分别记录。离线计算快不代表可以提前完成在线结算,服务器是否接受结果尚未验证。
|
||||
|
||||
看到“待核对”“不支持”或资源不足时,先查看任务详情和战斗记录中的具体原因。请求结果不明时,本账号的牧场、赠礼及任务等冲突写操作会暂停;重启不会清除待核对状态。恢复角色后点击“刷新任务 / 预览”,程序只在新的角色/任务状态足以证明结果时解除阻塞,随后可继续已保存的普通剧情检查点;证据不足时仍等待用户在游戏内核实。不要通过删除记录或反复开启来重发未知请求,策略导入也不能覆盖服务器通关进度或解除未知结算。
|
||||
|
||||
任务与战斗记录保存在本账号、区服和角色的本地工作区;规则导出不含凭据、任务执行记录、待核对日志或服务器进度。实现边界、验证记录和接口分流另见[v1.2 实施与阶段交接](../analysis/V1_2_IMPLEMENTATION.md)。
|
||||
|
||||
## 连接真实角色
|
||||
|
||||
默认未登录,使用本地示例数据。顶部账号页签用于切换账号,菜单“账号 → 新增账号页签”用于登录另一账号。
|
||||
@@ -247,8 +279,8 @@
|
||||
未知魔物和不完整资质不会自动派遣或喂养。
|
||||
- 自定义表:`typeId, sell_money, sell_exp, time_total`(秒),可只提供部分
|
||||
覆盖列;中文列名“编号、派遣金币、强化经验、孵化秒数”也支持。
|
||||
- 测试:`python -m unittest discover -s ranch_assistant/tests -v`。
|
||||
- 209 项本地测试通过,覆盖登录、会话隔离、账号关闭与移除、菜单账号路由、数字框滚轮、地图缓存、请求计数、等级与体力结算、成长同步、孵蛋与补货、同种魔物培养与资质提升保护、批量喂养、派遣、赠礼、统一策略配置、委托、扫荡、奖励统计与体力效率和每日奖励。
|
||||
- 测试:`python -B -m unittest discover -s ranch_assistant/tests -v`。
|
||||
- 1.1.1 阶段记录为 209 项本地测试;v1.2 的数据/规划、编排、模型和界面定向验证见[实施验证记录](../analysis/V1_2_IMPLEMENTATION.md#验证记录),完整集成 QA 仍在进行,各组数量不能直接相加作为全量结果。原有回归覆盖登录、会话隔离、账号关闭与移除、菜单账号路由、数字框滚轮、地图缓存、请求计数、等级与体力结算、成长同步、孵蛋与补货、同种魔物培养与资质提升保护、批量喂养、派遣、赠礼、统一策略配置、委托、扫荡、奖励统计与体力效率和每日奖励。
|
||||
赠礼覆盖手动目标冷却跳过、连续赠礼、独立到期调度、成功响应回写、滞后查询及本地培养筛选不发请求的回归测试;本地策略与页面异常写入调试日志并标记为本地错误。
|
||||
登录后自动刷新、顶部统一策略开关、关闭策略后继续刷新及多账号批量开关均有回归覆盖。
|
||||
新增牧场树形/平铺切换、分组数量与空位、刷新保留折叠和控件、4S保留条件、随机刷新间隔及到期独立同步的回归测试。
|
||||
@@ -260,21 +292,18 @@
|
||||
“自动委托”需单独启用;可先关闭“自动孵蛋”的自动管理,只运行委托。
|
||||
道具和魔物提交默认关闭,金币提交上限默认 0;锁定、队伍、高星和高资质保护继续生效。
|
||||
已接委托需要的魔物种类和蛋会纳入牧场保留。
|
||||
“也接取需要实战的委托”只允许接取此类任务,当前不会自动导航到每项委托的专用战斗。
|
||||
“也接取需要实战的委托”允许经检查后接取实战委托;已支持的剧情、交付和专用战斗通过任务调度继续推进。战斗模式与队伍在“自动主线 → 推进策略”选择,委托资源限制仍由本页配置。当前默认原版模式的实际阵容桥接尚待完成,不应把这个开关视为所有委托均已可用。
|
||||
|
||||
普通关卡首次通关仍需在游戏内实际战斗。客户端有 `startSaodang` /
|
||||
`doSaodangBattle` 扫荡分支:普通、非剧情定位关卡的三个难度全部通关后才开放。
|
||||
它复用 `stageStart` → `battleEnd` → `recordBattleResult`,无需本地战斗演算或手机截图。
|
||||
此前只搜索英文 sweep 和中文“扫荡”漏掉了这个拼音方法;现已按该分支实现。
|
||||
普通、非剧情定位关卡的三个难度全部通关后才开放扫荡,无需本地战斗演算或手机截图。首次挑战、任务专属战斗与扫荡分别处理,当前可执行范围见上方能力表。客户端调用链与字段证据见[地图及每日事务研究](../analysis/STAGES_DAILY.md)和[战斗路线说明](../analysis/V1_2_IMPLEMENTATION.md#调度与恢复约定)。
|
||||
|
||||
在“自动扫荡”展开地区,每关勾选“刷图”、选择难度、输入“本日上限”,勾选该页功能,再开启顶部策略开关。
|
||||
星级是服务器通关进度计算出来的,只读。未解锁难度不能选;特殊关卡、未全通关、剧情任务、
|
||||
体力/金币/门票不足的关卡会显示原因并跳过。次数按角色、日期、关卡和难度保存,
|
||||
是本地已开始次数,不冒充服务器每日限制。
|
||||
一次扫荡内部的几个请求顺序执行,完成后重读账号状态;开启其他策略时与孵蛋/委托逐轮串行。
|
||||
探索奖励事件由 `stageStart` 返回的 `stageEvent.result` 直接结算,无需提交 `battleEnd`,刷新角色后可继续下一轮。
|
||||
探索奖励事件已由地图开始响应直接发放,刷新角色后可继续下一轮,不再提交普通战斗结算。
|
||||
旧版将此类奖励事件误记为未完成时,只在本地日志能匹配当前角色、关卡和成功响应的情况下自动解除阻塞,不重发请求。
|
||||
隐藏关卡需要游戏内实战;缺失事件状态或请求结果不明确时保持待处理,避免重复扣体力,在游戏内确认处理后可清除本地记录。
|
||||
隐藏关卡单独检查运行时能力;不支持、缺失事件状态或请求结果不明确时保持待处理,避免重复扣体力。恢复前先刷新并在游戏内核实,未知写请求不会自动重发。
|
||||
|
||||
“每日事务”选择要处理的奖励类别,点“领取勾选项目”可立即领取;
|
||||
勾选“启用每日奖励领取”并开启顶部策略开关后,只自动处理符合状态的项目。
|
||||
@@ -284,8 +313,8 @@ VIP奖励只对已有资格领取;不会购买VIP或升级礼包。邮件仅
|
||||
|
||||
资料包含此APK的1178个关卡、各难度奖励和2079种道具名称。
|
||||
这些是安装包配置中的可能掉落,并非实时掉落概率保证;后续热更新新增数据需要重新提取。
|
||||
本次签到、领邮件和扫荡均由本地模拟验证,尚未在真实账号上执行验证。
|
||||
静态证据与字段规则见 `analysis/STAGES_DAILY.md`。
|
||||
这些流程有本地模拟验证;本轮开发验证未执行真实游戏请求,v1.2 的任务与战斗服务器验收仍待用户手动验证。软件在用户开启策略后,可按配置和能力检查自动执行已支持操作。
|
||||
静态证据与字段规则见[地图及每日事务研究](../analysis/STAGES_DAILY.md)。
|
||||
|
||||
## 刷新响应与批量喂养
|
||||
|
||||
|
||||
+15
-8
@@ -58,15 +58,22 @@ class Reader:
|
||||
self.objects.append(value)
|
||||
return value
|
||||
if kind == 9:
|
||||
associative, dense = {}, []
|
||||
result = associative if not h >> 1 else dense
|
||||
self.objects.append(result)
|
||||
while (name := self.string()):
|
||||
associative[name] = self.read()
|
||||
for _ in range(h >> 1):
|
||||
dense.append(self.read())
|
||||
if dense and associative:
|
||||
dense_length = h >> 1
|
||||
# The first key decides the shape, including dense length 0.
|
||||
# Reading a key uses only the string table; reserve the final
|
||||
# object container before any child value can reference it.
|
||||
name = self.string()
|
||||
if name and dense_length:
|
||||
raise ValueError("Mixed AMF array unsupported")
|
||||
result = {} if name else []
|
||||
self.objects.append(result)
|
||||
if name:
|
||||
while name:
|
||||
result[name] = self.read()
|
||||
name = self.string()
|
||||
else:
|
||||
for _ in range(dense_length):
|
||||
result.append(self.read())
|
||||
return result
|
||||
if not h & 2:
|
||||
external, dynamic, names = self.traits[h >> 2]
|
||||
|
||||
@@ -0,0 +1,373 @@
|
||||
"""Execute pinned original AIR combat offline, with original result/check callbacks.
|
||||
|
||||
Canonical stage/task inputs and complete snapshots use the original compiled
|
||||
BattleCenter/BattleGround/skills. This development adapter never authorizes game
|
||||
API actions or claims server compatibility. See the implementation evidence.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import asdict, dataclass, fields
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
from typing import Any
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
LOCAL = ROOT / "local_state/battle_runtime"
|
||||
ORIGINAL_APK_SHA256 = "01678ee3a8465d818d32cbbd94baa0d8253b04b4c57b70ebc5544ed341f1015d"
|
||||
ORIGINAL_MAIN_SHA256 = "c6838331a198a22ffa486cbf61cc74c97619e011bc3364c8bb8dc99e269036cf"
|
||||
CONTEXTS = frozenset(("ordinary_stage", "task_battle", "task_pass_stage"))
|
||||
# Release checkpoint: final callback-binding/Engine integration QA is pending.
|
||||
# Offline execution remains available. Do not enable before that bounded QA.
|
||||
NATIVE_ADMISSION_ENABLED = False
|
||||
ORIGINAL_FIXTURE_ROSTER = {"kind": "original_fixture", "species": 1001010, "players": 3,
|
||||
"level": 1, "mode": 2, "growth_area": .5, "master_level": 1}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class BattleRequest:
|
||||
context: str
|
||||
original_data: Mapping[str, Any]
|
||||
roster: Mapping[str, Any]
|
||||
stage_id: str | None = None
|
||||
difficulty: int = 1
|
||||
task_id: str | None = None
|
||||
step_index: int | None = None
|
||||
purpose: str = "settlement"
|
||||
team: str | None = None
|
||||
battle_position: Mapping[str, Any] | None = None
|
||||
|
||||
|
||||
def original_fixture_request() -> BattleRequest:
|
||||
"""Explicit synthetic fixture, never an account roster or settlement request."""
|
||||
return BattleRequest("ordinary_stage", {"source": "original_apk", "resource_identity": {
|
||||
"apk_sha256": ORIGINAL_APK_SHA256, "main_swf_sha256": ORIGINAL_MAIN_SHA256}},
|
||||
dict(ORIGINAL_FIXTURE_ROSTER), stage_id="0101", purpose="offline_validation")
|
||||
|
||||
|
||||
def _canonical(value: Any) -> bytes:
|
||||
return json.dumps(value, ensure_ascii=True, allow_nan=False, sort_keys=True,
|
||||
separators=(",", ":")).encode("ascii")
|
||||
|
||||
|
||||
def _validate_callback_binding(scene, native, evidence, validation):
|
||||
"""Validate original callback provenance/data; never synthesize statistics."""
|
||||
data=scene["battle_data"]
|
||||
events=native.get("events",[])
|
||||
completed=[event for event in events if event.get("kind")=="original_battle_completed"]
|
||||
built=[event for event in events if event.get("kind")=="snapshot_bridge_built"]
|
||||
if len(completed)!=1 or completed[0].get("data")!=scene or not built or built[-1].get("data",{}).get("installed") is not True:
|
||||
raise ValueError("Missing or mismatched original snapshot/completion callback evidence")
|
||||
if not any(event.get("kind")=="BattleCenter_started" for event in events):
|
||||
raise ValueError("Missing original BattleCenter execution evidence")
|
||||
ids=data.get("battleMonIds")
|
||||
expected=validation["expected_battle_mon_ids"]
|
||||
if not isinstance(ids,list) or any(type(mid) is not int for mid in ids) or sorted(ids)!=sorted(expected):
|
||||
raise ValueError("Original callback roster does not match the selected input team")
|
||||
records=scene["anomaly_records"]
|
||||
if set(records)!={"mons","damages","master","text"} or not isinstance(records["mons"],list) or not isinstance(records["damages"],list) or not isinstance(records["text"],str):
|
||||
raise ValueError("Original anomaly records are incomplete")
|
||||
checked=[record.get("mid") for record in records["mons"] if isinstance(record,dict)]
|
||||
# Original makeRecord may serialize mid as a decimal String, while
|
||||
# BattleData.battleMonIds is numeric. Compare identity without rewriting
|
||||
# either original output representation.
|
||||
if any(type(mid) not in (str,int) or not str(mid).isdecimal() for mid in checked):
|
||||
raise ValueError("Invalid original player integrity record identity")
|
||||
if len(checked)!=len(records["mons"]) or sorted(map(int,checked))!=sorted(expected):
|
||||
raise ValueError("Original player integrity checks do not match the selected roster")
|
||||
if data["cheatNum"]==0:
|
||||
if data.get("cheatRecords")!="": raise ValueError("Original zero-count callback serialization mismatch")
|
||||
elif not isinstance(data.get("cheatRecords"),str) or json.loads(data["cheatRecords"])!=records:
|
||||
raise ValueError("Original serialized anomaly records were altered")
|
||||
for field in ("leftTime","killNum","totalDamage","bossDamage","deadNum","aliveNum","apLeft"):
|
||||
if type(data.get(field)) is not int: raise ValueError("Missing original callback statistic: "+field)
|
||||
if not 0 <= data["leftTime"] <= validation["battle_seconds"]*1000 or not isinstance(data.get("killMonster"),dict):
|
||||
raise ValueError("Invalid original battle clock or kill dictionary")
|
||||
if scene.get("game_api_requests")!=0 or scene.get("requested_fps")!=50 or not isinstance(scene.get("wall_ms"),(int,float)) or scene["wall_ms"]<=0 or scene.get("observed_frames",0)<=0:
|
||||
raise ValueError("Missing original offline clock/frame evidence")
|
||||
if not native.get("nonce") or not native.get("application_id") or not native.get("storage_directory"):
|
||||
raise ValueError("Missing isolated native application identity")
|
||||
return True
|
||||
|
||||
|
||||
def _coerce(request) -> tuple[BattleRequest | None, list[dict]]:
|
||||
if isinstance(request, BattleRequest):
|
||||
try:
|
||||
request = asdict(request)
|
||||
except (TypeError, ValueError, RecursionError) as error:
|
||||
return None, [{"code": "invalid_request", "detail": str(error)}]
|
||||
if not isinstance(request, Mapping):
|
||||
return None, [{"code": "invalid_request", "detail": "Expected BattleRequest or a mapping"}]
|
||||
allowed = {field.name for field in fields(BattleRequest)}
|
||||
unknown = set(request) - allowed
|
||||
if unknown:
|
||||
return None, [{"code": "unknown_request_fields", "detail": ", ".join(sorted(map(str, unknown)))}]
|
||||
try:
|
||||
encoded = _canonical(dict(request))
|
||||
if len(encoded) > 4 * 1024 * 1024:
|
||||
raise ValueError("Request exceeds 4 MiB")
|
||||
snapshot = json.loads(encoded) # detached from mutable caller state
|
||||
result = BattleRequest(**snapshot)
|
||||
except (TypeError, ValueError, OverflowError, RecursionError) as error:
|
||||
return None, [{"code": "invalid_request", "detail": str(error)}]
|
||||
return result, []
|
||||
|
||||
|
||||
class BattleRuntime:
|
||||
"""Fixed original runtime, with a separate offline-validation capability.
|
||||
|
||||
inspect() is read-only and returns a dictionary. supported means this exact
|
||||
OFFLINE job can execute. Online callers must additionally require faithful
|
||||
AND settlement_eligible. Complete original snapshot requests can be admitted;
|
||||
only a verified completed callback can yield an eligible result. Server
|
||||
acceptance remains explicitly unverified. Diagnostic fixtures never qualify.
|
||||
Imported commands, paths, manifests, engine results and verified claims
|
||||
never select an executable or enable support.
|
||||
"""
|
||||
def __init__(self, runtime_config: Mapping | None = None):
|
||||
self._config_reasons = []
|
||||
if runtime_config is not None:
|
||||
if not isinstance(runtime_config, Mapping) or set(runtime_config) - {"backend"}:
|
||||
self._config_reasons.append({"code": "untrusted_runtime_config",
|
||||
"detail": "Only backend=original_air is accepted; commands and verification claims are forbidden"})
|
||||
elif runtime_config.get("backend", "original_air") != "original_air":
|
||||
self._config_reasons.append({"code": "unknown_backend", "detail": "Expected original_air"})
|
||||
|
||||
def inspect(self, request: BattleRequest | Mapping) -> dict:
|
||||
req, reasons = _coerce(request)
|
||||
reasons.extend(self._config_reasons)
|
||||
result = {"supported": False, "offline_supported": False, "settlement_eligible": False,
|
||||
"faithful": False, "approximate":False,"original_core": True, "backend": "original_air",
|
||||
"execution_mode":"original","server_acceptance_verified":False,
|
||||
"reasons": reasons, "resource_identity": {"apk_sha256": ORIGINAL_APK_SHA256,
|
||||
"main_swf_sha256": ORIGINAL_MAIN_SHA256, "baseline": "original APK 1.9.68",
|
||||
"live_resource_match_verified": False},
|
||||
"coverage": {"validated_offline_fixtures": ["ordinary_stage:0101:1:three_level1_slimes"],
|
||||
"validated_skills": [3], "validated_online_contexts": [],
|
||||
"validated_callback_route":"BattlePanel.battleCompleteHandler to local observer",
|
||||
"original_checks_preserved": True},
|
||||
"limitations": ["Original APK lacks 1001010_q_2s.png; original local error callbacks execute",
|
||||
"Math.random is native and unseeded; no synchronized trace comparison",
|
||||
"Current live-resource matching and server acceptance remain unvalidated"]}
|
||||
if req is None:
|
||||
return result
|
||||
result["request_sha256"] = hashlib.sha256(_canonical(asdict(req))).hexdigest()
|
||||
if isinstance(req.roster,Mapping) and ("snapshot" in req.roster or "master" in req.roster):
|
||||
return self._inspect_snapshot(req,result)
|
||||
if not isinstance(req.context, str) or req.context not in CONTEXTS:
|
||||
reasons.append({"code": "unknown_context", "detail": str(req.context)})
|
||||
elif req.context != "ordinary_stage":
|
||||
reasons.append({"code": "task_route_not_validated", "detail": req.context})
|
||||
if req.purpose not in ("settlement", "offline_validation"):
|
||||
reasons.append({"code": "unknown_purpose", "detail": str(req.purpose)})
|
||||
if req.purpose != "offline_validation":
|
||||
reasons.append({"code": "settlement_not_validated", "detail":
|
||||
"This development build cannot authorize an online battle start or settlement"})
|
||||
if req.stage_id != "0101" or type(req.difficulty) is not int or req.difficulty != 1:
|
||||
reasons.append({"code": "scene_not_validated", "detail": "Only original stage 0101, difficulty 1 has a native fixture proof"})
|
||||
if req.task_id is not None or req.step_index is not None:
|
||||
reasons.append({"code": "task_input_not_validated", "detail": "No task context may reuse the ordinary-stage fixture"})
|
||||
if not isinstance(req.original_data, Mapping):
|
||||
reasons.append({"code": "original_data_required", "detail": "Expected original APK source and resource identity"})
|
||||
else:
|
||||
data = req.original_data
|
||||
if set(data) - {"source", "resource_identity"}:
|
||||
reasons.append({"code": "external_battle_data_unvalidated", "detail":
|
||||
"Only pinned original APK tables are executed; imported tables/commands/verification claims are refused"})
|
||||
identity = data.get("resource_identity")
|
||||
if data.get("source") != "original_apk" or not isinstance(identity, Mapping):
|
||||
reasons.append({"code": "original_data_identity_missing", "detail": "Expected source=original_apk and resource_identity"})
|
||||
elif dict(identity) != {"apk_sha256": ORIGINAL_APK_SHA256, "main_swf_sha256": ORIGINAL_MAIN_SHA256}:
|
||||
reasons.append({"code": "resource_identity_mismatch", "detail": "Expected the pinned original APK and main SWF"})
|
||||
if not isinstance(req.roster, Mapping) or dict(req.roster) != ORIGINAL_FIXTURE_ROSTER:
|
||||
reasons.append({"code": "roster_not_validated", "detail":
|
||||
"Only the explicit original_fixture roster is supported offline; real snapshots and reference stats are unvalidated"})
|
||||
if os.name != "nt":
|
||||
reasons.append({"code": "runtime_platform_unavailable", "detail": "The pinned native runner uses Windows x64 AIR"})
|
||||
from tools.battle_runtime.trusted import LIBRARY_FILES, SDK_FILES, verify_files
|
||||
sdk_reasons = verify_files(LOCAL / "air_sdk", SDK_FILES)
|
||||
library_reasons = verify_files(LOCAL / "original", LIBRARY_FILES)
|
||||
reasons.extend(sdk_reasons)
|
||||
reasons.extend(library_reasons)
|
||||
result["resource_identity"]["sdk_pins_match"] = not sdk_reasons
|
||||
result["resource_identity"]["prepared_library_pins_match"] = not library_reasons
|
||||
candidates = list(ROOT.glob("*_1.9.68.apk"))
|
||||
if not candidates:
|
||||
reasons.append({"code": "original_apk_missing", "detail": "The worker re-verifies the original local APK before executing"})
|
||||
elif len(candidates) != 1:
|
||||
reasons.append({"code":"original_apk_ambiguous","detail":"Expected exactly one original *_1.9.68.apk"})
|
||||
result["supported"] = result["offline_supported"] = not reasons
|
||||
return result
|
||||
|
||||
def _inspect_snapshot(self,req,result):
|
||||
from tools.battle_runtime.inputs import validate
|
||||
from tools.battle_runtime.trusted import LIBRARY_FILES,SDK_FILES,verify_files
|
||||
reasons = result["reasons"]
|
||||
if req.purpose not in ("settlement","offline_validation"):
|
||||
reasons.append({"code":"unknown_purpose","detail":str(req.purpose)})
|
||||
if os.name != "nt": reasons.append({"code":"runtime_platform_unavailable","detail":"Windows x64 AIR is required"})
|
||||
if not (ROOT / "tools/battle_runtime/SnapshotBridge.as").is_file():
|
||||
reasons.append({"code":"snapshot_bridge_unavailable","detail":"Bundled original snapshot bridge source is missing"})
|
||||
try:
|
||||
validation = validate(asdict(req))
|
||||
except (OSError,ValueError,KeyError,TypeError,AttributeError) as error:
|
||||
validation = {"reasons":[{"code":"invalid_original_request","detail":str(error)}]}
|
||||
reasons.extend(validation["reasons"])
|
||||
sdk_reasons = verify_files(LOCAL/"air_sdk",SDK_FILES)
|
||||
library_reasons = verify_files(LOCAL/"original",LIBRARY_FILES)
|
||||
reasons.extend(sdk_reasons);reasons.extend(library_reasons)
|
||||
result["resource_identity"].update(sdk_pins_match=not sdk_reasons,prepared_library_pins_match=not library_reasons)
|
||||
result["coverage"] = {**result["coverage"],**validation.get("coverage",{}),"input_mode":"original_snapshot"}
|
||||
result["coverage"]["validated_offline_contexts"] = sorted(CONTEXTS)
|
||||
result["coverage"]["fidelity_basis"] = "unchanged original compiled core, original event loop and result/check callbacks"
|
||||
result["limitations"] = ["Server acceptance and current live-resource compatibility have not been tested",
|
||||
"Native Math.random is unseeded; results use the actual original event loop",
|
||||
"Original empty optional image declarations retain their recorded local IO-error callbacks"]
|
||||
result["native_position"] = validation.get("position")
|
||||
seconds = validation.get("battle_seconds",300)
|
||||
result["battle_seconds"] = seconds
|
||||
result["watchdog_seconds"] = seconds*2+90
|
||||
result["supported"] = result["offline_supported"] = not reasons
|
||||
result["faithful"] = not reasons
|
||||
result["settlement_eligible"] = NATIVE_ADMISSION_ENABLED and not reasons and req.purpose=="settlement"
|
||||
result["native_admission_validation_pending"] = not NATIVE_ADMISSION_ENABLED
|
||||
result["admission_requires_completed_original_checks"] = True
|
||||
return result
|
||||
|
||||
def run(self, request: BattleRequest | Mapping, *, cancel_event=None, timeout: float | None = None) -> dict:
|
||||
if timeout is not None and (isinstance(timeout, bool) or not isinstance(timeout, (float, int)) or not math.isfinite(timeout) or timeout <= 0):
|
||||
raise ValueError("timeout must be a finite positive number")
|
||||
started = time.monotonic()
|
||||
if cancel_event is not None and cancel_event.is_set():
|
||||
return {"status": "cancelled", "battle_executed": False, "settlement_eligible": False, "faithful": False}
|
||||
# Freeze caller input once, before inspection and process serialization.
|
||||
# Mutating a shared policy/snapshot cannot redirect an inspected job.
|
||||
frozen, _ = _coerce(request)
|
||||
from tools.battle_runtime.inputs import InspectionInterrupted, inspection_budget
|
||||
try:
|
||||
with inspection_budget(cancel_event,started+timeout if timeout is not None else None):
|
||||
capability = self.inspect(frozen if frozen is not None else request)
|
||||
except InspectionInterrupted as error:
|
||||
return {"status":error.status,"battle_executed":False,"battle_completed":False,
|
||||
"settlement_eligible":False,"faithful":False}
|
||||
if not capability["supported"]:
|
||||
return {"status": "unsupported", "battle_executed": False, "settlement_eligible": False,
|
||||
"faithful": False, "capability": capability, "reasons": capability["reasons"]}
|
||||
deadline = timeout if timeout is not None else capability.get("watchdog_seconds",690.0)
|
||||
remaining = deadline-(time.monotonic()-started)
|
||||
if (cancel_event is not None and cancel_event.is_set()) or remaining <= 0:
|
||||
return {"status":"cancelled" if cancel_event is not None and cancel_event.is_set() else "timeout",
|
||||
"battle_executed":False,"battle_completed":False,"faithful":False,"settlement_eligible":False}
|
||||
source_request = asdict(frozen) if capability["coverage"].get("input_mode")=="original_snapshot" else None
|
||||
return self._execute(scene=True, timeout=remaining, cancel_event=cancel_event,
|
||||
request_sha256=capability["request_sha256"],source_request=source_request,
|
||||
expected_position=capability.get("native_position"),admitted=capability["settlement_eligible"])
|
||||
|
||||
def probe_original_components(self, *, cancel_event=None, timeout: float = 60.0) -> dict:
|
||||
"""Explicit diagnostic operation; cannot produce settlement data."""
|
||||
if self._config_reasons:
|
||||
return {"status": "unsupported", "reasons": list(self._config_reasons), "settlement_eligible": False}
|
||||
from tools.battle_runtime.trusted import SDK_FILES, verify_files
|
||||
reasons = verify_files(LOCAL / "air_sdk", SDK_FILES)
|
||||
if reasons:
|
||||
return {"status": "unsupported", "reasons": reasons, "settlement_eligible": False}
|
||||
return self._execute(scene=False, timeout=timeout, cancel_event=cancel_event, request_sha256=None)
|
||||
|
||||
def _execute(self, *, scene, timeout, cancel_event, request_sha256,source_request=None,expected_position=None,admitted=False):
|
||||
from tools.battle_runtime.isolation import run_isolated
|
||||
validation=None
|
||||
if source_request is not None:
|
||||
from tools.battle_runtime.inputs import validate
|
||||
validation=validate(source_request)
|
||||
if validation["reasons"]:
|
||||
return {"status":"unsupported","supported":False,"faithful":False,"settlement_eligible":False,
|
||||
"battle_executed":False,"battle_completed":False,"server_acceptance_verified":False,
|
||||
"reasons":validation["reasons"]}
|
||||
attempt = LOCAL / "jobs" / uuid.uuid4().hex
|
||||
attempt.mkdir(parents=True)
|
||||
nonce = uuid.uuid4().hex
|
||||
output = attempt / "worker-result.json"
|
||||
argv = [sys.executable, "-I", "-B", str(ROOT / "tools/battle_runtime/worker.py"),
|
||||
"--output", str(output), "--nonce", nonce, "--action", "scene" if scene else "components","--timeout",str(timeout)]
|
||||
if source_request is not None:
|
||||
input_path = attempt / "worker-input.local.json"
|
||||
input_path.write_bytes(_canonical(source_request))
|
||||
argv.extend(("--input",str(input_path)))
|
||||
process = run_isolated(argv, cwd=attempt, timeout=timeout, cancel_event=cancel_event)
|
||||
result = {"status": process.status, "settlement_eligible": False, "faithful": False,
|
||||
"approximate":False,"original_core":True,"execution_mode":"original",
|
||||
"server_acceptance_verified":False,"supported":False,"terminal":False,
|
||||
"battle_executed": None, "battle_completed": False, "request_sha256": request_sha256,
|
||||
"diagnostics_directory": str(attempt), "process_exit_code": process.returncode}
|
||||
if process.status != "completed":
|
||||
result["error"] = process.stderr[-4000:] or process.stdout[-4000:]
|
||||
return result
|
||||
try:
|
||||
if output.stat().st_size > 2 * 1024 * 1024:
|
||||
raise ValueError("Oversized original runner evidence")
|
||||
payload = json.loads(output.read_text(encoding="utf-8"))
|
||||
if payload["nonce"] != nonce or payload["schema"] != 1:
|
||||
raise ValueError("Original runner evidence binding mismatch")
|
||||
evidence = payload["evidence"]
|
||||
native = evidence["result"]
|
||||
if source_request is not None and evidence.get("input_sha256") != request_sha256:
|
||||
raise ValueError("Native execution belongs to a different input snapshot")
|
||||
if evidence["resource_identity"].get("apk_sha256") != ORIGINAL_APK_SHA256 or evidence["resource_identity"]["main_swf_sha256"] != ORIGINAL_MAIN_SHA256:
|
||||
raise ValueError("Original runner resource identity mismatch")
|
||||
if native.get("settlement_eligible") is not False or native.get("faithful", False) is not False:
|
||||
raise ValueError("Runner claimed unvalidated settlement eligibility or fidelity")
|
||||
if evidence.get("resource_audit", {}).get("all_present_assets_match_apk") is not True:
|
||||
raise ValueError("Original assets do not match the pinned APK")
|
||||
completed = native.get("status") == ("scene_completed" if scene else "probe_completed")
|
||||
if completed and evidence["process_exit_code"] == 0:
|
||||
result["status"] = "completed"
|
||||
else:
|
||||
result["status"] = "error"
|
||||
result["error"] = native.get("error") or {"code":"native_process_failed",
|
||||
"detail":"Original runtime did not complete the requested operation"}
|
||||
result["battle_executed"] = native.get("battle_executed") is True
|
||||
result["evidence"] = evidence
|
||||
if completed and scene:
|
||||
if not result["battle_executed"] or not isinstance(native.get("scene_result"), dict):
|
||||
raise ValueError("Scene completion lacks an executed original battle result")
|
||||
scene_result = native["scene_result"]
|
||||
outcome = scene_result.get("outcome")
|
||||
data = scene_result.get("battle_data")
|
||||
if outcome not in ("win", "loss") or not isinstance(data, dict) or type(data.get("win")) is not bool:
|
||||
raise ValueError("Invalid native outcome/data")
|
||||
cheat_num = data.get("cheatNum")
|
||||
if type(cheat_num) not in (int,float) or not math.isfinite(cheat_num) or cheat_num < 0 or int(cheat_num) != cheat_num:
|
||||
raise ValueError("Missing or invalid original anomaly count")
|
||||
if data["win"] != (outcome == "win") or not isinstance(scene_result.get("anomaly_records"), dict):
|
||||
raise ValueError("Native result is inconsistent or lacks original anomaly records")
|
||||
wanted_position = expected_position if expected_position is not None else {"battleType":"stage", "stageLevel":"1", "stageId":"0101", "taskTypeId":None, "taskStep":0}
|
||||
if data.get("battlePosition") != wanted_position:
|
||||
raise ValueError("Native result belongs to a different battle route")
|
||||
if validation is not None:
|
||||
_validate_callback_binding(scene_result,native,evidence,validation)
|
||||
result["outcome"] = outcome
|
||||
result["offline_result"] = scene_result
|
||||
result["battle_data"] = data
|
||||
result["battle_completed"] = True
|
||||
result["checks_passed"] = data.get("cheatNum")==0
|
||||
result["server_validated"] = False
|
||||
result["faithful"] = validation is not None
|
||||
result["supported"] = True
|
||||
result["terminal"] = True
|
||||
result["execution_status"] = "completed"
|
||||
result["terminal_reason"] = scene_result.get("terminal_reason")
|
||||
result["wall_time_ms"] = scene_result.get("wall_ms")
|
||||
result["requires_realtime_wait"] = False
|
||||
result["resource_identity"] = evidence["resource_identity"]
|
||||
result["settlement_eligible"] = admitted and validation is not None and result["checks_passed"]
|
||||
if data.get("cheatNum",0)>0: result["status"]="anomaly"
|
||||
except (OSError, KeyError, TypeError, ValueError) as error:
|
||||
result.update(status="error", battle_executed=None, battle_completed=False,settlement_eligible=False,faithful=False,error=str(error))
|
||||
result.pop("outcome", None); result.pop("offline_result", None);result.pop("battle_data",None)
|
||||
return result
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,631 @@
|
||||
"""Durable orchestration; combat statistics belong exclusively to the runtime.
|
||||
|
||||
Partner contract: BattleOrchestrator accepts ProgressionIntent objects (or dicts).
|
||||
The runtime adapter implements inspect(request) and run(request, cancel_event=Event).
|
||||
Inspection must explicitly report supported=True. Original settlement requires
|
||||
settlement_eligible=True; experimental execution requires its separate
|
||||
experimental_settlement_eligible=True after completed model execution.
|
||||
Original execution must be faithful; explicitly selected experimental execution
|
||||
must identify itself as approximate and retain its limitations and trace.
|
||||
Both supply unmodified, computed battle_data. The request
|
||||
contains snapshot, team, battle_position, stage_id, difficulty, task_type_id,
|
||||
step_number and battle_kind. Engine adapts the concrete runtime's input builder.
|
||||
No estimation module is imported here. SweepRunner is the sole sweep executor.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
from dataclasses import asdict, is_dataclass
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from .drop_statistics import event_reward
|
||||
from .maps import stages
|
||||
from .quests import indexed, stage_has_level
|
||||
from .sweeping import SweepPolicy
|
||||
|
||||
|
||||
def value(obj, name, default=None):
|
||||
return obj.get(name, default) if isinstance(obj, dict) else getattr(obj, name, default)
|
||||
|
||||
|
||||
class CancelledBeforeDispatch(Exception):
|
||||
"""Raised only before Client.call is invoked; the request was not sent."""
|
||||
|
||||
|
||||
def role_id(snapshot):
|
||||
owner = snapshot.raw.get("master", {}).get("id")
|
||||
if owner is None:
|
||||
raise ValueError("角色身份缺失,不能推进任务")
|
||||
return str(owner)
|
||||
|
||||
|
||||
def digest(obj):
|
||||
return hashlib.sha256(json.dumps(obj, sort_keys=True, ensure_ascii=False,
|
||||
separators=(",", ":"), default=str).encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def public_data(obj):
|
||||
"""Never persist transport credentials, even in an unexpected response."""
|
||||
if is_dataclass(obj):
|
||||
obj = asdict(obj)
|
||||
if isinstance(obj, dict):
|
||||
return {str(k): public_data(v) for k, v in obj.items()
|
||||
if str(k).lower().replace("_", "") not in ("key", "sessionkey", "session", "sessionid", "aeskey", "encryptionkey", "sdkkey", "appkey",
|
||||
"reqid", "reqsid", "uid", "sdkuid", "deviceid")
|
||||
and not any(secret in str(k).lower() for secret in ("token", "password", "secret", "authorization", "cookie"))}
|
||||
if isinstance(obj, (list, tuple)):
|
||||
return [public_data(v) for v in obj]
|
||||
if obj is None or isinstance(obj, (str, int, float, bool)):
|
||||
return obj
|
||||
return str(obj)
|
||||
|
||||
|
||||
def gameplay_response(response):
|
||||
result = {k: v for k, v in response.items() if k in (
|
||||
"resCode", "triggerEvent", "stageEvent", "reward", "stageReward", "costTi", "unlockStage", "lockStage",
|
||||
"monsterExpInfos", "taskStepValue", "task", "nextTasks", "unlockTasks", "unlockStages", "receiveTasks", "loopTask",
|
||||
"loopTaskNum", "loopTaskTime")}
|
||||
def task_fields(task):
|
||||
return {key: task[key] for key in ("id", "typeId", "curStep", "stepValue") if key in task}
|
||||
if isinstance(result.get("task"), dict):
|
||||
result["task"] = task_fields(result["task"])
|
||||
for field in ("nextTasks", "receiveTasks"):
|
||||
if isinstance(result.get(field), list):
|
||||
result[field] = [task_fields(task) for task in result[field] if isinstance(task, dict)]
|
||||
return public_data(result)
|
||||
|
||||
|
||||
_locks_guard = threading.Lock()
|
||||
_locks = {}
|
||||
|
||||
|
||||
def account_lock(path):
|
||||
if path is None:
|
||||
return threading.RLock()
|
||||
key = os.path.normcase(str(Path(path).resolve()))
|
||||
with _locks_guard:
|
||||
return _locks.setdefault(key, threading.RLock())
|
||||
|
||||
|
||||
class BattleJournal:
|
||||
"""Atomic per-role write-ahead records, including local story checkpoints."""
|
||||
|
||||
def __init__(self, path=None):
|
||||
self.path = Path(path) if path else None
|
||||
self.lock = account_lock(path)
|
||||
self.state = {"version": 1, "roles": {}}
|
||||
self.reload()
|
||||
|
||||
def reload(self):
|
||||
if self.path and self.path.exists():
|
||||
try:
|
||||
state = json.loads(self.path.read_text(encoding="utf-8"))
|
||||
if state.get("version") != 1 or not isinstance(state.get("roles"), dict):
|
||||
raise ValueError("unsupported journal")
|
||||
self.state = state
|
||||
except (OSError, ValueError, AttributeError) as error:
|
||||
raise ValueError("任务 / 战斗日志无法读取;请保留日志并核对,不能自动重试") from error
|
||||
|
||||
def save(self):
|
||||
for state in self.state["roles"].values():
|
||||
completed = [r for r in state["records"] if r["attempt_id"] != state["pending"]]
|
||||
keep = {r["attempt_id"] for r in completed[-500:]}
|
||||
state["records"] = [r for r in state["records"] if r["attempt_id"] == state["pending"] or r["attempt_id"] in keep]
|
||||
if self.path:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = self.path.with_name(self.path.name + "." + uuid.uuid4().hex + ".tmp")
|
||||
try:
|
||||
with temporary.open("w", encoding="utf-8") as stream:
|
||||
json.dump(self.state, stream, ensure_ascii=False, allow_nan=False)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
for attempt in range(5):
|
||||
try:
|
||||
temporary.replace(self.path)
|
||||
break
|
||||
except PermissionError:
|
||||
if attempt == 4:
|
||||
raise
|
||||
# Windows indexers can briefly hold a just-closed file.
|
||||
# Only local atomic replacement is retried, never an API.
|
||||
time.sleep(0.01 * (attempt + 1))
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
def role(self, snapshot):
|
||||
return self.state["roles"].setdefault(role_id(snapshot),
|
||||
{"pending": None, "records": [], "cursors": {}, "losses": 0})
|
||||
|
||||
def pending(self, snapshot):
|
||||
state = self.role(snapshot)
|
||||
return next((r for r in state["records"] if r["attempt_id"] == state["pending"]), None)
|
||||
|
||||
def records(self, snapshot):
|
||||
with self.lock:
|
||||
self.reload()
|
||||
return deepcopy(list(reversed(self.role(snapshot)["records"])))
|
||||
|
||||
def begin(self, snapshot, intent, *, kind=None):
|
||||
if self.pending(snapshot):
|
||||
raise ValueError("有待核对的任务 / 战斗,禁止重复开始")
|
||||
record = {name: public_data(value(intent, name)) for name in (
|
||||
"kind", "description", "path", "payload", "task_id", "task_type_id", "step_number",
|
||||
"position", "stage_id", "difficulty", "battle_kind", "source_task_id", "source_task_type_id", "source_step_number", "farming_target")}
|
||||
record.update(attempt_id=uuid.uuid4().hex, role_id=role_id(snapshot),
|
||||
phase="prepared", outcome="", timestamp=time.time(), started_at=time.time(), team=value(intent, "team", ""),
|
||||
message="", kind=kind or record["kind"], battle_mode=value(intent, "battle_mode", "original"),
|
||||
baseline={"tasks": [{k: t[k] for k in ("id", "typeId", "curStep", "stepValue") if k in t}
|
||||
for t in snapshot.raw.get("currentTasks", []) if str(t.get("id")) == str(value(intent, "task_id"))
|
||||
or str(t.get("typeId")) == str(value(intent, "task_type_id"))],
|
||||
"loop_time": snapshot.raw.get("history", {}).get("loopTaskTime"),
|
||||
"passed": stage_has_level(snapshot.raw.get("history", {}), "passStage",
|
||||
value(intent, "stage_id", ""), value(intent, "difficulty", "1"))})
|
||||
if value(intent, "token") and value(intent, "account_key"):
|
||||
record.update(intent_id=value(intent, "token"), account_key=value(intent, "account_key"))
|
||||
state = self.role(snapshot)
|
||||
state["records"].append(record)
|
||||
state["pending"] = record["attempt_id"]
|
||||
self.save() # Must succeed BEFORE any non-retryable request.
|
||||
return record
|
||||
|
||||
def update(self, record, phase, **fields):
|
||||
record.update(public_data(fields), phase=phase, updated_at=time.time())
|
||||
self.save()
|
||||
|
||||
def finish(self, snapshot, record, outcome, message=""):
|
||||
state = self.role(snapshot)
|
||||
record.update(phase="done", outcome=outcome, message=message, finished_at=time.time())
|
||||
if state["pending"] == record["attempt_id"]:
|
||||
state["pending"] = None
|
||||
if outcome == "loss":
|
||||
state["losses"] += 1
|
||||
elif outcome == "win":
|
||||
state["losses"] = 0
|
||||
self.save()
|
||||
|
||||
def cursors(self, snapshot):
|
||||
return deepcopy(self.role(snapshot)["cursors"])
|
||||
|
||||
def checkpoint(self, snapshot, intent, response=None):
|
||||
"""Local acknowledgements never rewrite the authoritative snapshot."""
|
||||
key = f"{value(intent, 'task_id', 0)}:{value(intent, 'task_type_id', '')}"
|
||||
step = int(value(intent, "step_number", 0) or 0)
|
||||
current = next((t for t in snapshot.raw.get("currentTasks", [])
|
||||
if str(t.get("id")) == str(value(intent, "task_id"))), {})
|
||||
entry = self.role(snapshot)["cursors"].setdefault(key,
|
||||
{"task_id": value(intent, "task_id"), "task_type_id": value(intent, "task_type_id"),
|
||||
"server_step": int(current.get("curStep", step) or step), "steps": {}})
|
||||
checkpoint = entry["steps"].setdefault(str(step), {"operations": {}, "submitted": False, "local_complete": False})
|
||||
kind, phase = value(intent, "kind"), value(intent, "phase", "")
|
||||
checkpoint["operations"][f"{kind}:{phase}"] = {"kind": kind, "phase": phase,
|
||||
"response": gameplay_response(response) if isinstance(response, dict) else None}
|
||||
if isinstance(response, dict) and ((value(intent, "path", "") or "").endswith("taskCompleteStep")
|
||||
or kind in ("battle", "task_battle", "progression_battle")):
|
||||
checkpoint["submitted"] = True
|
||||
if kind in ("progression_local_step", "local_step"):
|
||||
checkpoint["local_complete"] = True
|
||||
self.save()
|
||||
|
||||
def reconcile(self, snapshot, *, trusted=False):
|
||||
"""Only a new role-checked server snapshot can resolve uncertain writes.
|
||||
|
||||
An unchanged step, stamina change or old three-star clear is insufficient.
|
||||
No endpoint is replayed by reconciliation.
|
||||
"""
|
||||
if not trusted:
|
||||
return False
|
||||
with self.lock:
|
||||
self.reload()
|
||||
record = self.pending(snapshot)
|
||||
tasks = snapshot.raw.get("currentTasks", [])
|
||||
history = snapshot.raw.get("history", {})
|
||||
state = self.role(snapshot)
|
||||
changed = False
|
||||
# Keep checkpoints for steps that the server has not incorporated.
|
||||
for key, cursor in list(state["cursors"].items()):
|
||||
task = next((t for t in tasks if str(t.get("id")) == str(cursor.get("task_id"))
|
||||
and str(t.get("typeId")) == str(cursor.get("task_type_id"))), None)
|
||||
if task is None:
|
||||
del state["cursors"][key]
|
||||
changed = True
|
||||
elif int(task.get("curStep", 1)) > int(cursor.get("server_step", 0)):
|
||||
cursor["server_step"] = int(task["curStep"])
|
||||
cursor["steps"] = {k: v for k, v in cursor["steps"].items() if int(k) >= int(task["curStep"])}
|
||||
changed = True
|
||||
resolved = False
|
||||
if record:
|
||||
task = next((t for t in tasks if str(t.get("id")) == str(record.get("task_id"))
|
||||
and str(t.get("typeId")) == str(record.get("task_type_id"))), None)
|
||||
path = record.get("path") or ""
|
||||
if record.get("task_id") and record.get("step_number"):
|
||||
resolved = bool(task and int(task.get("curStep", 1)) > int(record["step_number"]))
|
||||
response = record.get("response") or {}
|
||||
baseline = next((t for t in record["baseline"]["tasks"]
|
||||
if str(t.get("id")) == str(record["task_id"])), {})
|
||||
if (not resolved and "planner_state" not in state and task and response.get("taskStepValue") is not None
|
||||
and task.get("stepValue") == response["taskStepValue"]
|
||||
and baseline.get("stepValue") != response["taskStepValue"]):
|
||||
self.checkpoint(snapshot, record, response)
|
||||
resolved = True
|
||||
if record.get("task_type_id") and path.endswith(("taskReceive", "taskLoopReceive")):
|
||||
old = {str(t.get("id")) for t in record["baseline"]["tasks"]}
|
||||
resolved = any(str(t.get("typeId")) == str(record["task_type_id"])
|
||||
and str(t.get("id")) not in old for t in tasks)
|
||||
if path.endswith("taskComplete"):
|
||||
resolved = task is None and bool(indexed(history.get("passTask"), record["task_type_id"], False))
|
||||
if path.endswith("taskLoopFlush"):
|
||||
resolved = history.get("loopTaskTime") != record["baseline"].get("loop_time")
|
||||
if path.endswith("taskUpdate"):
|
||||
payload = record.get("payload") or {}
|
||||
resolved = (all(any(str(t.get("typeId")) == str(row.get("taskTypeId")) for t in tasks)
|
||||
for row in payload.get("receiveTasks", []))
|
||||
and all(indexed(history.get("unlockTask"), row.get("taskTypeId"), False)
|
||||
for row in payload.get("unlockTasks", []))
|
||||
and all(not any(str(t.get("id")) == str(mid) for t in tasks) for mid in payload.get("removeTasks", [])))
|
||||
if record.get("stage_id") and not record.get("task_id"):
|
||||
# A first clear proves settlement, but NOT the optional record request.
|
||||
resolved = (not record["baseline"]["passed"] and
|
||||
stage_has_level(history, "passStage", record["stage_id"], record.get("difficulty", "1"))
|
||||
and record["phase"] not in ("record_pending", "record_unknown"))
|
||||
if resolved:
|
||||
self.finish(snapshot, record, "reconciled", "已由服务器任务 / 首次通关快照核对;未重发请求")
|
||||
if changed and not resolved:
|
||||
self.save()
|
||||
return resolved
|
||||
|
||||
|
||||
class BattleOrchestrator:
|
||||
def __init__(self, catalog, journal=None, runtime=None, sweeper=None, request_builder=None, observer=None, clock=None):
|
||||
self.catalog = catalog
|
||||
self.journal = journal or BattleJournal()
|
||||
self.runtime = runtime
|
||||
self.sweeper = sweeper
|
||||
self.request_builder = request_builder
|
||||
self.observer = observer
|
||||
self.clock = clock or time.monotonic
|
||||
|
||||
def pending(self, snapshot):
|
||||
return self.journal.pending(snapshot)
|
||||
|
||||
def task_at_position(self, snapshot, position):
|
||||
positions = self.catalog.data.get("stage_task_positions", {})
|
||||
for task in snapshot.raw.get("currentTasks", []):
|
||||
steps = positions.get(str(task.get("typeId")), [])
|
||||
number = int(task.get("curStep", 1)) - 1
|
||||
if 0 <= number < len(steps) and steps[number] == position:
|
||||
return task
|
||||
|
||||
def request(self, snapshot, intent, policy):
|
||||
task = bool(value(intent, "task_id")) or bool(value(intent, "task_type_id")) and value(intent, "battle_kind") in (
|
||||
"task", "battle", "passStage", "task_battle", "task_pass_stage")
|
||||
position = {"battleType": "task" if task else "stage",
|
||||
"stageId": None if task else str(value(intent, "stage_id", "")),
|
||||
"stageLevel": None if task else str(value(intent, "difficulty", "1")),
|
||||
"taskTypeId": str(value(intent, "task_type_id")) if task else None,
|
||||
"taskStep": max(0, int(value(intent, "step_number", 1) or 1) - 1) if task else 0}
|
||||
request = {"snapshot": snapshot.raw if self.request_builder else deepcopy(snapshot.raw), "team": policy.team, "battle_position": position,
|
||||
"battle_mode": value(policy, "battle_mode", "original"),
|
||||
**{name: value(intent, name) for name in ("stage_id", "difficulty", "task_type_id", "step_number", "battle_kind")}}
|
||||
return self.request_builder(snapshot, intent, policy, request) if self.request_builder else request
|
||||
|
||||
def resource_reason(self, snapshot, intent, policy, ranch=None):
|
||||
if self.sweeper and self.sweeper.state.get("pending"):
|
||||
return "有未核对的扫荡,不能开始任务 / 战斗"
|
||||
if self.journal.pending(snapshot):
|
||||
return "有待核对的任务 / 战斗,禁止重复开始"
|
||||
if value(intent, "task_id"):
|
||||
planner_validated = self.observer("validate", intent, None) if self.observer else None
|
||||
task = next((t for t in snapshot.raw.get("currentTasks", [])
|
||||
if str(t.get("id")) == str(value(intent, "task_id"))
|
||||
and str(t.get("typeId")) == str(value(intent, "task_type_id"))), None)
|
||||
number = int(value(intent, "step_number", 1))
|
||||
key = f"{value(intent, 'task_id')}:{value(intent, 'task_type_id')}"
|
||||
checkpoints = self.journal.cursors(snapshot).get(key, {}).get("steps", {})
|
||||
server = int(task.get("curStep", 1)) if task else 0
|
||||
locally_completed = task and server < number and all(checkpoints.get(str(i), {}).get("local_complete")
|
||||
for i in range(server, number))
|
||||
if planner_validated is False or planner_validated is None and (task is None or server != number and not locally_completed):
|
||||
return "任务实例或服务器步骤已变化,请重新规划"
|
||||
if planner_validated is None and checkpoints.get(str(number), {}).get("submitted"):
|
||||
return "该任务步骤已有确认记录,等待剧情 / 服务器步骤核对"
|
||||
limit = max(0, int(policy.stop_after_loss))
|
||||
if limit and self.journal.role(snapshot)["losses"] >= limit:
|
||||
return "已达战败停止次数,请核对阵容后重置战败计数"
|
||||
teams = snapshot.raw.get("teams", [])
|
||||
team = next((t for t in teams if t.get("teamName") == policy.team and t.get("teamType") == "battleTeam"), {})
|
||||
ids = [int(mid) for mid in team.get("monsters", []) if mid and int(mid) > 0]
|
||||
if not ids or any(mid not in snapshot.monsters for mid in ids):
|
||||
return "所选战队无有效魔物或实例缺失"
|
||||
stage_id = str(value(intent, "stage_id", "") or "")
|
||||
difficulty = str(value(intent, "difficulty", "1") or "1")
|
||||
if not stage_id:
|
||||
return "" if value(intent, "task_id") else "缺少关卡定位"
|
||||
stage = self.catalog.data.get("stage_info", {}).get(stage_id)
|
||||
if not stage or difficulty not in stage.get("level", {}):
|
||||
return "关卡配置缺失"
|
||||
if not value(intent, "task_id"):
|
||||
position = value(intent, "position") or f"city{stage.get('city')}_wild_stage{stage_id}_level{difficulty}"
|
||||
if self.task_at_position(snapshot, position):
|
||||
return "该位置由当前任务优先处理,不能执行普通挑战或扫荡"
|
||||
match = next((s for s in stages(self.catalog, snapshot) if s.stage_id == stage_id and s.level == difficulty), None)
|
||||
if match is None or not match.unlocked or not match.open:
|
||||
return "关卡尚未解锁或当前未开放"
|
||||
base = stage.get("cost") or {}
|
||||
master = snapshot.raw["master"]
|
||||
stamina = float(base.get("ti") or 0) + float(stage["level"][difficulty].get("cost") or 0)
|
||||
if float(master.get("ti") or 0) < stamina + max(0, policy.reserve_ti):
|
||||
return "体力不足或已达保留体力"
|
||||
if base.get("ke"):
|
||||
return "入场需要氪金,未启用"
|
||||
money = float(base.get("money") or 0)
|
||||
if money > policy.max_money or float(master.get("money") or 0) - money < max(0, value(ranch, "keep_money", 0)):
|
||||
return "入场金币超过上限或保留金币不足"
|
||||
for item in base.get("items") or []:
|
||||
key, count = str(item["typeId"]), int(item["num"])
|
||||
if count and not policy.allow_items:
|
||||
return "入场需要消耗道具,未启用"
|
||||
reserve = max(int(policy.item_reserves.get(key, 0)), int(value(ranch, "reserved_eggs", {}).get(key, 0)))
|
||||
owned = sum(int(i.get("num") or 0) for i in snapshot.raw.get("items", [])
|
||||
if str(i.get("typeId")) == key and not i.get("lock") and not i.get("sysLock") and not i.get("feedLock"))
|
||||
reserve = max(reserve, int(value(ranch, "gift_items", {}).get(key, {}).get("reserve", 0)))
|
||||
if owned - count < reserve:
|
||||
return "入场道具不足或已达保留数量"
|
||||
return ""
|
||||
|
||||
def inspect(self, request):
|
||||
self._inspection_evidence = {}
|
||||
if self.runtime is None:
|
||||
return False, "所选战斗运行时尚未提供,未开始战斗"
|
||||
report = self.runtime.inspect(request.get("runtime_request", request))
|
||||
self._inspection_evidence = self.runtime_evidence(report, request.get("battle_mode", "original"))
|
||||
supported = value(report, "supported") is True
|
||||
if request.get("battle_mode", "original") == "experimental":
|
||||
supported = (supported and value(report, "execution_mode") == "experimental"
|
||||
and value(report, "approximate") is True and value(report, "faithful") is False)
|
||||
else:
|
||||
supported = supported and value(report, "settlement_eligible") is True and value(report, "approximate") is not True
|
||||
blockers = list(value(report, "anomalies", []) or [])
|
||||
blockers += [row for row in value(report, "diagnostics", []) or [] if isinstance(row, dict) and row.get("blocking") is True]
|
||||
supported = supported and not blockers
|
||||
reasons = list(value(report, "reasons", []) or []) + blockers
|
||||
reason = value(report, "block_reason") or value(report, "reason") or "; ".join(
|
||||
str(row.get("detail") or row.get("code")) if isinstance(row, dict) else str(row) for row in reasons) or \
|
||||
"运行时尚未验证支持此阵容 / 关卡,未开始战斗"
|
||||
return supported, "" if supported else str(reason)
|
||||
|
||||
@staticmethod
|
||||
def runtime_evidence(result, mode):
|
||||
evidence = {"battle_mode": mode, **{field: public_data(value(result, field)) for field in (
|
||||
"faithful", "approximate", "limitations", "reasons", "status", "elapsed_ms", "model_elapsed_ms",
|
||||
"requires_realtime_wait", "wall_time_ms", "trace_path", "resource_identity", "terminal_reason", "settlement_eligible",
|
||||
"experimental_settlement_eligible", "execution_mode", "execution_status", "terminal", "diagnostics",
|
||||
"ignored_mechanics", "anomalies", "assumptions", "experimental_eligibility_reasons", "omitted_events")}}
|
||||
trace = value(result, "trace")
|
||||
if trace is None:
|
||||
trace = value(result, "events")
|
||||
evidence["trace_source"] = "events"
|
||||
if isinstance(trace, (list, tuple)):
|
||||
evidence.update(trace=public_data(list(trace[:128]) + list(trace[-128:]) if len(trace) > 256 else trace),
|
||||
trace_count=len(trace), trace_truncated=len(trace) > 256 or bool(value(result, "trace_truncated")),
|
||||
journal_trace_truncated=len(trace) > 256, trace_digest=digest(trace))
|
||||
elif trace is not None:
|
||||
evidence["trace"] = public_data(trace)
|
||||
return evidence
|
||||
|
||||
def wait_for_battle_clock(self, record, request, result, data, started, cancel):
|
||||
if value(result, "requires_realtime_wait") is not True:
|
||||
return True
|
||||
duration = None
|
||||
for field, scale in (("model_elapsed_ms", .001), ("battle_elapsed_ms", .001), ("elapsed_ms", .001),
|
||||
("model_elapsed_seconds", 1), ("elapsed_seconds", 1), ("elapsed", 1)):
|
||||
elapsed = value(result, field)
|
||||
if type(elapsed) in (int, float) and math.isfinite(elapsed) and elapsed >= 0:
|
||||
duration = elapsed * scale
|
||||
break
|
||||
battle = (request.get("original_data") or {}).get("battle") or {}
|
||||
limit, left = battle.get("time"), data.get("leftTime")
|
||||
if type(limit) in (int, float) and math.isfinite(limit) and limit > 0 and type(left) in (int, float) and 0 <= left <= limit * 1000:
|
||||
duration = max(duration or 0, limit - left / 1000)
|
||||
if duration is None:
|
||||
self._unknown(record, "模型未提供有效战斗时钟,未提交结算")
|
||||
return False
|
||||
self.journal.update(record, "waiting_for_battle_clock", battle_clock_seconds=duration,
|
||||
message="等待已计算的战斗时钟;可以停止,停止后保留待核对记录")
|
||||
deadline = started + duration
|
||||
while not cancel.is_set():
|
||||
remaining = deadline - self.clock()
|
||||
if remaining <= 0:
|
||||
return True
|
||||
if cancel.wait(min(remaining, .25)):
|
||||
break
|
||||
self._unknown(record, "等待战斗时钟期间已取消,开战记录保留待核对")
|
||||
return False
|
||||
|
||||
def run(self, client, snapshot, intent, policy, *, cancel=None, ranch=None):
|
||||
if not self.journal.lock.acquire(blocking=False):
|
||||
return "同账号已有任务 / 战斗正在执行"
|
||||
try:
|
||||
return self._run(client, snapshot, intent, policy, cancel=cancel, ranch=ranch)
|
||||
finally:
|
||||
self.journal.lock.release()
|
||||
|
||||
def _run(self, client, snapshot, intent, policy, *, cancel=None, ranch=None):
|
||||
cancel = cancel or threading.Event()
|
||||
with self.journal.lock:
|
||||
self.journal.reload()
|
||||
if not policy.enabled:
|
||||
return "自动主线策略未启用"
|
||||
reason = value(intent, "block_reason") or self.resource_reason(snapshot, intent, policy, ranch)
|
||||
if reason:
|
||||
return str(reason)
|
||||
if cancel.is_set():
|
||||
return "任务 / 战斗已取消,未开始"
|
||||
if value(intent, "kind") in ("sweep", "progression_sweep", "progression_farm_sweep", "progression_map_sweep") or value(intent, "battle_kind") == "sweep":
|
||||
return self._sweep(client, snapshot, intent, policy, cancel)
|
||||
request = self.request(snapshot, intent, policy)
|
||||
mode = request.get("battle_mode", "original")
|
||||
supported, reason = self.inspect(request)
|
||||
if not supported:
|
||||
record = self.journal.begin(snapshot, intent)
|
||||
record.update(self._inspection_evidence, team=policy.team, battle_mode=mode)
|
||||
self.journal.finish(snapshot, record, "unsupported", reason)
|
||||
return reason
|
||||
if cancel.is_set():
|
||||
return "任务 / 战斗已取消,未开始"
|
||||
record = self.journal.begin(snapshot, intent)
|
||||
try:
|
||||
if self.observer:
|
||||
self.observer("started", intent, None)
|
||||
if value(intent, "task_id"):
|
||||
path, payload = "battleService/battleStart", {"battleType": "task", "taskTypeId": str(value(intent, "task_type_id"))}
|
||||
else:
|
||||
path, payload = "stageService/stageStart", {"stageTypeId": str(value(intent, "stage_id")), "stageLevel": str(value(intent, "difficulty", "1"))}
|
||||
self.journal.update(record, "start_pending", start_path=path, input_digest=digest(public_data(request)),
|
||||
team=policy.team, battle_mode=mode,
|
||||
resource_identity=(request.get("original_data") or {}).get("manifest", {}).get("source"))
|
||||
try:
|
||||
started = self._call(client, path, payload, cancel=cancel)
|
||||
except CancelledBeforeDispatch:
|
||||
if self.observer:
|
||||
self.observer("cancelled_before_start", intent, None)
|
||||
self.journal.finish(snapshot, record, "cancelled", "开战请求尚未发送,已取消;未消耗入场资源")
|
||||
return record["message"]
|
||||
battle_started = self.clock()
|
||||
self.journal.update(record, "started", start_response=gameplay_response(started))
|
||||
if not value(intent, "task_id"):
|
||||
reward = event_reward(started)
|
||||
if reward is not None:
|
||||
self.journal.update(record, "event_reward", reward=reward)
|
||||
if self.observer:
|
||||
self.observer("event", intent, started)
|
||||
self.journal.finish(snapshot, record, "event", "探索事件奖励已由开始响应发放")
|
||||
return "探索事件奖励已结算;未执行战斗"
|
||||
flag = started.get("triggerEvent")
|
||||
if flag is not False and not (type(flag) is int and flag == 0):
|
||||
event = started.get("stageEvent")
|
||||
if isinstance(event, dict) and event.get("hideStageId") is not None:
|
||||
hidden = str(event["hideStageId"])
|
||||
fields = asdict(intent) if is_dataclass(intent) else dict(intent) if isinstance(intent, dict) else vars(intent).copy()
|
||||
fields.update(stage_id=hidden, difficulty="1", battle_kind="hidden")
|
||||
request = self.request(snapshot, fields, policy)
|
||||
supported, reason = self.inspect(request)
|
||||
if not supported:
|
||||
return self._unknown(record, "隐藏关卡待处理:" + reason)
|
||||
self.journal.update(record, "hidden_started", stage_id=hidden, difficulty="1")
|
||||
else:
|
||||
return self._unknown(record, "探索事件或开战状态未知,等待核对")
|
||||
if cancel.is_set():
|
||||
return self._unknown(record, "开战后已取消,等待服务器状态核对")
|
||||
self.journal.update(record, "running")
|
||||
result = self.runtime.run(request.get("runtime_request", request), cancel_event=cancel)
|
||||
evidence = self.runtime_evidence(result, mode)
|
||||
self.journal.update(record, "runtime_returned", **evidence)
|
||||
if cancel.is_set() or value(result, "outcome") in ("cancelled", "cancel", "timeout", "unknown", "unsupported"):
|
||||
return self._unknown(record, "战斗已取消、超时或结果不确定,等待核对")
|
||||
data = value(result, "battle_data")
|
||||
eligible = value(result, "outcome") in ("win", "loss")
|
||||
if mode == "experimental":
|
||||
eligible = (eligible and value(result, "experimental_settlement_eligible") is True
|
||||
and value(result, "execution_mode") == "experimental" and value(result, "execution_status") == "completed"
|
||||
and value(result, "supported") is True and value(result, "terminal") is True
|
||||
and value(result, "approximate") is True and value(result, "faithful") is False and not value(result, "anomalies"))
|
||||
else:
|
||||
eligible = eligible and value(result, "settlement_eligible") is True and value(result, "faithful") is True and value(result, "approximate") is not True
|
||||
if not eligible or not isinstance(data, dict) or type(data.get("win")) is not bool:
|
||||
return self._unknown(record, "所选运行时未提供可结算的实际执行结果,未提交结算")
|
||||
if data["win"] != (value(result, "outcome") == "win"):
|
||||
return self._unknown(record, "运行结果与战果胜负不一致,未提交结算")
|
||||
position = data.get("battlePosition")
|
||||
if (not isinstance(position, dict) or {k: v for k, v in position.items() if v is not None}
|
||||
!= {k: v for k, v in request["battle_position"].items() if v is not None}):
|
||||
return self._unknown(record, "运行时战果定位不匹配,未提交结算")
|
||||
# Keep all statistics and integrity records exactly as supplied.
|
||||
self.journal.update(record, "runtime_complete", battle_data=data)
|
||||
if not self.wait_for_battle_clock(record, request, result, data, battle_started, cancel):
|
||||
return record["message"]
|
||||
if not data["win"]:
|
||||
if not value(intent, "task_id") or value(intent, "battle_kind") == "passStage":
|
||||
self._record(client, record, request["stage_id"], False, cancel=cancel)
|
||||
if self.observer:
|
||||
self.observer("loss", intent, None)
|
||||
label = "实验模型战败(近似)" if mode == "experimental" else "实际战败"
|
||||
self.journal.finish(snapshot, record, "loss", label + ";未提交胜利结算或推进任务")
|
||||
return label + ";已停止此轮任务推进"
|
||||
if value(intent, "task_id"):
|
||||
path, payload = "taskService/taskCompleteStep", {"taskId": int(value(intent, "task_id")),
|
||||
"taskTypeId": str(value(intent, "task_type_id")), "removeIds": None, "battleData": data}
|
||||
else:
|
||||
path, payload = "battleService/battleEnd", {"battleData": data}
|
||||
self.journal.update(record, "settlement_pending", path=path)
|
||||
response = self._call(client, path, payload, cancel=cancel)
|
||||
self.journal.update(record, "settlement_acknowledged", response=gameplay_response(response), settlement_confirmed=True,
|
||||
reward=response["stageReward"] if response.get("stageReward") is not None else response.get("reward"))
|
||||
if value(intent, "task_id"):
|
||||
if self.observer:
|
||||
self.observer("settled", intent, response)
|
||||
else:
|
||||
self.journal.checkpoint(snapshot, intent, response)
|
||||
else:
|
||||
self._record(client, record, request["stage_id"], True, cancel=cancel)
|
||||
if self.observer:
|
||||
self.observer("settled", intent, response)
|
||||
label = "实验模型胜利(近似)" if mode == "experimental" else "实际胜利"
|
||||
self.journal.finish(snapshot, record, "win", label + ",结算接口已确认;后续进度以服务器快照核对")
|
||||
return label + ",已确认对应结算"
|
||||
except Exception as error:
|
||||
self._unknown(record, "任务 / 战斗请求或运行未确认;禁止自动重试", error_type=type(error).__name__)
|
||||
raise
|
||||
|
||||
def _sweep(self, client, snapshot, intent, policy, cancel):
|
||||
if not policy.allow_sweep or self.sweeper is None or value(intent, "task_id"):
|
||||
return "任务战斗或当前策略不允许普通扫荡"
|
||||
stage = next((s for s in stages(self.catalog, snapshot) if s.stage_id == str(value(intent, "stage_id"))
|
||||
and s.level == str(value(intent, "difficulty", "1"))), None)
|
||||
if stage is None or not stage.sweep:
|
||||
return "仅三个难度全通且客户端允许的普通关卡可扫荡"
|
||||
if cancel.is_set():
|
||||
return "扫荡已取消,未开始"
|
||||
policy = SweepPolicy(enabled=True, team=policy.team, keep_stamina=policy.reserve_ti,
|
||||
rules={stage.stage_id: {"enabled": True, "level": stage.level, "limit": self.sweeper.used(snapshot, stage) + 1}})
|
||||
record = self.journal.begin(snapshot, intent)
|
||||
self.journal.update(record, "sweep_pending")
|
||||
try:
|
||||
if self.observer:
|
||||
self.observer("started", intent, None)
|
||||
response = self.sweeper.run(client, snapshot, stage, policy)
|
||||
if self.observer:
|
||||
self.observer("event" if self.sweeper.last_outcome == "event" else "settled", intent, response)
|
||||
self.journal.finish(snapshot, record, "event" if self.sweeper.last_outcome == "event" else "sweep", "复用客户端已有扫荡路径")
|
||||
return "探索奖励事件已结算" if self.sweeper.last_outcome == "event" else "扫荡已完成"
|
||||
except Exception as error:
|
||||
self._unknown(record, "扫荡结果未确认,禁止自动重试", error_type=type(error).__name__)
|
||||
raise
|
||||
|
||||
@staticmethod
|
||||
def _call(client, path, payload, *, cancel=None):
|
||||
if cancel is not None and cancel.is_set():
|
||||
raise CancelledBeforeDispatch()
|
||||
response = client.call(path, payload)
|
||||
if not isinstance(response, dict) or response.get("resCode", 0) not in (0, "0"):
|
||||
raise ValueError("游戏接口未返回可信的成功响应")
|
||||
return response
|
||||
|
||||
def _record(self, client, record, stage, win, *, cancel=None):
|
||||
self.journal.update(record, "record_pending")
|
||||
try:
|
||||
self._call(client, "battleService/recordBattleResult", {"stageId": str(stage), "cityId": str(stage)[1:2], "result": int(win)}, cancel=cancel)
|
||||
except Exception:
|
||||
self.journal.update(record, "record_unknown", message="战果记录未确认,不能重放战斗")
|
||||
raise
|
||||
|
||||
def _unknown(self, record, message, **fields):
|
||||
phase = "record_unknown" if record["phase"] == "record_unknown" else "unknown"
|
||||
self.journal.update(record, phase, message=message, **fields)
|
||||
return message
|
||||
Binary file not shown.
@@ -0,0 +1,336 @@
|
||||
{
|
||||
"artifact": {
|
||||
"bytes": 242430,
|
||||
"decoded_sha256": "dd3ba996346dd682d052dfc63e9d8112b1096739df77cd7b2f500703c36d1742",
|
||||
"name": "combat_tables.json.gz",
|
||||
"sha256": "1348e2e80c8803dbe4e44999f151d939d847002ddb5aa992acb3aa0086877c12"
|
||||
},
|
||||
"artifacts": {
|
||||
"combat_battles.json.gz": {
|
||||
"bytes": 1465404,
|
||||
"decoded_sha256": "b3ecc8bed6190db9b960088022bb845fa422f705908a7b9d8140200d588f924a",
|
||||
"name": "combat_battles.json.gz",
|
||||
"sha256": "8d8798040c5d79eb60b971efac8e250cc37f01986cc96d917d3f87af74916515"
|
||||
},
|
||||
"combat_tables.json.gz": {
|
||||
"bytes": 242430,
|
||||
"decoded_sha256": "dd3ba996346dd682d052dfc63e9d8112b1096739df77cd7b2f500703c36d1742",
|
||||
"name": "combat_tables.json.gz",
|
||||
"sha256": "1348e2e80c8803dbe4e44999f151d939d847002ddb5aa992acb3aa0086877c12"
|
||||
}
|
||||
},
|
||||
"attack_sources": {
|
||||
"net/pixvi/myr/view/attack/AttackType1.as": "0dffc06552cf2a0e382bd30eed877d2e2bc46c87136ef95f415a57b2ecea62d0",
|
||||
"net/pixvi/myr/view/attack/AttackType10.as": "6c6d1d4b96724a14abb6b8fa0eb099f5bb21b20ea235b1f5e78bf53fb25c0b7d",
|
||||
"net/pixvi/myr/view/attack/AttackType100.as": "935eb7beee181b9ec91f85ff917bded6b1ebd9436d460009f0b6f980400ddb76",
|
||||
"net/pixvi/myr/view/attack/AttackType101.as": "8d4305a74797a2f88c4e0a6454e080097edcb42db6bc9e2991fb21d68fc15f8e",
|
||||
"net/pixvi/myr/view/attack/AttackType103.as": "5b0947393b8ada6dd72d30faef7ce0861f6f410a9de16b4950c37dd202a5a551",
|
||||
"net/pixvi/myr/view/attack/AttackType104.as": "ab374cd66e63bcd8c9cf3072e34c01b648c086a4309c212bf03feece96327207",
|
||||
"net/pixvi/myr/view/attack/AttackType105.as": "a34653f6e278dbbfee55e7e9d00279c2bbf810c8ea58217236dbf520ea874444",
|
||||
"net/pixvi/myr/view/attack/AttackType106.as": "0abe774699386a2244ab8a39787363f3201c3caebfffd7355a9cc51e16552b49",
|
||||
"net/pixvi/myr/view/attack/AttackType107.as": "745d993e4782741f11e5d5f3bb31c5732e36ba10cc4ac6ceab0e7cc5b871608a",
|
||||
"net/pixvi/myr/view/attack/AttackType108.as": "875e9d2db43079b59d20d52071e3632825180ca7d1625abc8c2fc7a2b5b102b0",
|
||||
"net/pixvi/myr/view/attack/AttackType109.as": "f5ad710478d0669ec8cc4a4ab1d2ae7dea0bc9ac32ad48e1aab2211374943a44",
|
||||
"net/pixvi/myr/view/attack/AttackType11.as": "98b98a51104a23892a5fecf30ec585d459c9c4ab05ea94622d4aba2b8e9f5f0d",
|
||||
"net/pixvi/myr/view/attack/AttackType110.as": "df2c574bda929d78a11c899a94c0213a0c498d1c809c5c237947481b0944b300",
|
||||
"net/pixvi/myr/view/attack/AttackType111.as": "fd111aea97ce86a9978514613f957f872001e261676f48346db9ffb6c62058dc",
|
||||
"net/pixvi/myr/view/attack/AttackType112.as": "63ce66d7ebab8b044bef81eaa5dc723594f158b58d2e64fe88047c88f410ca0e",
|
||||
"net/pixvi/myr/view/attack/AttackType113.as": "55df84bad4470c10c36cfc0a9381bc7b7835f2b31cff790f6a04ed3551bce5e1",
|
||||
"net/pixvi/myr/view/attack/AttackType114.as": "882c6272945cc29f38e4a6008042837d7036f9d08af9ec56a3750a60de7c4616",
|
||||
"net/pixvi/myr/view/attack/AttackType115.as": "66fdefe5e613187633371807db48bead69769adb48d26b93c324afd4437f898b",
|
||||
"net/pixvi/myr/view/attack/AttackType116.as": "15e9957dcb57d9e9aaaa554cb83faef4d03c0eab5fb542fff19675f8368ed675",
|
||||
"net/pixvi/myr/view/attack/AttackType117.as": "977dbbe2e2c04a724eeba8573f0337bd2dde4ca199eda14966020b08f4313603",
|
||||
"net/pixvi/myr/view/attack/AttackType118.as": "ab25bf71f5d18e403e6452c4c567330f301108cfa93b49941b15cc0f6864096f",
|
||||
"net/pixvi/myr/view/attack/AttackType119.as": "6773e33051522b260b98141fc57ec8c6c72c65c38c215ece0a98cc9c244e3858",
|
||||
"net/pixvi/myr/view/attack/AttackType12.as": "644a3d29aa83ea9c2ac90c40ebae4229e84e63247d1f0613ead5cd213bc8cbc9",
|
||||
"net/pixvi/myr/view/attack/AttackType120.as": "2818a113ae7f3f3054c31a4d15d182c3891ff5333f678c04d8e7e0f84e5b47a3",
|
||||
"net/pixvi/myr/view/attack/AttackType121.as": "9bba26701a1fc3001a0ce6e462120c0e023c4c64ba24500539afeaa8942ec5ed",
|
||||
"net/pixvi/myr/view/attack/AttackType122.as": "20ddc709700060db16dc77ee35d3eb10197a02c6ca8c79b39e431d247e33135c",
|
||||
"net/pixvi/myr/view/attack/AttackType123.as": "6cbacf698081d3bd51ede16a73c181cbc0815c01625196ca9db06827495cca16",
|
||||
"net/pixvi/myr/view/attack/AttackType124.as": "733d2eda0bfa0b9037e2c547ba4d7fe4edf33c4e2ba01510271f439d914d9037",
|
||||
"net/pixvi/myr/view/attack/AttackType125.as": "0d352666335baf476b75c9cce6b3af9a3a2f9d6fbac0d87fb22a455a0fa26f7e",
|
||||
"net/pixvi/myr/view/attack/AttackType126.as": "7f775e355c8c6cefa4799fa359bb48ead8bb3825235b0cebb4f837d21bb402df",
|
||||
"net/pixvi/myr/view/attack/AttackType127.as": "efba984f19354331d1592678293d52308d7753f75af965758ea4541c4d7a83ec",
|
||||
"net/pixvi/myr/view/attack/AttackType129.as": "dbb285b1a2d3fc8ac9e386164dd6820f667981df472c305981072aba53669d57",
|
||||
"net/pixvi/myr/view/attack/AttackType13.as": "0c4655520e90c147f0e99a5dd683bb6262283495c0207d401d36912666733990",
|
||||
"net/pixvi/myr/view/attack/AttackType130.as": "3a96142623ea5ed38ec5963de8732b27993444361e5f8e748de2d33581be3672",
|
||||
"net/pixvi/myr/view/attack/AttackType131.as": "2cbf0b8dfa3c0c630977b60b738ae777b10b0ea4565d36aa1dea06efb4538450",
|
||||
"net/pixvi/myr/view/attack/AttackType132.as": "54f572d79db1d5acb0e9c1f697a6d99bc70864b9b625df7b5c07ef0001817b07",
|
||||
"net/pixvi/myr/view/attack/AttackType133.as": "7a01ecf35c2c1f2f31797775d91a1280fa21786b188f70cbbf95fc298c01595a",
|
||||
"net/pixvi/myr/view/attack/AttackType134.as": "87fcc3c6e4c24a1a13be051cf2f68556f1e8c33fedda904b64b01d849eba05c6",
|
||||
"net/pixvi/myr/view/attack/AttackType135.as": "5602be86e8f0ba6c9b01d197f8dc1f924ad8602a77f3641f05d129269a721f3d",
|
||||
"net/pixvi/myr/view/attack/AttackType136.as": "5a6ff9b57519ac124a5bf7c2aafb4aac92e8b05915955e82e3fc8b99df70e602",
|
||||
"net/pixvi/myr/view/attack/AttackType137.as": "851f1df4a70fdb2b6cde5515023692a85edf4b26eba0d6cf7d69880e216abf5c",
|
||||
"net/pixvi/myr/view/attack/AttackType138.as": "a369f54614099cc0bbff87eed83dde2a0ddf496ed29a4499ac02fb7832de0be4",
|
||||
"net/pixvi/myr/view/attack/AttackType139.as": "d882cbab23627c96c4342d0981936e15454e835305f2b2ed98ebfb61eb4825e1",
|
||||
"net/pixvi/myr/view/attack/AttackType14.as": "6986f6705444066bb62a324e0f927bf0e4ba80cacf77facb42c94cdabba2b925",
|
||||
"net/pixvi/myr/view/attack/AttackType140.as": "dc39d24b77e88ca0f86092cd8d68f0167be4d845cad703c8e3aa97552c740eb0",
|
||||
"net/pixvi/myr/view/attack/AttackType141.as": "2feaea684006b0fa72b39cd61415c8f58bdc33bfac5a86b5d1fbb4acf18bae24",
|
||||
"net/pixvi/myr/view/attack/AttackType142.as": "62d07f6d11548d975c2873d88b1a848c7c90308e5446e7fd4a0103a120ce330b",
|
||||
"net/pixvi/myr/view/attack/AttackType143.as": "4371a86e568a59a82aaad269481abe4daba14739fe484666097649827e2b3a31",
|
||||
"net/pixvi/myr/view/attack/AttackType144.as": "fdc94785f9781b54a22f005274c7c5fbcd04110f7c1164c3e5caa446bad62208",
|
||||
"net/pixvi/myr/view/attack/AttackType145.as": "9cc056bfcc138518a1bfdea213859c1b479ffc4635fc77314dbd1f85ed70dafe",
|
||||
"net/pixvi/myr/view/attack/AttackType146.as": "c2dd3bcb089a1fa7b6adeaa4efda51b5c0e6cf34ebd7a7f48e2da26214052e13",
|
||||
"net/pixvi/myr/view/attack/AttackType147.as": "cf050b3597ee610b17bebd7696d5b0ef302e9d3a11e3383db2c4c7daf1e8b02c",
|
||||
"net/pixvi/myr/view/attack/AttackType148.as": "df27b64bbec556bf9042faf94607f51775b903ae5c8671a196df8eb90dd640aa",
|
||||
"net/pixvi/myr/view/attack/AttackType149.as": "3e82c4d78f2118bf61bc3b471d475ae49bf2d5eefeb508628820453d90e66e9b",
|
||||
"net/pixvi/myr/view/attack/AttackType15.as": "087b4797c732b50acade0305640f5fc69e38907b4574c007d8ee145d53fe4c2c",
|
||||
"net/pixvi/myr/view/attack/AttackType150.as": "ee959a667c2bc18bb3954ca52b8fefa7728d9f1ce78dd8c167f5aa769815fb9c",
|
||||
"net/pixvi/myr/view/attack/AttackType151.as": "fc92767832c39c1484851da08efec1c4ad8460159a07d2d802e9b62c447d52f3",
|
||||
"net/pixvi/myr/view/attack/AttackType152.as": "7fa3c669492ffd8701c0d481e32e8f524aa9d66ae8a3e993e36ec4867009402f",
|
||||
"net/pixvi/myr/view/attack/AttackType153.as": "d57169f5e30d9a8cfc0537224db0ec2f4911ef192bcf1729b22da491a559e9fb",
|
||||
"net/pixvi/myr/view/attack/AttackType154.as": "f737893f9cd07637e3643b63247bc0da7860a31531247e897329a6a8479d7106",
|
||||
"net/pixvi/myr/view/attack/AttackType155.as": "204d9066aa2a407a89a2fdd27c12d670c66cec4ca32b2e2c509d7b2e2862d3c4",
|
||||
"net/pixvi/myr/view/attack/AttackType156.as": "27f91fddf1bbd34051271e71db28bc243466e863ddb2f4ac0d090981d6f76655",
|
||||
"net/pixvi/myr/view/attack/AttackType157.as": "90e47846087eb12260253155d4f4742ff9c756817c0965d1fa800ca73da4784e",
|
||||
"net/pixvi/myr/view/attack/AttackType159.as": "ad2d2ffe5968fde2e5fba35d229da96a12df1c520663c3d8436cb4d49e02f6be",
|
||||
"net/pixvi/myr/view/attack/AttackType16.as": "3cbb8838e547d15e20ef4d26c7ef2efe151ed00dd8e85b95809562bcf56aa4e3",
|
||||
"net/pixvi/myr/view/attack/AttackType161.as": "50d6819563e7b5a77f653278c609c357f19a8eba35ba1f149fc47dbeef3f31bf",
|
||||
"net/pixvi/myr/view/attack/AttackType162.as": "20c710190af9dc57aa81aeed6b9f4875234e88a84356c49c25501eb1fe5aaec8",
|
||||
"net/pixvi/myr/view/attack/AttackType163.as": "8e85047f44f6019dd8d7387532f7d67c41c1504bfbbb3b9e1dbd7f80f22bed8c",
|
||||
"net/pixvi/myr/view/attack/AttackType164.as": "7adc1d4ad8c996314a07007456ecb89c72654098d060139c7a7486091309ba3c",
|
||||
"net/pixvi/myr/view/attack/AttackType165.as": "323e06ca412dd3bc14055851610d6a4bcf190614c04f16fec818301ca64455d2",
|
||||
"net/pixvi/myr/view/attack/AttackType166.as": "a074dfdd3f8102a3ddad9eaabd88bf8c4e863537d745da15ecbc68eaaa9f9632",
|
||||
"net/pixvi/myr/view/attack/AttackType167.as": "3cad12e54bb746d257adc436aba2caa5c7d3ba0e91daa4dbbc28e4ec288d8801",
|
||||
"net/pixvi/myr/view/attack/AttackType168.as": "1a459d0454da026b5d317859efe410a160be15444c9ca68a1238015f00a37acd",
|
||||
"net/pixvi/myr/view/attack/AttackType169.as": "8de58d6d7a63162ab134ca6931e4f38e9778e33a4251a8a61c9d21942bf984a1",
|
||||
"net/pixvi/myr/view/attack/AttackType17.as": "8e6d41c9a474919bc0cca92677eec296c5fb372573b3fffd46fe4c4bfbeef9f1",
|
||||
"net/pixvi/myr/view/attack/AttackType170.as": "c9077b83e5a9bce3e5c2201c07b2c6d926e3e7ea9e400e7ddab401ca0b112b77",
|
||||
"net/pixvi/myr/view/attack/AttackType171.as": "9b266e40b6cbb05058449b342aaecae0ee0e26dece9d0d4e8587479b7028c6e4",
|
||||
"net/pixvi/myr/view/attack/AttackType172.as": "1627326b34268b3d1f3ed4bb9b43ce883b6f5357bd8e0238ef3bc811e19bd2a9",
|
||||
"net/pixvi/myr/view/attack/AttackType173.as": "2fbfaa83e3b533d00f3016a1fac5b87fefb28a06eefb02ec82869897c3ffeb93",
|
||||
"net/pixvi/myr/view/attack/AttackType174.as": "436a986d644fac77e43f8377bc276600ca9d010f28b7bc4389060ced6e97c92a",
|
||||
"net/pixvi/myr/view/attack/AttackType175.as": "bf6512783506026d0e9ebb6c72f698fb97c912ab9e66d2b4db8851428e9ac336",
|
||||
"net/pixvi/myr/view/attack/AttackType176.as": "8a8bbea7f6fcfd2596be161c1d2c72784632329e902ffaf69b81672fa6b0c339",
|
||||
"net/pixvi/myr/view/attack/AttackType177.as": "f92ee0d405cf0be5558bc4818c35057dc975a4f16254a5e2510fe1967656fcfc",
|
||||
"net/pixvi/myr/view/attack/AttackType178.as": "5a3d2a51a7fc797a86a6c6cc539f84db7663a6487d446f2fbe612c37f5af7560",
|
||||
"net/pixvi/myr/view/attack/AttackType179.as": "d90de0d02651d9c2f6f9a50e970693d967e3a4f23089ac521f32c9a8f3a2c0bc",
|
||||
"net/pixvi/myr/view/attack/AttackType18.as": "fcbf833515bfc5f3e3ba25385d767c92aff3623c1d81ba1979d2f1651ed60642",
|
||||
"net/pixvi/myr/view/attack/AttackType180.as": "f8f7fdff5cd8616473a87b370c1cc29d65fd94d4daf5aed079c5698dc3c0f2a6",
|
||||
"net/pixvi/myr/view/attack/AttackType181.as": "b41c85e623a00d1fb2e12502f59fb33d30e16753f3255c0263cc6436014fe288",
|
||||
"net/pixvi/myr/view/attack/AttackType182.as": "fe3b6b96fa41d7ee5d498bac024d88d69eb2f876bd737394e63b5fdd7f8438af",
|
||||
"net/pixvi/myr/view/attack/AttackType183.as": "e111732254e4d768dce458e637ca7960397e50406ba5110244eb09313037b8ba",
|
||||
"net/pixvi/myr/view/attack/AttackType184.as": "6e10dfbf19f041f941cd44f8b4c15a0df6b636a00319c1b14642579742dd63e3",
|
||||
"net/pixvi/myr/view/attack/AttackType185.as": "2789ec6290683d0b97cad976dd9be6dc678e8525947fd565551772f8c4ea0008",
|
||||
"net/pixvi/myr/view/attack/AttackType186.as": "205e9d06a7012ae9ea1bc5b59d143906d55b2a53ecc2a2e7e178a2906e393b4b",
|
||||
"net/pixvi/myr/view/attack/AttackType187.as": "af1c3b003a51e7a1fc4df3abea6c18ee60afec748b2e2295d6551fdad9eef657",
|
||||
"net/pixvi/myr/view/attack/AttackType188.as": "a06a06e75901f94bdcb6b4182457e900d688b3a91e96073f3e6271c373af3709",
|
||||
"net/pixvi/myr/view/attack/AttackType189.as": "00cc15523cf73fd167978bb24dd113a01c1c11fff37628e48c3d2446a6b6486b",
|
||||
"net/pixvi/myr/view/attack/AttackType19.as": "70b66c36d589b1558e5ec18a2e9dcad5208af2d235c29938b58004fdfee1fc81",
|
||||
"net/pixvi/myr/view/attack/AttackType190.as": "72a8750997a341b1db297a4243962c5baa019c05a69f88ed7e3abb73bba11e78",
|
||||
"net/pixvi/myr/view/attack/AttackType191.as": "f5a64c46e0b4db246f36ee3f625c4d87e07d063e56b7654eb09e5c23194d1d4c",
|
||||
"net/pixvi/myr/view/attack/AttackType192.as": "48dbc616501f01f15b38b8b566e0eb629e57d6cd6f24b301b236a2bc5c1367e9",
|
||||
"net/pixvi/myr/view/attack/AttackType193.as": "a1ac302369634d93ab00151bdc4696f683d49fc2b79554cad7e981b10ab6a52d",
|
||||
"net/pixvi/myr/view/attack/AttackType194.as": "197128dcc29002a4753cff7abb72b3001faabbff15356bf2792827a94f4dad54",
|
||||
"net/pixvi/myr/view/attack/AttackType195.as": "01e0d38843a19deb8fe3889d517117396355e2729db14116744b9b5cccea6b57",
|
||||
"net/pixvi/myr/view/attack/AttackType196.as": "d9b4f60d278d42796dc348426d92f76503cabff904497c269812d43a2041d0c5",
|
||||
"net/pixvi/myr/view/attack/AttackType197.as": "1fd3c13ab5b7b76644ec7039423782837b6440312ac862fd8ea52744f9d520c9",
|
||||
"net/pixvi/myr/view/attack/AttackType198.as": "3b7f4522e9a309a7b510467b3160f852b2fb8b06d5dea3c5b0a56cdfe5c39d99",
|
||||
"net/pixvi/myr/view/attack/AttackType199.as": "8f69cd93990909829b9500dfedb46c9df1b8f8bd4251f087cc49d70506176e6a",
|
||||
"net/pixvi/myr/view/attack/AttackType2.as": "11d7ac16ec956905ce455886bcaf12d52b889e5b835100e2a7deae76830a2cc0",
|
||||
"net/pixvi/myr/view/attack/AttackType20.as": "44a8f8bfc0388c95f7daf564fac429b021fa45de6d4d001f0489ed76fda5b935",
|
||||
"net/pixvi/myr/view/attack/AttackType21.as": "f07fc1544ce46c6c03dd8c80c63cb4239e6f5ea9e05a905f6c0a629062ba3510",
|
||||
"net/pixvi/myr/view/attack/AttackType22.as": "a2f5e8ecc2ebfa2e7d46a97c6175fe9fd17942bd5ca0643febb058a2b75e8809",
|
||||
"net/pixvi/myr/view/attack/AttackType23.as": "0a4f4ff4b4e8942361c2fb4e92cab873ef458cca500507703094aaf78b7e9f57",
|
||||
"net/pixvi/myr/view/attack/AttackType24.as": "c2ad78ae100cdc83452f814b5ef49990fe0b73a1863af7bb8b3e06e70a087155",
|
||||
"net/pixvi/myr/view/attack/AttackType25.as": "fb86a08860c54541db2aee35fc47c73233a94652caeb9cb96ff8168d6ae23016",
|
||||
"net/pixvi/myr/view/attack/AttackType26.as": "cb0238e0251a34a246f7273a63161021814fbc532a6e3b8ebf1e623617743e78",
|
||||
"net/pixvi/myr/view/attack/AttackType27.as": "fb07c83055653a911cbfba1ff047056a5086998b550c453e5b8a74eae9e68c74",
|
||||
"net/pixvi/myr/view/attack/AttackType28.as": "dfa44ffb29ce7473c60192809575802968d999036ae668a77e88101686204216",
|
||||
"net/pixvi/myr/view/attack/AttackType29.as": "03b231e5dc9edbd634fa5e26c959cd8242a79a2a5f52884f3a07ccb1b2dfd3c7",
|
||||
"net/pixvi/myr/view/attack/AttackType3.as": "1fd991981bcc58a0f1cbaeb0ac37f78f73e22146f7745ff5c9b0919ffd6e824f",
|
||||
"net/pixvi/myr/view/attack/AttackType30.as": "46252e49598b802a2b6a456f3acee115f3bad7417b2494ff49ce2e2ad7099050",
|
||||
"net/pixvi/myr/view/attack/AttackType31.as": "d6fcc6f03cb77265bdba9d37f0d82f1e450ec3ccfb17f6ca131e610e7c3db8a8",
|
||||
"net/pixvi/myr/view/attack/AttackType32.as": "e4c542f5cbd719f30b2b076575d3cf8dadc4b02cabe1ca37269e3593fb3e26a1",
|
||||
"net/pixvi/myr/view/attack/AttackType33.as": "e34da954bd5538928b7019155df2ba3e99f25f6880775a9bc60eef08216d1d2a",
|
||||
"net/pixvi/myr/view/attack/AttackType34.as": "f8f27ac279a5e1ee404eacdbb7d5dc7fe21401a43d2d1e622c64e6af92072ddb",
|
||||
"net/pixvi/myr/view/attack/AttackType35.as": "ff57aa89b4b06949ee69fa4219c364c1cc47c1f69fb9a33cbae3ffc4d5fcbea6",
|
||||
"net/pixvi/myr/view/attack/AttackType36.as": "853b3f2f330e134e7696756d728f1e6f67d625aecccd458f87af368a9c90d033",
|
||||
"net/pixvi/myr/view/attack/AttackType37.as": "f14ffa6e9b75f1a1a45891a7d4e5155e912088584ea5242368e2f1b780d12e7a",
|
||||
"net/pixvi/myr/view/attack/AttackType38.as": "33cc7324a5b0a5b11634f2cf6393a37e28d30a3ae5da84f2fae898118f9b959e",
|
||||
"net/pixvi/myr/view/attack/AttackType39.as": "9dc5430dc4fd2f7894ea67556270d393372a220b5bb86e7234ddedcfbe748016",
|
||||
"net/pixvi/myr/view/attack/AttackType4.as": "1422775f7e9751002167280c3e73921783911f1a239f20550f294ba728a99ce6",
|
||||
"net/pixvi/myr/view/attack/AttackType40.as": "afc3bf6d31b06eaf5e6d756c0ae103c7f8786df1bc3f811c6f993ca0deb405d3",
|
||||
"net/pixvi/myr/view/attack/AttackType41.as": "6a92bc1459bc97df9dd0e605268760dc13498c35709fde7aa61ee51ac22a0eae",
|
||||
"net/pixvi/myr/view/attack/AttackType42.as": "3c190ce02663246985f9d007549aa94fcf5bd701584289446d90d39941c54dab",
|
||||
"net/pixvi/myr/view/attack/AttackType45.as": "28d54d026806fb95c5312277609ffbe5d7133148fdf6c3b1411e5681c6418b58",
|
||||
"net/pixvi/myr/view/attack/AttackType46.as": "42ce24054433264fa277236dc50c2892dd16c381f151ed6dbed3815debe8483d",
|
||||
"net/pixvi/myr/view/attack/AttackType47.as": "7708f991956ce989f56dda081cb38e27aa5b686e9b6f4010a71f284171d5360d",
|
||||
"net/pixvi/myr/view/attack/AttackType48.as": "752a7136c5b56a5f0a4da6cd9b3e74643548947573d8f1c70672d07f98101119",
|
||||
"net/pixvi/myr/view/attack/AttackType49.as": "2a4edf8a2932f0aadc198d52184512e57d62fe72dbb23f8d8ebbd55a400f2243",
|
||||
"net/pixvi/myr/view/attack/AttackType5.as": "32f0c68d7dc78c5ff3d2a49bca86771c2ab9e9dbb49c44011ccf228f59b78566",
|
||||
"net/pixvi/myr/view/attack/AttackType50.as": "3b41931ae51634ade5deb2c50314f1989047b78eabbdff4e40ac9d2b9d8c8139",
|
||||
"net/pixvi/myr/view/attack/AttackType51.as": "d4c5fed8aa2defc4f68f63c7f834aae14397f92b3f14635544de6390f47f044a",
|
||||
"net/pixvi/myr/view/attack/AttackType52.as": "e5d9e6ccab505d046adcafd5b8a1a8b171111f1d5c35bfeecfe2d539b566fcd5",
|
||||
"net/pixvi/myr/view/attack/AttackType53.as": "5958aa3bd0b6430eb01eac7e6bc786752faa608786584dab732abc7eaa7eb463",
|
||||
"net/pixvi/myr/view/attack/AttackType54.as": "cab1ae59f0336c5c11d5101bb6225f65b0d4b761907de49488de46e042511d19",
|
||||
"net/pixvi/myr/view/attack/AttackType55.as": "cc3276af937449fc14e4175b72a4d66626a326234fb90a06d1c4052b822042a9",
|
||||
"net/pixvi/myr/view/attack/AttackType56.as": "9ebf3bd60bb88ca87106c417dae10e73c034da28667c34a46857c07583feeef9",
|
||||
"net/pixvi/myr/view/attack/AttackType57.as": "821ca9c2a194319577d75bea0c5960c8fe3d86b59bbe4ecc9716bd694aa8a760",
|
||||
"net/pixvi/myr/view/attack/AttackType58.as": "bbcce3d45da79d28298550df76c88516c69291a1e13a7acaa29347a414d5c529",
|
||||
"net/pixvi/myr/view/attack/AttackType59.as": "a63f9b041892325656ca692715929f8564665e5368eed3494c615fe88669957e",
|
||||
"net/pixvi/myr/view/attack/AttackType6.as": "e89b64a54d754d4eeea548b867652fdbe6d7cd3c9f55674a85f797fbd6a043ae",
|
||||
"net/pixvi/myr/view/attack/AttackType60.as": "92b4b5356b505f47b703bb4540a0c8c79a7a5ad9015b2f7ca65d35a8c277d2b2",
|
||||
"net/pixvi/myr/view/attack/AttackType61.as": "7da4e03069543f9bb6d9452c0b072a2468f310462da554e32dbf51e0981ddf6b",
|
||||
"net/pixvi/myr/view/attack/AttackType62.as": "76468a4f435e039851eba8818791c04bdb380e3dedda2bb1ed9c06eeb6fff140",
|
||||
"net/pixvi/myr/view/attack/AttackType63.as": "601bfe31181613a89e679c6d10b63c397c21a3b0155a756767a7f3936d34d4e0",
|
||||
"net/pixvi/myr/view/attack/AttackType64.as": "e2e71fed79135e9c7673a0b5623257e088c265e70d23102d7fa62490faf7379e",
|
||||
"net/pixvi/myr/view/attack/AttackType65.as": "03d9d8117f38f1c4a55bee9d16e1fe0279a12bdd7ccdb5b3ba56a2bc22b1ef80",
|
||||
"net/pixvi/myr/view/attack/AttackType66.as": "c3c66e956d036c4d65cb829a8a063914f91c7b58b0f5926e47800771ec90698c",
|
||||
"net/pixvi/myr/view/attack/AttackType67.as": "a654f614cf92c0ce90489a3e86233ade0fe82a1f489e020bc5cbcdff505c7174",
|
||||
"net/pixvi/myr/view/attack/AttackType68.as": "997def7202226e486415283e1c08794992e609088580a099904ec5e134e37145",
|
||||
"net/pixvi/myr/view/attack/AttackType69.as": "6788f24562510db10ae80a43fd7ebaafb130ca4e18550cce6e9f27ac877843cc",
|
||||
"net/pixvi/myr/view/attack/AttackType7.as": "3beb8725a71189fd12f72616c9c748d81a53d08bf4d11d2d98834c89e0e47906",
|
||||
"net/pixvi/myr/view/attack/AttackType70.as": "e695bd657fb6aa5ab088234226d691c1649b2050066fd272fa83e72d0c7ca2ca",
|
||||
"net/pixvi/myr/view/attack/AttackType71.as": "56d36824b5f45491dc6177396ac479ca1e48a0e69d0ecd55309d24bf1a5cd367",
|
||||
"net/pixvi/myr/view/attack/AttackType72.as": "27d729b9f466d8771c37b494e5a7665f852eefc8ed07819d5a935218c8abb15a",
|
||||
"net/pixvi/myr/view/attack/AttackType73.as": "97a7df2ef72f3164d8b37bb55f25fd4ab13dbb3c81070deb159f6311c66bb754",
|
||||
"net/pixvi/myr/view/attack/AttackType74.as": "66d3d2fd44d4919407f4c39e92d2c782b322b584c20f27f418ed926ffe5cfc4a",
|
||||
"net/pixvi/myr/view/attack/AttackType75.as": "ab3642aba6d6edc56dbbd13d6145efae83676c2fd0c6f999e468ab1dcd10ef84",
|
||||
"net/pixvi/myr/view/attack/AttackType76.as": "74482eb72c07dbb7d029b26d1cae7f870373f6a4b283081349db76f3ca0d5d7c",
|
||||
"net/pixvi/myr/view/attack/AttackType77.as": "a3acef9185308cd283afea3deff491b70fbf5d3de64a9834aad5a5ef8f167841",
|
||||
"net/pixvi/myr/view/attack/AttackType78.as": "4cd107cf64c2570a64e667359871619c39f4d6c9c867cc3156e68a162072101d",
|
||||
"net/pixvi/myr/view/attack/AttackType79.as": "5701373df6d08bcc5d89c7a92843b468f97ffef0211fcfeef03c05d2918626f0",
|
||||
"net/pixvi/myr/view/attack/AttackType8.as": "3f12d1e9eeb3fd01644b814d1abfc425fed2fa041404a5fe70d96c50ed778f1c",
|
||||
"net/pixvi/myr/view/attack/AttackType80.as": "4f92579c57f6ab40c1d3e85e32cba0e67aee496cba49e032e8932cf513e19ba9",
|
||||
"net/pixvi/myr/view/attack/AttackType81.as": "b6301fb386483fe769d3ad5d8d54dbc7c5ef31a6bbdfdfc59b432b4dd1fc5bd8",
|
||||
"net/pixvi/myr/view/attack/AttackType82.as": "8e306dba1c95661095716fb97e865c610c98babe635d96fc7b93c264aadffdb3",
|
||||
"net/pixvi/myr/view/attack/AttackType83.as": "55ccd1b7480b5120b47f4c83820fc567bab11bb116b0364c8e9d75a2fc2e1c7e",
|
||||
"net/pixvi/myr/view/attack/AttackType84.as": "b18ea22798aec560fac108dca48b23c19d64b5d0040b4881f91be77b5b7c61a4",
|
||||
"net/pixvi/myr/view/attack/AttackType85.as": "4182a5a89472bc807206b431a9f7ca765b1b2be87b5e22996a9a42f47774869f",
|
||||
"net/pixvi/myr/view/attack/AttackType86.as": "944db4431ed87edf20827984336280d3b5d3fc428f1a2191eb988050b5d2c21b",
|
||||
"net/pixvi/myr/view/attack/AttackType87.as": "25c92f209834c79e6ba3498d98c93339e0245a7b9b51129ca17a860729f227f0",
|
||||
"net/pixvi/myr/view/attack/AttackType88.as": "559c7cb9f95184f76d99fb006849f78adf5d1e159aa77d90bd3b64153901dcbb",
|
||||
"net/pixvi/myr/view/attack/AttackType89.as": "d65b9f1e7e21d7dbc82032ff826e927bdfc0eed0519809058db25fcae854c8bf",
|
||||
"net/pixvi/myr/view/attack/AttackType9.as": "7e38d439e41c7e22a8fc33ecd5cc4c91b6dca89965db4c129c0b2fb7a3e26b0f",
|
||||
"net/pixvi/myr/view/attack/AttackType90.as": "3952c1ebb4f8d73e03c6e246fc7a1ab481de642b61be1ce993eb3515ce87908c",
|
||||
"net/pixvi/myr/view/attack/AttackType91.as": "e6f3a19bbabbbd58a4bfe421801821b47e9f418ea9a9c12d1ddf5f531c7ad3a8",
|
||||
"net/pixvi/myr/view/attack/AttackType92.as": "adc98f8657b64e1af3b4bfbabe6e6021552b7b9ce7ba722fa04d100577607a34",
|
||||
"net/pixvi/myr/view/attack/AttackType93.as": "56bf88bb8b76f76c27fdcedb599aa37a5e0a138299766747dc78e3baa75eb024",
|
||||
"net/pixvi/myr/view/attack/AttackType94.as": "ebf37c24a1ff73a741040e71bb92c464000f9acc2b13b6aadec8074fa63a3798",
|
||||
"net/pixvi/myr/view/attack/AttackType95.as": "1c231e8854d3396d5dd2e47be7182ba059f1da5f71e18434f5de0032f0d72033",
|
||||
"net/pixvi/myr/view/attack/AttackType96.as": "8490bd84bb19a054580c609440b38a6a9ddbb1e2dffe4c262c0c604e506260fc",
|
||||
"net/pixvi/myr/view/attack/AttackType97.as": "736600dbce8b0999cc3f55ac946d9d7454b2bec0d9f0097c8b20a810079cb3ce",
|
||||
"net/pixvi/myr/view/attack/AttackType98.as": "1c5e8ca69ae457cc3e4760181e0218ae1133c1e19d53f6931adcb24ea058db0b",
|
||||
"net/pixvi/myr/view/attack/AttackType99.as": "51c76ccaf2c59e36c699e2c911c39c22f397989f1d2130dae27e7d0b20230f20",
|
||||
"net/pixvi/myr/view/attack/BaseAttack.as": "6eb67299c8a228f82fe72e98ee363c7832b6d79d359fe896da2170e0c0b2598c",
|
||||
"net/pixvi/myr/view/attack/action/BaseHitAction.as": "a206304b74660bda2a2b44c1cf4f8a3d4476383152869add2270bfdbbbfd2d11",
|
||||
"net/pixvi/myr/view/attack/action/HitAction10XScalehit.as": "c46050034738af4008a9262a94f3e032aba66c18f437a5ef9791f9dd1c8b65b1",
|
||||
"net/pixvi/myr/view/attack/action/HitAction1Jumphit.as": "708c37ac00c953fc0e4247a33000226f1d2cc3223dca5d7ff1a71ddca02bebc4",
|
||||
"net/pixvi/myr/view/attack/action/HitAction2YScalehit.as": "013208ab246f7c6dc52aba094a84b20f8bfdb96862ae45f274e438ec5cefc0b2",
|
||||
"net/pixvi/myr/view/attack/action/HitAction3Horizonhit.as": "2dba19351fec44c3d647345b4966d3a10d74496e33a559e264e2cb05956c92a9",
|
||||
"net/pixvi/myr/view/attack/action/HitAction4Ymovehit.as": "7edfe705a05df20ca1a564f997044855e410a0e44e6917c0cb29599bc0ce016a",
|
||||
"net/pixvi/myr/view/attack/action/HitAction5Nonehit.as": "d16cc43eb246365d1dd5a08a62a744652b2103f6c671232cbc18d6bd46556196",
|
||||
"net/pixvi/myr/view/attack/action/HitAction6HorizonhitDelay.as": "35d62d8defefb6aafcdb0dd29fa20473a943046ebab35b596967628af558c0ac",
|
||||
"net/pixvi/myr/view/attack/action/HitAction7HorizionhitQuick.as": "670b5da16c54c22b578757eec146f29f154ad53eff2ecd6ce3fb868dd814a617",
|
||||
"net/pixvi/myr/view/attack/action/HitAction8FrontHit.as": "46d765d27c47674dec866107d8cf66acfe8710acc982c83b53a5e1217fcd2e35",
|
||||
"net/pixvi/myr/view/attack/action/HitAction9Jumphit2.as": "ee8ca7eb8a556ef3f19f4655a616b711dce82aa441d9882bee29975c82a707bf",
|
||||
"net/pixvi/myr/view/attack/action/type/HitActionType.as": "a4b25f7c2f790ff6d8c3eb0c25cbd2ad4102ef97419673cd390d3cd4f94847e6",
|
||||
"net/pixvi/myr/view/attack/type/AttackType.as": "66c3825acebff052befe99b8b0057b1330591e95ee5bab8d1969c0935614e5e4"
|
||||
},
|
||||
"original_frame_rate": 50.0,
|
||||
"schema_version": 1,
|
||||
"scope": "Public original combat tables; experimental simulator, not engine fidelity.",
|
||||
"source": {
|
||||
"apk_sha256": "01678ee3a8465d818d32cbbd94baa0d8253b04b4c57b70ebc5544ed341f1015d",
|
||||
"main_swf_sha256": "c6838331a198a22ffa486cbf61cc74c97619e011bc3364c8bb8dc99e269036cf"
|
||||
},
|
||||
"tables": {
|
||||
"entangle_info": {
|
||||
"compressed_bytes": 1040,
|
||||
"decoded_bytes": 1820,
|
||||
"logical_path": "data/table/entangle_info.json",
|
||||
"member": "assets/codes/e814d801e619000ae8af8f08fcbdc5b8",
|
||||
"record_count": 8,
|
||||
"sha256": "9be02321151385379b0992053a41f2df6e911d6e3a9474701c118faad386e8b0"
|
||||
},
|
||||
"game_setting": {
|
||||
"compressed_bytes": 3559,
|
||||
"decoded_bytes": 5820,
|
||||
"logical_path": "data/table/game_setting.json",
|
||||
"member": "assets/codes/f1c2e2603d6c82bbb8b5f94585273208",
|
||||
"record_count": 141,
|
||||
"sha256": "8810981688414e3cef520976911d16e2847df0a435dccd792e2dd527695283e3"
|
||||
},
|
||||
"item_info": {
|
||||
"compressed_bytes": 132384,
|
||||
"decoded_bytes": 494454,
|
||||
"logical_path": "data/table/item_info.json",
|
||||
"member": "assets/codes/1cabfff17cd6d6a38368b9068204329d",
|
||||
"record_count": 2079,
|
||||
"sha256": "9beeab37d107b09d02c4491a052594390c874c92328f524752080f5a7fab21e2"
|
||||
},
|
||||
"monster_info": {
|
||||
"compressed_bytes": 219398,
|
||||
"decoded_bytes": 933486,
|
||||
"logical_path": "data/table/monster_info.json",
|
||||
"member": "assets/codes/08b83182d2a7882bfe2bb0ed710d343f",
|
||||
"record_count": 749,
|
||||
"sha256": "081747ddc5b7afba03f69e65f5eba6af815b9fbd3ea7e0821c7f8807d9486921"
|
||||
},
|
||||
"monster_setting": {
|
||||
"compressed_bytes": 6687,
|
||||
"decoded_bytes": 22488,
|
||||
"logical_path": "data/table/monster_setting.json",
|
||||
"member": "assets/codes/1d188dbf8ca7a253fb2e5bc2475b2669",
|
||||
"record_count": 11,
|
||||
"sha256": "49388d221e3d4461fede3b176526d593ec0f1647a8b93a8d2b33a712761febab"
|
||||
},
|
||||
"monster_skill": {
|
||||
"compressed_bytes": 50349,
|
||||
"decoded_bytes": 236294,
|
||||
"logical_path": "data/table/monster_skill.json",
|
||||
"member": "assets/codes/8da7ff8cb5aeb85080ac37ca677f52ef",
|
||||
"record_count": 266,
|
||||
"sha256": "0fea0eb8553a4868ff704210e9adfd09c6e2b2c3b2730e9ebe25642fa478bf9b"
|
||||
},
|
||||
"potential_info": {
|
||||
"compressed_bytes": 992,
|
||||
"decoded_bytes": 1913,
|
||||
"logical_path": "data/table/potential_info.json",
|
||||
"member": "assets/codes/f4b5363a0460df23903e7f605c50f82e",
|
||||
"record_count": 13,
|
||||
"sha256": "cf43bde8204ed1e13c555cfc48df5a54ea7f2df7813e017a04ba02f0453d7895"
|
||||
},
|
||||
"setting": {
|
||||
"compressed_bytes": 14422,
|
||||
"decoded_bytes": 47740,
|
||||
"logical_path": "data/table/setting.json",
|
||||
"member": "assets/codes/82885f1c0190a591b6aaee2521bf3daa",
|
||||
"record_count": 64,
|
||||
"sha256": "68bb8d2ee882a1c14b98315eb61dfb3545dc633173b53409b1dec3af68fb7af3"
|
||||
},
|
||||
"stage_info": {
|
||||
"compressed_bytes": 1061791,
|
||||
"decoded_bytes": 19703775,
|
||||
"logical_path": "data/table/stage_info.json",
|
||||
"member": "assets/codes/9484cfff9fb912e4791832375e771475",
|
||||
"record_count": 1178,
|
||||
"sha256": "47ccef41d460f4ef23732624cf302e863a22ca33148dc02629841d764c38b487"
|
||||
},
|
||||
"task_info": {
|
||||
"compressed_bytes": 271024,
|
||||
"decoded_bytes": 1622428,
|
||||
"logical_path": "data/table/task_info.json",
|
||||
"member": "assets/codes/70d0e869536fc2b968582dd1f1ea86d6",
|
||||
"record_count": 1165,
|
||||
"sha256": "b833985c54e11f3079a3ccc53709f87d25b1f8301699b3eb99613a826a469744"
|
||||
},
|
||||
"team_info": {
|
||||
"compressed_bytes": 1961,
|
||||
"decoded_bytes": 4416,
|
||||
"logical_path": "data/table/team_info.json",
|
||||
"member": "assets/codes/26e7c61bf20be81add4b8335bf8623ed",
|
||||
"record_count": 10,
|
||||
"sha256": "21254655b6966ab67d5b3f1105568ab6ed13e2eecc4f05d27ef016de0e34ced2"
|
||||
},
|
||||
"upstar_info": {
|
||||
"compressed_bytes": 177,
|
||||
"decoded_bytes": 326,
|
||||
"logical_path": "data/table/upstar_info.json",
|
||||
"member": "assets/codes/3498a00946020cb39986776e1dc87f79",
|
||||
"record_count": 7,
|
||||
"sha256": "b53db40bd0c94e0c0fff7e6c1bc5519b05c0aa353f4ba384cd3062ad5865c350"
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,165 @@
|
||||
{
|
||||
"artifacts": {
|
||||
"progression.json.gz": {
|
||||
"bytes": 779024,
|
||||
"decoded_bytes": 8710604,
|
||||
"decoded_sha256": "213a8ab328522c7b033cc17ffe6da79cd4eb3584edb734a411cec354b836685c",
|
||||
"sha256": "f3255cc27be99520af0fafc43769492138c5794bb1a65ae83c5d8c732505b8a4"
|
||||
},
|
||||
"progression_battles.zip": {
|
||||
"bytes": 2457497,
|
||||
"sha256": "30ba36932d57051f9873b57c64d1f79d0cf2e564b53d2c1d74beb8450e9a8328"
|
||||
},
|
||||
"progression_support.json": {
|
||||
"bytes": 18760,
|
||||
"sha256": "d6d98cbc6fe115e636b169f315f5c8f72dc1f9c360c54b4f055809148c8ec948"
|
||||
}
|
||||
},
|
||||
"as3_sources": {
|
||||
"analysis/as3/scripts/net/pixvi/myr/battle/BattleGround.as": "d2e8679fb3557163d9ac57aca3405e27bb5140364f528b6a073adffd27dd5c54",
|
||||
"analysis/as3/scripts/net/pixvi/myr/center/BagCenter.as": "846213b6f72da7ee6fb653d22717ecf5e42fe96b4723b3c7fc205d7991da2638",
|
||||
"analysis/as3/scripts/net/pixvi/myr/center/GuideCenter.as": "e4728dde31c6d1ec89cfa600e86685e384f5ac2b64a76c7aa663dff66ef79cb8",
|
||||
"analysis/as3/scripts/net/pixvi/myr/center/LibCenter.as": "3630efbb0c20a5ab778bcc63177377f454b0d6318dc56d68ecdb1545c3e3b7a4",
|
||||
"analysis/as3/scripts/net/pixvi/myr/center/MonsterCenter.as": "5c3c5f80de4e6ce22b6a2d4ae218b3c760a4bcf34243265f62c516d5e3c7f06d",
|
||||
"analysis/as3/scripts/net/pixvi/myr/center/PosCenter.as": "cf3843df8abc588b6857ab3155684c5434a88f369b80cfcdd7d8af63ed8d15f5",
|
||||
"analysis/as3/scripts/net/pixvi/myr/center/StageCenter.as": "5e477ecafeecfc1ce2e0d1fea160ed05b2483825abe6e7dd4ff2971a28fcbc59",
|
||||
"analysis/as3/scripts/net/pixvi/myr/center/TaskCenter.as": "0cc9770aa214d98bdfede7f6130ca948e428cd8280e3c4f2f3107176b9d73dcc",
|
||||
"analysis/as3/scripts/net/pixvi/myr/element/city/CityVo.as": "9631e65acc6a50c2308780bbe60e20e7840b7a26114d74cde71a196916f3fe35",
|
||||
"analysis/as3/scripts/net/pixvi/myr/element/npc/ConditionVo.as": "c76a2ec36571737897c509e0fe8ee39b9134fe2315727b77d0c858f5fd26d410",
|
||||
"analysis/as3/scripts/net/pixvi/myr/element/reward/RewardPieceVo.as": "45f397a734efcab23d2a4827042568e54a2847667a15e15579d20e96ad2a4e3d",
|
||||
"analysis/as3/scripts/net/pixvi/myr/element/stage/StageVo.as": "3a5c25d60fd60e699c75c04bf2102e100c325f9e07fe12c86ae15c3f77dd8f84",
|
||||
"analysis/as3/scripts/net/pixvi/myr/element/task/TaskStatusType.as": "ce8b50bfca362428f624fdccea95d6697cad6b23670ac2e83a1ba4bd0afb1335",
|
||||
"analysis/as3/scripts/net/pixvi/myr/element/task/TaskStepVo.as": "bc7c7f418260257a9df66642b158b5765491ea7e0a7bc88b1fe938cbcbd2c41a",
|
||||
"analysis/as3/scripts/net/pixvi/myr/element/task/TaskType.as": "c5bc4eae6027ae7b00712893bb4563d84d90c924f64192cdac19e0fa7174722b",
|
||||
"analysis/as3/scripts/net/pixvi/myr/element/task/TaskVo.as": "e996300986dac7db2adfe713058dd26e1459c2900cab94a07c5c51f1a03f59a9",
|
||||
"analysis/as3/scripts/net/pixvi/myr/net/NetBattle.as": "5fc5558b72bdd016a664b423f145d31bdc035f2af4619357e1a1387cf4163cdf",
|
||||
"analysis/as3/scripts/net/pixvi/myr/net/NetTask.as": "b54f07bca6912aa93472cf607e8710ff3941586d77422bdda2cbeb4f481c42dc",
|
||||
"analysis/as3/scripts/net/pixvi/myr/panel/battle/BattlePanel.as": "5540956d4a4e4b35617ffda13b10f4b69ced5efaa247fb553d398c2f0ddf50bf",
|
||||
"analysis/as3/scripts/net/pixvi/myr/panel/loopStagePanel/LoopStagePanel.as": "4a210a6178f5c0c670ed54ea10b58fdca1f6d30a02b2ee0e131336f517ed282f",
|
||||
"analysis/as3/scripts/net/pixvi/myr/panel/stage/StagePanel.as": "39d9291d447833a546f0400d303c177ca4f9a1177dedfc73c3116b0ddfa3b104",
|
||||
"analysis/as3/scripts/net/pixvi/myr/panel/stage/StageStartPanel.as": "faf901b266f1786cdeefe8aee394c114e6c96c7c4d87b1dfacb1ec009926a797",
|
||||
"analysis/as3/scripts/net/pixvi/myr/panel/story/GAoNanoEventVo.as": "a67602f2de90bdc08d2bac91c7f86a376414e1a71d5c387d0116479b123bbb7d",
|
||||
"analysis/as3/scripts/net/pixvi/myr/panel/story/StoryPanel.as": "626c661a104847963dc60cf139227b27565a50bbf2569edaa95dc3fceeb693df",
|
||||
"analysis/as3/scripts/net/pixvi/myr/panel/task/TaskViewPanel.as": "d59c6a34affb7f8d5409facc010ff226108243f5f0a2b3cbd21a2ace9f5507bc",
|
||||
"analysis/as3/scripts/net/pixvi/myr/panel/taskstartpanel/TaskStartPanel.as": "a3123e266f0f8b87a2f3218af3cf23fc5646224b2b1f59e73f2965ba68bcfb18",
|
||||
"analysis/as3/scripts/net/pixvi/myr/panel/wild/AreaIconUI.as": "34d961f71b0d8f8030affb8209a6d5b833c6a26e1f096585cae32408180437ea",
|
||||
"analysis/as3/scripts/net/pixvi/myr/panel/wild/AreaPositionIconUI.as": "f2628f23a751b1ce02186e60be3b9d1a5a2fc03f7e4257f7630532bde846389f",
|
||||
"analysis/as3/scripts/net/pixvi/myr/panel/wild/AreaVo.as": "c085696d9c928be393f30fef03eaa0f4f749313e66d18992ddb19c1d493f0913",
|
||||
"analysis/as3/scripts/net/pixvi/myr/panel/wild/StageMap.as": "15f99de22e9bbee8d029dcc9272dee91761bf33c4f091597e63b18a3d1ca713d",
|
||||
"analysis/as3/scripts/net/pixvi/myr/panel/wild/WildPanel.as": "f66ce96cb780c3316f2973a5e7b6e90904c772be79b01768acce6d479fbff5b0"
|
||||
},
|
||||
"builder": {
|
||||
"python": "3.13.15",
|
||||
"sha256": "c77c02e814c44a14768bbc2e9557bb2fc27c33da8e19a0b49a8f814586636a77",
|
||||
"zlib": "1.3.1"
|
||||
},
|
||||
"counts": {
|
||||
"areas": 41,
|
||||
"linear_scripts": 4239,
|
||||
"mainline_linear_scripts": 718,
|
||||
"mainline_referenced_scripts": 720,
|
||||
"mines": 7,
|
||||
"referenced_scripts": 4269,
|
||||
"scripts": 4269,
|
||||
"stages": 1178,
|
||||
"steps": 3462,
|
||||
"supported_scripts": 4239,
|
||||
"task_types": {
|
||||
"1": 176,
|
||||
"2": 138,
|
||||
"3": 431,
|
||||
"4": 83,
|
||||
"5": 336,
|
||||
"6": 1
|
||||
},
|
||||
"tasks": 1165
|
||||
},
|
||||
"limitations": [
|
||||
"Static original APK baseline; live resource version not verified.",
|
||||
"Script support means linear dialogue/presentation and boolean GAoEvent only.",
|
||||
"ConditionVo passStage loading and lang assignment anomalies require conservative checks.",
|
||||
"No account data, network operations, combat execution, or battle results."
|
||||
],
|
||||
"schema_version": 1,
|
||||
"source": {
|
||||
"amf_reader_sha256": "482019cb9b4210693d2bec86695b8320c06977a69fe93063255c1a8bd7584109",
|
||||
"apk_sha256": "01678ee3a8465d818d32cbbd94baa0d8253b04b4c57b70ebc5544ed341f1015d",
|
||||
"apk_version": "1.9.68",
|
||||
"main_swf_sha256": "c6838331a198a22ffa486cbf61cc74c97619e011bc3364c8bb8dc99e269036cf"
|
||||
},
|
||||
"tables": {
|
||||
"area_info": {
|
||||
"compressed_bytes": 9780,
|
||||
"decoded_bytes": 25811,
|
||||
"logical_path": "data/table/area_info.json",
|
||||
"member": "assets/codes/b03e7e576d730454d1be826aeda1ae5f",
|
||||
"record_count": 3,
|
||||
"recovered_sha256": "889dac99b4e707262f8a53fae24f8d7a250e45cf122199507721e29e6bc4686d",
|
||||
"sha256": "f1c8b72715b30eb42ff8b60906247ee8ac12292b0e55e0642917502eac23fe35"
|
||||
},
|
||||
"game_setting": {
|
||||
"compressed_bytes": 3559,
|
||||
"decoded_bytes": 5820,
|
||||
"logical_path": "data/table/game_setting.json",
|
||||
"member": "assets/codes/f1c2e2603d6c82bbb8b5f94585273208",
|
||||
"record_count": 141,
|
||||
"recovered_sha256": "fdc64a2d196463a8afda740b8017a512aafec784eb689ef98b3ba0d8ac7e8696",
|
||||
"sha256": "8810981688414e3cef520976911d16e2847df0a435dccd792e2dd527695283e3"
|
||||
},
|
||||
"mine_info": {
|
||||
"compressed_bytes": 7043,
|
||||
"decoded_bytes": 28341,
|
||||
"logical_path": "data/table/mine_info.json",
|
||||
"member": "assets/codes/99e6627e76cd0e6c44fca31711fdd82f",
|
||||
"record_count": 4,
|
||||
"recovered_sha256": "eb61748195e42091d7db0bc183fc206e372681b7f5224e7ad713452905d8f733",
|
||||
"sha256": "8a547ab20f86d7ed9a53c57bf547afec6d03bdaf16abd1046712f130ffaab73d"
|
||||
},
|
||||
"npc_info": {
|
||||
"compressed_bytes": 9744,
|
||||
"decoded_bytes": 21631,
|
||||
"logical_path": "data/table/npc_info.json",
|
||||
"member": "assets/codes/b6f76ee8807eb37648844bd01120814b",
|
||||
"record_count": 337,
|
||||
"recovered_sha256": "426c588c5dc12cd1e85bedb1137b070505b1d5dd7e27b7fa19c92beace543573",
|
||||
"sha256": "42e82cfa5a8245a2cd15bbba9a0ae4351a5a5d5a724dcf15e828d2de4649b338"
|
||||
},
|
||||
"setting": {
|
||||
"compressed_bytes": 14422,
|
||||
"decoded_bytes": 47740,
|
||||
"logical_path": "data/table/setting.json",
|
||||
"member": "assets/codes/82885f1c0190a591b6aaee2521bf3daa",
|
||||
"record_count": 64,
|
||||
"recovered_sha256": "8db94bc4ff30ddf3b99d856c75be807ae6298c97fc90e9341cff4a1eeaa9d6cb",
|
||||
"sha256": "68bb8d2ee882a1c14b98315eb61dfb3545dc633173b53409b1dec3af68fb7af3"
|
||||
},
|
||||
"stage_info": {
|
||||
"compressed_bytes": 1061791,
|
||||
"decoded_bytes": 19703775,
|
||||
"logical_path": "data/table/stage_info.json",
|
||||
"member": "assets/codes/9484cfff9fb912e4791832375e771475",
|
||||
"record_count": 1178,
|
||||
"recovered_sha256": "093e2ad3d2e51eeebc149b02ad85cefc518fddbf5ca744d60900cdac609843ee",
|
||||
"sha256": "47ccef41d460f4ef23732624cf302e863a22ca33148dc02629841d764c38b487"
|
||||
},
|
||||
"stage_sp": {
|
||||
"compressed_bytes": 3020,
|
||||
"decoded_bytes": 17857,
|
||||
"logical_path": "data/table/stage_sp.json",
|
||||
"member": "assets/codes/eb91238441fb5bd21f029f8eb2967efb",
|
||||
"record_count": 78,
|
||||
"recovered_sha256": "267de867ec7da43d572c0b27e715513b41a7ae9690f6b919b5718cbf16a5089a",
|
||||
"sha256": "8938ac51752b5f2eaf086943ee45210e1ba04f27d42af6684f47f4c8b9283c30"
|
||||
},
|
||||
"task_info": {
|
||||
"compressed_bytes": 271024,
|
||||
"decoded_bytes": 1622428,
|
||||
"logical_path": "data/table/task_info.json",
|
||||
"member": "assets/codes/70d0e869536fc2b968582dd1f1ea86d6",
|
||||
"record_count": 1165,
|
||||
"recovered_sha256": "3e70889ee05a5f639be64752696b158978cc5e7f2560e4a464a308b60b2e3920",
|
||||
"sha256": "b833985c54e11f3079a3ccc53709f87d25b1f8301699b3eb99613a826a469744"
|
||||
}
|
||||
},
|
||||
"task_update_mode": "new"
|
||||
}
|
||||
@@ -0,0 +1,879 @@
|
||||
{
|
||||
"battle_routing": {
|
||||
"battle": "battleStart(task) -> real battle -> taskCompleteStep",
|
||||
"passStage": "same task route; stage configuration; never a sweep"
|
||||
},
|
||||
"condition_loader_anomalies": [
|
||||
{
|
||||
"condition": {
|
||||
"channel": "all",
|
||||
"close": false,
|
||||
"endTime": 2400,
|
||||
"finishTask": [],
|
||||
"maxLevel": 99999,
|
||||
"minLevel": 0,
|
||||
"passStage": [
|
||||
"10dg5"
|
||||
],
|
||||
"platform": "all",
|
||||
"startTime": 0,
|
||||
"unfinishTask": [],
|
||||
"week": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6
|
||||
]
|
||||
},
|
||||
"reason": "Retained ConditionVo loader anomaly; declared conditions checked conservatively",
|
||||
"step_number": 2,
|
||||
"task_type_id": "1014011"
|
||||
},
|
||||
{
|
||||
"condition": {
|
||||
"channel": "all",
|
||||
"close": false,
|
||||
"endTime": 2400,
|
||||
"finishTask": [],
|
||||
"maxLevel": 99999,
|
||||
"minLevel": 0,
|
||||
"passStage": [
|
||||
"dg201"
|
||||
],
|
||||
"platform": "all",
|
||||
"startTime": 0,
|
||||
"unfinishTask": [],
|
||||
"week": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6
|
||||
]
|
||||
},
|
||||
"reason": "Retained ConditionVo loader anomaly; declared conditions checked conservatively",
|
||||
"step_number": 4,
|
||||
"task_type_id": "2006001"
|
||||
},
|
||||
{
|
||||
"condition": {
|
||||
"channel": "all",
|
||||
"close": false,
|
||||
"endTime": 2400,
|
||||
"finishTask": [],
|
||||
"maxLevel": 99999,
|
||||
"minLevel": 0,
|
||||
"passStage": [
|
||||
"dg218"
|
||||
],
|
||||
"platform": "all",
|
||||
"startTime": 0,
|
||||
"unfinishTask": [],
|
||||
"week": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6
|
||||
]
|
||||
},
|
||||
"reason": "Retained ConditionVo loader anomaly; declared conditions checked conservatively",
|
||||
"step_number": 5,
|
||||
"task_type_id": "2006001"
|
||||
},
|
||||
{
|
||||
"condition": {
|
||||
"channel": "all",
|
||||
"close": false,
|
||||
"endTime": 2400,
|
||||
"finishTask": [],
|
||||
"maxLevel": 99999,
|
||||
"minLevel": 0,
|
||||
"passStage": [
|
||||
"dg219"
|
||||
],
|
||||
"platform": "all",
|
||||
"startTime": 0,
|
||||
"unfinishTask": [],
|
||||
"week": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6
|
||||
]
|
||||
},
|
||||
"reason": "Retained ConditionVo loader anomaly; declared conditions checked conservatively",
|
||||
"step_number": 6,
|
||||
"task_type_id": "2006001"
|
||||
},
|
||||
{
|
||||
"condition": {
|
||||
"channel": "all",
|
||||
"close": false,
|
||||
"endTime": 2400,
|
||||
"finishTask": [],
|
||||
"maxLevel": 99999,
|
||||
"minLevel": 0,
|
||||
"passStage": [
|
||||
"dg501"
|
||||
],
|
||||
"platform": "all",
|
||||
"startTime": 0,
|
||||
"unfinishTask": [],
|
||||
"week": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6
|
||||
]
|
||||
},
|
||||
"reason": "Retained ConditionVo loader anomaly; declared conditions checked conservatively",
|
||||
"step_number": 2,
|
||||
"task_type_id": "2009005"
|
||||
},
|
||||
{
|
||||
"condition": {
|
||||
"channel": "all",
|
||||
"close": false,
|
||||
"endTime": 2400,
|
||||
"finishTask": [],
|
||||
"maxLevel": 99999,
|
||||
"minLevel": 0,
|
||||
"passStage": [
|
||||
"dg502"
|
||||
],
|
||||
"platform": "all",
|
||||
"startTime": 0,
|
||||
"unfinishTask": [],
|
||||
"week": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6
|
||||
]
|
||||
},
|
||||
"reason": "Retained ConditionVo loader anomaly; declared conditions checked conservatively",
|
||||
"step_number": 3,
|
||||
"task_type_id": "2009005"
|
||||
},
|
||||
{
|
||||
"condition": {
|
||||
"channel": "all",
|
||||
"close": false,
|
||||
"endTime": 2400,
|
||||
"finishTask": [],
|
||||
"maxLevel": 99999,
|
||||
"minLevel": 0,
|
||||
"passStage": [
|
||||
"dg503"
|
||||
],
|
||||
"platform": "all",
|
||||
"startTime": 0,
|
||||
"unfinishTask": [],
|
||||
"week": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6
|
||||
]
|
||||
},
|
||||
"reason": "Retained ConditionVo loader anomaly; declared conditions checked conservatively",
|
||||
"step_number": 4,
|
||||
"task_type_id": "2009005"
|
||||
},
|
||||
{
|
||||
"condition": {
|
||||
"channel": "all",
|
||||
"close": false,
|
||||
"endTime": 2400,
|
||||
"finishTask": [],
|
||||
"maxLevel": 99999,
|
||||
"minLevel": 0,
|
||||
"passStage": [
|
||||
"dg504"
|
||||
],
|
||||
"platform": "all",
|
||||
"startTime": 0,
|
||||
"unfinishTask": [],
|
||||
"week": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6
|
||||
]
|
||||
},
|
||||
"reason": "Retained ConditionVo loader anomaly; declared conditions checked conservatively",
|
||||
"step_number": 5,
|
||||
"task_type_id": "2009005"
|
||||
},
|
||||
{
|
||||
"condition": {
|
||||
"channel": "all",
|
||||
"close": false,
|
||||
"endTime": 2400,
|
||||
"finishTask": [],
|
||||
"maxLevel": 99999,
|
||||
"minLevel": 0,
|
||||
"passStage": [
|
||||
"dg505"
|
||||
],
|
||||
"platform": "all",
|
||||
"startTime": 0,
|
||||
"unfinishTask": [],
|
||||
"week": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6
|
||||
]
|
||||
},
|
||||
"reason": "Retained ConditionVo loader anomaly; declared conditions checked conservatively",
|
||||
"step_number": 6,
|
||||
"task_type_id": "2009005"
|
||||
},
|
||||
{
|
||||
"condition": {
|
||||
"channel": "all",
|
||||
"close": false,
|
||||
"endTime": 2400,
|
||||
"finishTask": [],
|
||||
"maxLevel": 99999,
|
||||
"minLevel": 0,
|
||||
"passStage": [
|
||||
"dg506"
|
||||
],
|
||||
"platform": "all",
|
||||
"startTime": 0,
|
||||
"unfinishTask": [],
|
||||
"week": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6
|
||||
]
|
||||
},
|
||||
"reason": "Retained ConditionVo loader anomaly; declared conditions checked conservatively",
|
||||
"step_number": 7,
|
||||
"task_type_id": "2009005"
|
||||
},
|
||||
{
|
||||
"condition": {
|
||||
"channel": "all",
|
||||
"close": false,
|
||||
"endTime": 2400,
|
||||
"finishTask": [],
|
||||
"maxLevel": 99999,
|
||||
"minLevel": 0,
|
||||
"passStage": [
|
||||
"dg508"
|
||||
],
|
||||
"platform": "all",
|
||||
"startTime": 0,
|
||||
"unfinishTask": [],
|
||||
"week": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6
|
||||
]
|
||||
},
|
||||
"reason": "Retained ConditionVo loader anomaly; declared conditions checked conservatively",
|
||||
"step_number": 1,
|
||||
"task_type_id": "2009006"
|
||||
},
|
||||
{
|
||||
"condition": {
|
||||
"channel": "all",
|
||||
"close": false,
|
||||
"endTime": 2400,
|
||||
"finishTask": [],
|
||||
"maxLevel": 99999,
|
||||
"minLevel": 0,
|
||||
"passStage": [
|
||||
"dg509"
|
||||
],
|
||||
"platform": "all",
|
||||
"startTime": 0,
|
||||
"unfinishTask": [],
|
||||
"week": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6
|
||||
]
|
||||
},
|
||||
"reason": "Retained ConditionVo loader anomaly; declared conditions checked conservatively",
|
||||
"step_number": 2,
|
||||
"task_type_id": "2009006"
|
||||
},
|
||||
{
|
||||
"condition": {
|
||||
"channel": "all",
|
||||
"close": false,
|
||||
"endTime": 2400,
|
||||
"finishTask": [],
|
||||
"maxLevel": 99999,
|
||||
"minLevel": 0,
|
||||
"passStage": [
|
||||
"dg511"
|
||||
],
|
||||
"platform": "all",
|
||||
"startTime": 0,
|
||||
"unfinishTask": [],
|
||||
"week": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6
|
||||
]
|
||||
},
|
||||
"reason": "Retained ConditionVo loader anomaly; declared conditions checked conservatively",
|
||||
"step_number": 5,
|
||||
"task_type_id": "2009006"
|
||||
},
|
||||
{
|
||||
"condition": {
|
||||
"channel": "all",
|
||||
"close": false,
|
||||
"endTime": 2400,
|
||||
"finishTask": [],
|
||||
"maxLevel": 99999,
|
||||
"minLevel": 0,
|
||||
"passStage": [
|
||||
"dg512"
|
||||
],
|
||||
"platform": "all",
|
||||
"startTime": 0,
|
||||
"unfinishTask": [],
|
||||
"week": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6
|
||||
]
|
||||
},
|
||||
"reason": "Retained ConditionVo loader anomaly; declared conditions checked conservatively",
|
||||
"step_number": 6,
|
||||
"task_type_id": "2009006"
|
||||
},
|
||||
{
|
||||
"condition": {
|
||||
"channel": "all",
|
||||
"close": false,
|
||||
"endTime": 2400,
|
||||
"endTimestamp": 2147483647.0,
|
||||
"finishTask": [],
|
||||
"lang": "all",
|
||||
"maxLevel": 99999,
|
||||
"minLevel": 0,
|
||||
"passStage": [
|
||||
"dg315"
|
||||
],
|
||||
"platform": "all",
|
||||
"startTime": 0,
|
||||
"startTimestamp": 0,
|
||||
"unfinishTask": [],
|
||||
"unlockStage": [],
|
||||
"week": [
|
||||
0,
|
||||
1,
|
||||
2,
|
||||
3,
|
||||
4,
|
||||
5,
|
||||
6
|
||||
]
|
||||
},
|
||||
"reason": "Retained ConditionVo loader anomaly; declared conditions checked conservatively",
|
||||
"step_number": 2,
|
||||
"task_type_id": "3001027"
|
||||
}
|
||||
],
|
||||
"counts": {
|
||||
"linear_scripts": 4239,
|
||||
"mainline_linear_scripts": 718,
|
||||
"mainline_referenced_scripts": 720,
|
||||
"referenced_scripts": 4269
|
||||
},
|
||||
"delegated_categories": {
|
||||
"3": "event",
|
||||
"4": "commission_plan driven by existing QuestPolicy",
|
||||
"5": "bond"
|
||||
},
|
||||
"farming": {
|
||||
"item_or_egg_types": 259,
|
||||
"kill_rule": "team != 1 and !isObject and mode == 2; declared battle teams only",
|
||||
"kill_species": 440,
|
||||
"loot": "Configured potential rewards; actual inventory and kills must be refreshed after settlement",
|
||||
"sweep_kill_credit": false,
|
||||
"unindexed": "Dynamic controller/skill spawns and external reward sources"
|
||||
},
|
||||
"guide_gates": [
|
||||
{
|
||||
"record": "minefail",
|
||||
"step_number": 0,
|
||||
"task_type_id": "2001008"
|
||||
}
|
||||
],
|
||||
"scope": "Static planning support only; no game server calls or combat execution.",
|
||||
"script_classification_basis": "Original GAo expression keys and literal text formatting; StoryPanel/GAoNanoEventVo event handlers. Bundled GAo renderer implementation is not retained.",
|
||||
"source_apk_sha256": "01678ee3a8465d818d32cbbd94baa0d8253b04b4c57b70ebc5544ed341f1015d",
|
||||
"special_acceptance_task_types": [
|
||||
"1001001",
|
||||
"1001002",
|
||||
"2001009",
|
||||
"2001012"
|
||||
],
|
||||
"special_local_hooks": [
|
||||
{
|
||||
"action": "GachaPanel.popInGacha('task1')",
|
||||
"step_number": 4,
|
||||
"supported": false,
|
||||
"task_type_id": "1001006"
|
||||
}
|
||||
],
|
||||
"supported_nonbattle_statuses": [
|
||||
"none",
|
||||
"getItem",
|
||||
"getMonster",
|
||||
"getMoney",
|
||||
"killMonster",
|
||||
"passLevel",
|
||||
"unlockMonster",
|
||||
"sysLock"
|
||||
],
|
||||
"unknown_task_types": {
|
||||
"542160100": 6
|
||||
},
|
||||
"unsupported_scripts": {
|
||||
"event_cmas2_3": {
|
||||
"reasons": [
|
||||
"unsupported command: jump",
|
||||
"unsupported command: option"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 3,
|
||||
"task_type_id": "3000039"
|
||||
},
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 3,
|
||||
"task_type_id": "30000391"
|
||||
},
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 3,
|
||||
"task_type_id": "30000392"
|
||||
}
|
||||
]
|
||||
},
|
||||
"event_midatum_3_4": {
|
||||
"reasons": [
|
||||
"unsupported command: jump",
|
||||
"unsupported command: option"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 4,
|
||||
"task_type_id": "3010008"
|
||||
}
|
||||
]
|
||||
},
|
||||
"event_qianxi_3t": {
|
||||
"reasons": [
|
||||
"unsupported inline command: 主人公"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "afterStory",
|
||||
"step_number": 3,
|
||||
"task_type_id": "3001005"
|
||||
}
|
||||
]
|
||||
},
|
||||
"event_sbh_5_2": {
|
||||
"reasons": [
|
||||
"unsupported command: jump",
|
||||
"unsupported command: option"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 2,
|
||||
"task_type_id": "3013005"
|
||||
},
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 2,
|
||||
"task_type_id": "3013105"
|
||||
}
|
||||
]
|
||||
},
|
||||
"event_uma_12_4t": {
|
||||
"reasons": [
|
||||
"unsupported inline command: [l"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "afterStory",
|
||||
"step_number": 4,
|
||||
"task_type_id": "3005012"
|
||||
},
|
||||
{
|
||||
"phase": "afterStory",
|
||||
"step_number": 4,
|
||||
"task_type_id": "30050121"
|
||||
}
|
||||
]
|
||||
},
|
||||
"event_warm_newseason_4": {
|
||||
"reasons": [
|
||||
"unsupported inline command: 主人公"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 1,
|
||||
"task_type_id": "2001015"
|
||||
}
|
||||
]
|
||||
},
|
||||
"main_1020": {
|
||||
"reasons": [
|
||||
"unsupported command: option"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 0,
|
||||
"task_type_id": "2001003"
|
||||
}
|
||||
]
|
||||
},
|
||||
"mp3010010_1_1t": {
|
||||
"reasons": [
|
||||
"unsupported inline command: [l"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "afterStory",
|
||||
"step_number": 1,
|
||||
"task_type_id": "530100101"
|
||||
}
|
||||
]
|
||||
},
|
||||
"mp3129010_0_2": {
|
||||
"reasons": [
|
||||
"unsupported inline command: show[l"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 2,
|
||||
"task_type_id": "531290100"
|
||||
}
|
||||
]
|
||||
},
|
||||
"mp3183010_1_1f": {
|
||||
"reasons": [
|
||||
"unsupported inline command: coor"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 1,
|
||||
"task_type_id": "531830101"
|
||||
}
|
||||
]
|
||||
},
|
||||
"mp4019010_0_0": {
|
||||
"reasons": [
|
||||
"unsupported inline command: "
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 0,
|
||||
"task_type_id": "540190100"
|
||||
}
|
||||
]
|
||||
},
|
||||
"mp4019010_0_1a": {
|
||||
"reasons": [
|
||||
"unsupported inline command: "
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "afterStory",
|
||||
"step_number": 1,
|
||||
"task_type_id": "540190100"
|
||||
}
|
||||
]
|
||||
},
|
||||
"mp5109010_0_2": {
|
||||
"reasons": [
|
||||
"unsupported command: option"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 2,
|
||||
"task_type_id": "551090100"
|
||||
}
|
||||
]
|
||||
},
|
||||
"task_1004010_1": {
|
||||
"reasons": [
|
||||
"unsupported command: option"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 2,
|
||||
"task_type_id": "1004010"
|
||||
}
|
||||
]
|
||||
},
|
||||
"task_1004013_0": {
|
||||
"reasons": [
|
||||
"unsupported command: option"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 1,
|
||||
"task_type_id": "1004013"
|
||||
}
|
||||
]
|
||||
},
|
||||
"task_2001002g": {
|
||||
"reasons": [
|
||||
"unsupported command: option"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 0,
|
||||
"task_type_id": "2001002"
|
||||
}
|
||||
]
|
||||
},
|
||||
"task_2001004_1": {
|
||||
"reasons": [
|
||||
"unsupported command: option"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 0,
|
||||
"task_type_id": "2001004"
|
||||
}
|
||||
]
|
||||
},
|
||||
"task_2001005_0": {
|
||||
"reasons": [
|
||||
"unsupported command: option"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 0,
|
||||
"task_type_id": "2001005"
|
||||
}
|
||||
]
|
||||
},
|
||||
"task_2001006_0": {
|
||||
"reasons": [
|
||||
"unsupported command: option"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 0,
|
||||
"task_type_id": "2001006"
|
||||
}
|
||||
]
|
||||
},
|
||||
"task_2001006_1": {
|
||||
"reasons": [
|
||||
"unsupported command: option"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 1,
|
||||
"task_type_id": "2001006"
|
||||
}
|
||||
]
|
||||
},
|
||||
"task_2001008_0": {
|
||||
"reasons": [
|
||||
"unsupported command: option"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 0,
|
||||
"task_type_id": "2001008"
|
||||
}
|
||||
]
|
||||
},
|
||||
"task_2002001_0": {
|
||||
"reasons": [
|
||||
"unsupported command: option"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 0,
|
||||
"task_type_id": "2002001"
|
||||
}
|
||||
]
|
||||
},
|
||||
"task_2002002_0": {
|
||||
"reasons": [
|
||||
"unsupported command: option"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 0,
|
||||
"task_type_id": "2002002"
|
||||
}
|
||||
]
|
||||
},
|
||||
"task_2002003_0": {
|
||||
"reasons": [
|
||||
"unsupported command: option"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 0,
|
||||
"task_type_id": "2002003"
|
||||
}
|
||||
]
|
||||
},
|
||||
"task_2002004_0": {
|
||||
"reasons": [
|
||||
"unsupported command: option"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 0,
|
||||
"task_type_id": "2002004"
|
||||
}
|
||||
]
|
||||
},
|
||||
"task_2003002_0": {
|
||||
"reasons": [
|
||||
"unsupported command: option"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 0,
|
||||
"task_type_id": "2003002"
|
||||
}
|
||||
]
|
||||
},
|
||||
"task_2003003_0": {
|
||||
"reasons": [
|
||||
"unsupported command: option"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 0,
|
||||
"task_type_id": "2003003"
|
||||
}
|
||||
]
|
||||
},
|
||||
"task_2003005_0": {
|
||||
"reasons": [
|
||||
"unsupported command: option",
|
||||
"unsupported command: para"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 0,
|
||||
"task_type_id": "2003005"
|
||||
}
|
||||
]
|
||||
},
|
||||
"task_2009001_3": {
|
||||
"reasons": [
|
||||
"unsupported inline command: wit"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 3,
|
||||
"task_type_id": "2009001"
|
||||
}
|
||||
]
|
||||
},
|
||||
"task_lnp_k_0": {
|
||||
"reasons": [
|
||||
"unsupported command: option"
|
||||
],
|
||||
"uses": [
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 0,
|
||||
"task_type_id": "3001006"
|
||||
},
|
||||
{
|
||||
"phase": "story",
|
||||
"step_number": 0,
|
||||
"task_type_id": "30010061"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
+579
-7
@@ -1,7 +1,10 @@
|
||||
from __future__ import annotations
|
||||
from copy import copy, deepcopy
|
||||
from dataclasses import replace
|
||||
from functools import wraps
|
||||
import json
|
||||
from pathlib import Path
|
||||
import threading
|
||||
import time
|
||||
from .model import Action, Catalog, Planner, Policy, Snapshot, seconds
|
||||
from .daily import DailyLedger, DailyPolicy, selected_entries
|
||||
@@ -14,10 +17,37 @@ from .master_sync import MasterSync
|
||||
from .stage_cache import StageCache
|
||||
from .drop_statistics import reward_text
|
||||
from .cultivation import CultivationSelector
|
||||
from .battles import BattleJournal, BattleOrchestrator, CancelledBeforeDispatch, digest, gameplay_response, public_data, value
|
||||
from .progression import ProgressionIntent, ProgressionPlanner, ProgressionPolicy
|
||||
|
||||
|
||||
def account_serial(method):
|
||||
"""Serialize whole operations, not just individual Client.call requests."""
|
||||
@wraps(method)
|
||||
def invoke(self, *args, **kwargs):
|
||||
with self.battle_journal.lock:
|
||||
return method(self, *args, **kwargs)
|
||||
return invoke
|
||||
|
||||
|
||||
def single_flight(method):
|
||||
@wraps(method)
|
||||
def invoke(self, *args, **kwargs):
|
||||
generation = self._progression_cancel_generation
|
||||
if not self.battle_journal.lock.acquire(blocking=False):
|
||||
return self.snapshot, [], "同账号已有任务 / 战斗正在执行"
|
||||
try:
|
||||
with self._progression_cancel_lock:
|
||||
if self.auto and generation == self._progression_cancel_generation and self._progression_cancel.is_set():
|
||||
self._progression_cancel = threading.Event()
|
||||
return method(self, *args, **kwargs)
|
||||
finally:
|
||||
self.battle_journal.lock.release()
|
||||
return invoke
|
||||
|
||||
|
||||
class Engine:
|
||||
def __init__(self, catalog, client=None, budget_path=None):
|
||||
def __init__(self, catalog, client=None, budget_path=None, *, game_data=None, battle_runtime=None, experimental_runtime=None):
|
||||
self.catalog, self.client = catalog, client
|
||||
folder = Path(budget_path).parent if budget_path else None
|
||||
self.cultivation = CultivationSelector(catalog, folder / "cultivation_choices.json" if folder else None)
|
||||
@@ -44,11 +74,500 @@ class Engine:
|
||||
self.daily_ledger = DailyLedger(folder / "daily_claims.json" if folder else None)
|
||||
self.sweep_policy = SweepPolicy()
|
||||
self.sweeper = SweepRunner(catalog, folder / "sweep_runs.json" if folder else None)
|
||||
self.progression_policy = ProgressionPolicy()
|
||||
self.progression_view_active = False
|
||||
self.progression_planner = None
|
||||
self.game_data = game_data
|
||||
self._progression_namespace = str(folder.resolve()) if folder else ""
|
||||
self._progression_state_loaded = False
|
||||
self._battle_catalog_ready = False
|
||||
self.battle_journal = BattleJournal(folder / "progression" / "journal.json" if folder else None)
|
||||
self.battles = BattleOrchestrator(catalog, self.battle_journal, battle_runtime, self.sweeper,
|
||||
request_builder=self._battle_request, observer=self._battle_observer)
|
||||
self._progression_cancel = threading.Event()
|
||||
self._progression_cancel_lock = threading.Lock()
|
||||
self._progression_cancel_generation = 0
|
||||
self._progression_cache_key = None
|
||||
self._progression_rows = []
|
||||
self._progression_intents = []
|
||||
self._commission_planner_available = False
|
||||
self._commission_offer_reason = ""
|
||||
self._progression_records = []
|
||||
self._progression_error = ""
|
||||
self._planner_pending = False
|
||||
self._capability_cache = {}
|
||||
self._battle_snapshot_source = None
|
||||
self._battle_snapshot_digest = ""
|
||||
self._battle_roster_digest = None
|
||||
self._battle_roster = None
|
||||
self._battle_runtimes = {"original": battle_runtime, "experimental": experimental_runtime}
|
||||
self._selected_battle_mode = "original"
|
||||
|
||||
def cancel_progression(self):
|
||||
"""Safe on Qt's thread while a worker is running; never waits or calls APIs."""
|
||||
with self._progression_cancel_lock:
|
||||
self.auto = False
|
||||
self._progression_cancel_generation += 1
|
||||
self._progression_cancel.set()
|
||||
|
||||
def progression_rows(self):
|
||||
"""A cached view only. Full-table planning always runs in an account worker."""
|
||||
return deepcopy(self._progression_rows)
|
||||
|
||||
def progression_records(self):
|
||||
return deepcopy(self._progression_records)
|
||||
|
||||
def _progression_pending(self):
|
||||
return self.snapshot is not None and (self.battle_journal.pending(self.snapshot)
|
||||
or self.sweeper.state.get("pending") or self._planner_pending)
|
||||
|
||||
def _require_no_battle(self):
|
||||
if self._progression_pending():
|
||||
raise ValueError("有待核对的任务 / 战斗,已暂停牧场、赠礼和任务写操作;请先刷新核对")
|
||||
|
||||
def _ensure_progression(self):
|
||||
if self.game_data is None:
|
||||
from .game_data import load_progression_data
|
||||
self.game_data = load_progression_data()
|
||||
if self.progression_planner is None:
|
||||
self.progression_planner = ProgressionPlanner(self.catalog, self.game_data, account_key=self._progression_namespace)
|
||||
if not self._progression_state_loaded and self.snapshot is not None:
|
||||
stored = deepcopy(self.battle_journal.role(self.snapshot).get("planner_state"))
|
||||
if stored:
|
||||
for account in stored.get("accounts", {}).values():
|
||||
pending = account.get("pending")
|
||||
if pending:
|
||||
pending["token"] = pending.pop("intent_id", "")
|
||||
pending["intent"]["token"] = pending["intent"].pop("intent_id", "")
|
||||
self.progression_planner.restore_state(stored)
|
||||
self._progression_state_loaded = True
|
||||
# A separate view preserves the commission-only legacy catalog.
|
||||
if not self._battle_catalog_ready:
|
||||
battle_catalog = copy(self.catalog)
|
||||
positions = dict(self.catalog.data.get("stage_task_positions", {}))
|
||||
for key, task in self.game_data.tasks.items():
|
||||
positions[str(key)] = [step.get("position", "") for step in task.get("steps", [])]
|
||||
battle_catalog.data = self.catalog.data | {"stage_info": self.game_data.stages,
|
||||
"stage_sp": self.game_data.stage_sp, "stage_task_positions": positions,
|
||||
"game_setting": self.game_data.game_setting}
|
||||
self.battles.catalog = battle_catalog
|
||||
self._battle_catalog_ready = True
|
||||
self._select_battle_runtime(self.progression_policy.battle_mode)
|
||||
|
||||
def _select_battle_runtime(self, mode):
|
||||
if mode not in ("original", "experimental"):
|
||||
raise ValueError("未知战斗模式,未开始战斗")
|
||||
if self.battles.runtime is not None:
|
||||
self._battle_runtimes[self._selected_battle_mode] = self.battles.runtime
|
||||
self._selected_battle_mode = mode
|
||||
runtime = self._battle_runtimes.get(mode)
|
||||
if runtime is None:
|
||||
try:
|
||||
if mode == "experimental":
|
||||
from .battle_simulator import ExperimentalBattleRuntime as Runtime
|
||||
else:
|
||||
from .battle_runtime import BattleRuntime as Runtime
|
||||
except ImportError:
|
||||
pass
|
||||
else:
|
||||
runtime = self._battle_runtimes[mode] = Runtime()
|
||||
self.battles.runtime = runtime
|
||||
|
||||
def _persist_progression(self, *, save=True):
|
||||
state = self.progression_planner.export_state()
|
||||
self._planner_pending = any(account.get("pending") for account in state.get("accounts", {}).values())
|
||||
for account in state.get("accounts", {}).values():
|
||||
account["applied"] = account["applied"][-1000:]
|
||||
account["received"] = {key: {field: task[field] for field in ("id", "typeId", "curStep", "stepValue") if field in task}
|
||||
for key, task in account["received"].items()}
|
||||
pending = account.get("pending")
|
||||
if pending:
|
||||
# These are planner-issued hashes, not authentication tokens.
|
||||
# Store them under an unambiguous local name on disk.
|
||||
pending["intent_id"] = pending.pop("token")
|
||||
pending["intent"]["intent_id"] = pending["intent"].pop("token")
|
||||
for task in account["tasks"].values():
|
||||
cutoff = min(task.get("cursor", 0), task.get("server_step", 0))
|
||||
for field in ("before", "after", "acknowledged"):
|
||||
task[field] = [number for number in task.get(field, []) if number >= cutoff]
|
||||
state = public_data(state)
|
||||
target = self.battle_journal.role(self.snapshot)
|
||||
if target.get("planner_state") != state:
|
||||
target["planner_state"] = state
|
||||
if save:
|
||||
self.battle_journal.save()
|
||||
|
||||
def _battle_observer(self, event, intent, response):
|
||||
farming = self._is_farm(intent)
|
||||
if value(intent, "kind") != "progression_battle" and not farming:
|
||||
return None
|
||||
planner = self.progression_planner
|
||||
if event == "cancelled_before_start":
|
||||
self._cancel_unsent_progression(intent)
|
||||
return None
|
||||
if farming:
|
||||
if event == "started":
|
||||
planner.mark_started(self.snapshot, intent) # validates the issued ordinary intent only
|
||||
# Farming is a normal map action. Its journal and fresh server
|
||||
# snapshot govern the result; it never acknowledges a task step.
|
||||
return None
|
||||
if event == "validate":
|
||||
account = planner.export_state().get("accounts", {}).get(intent.account_key, {})
|
||||
task = account.get("tasks", {}).get(f"{intent.task_id}:{intent.task_type_id}", {})
|
||||
return task.get("cursor") == intent.step_number
|
||||
if event == "started":
|
||||
planner.mark_started(self.snapshot, intent)
|
||||
elif event in ("settled", "event"):
|
||||
if not planner.acknowledge(self.snapshot, intent, gameplay_response(response)):
|
||||
raise ValueError("任务战斗结算已返回,但任务步骤确认未完成")
|
||||
elif event == "loss":
|
||||
planner.battle_lost(self.snapshot, intent)
|
||||
self._persist_progression()
|
||||
|
||||
def _cancel_unsent_progression(self, intent):
|
||||
"""Rollback only the matching planner send marker, before dispatch."""
|
||||
state = self.progression_planner.export_state()
|
||||
account = state.get("accounts", {}).get(value(intent, "account_key"), {})
|
||||
pending = account.get("pending")
|
||||
if pending:
|
||||
if pending.get("token") != value(intent, "token") or pending.get("intent") != intent.to_dict():
|
||||
raise ValueError("取消的未发送请求与任务检查点不匹配")
|
||||
account["pending"] = None
|
||||
self.progression_planner.restore_state(state)
|
||||
self._persist_progression(save=False)
|
||||
|
||||
def _recover_confirmed_progression(self):
|
||||
"""Replay only local acknowledgement of a durably received success."""
|
||||
record = self.battle_journal.pending(self.snapshot)
|
||||
if (not record or str(record.get("role_id")) != str(self.snapshot.raw["master"].get("id"))
|
||||
or not str(record.get("kind", "")).startswith("progression_")):
|
||||
return
|
||||
battle = record["kind"] == "progression_battle"
|
||||
confirmed = record.get("phase") == ("settlement_acknowledged" if battle else "acknowledged")
|
||||
confirmed = confirmed or record.get("settlement_confirmed" if battle else "response_confirmed") is True
|
||||
response = record.get("response")
|
||||
if not confirmed or not isinstance(response, dict) or response.get("resCode", 0) not in (0, "0"):
|
||||
return
|
||||
path = record.get("path") or ""
|
||||
if battle and path != "taskService/taskCompleteStep":
|
||||
return
|
||||
if not battle and path not in {"taskService/taskReceive", "taskService/taskLoopReceive", "taskService/taskLoopFlush",
|
||||
"taskService/taskCompleteStep", "taskService/taskComplete", "taskService/taskUpdate"}:
|
||||
return
|
||||
state = self.progression_planner.export_state()
|
||||
account = state.get("accounts", {}).get(record.get("account_key"), {})
|
||||
intent_id = record.get("intent_id")
|
||||
applied = bool(intent_id and intent_id in account.get("applied", []))
|
||||
if not applied:
|
||||
pending = self.progression_planner.pending(self.snapshot)
|
||||
if not pending or not isinstance(pending.get("intent"), dict):
|
||||
return
|
||||
intent = ProgressionIntent(**pending["intent"])
|
||||
if (pending.get("token") != intent.token or intent.blocked
|
||||
or intent_id and intent.token != intent_id
|
||||
or record.get("account_key") and intent.account_key != record["account_key"]):
|
||||
return
|
||||
if any(str(value(intent, field)) != str(record.get(field))
|
||||
for field in ("kind", "task_id", "task_type_id", "step_number")):
|
||||
return
|
||||
# The current restore_state API restores durable accounts but not
|
||||
# its transient issued-token registry. Rehydrate only this exact
|
||||
# saved pending intent after validating the successful receipt.
|
||||
# Cursor/story effects still belong exclusively to acknowledge.
|
||||
issued = self.progression_planner._issued
|
||||
if intent.token in issued and issued[intent.token] != intent.to_dict():
|
||||
raise ValueError("持久化确认与已签发任务意图不匹配")
|
||||
issued[intent.token] = intent.to_dict()
|
||||
if not self.progression_planner.acknowledge(self.snapshot, intent, response):
|
||||
return
|
||||
self._persist_progression(save=False)
|
||||
self.battle_journal.finish(self.snapshot, record, "win" if battle else "task",
|
||||
"已从持久化成功回包恢复本地任务检查点;未重发请求")
|
||||
|
||||
def _battle_capability(self, intent):
|
||||
try:
|
||||
if self._is_commission(intent) and not self.quest_policy.battle_tasks:
|
||||
return False, "战斗委托未启用;未开始战斗"
|
||||
if self.battles.runtime is None:
|
||||
return False, ("实验模型" if self.progression_policy.battle_mode == "experimental" else "原始战斗运行时") + "尚未提供,未开始战斗"
|
||||
policy = self._intent_policy(intent)
|
||||
preview = bool(value(intent, "task_type_id")) and not value(intent, "task_id") and not self._is_farm(intent)
|
||||
if not preview:
|
||||
reason = self.battles.resource_reason(self.snapshot, intent, policy, self.policy)
|
||||
if reason:
|
||||
return False, reason
|
||||
key = digest({"snapshot": self._battle_snapshot_digest, "runtime": id(self.battles.runtime), "team": policy.team, "mode": policy.battle_mode,
|
||||
**{name: value(intent, name) for name in ("task_type_id", "step_number", "stage_id", "difficulty", "battle_kind")}})
|
||||
if key not in self._capability_cache:
|
||||
request = self.battles.request(self.snapshot, intent, policy)
|
||||
self._capability_cache[key] = self.battles.inspect(request)
|
||||
while len(self._capability_cache) > 64:
|
||||
self._capability_cache.pop(next(iter(self._capability_cache)))
|
||||
return self._capability_cache[key]
|
||||
except (ImportError, OSError, ValueError, TypeError, KeyError, AttributeError) as error:
|
||||
return False, "战斗输入或运行时未就绪:" + str(error)
|
||||
|
||||
def _overlay_battle_capabilities(self, rows, intents):
|
||||
battle_kinds = {"task", "battle", "passStage", "task_battle", "task_pass_stage", "ordinary_stage", "stage", "map_battle", "hidden"}
|
||||
reasons = {}
|
||||
adjusted = []
|
||||
for intent in intents:
|
||||
if value(intent, "kind") == "progression_loop_accept" and not self._commission_offer_supported(value(intent, "task_type_id")):
|
||||
intent = replace(intent, block_reason=self._commission_offer_reason)
|
||||
if (value(intent, "kind") in ("progression_battle", "battle", "task_battle", "stage_battle", "map_battle")
|
||||
or self._is_farm(intent) and not self._is_sweep_intent(intent)) and not value(intent, "block_reason"):
|
||||
supported, reason = self._battle_capability(intent)
|
||||
reasons[str(value(intent, "source_task_type_id") or value(intent, "task_type_id"))] = (supported, reason)
|
||||
if not supported:
|
||||
intent = replace(intent, block_reason=reason) if not isinstance(intent, dict) else intent | {"block_reason": reason}
|
||||
adjusted.append(intent)
|
||||
commissions = {str(value(intent, "task_type_id")): intent for intent in adjusted if self._is_commission(intent)}
|
||||
farms = {str(value(intent, "source_task_type_id")): intent for intent in adjusted if self._is_farm(intent)}
|
||||
for row in rows:
|
||||
source_supported = row.get("supported") is not False
|
||||
commission = commissions.get(str(row.get("task_type_id")))
|
||||
if commission is not None:
|
||||
row.update(next_action=value(commission, "description"), block_reason=value(commission, "block_reason", ""))
|
||||
farm = farms.get(str(row.get("task_type_id")))
|
||||
if farm is not None:
|
||||
row.update(next_action=value(farm, "description"), block_reason=value(farm, "block_reason", ""),
|
||||
battle_kind="sweep" if self._is_sweep_intent(farm) else "ordinary_stage",
|
||||
stage_id=value(farm, "stage_id"), difficulty=value(farm, "difficulty"))
|
||||
reason = row.get("block_reason") or row.get("blocked_reason") or ""
|
||||
if row.get("battle_kind") in battle_kinds:
|
||||
supported, runtime_reason = reasons.get(str(row.get("task_type_id")),
|
||||
(False, "战斗运行时能力尚未核对;配置存在不代表已支持实战"))
|
||||
row["supported"] = bool(source_supported and supported and not reason)
|
||||
reason = reason or runtime_reason
|
||||
else:
|
||||
row["supported"] = bool(source_supported and not reason)
|
||||
row["block_reason"] = row["blocked_reason"] = reason
|
||||
return rows, adjusted
|
||||
|
||||
def _battle_request(self, snapshot, intent, policy, request):
|
||||
self._ensure_progression()
|
||||
if self._battle_snapshot_source is not snapshot:
|
||||
self._battle_snapshot_source = snapshot
|
||||
self._battle_snapshot_digest = digest(snapshot.raw)
|
||||
if self._battle_roster_digest != self._battle_snapshot_digest:
|
||||
self._battle_roster = deepcopy(snapshot.raw)
|
||||
self._battle_roster_digest = self._battle_snapshot_digest
|
||||
task = bool(value(intent, "task_type_id")) and value(intent, "battle_kind") in ("task", "battle", "passStage", "task_battle", "task_pass_stage")
|
||||
kind = value(intent, "battle_kind")
|
||||
battle = self.game_data.task_battle(value(intent, "task_type_id"), value(intent, "step_number")) if task else \
|
||||
self.game_data.stage_battle(value(intent, "stage_id"), value(intent, "difficulty", "1"))
|
||||
prepared = request | {"snapshot": self._battle_roster,
|
||||
"battle_mode": policy.battle_mode,
|
||||
"context": "task_pass_stage" if task and kind == "passStage" else "task_battle" if task else "ordinary_stage",
|
||||
"original_data": {"battle": battle, "manifest": self.game_data.manifest},
|
||||
"roster": self._battle_roster, "task_id": value(intent, "task_id"),
|
||||
"step_index": int(value(intent, "step_number", 1) or 1) - 1 if task else None}
|
||||
if policy.battle_mode == "original":
|
||||
from .battle_runtime import BattleRuntime
|
||||
if isinstance(self.battles.runtime, BattleRuntime):
|
||||
source = self.game_data.manifest.get("source", {})
|
||||
prepared["runtime_request"] = {name: prepared[name] for name in (
|
||||
"context", "roster", "stage_id", "task_id", "step_index")}
|
||||
prepared["runtime_request"].update(difficulty=int(value(intent, "difficulty", 1) or 1), purpose="settlement",
|
||||
original_data={"source": "original_apk", "resource_identity": {
|
||||
"apk_sha256": source.get("apk_sha256"), "main_swf_sha256": source.get("main_swf_sha256")}})
|
||||
return prepared
|
||||
|
||||
def _is_commission(self, intent):
|
||||
if value(intent, "kind") in ("progression_loop_accept", "progression_loop_reset"):
|
||||
return True
|
||||
info = self.game_data.task(value(intent, "source_task_type_id") or value(intent, "task_type_id")) if self.game_data else None
|
||||
return bool(info and info.get("type") == 4)
|
||||
|
||||
@staticmethod
|
||||
def _is_farm(intent):
|
||||
return bool(value(intent, "source_task_type_id")) and not value(intent, "task_id") and bool(value(intent, "stage_id"))
|
||||
|
||||
@staticmethod
|
||||
def _is_sweep_intent(intent):
|
||||
return value(intent, "kind") in ("sweep", "progression_sweep", "progression_farm_sweep", "progression_map_sweep") or value(intent, "battle_kind") == "sweep"
|
||||
|
||||
def _intent_policy(self, intent):
|
||||
if not self._is_commission(intent):
|
||||
return self.progression_policy
|
||||
quest = self.quest_policy
|
||||
return replace(self.progression_policy, enabled=quest.enabled, mainline=False, sidequests=False,
|
||||
commissions=True, accept=quest.accept, allow_items=quest.allow_items, allow_monsters=quest.allow_monsters,
|
||||
max_money=quest.max_money, item_reserves=dict(quest.item_reserves))
|
||||
|
||||
def _commission_offer_supported(self, type_id):
|
||||
self._commission_offer_reason = "委托后续条件、剧情或战斗未验证支持,未消耗接取次数"
|
||||
info = self.game_data.task(type_id)
|
||||
if not info or info.get("type") != 4:
|
||||
return False
|
||||
for number, step in enumerate(info.get("steps", []), 1):
|
||||
for name in (step.get("story"), step.get("afterStory")):
|
||||
if name and (self.game_data.script(name) or {}).get("supported") is not True:
|
||||
return False
|
||||
kind = step.get("statusType")
|
||||
if kind in ("battle", "passStage"):
|
||||
if not self.quest_policy.battle_tasks:
|
||||
return False
|
||||
intent = {"kind": "progression_battle", "task_type_id": str(type_id), "task_id": 0,
|
||||
"step_number": number, "battle_kind": "passStage" if kind == "passStage" else "task",
|
||||
"stage_id": (step.get("statusValue") or {}).get("stage"),
|
||||
"difficulty": (step.get("statusValue") or {}).get("level", 1)}
|
||||
supported, reason = self._battle_capability(intent)
|
||||
if not supported:
|
||||
self._commission_offer_reason = reason
|
||||
return False
|
||||
else:
|
||||
ready, _, _ = self.progression_planner.requirement(self.snapshot, step, {},
|
||||
self._intent_policy({"task_type_id": str(type_id)}), self.policy)
|
||||
if not ready:
|
||||
return False
|
||||
return bool(info.get("steps"))
|
||||
|
||||
def _refresh_progression_cache(self, *, force=False):
|
||||
if self.snapshot is None:
|
||||
return
|
||||
if not (force or self.progression_view_active or self.progression_policy.enabled or self.quest_policy.enabled):
|
||||
return
|
||||
try:
|
||||
self._ensure_progression()
|
||||
self._recover_confirmed_progression()
|
||||
self._battle_snapshot_source = self.snapshot
|
||||
self._battle_snapshot_digest = digest(self.snapshot.raw)
|
||||
key = digest({"snapshot": self._battle_snapshot_digest, "policy": vars(self.progression_policy),
|
||||
"quests": vars(self.quest_policy), "ranch": vars(self.policy), "local_state": self.progression_planner.state_signature(self.snapshot),
|
||||
"pending": self._progression_pending(), "runtime": id(self.battles.runtime), "day": int(self.snapshot.now // 86400)})
|
||||
if force or key != self._progression_cache_key:
|
||||
rows = self.progression_planner.rows(self.snapshot, self.progression_policy, self.policy, quest_policy=self.quest_policy)
|
||||
intents = self.progression_planner.plan(self.snapshot, self.progression_policy, self.policy)
|
||||
commission_plan = getattr(self.progression_planner, "commission_plan", None)
|
||||
self._commission_planner_available = callable(commission_plan)
|
||||
if self._commission_planner_available:
|
||||
intents += commission_plan(self.snapshot, self.quest_policy, self.policy, battle_policy=self.progression_policy)
|
||||
self._progression_rows, self._progression_intents = self._overlay_battle_capabilities(rows, intents)
|
||||
self._persist_progression()
|
||||
self._progression_cache_key = digest({"snapshot": self._battle_snapshot_digest, "policy": vars(self.progression_policy),
|
||||
"quests": vars(self.quest_policy), "ranch": vars(self.policy), "local_state": self.progression_planner.state_signature(self.snapshot),
|
||||
"pending": self._progression_pending(), "runtime": id(self.battles.runtime), "day": int(self.snapshot.now // 86400)})
|
||||
self._progression_error = ""
|
||||
except (ImportError, OSError, ValueError, TypeError, KeyError, AttributeError) as error:
|
||||
self._progression_error = "任务规划暂不可用:" + str(error)
|
||||
self._progression_rows = [{"state": "unsupported", "supported": False, "blocked_reason": self._progression_error}]
|
||||
self._progression_intents = []
|
||||
self._progression_records = self.battle_journal.records(self.snapshot)
|
||||
|
||||
@account_serial
|
||||
def refresh_progression(self):
|
||||
if not self.demo:
|
||||
self.read_snapshot(sync_master=False)
|
||||
elif self.snapshot is None:
|
||||
self.snapshot = demo_snapshot(self.catalog)
|
||||
self._refresh_progression_cache(force=True)
|
||||
pending = self.battle_journal.pending(self.snapshot)
|
||||
message = self._progression_error or (pending.get("message") or "存在待核对的任务 / 战斗") if pending else self._progression_error or "已刷新任务与战斗记录"
|
||||
return self.snapshot, self.plans(), message
|
||||
|
||||
@single_flight
|
||||
@account_serial
|
||||
def run_progression_once(self):
|
||||
self.last_executed = False
|
||||
if not self.demo:
|
||||
self.read_snapshot(sync_master=False)
|
||||
elif self.snapshot is None:
|
||||
self.snapshot = demo_snapshot(self.catalog)
|
||||
self._refresh_progression_cache()
|
||||
return self._run_progression_intent()
|
||||
|
||||
def _run_progression_intent(self, intent=None):
|
||||
if not self.progression_policy.enabled and not self.quest_policy.enabled:
|
||||
return self.snapshot, self.plans(), "自动主线策略未启用"
|
||||
if self._progression_pending():
|
||||
return self.snapshot, [], "有待核对的任务 / 战斗;未重复提交"
|
||||
if self._progression_cancel.is_set():
|
||||
return self.snapshot, self.plans(), "任务推进已取消"
|
||||
intents = self._progression_intents
|
||||
if intent is None:
|
||||
intent = next((i for i in intents if not value(i, "block_reason")), None)
|
||||
if intent is None:
|
||||
reasons = [str(value(i, "block_reason")) for i in intents if value(i, "block_reason")]
|
||||
return self.snapshot, self.plans(), self._progression_error or (";".join(dict.fromkeys(reasons)) if reasons else "当前没有可执行的任务步骤")
|
||||
if self.demo:
|
||||
return self.snapshot, self.plans(), "演示只展示任务;不会伪造战斗、任务进度或奖励"
|
||||
if value(intent, "block_reason"):
|
||||
return self.snapshot, self.plans(), str(value(intent, "block_reason"))
|
||||
effective_policy = self._intent_policy(intent)
|
||||
if not effective_policy.enabled:
|
||||
return self.snapshot, self.plans(), "对应任务策略未启用"
|
||||
try:
|
||||
self.last_executed = True
|
||||
kind = value(intent, "kind")
|
||||
if kind in ("progression_battle", "battle", "task_battle", "stage_battle", "map_battle", "sweep") or self._is_farm(intent):
|
||||
message = self.battles.run(self.client, self.snapshot, intent, effective_policy,
|
||||
cancel=self._progression_cancel, ranch=self.policy)
|
||||
else:
|
||||
message = self._execute_task_intent(intent)
|
||||
if self.battle_journal.pending(self.snapshot) and kind == "progression_battle":
|
||||
self.progression_planner.mark_uncertain(self.snapshot, intent, "战斗待核对,禁止重放")
|
||||
self._persist_progression()
|
||||
if not self._progression_cancel.is_set():
|
||||
self.read_snapshot(sync_master=False)
|
||||
return self.snapshot, self.plans(), message
|
||||
except Exception:
|
||||
if self.battle_journal.pending(self.snapshot) and not self._is_farm(intent) and value(intent, "kind", "").startswith("progression_"):
|
||||
self.progression_planner.mark_uncertain(self.snapshot, intent, "任务 / 战斗结果待核对,禁止重放")
|
||||
self._persist_progression()
|
||||
raise
|
||||
finally:
|
||||
self._refresh_progression_cache(force=True)
|
||||
|
||||
def _execute_task_intent(self, intent):
|
||||
path, kind = value(intent, "path", "") or "", value(intent, "kind")
|
||||
payload = deepcopy(value(intent, "payload", {}) or {})
|
||||
allowed = {"taskService/taskReceive": {"taskTypeId"}, "taskService/taskLoopReceive": {"taskTypeId", "city"},
|
||||
"taskService/taskCompleteStep": {"taskId", "taskTypeId", "removeIds"},
|
||||
"taskService/taskComplete": {"taskId", "taskTypeId"}, "taskService/taskLoopFlush": set(),
|
||||
"taskService/taskUpdate": {"unlockTasks", "receiveTasks", "removeTasks"}}
|
||||
local = kind in ("progression_navigate", "progression_dialogue", "progression_local_step") and not path
|
||||
if not local and (path not in allowed or set(payload) != allowed[path]):
|
||||
return "任务请求字段或本地剧情类型未受支持,未执行"
|
||||
if path.endswith("taskUpdate") and (not all(isinstance(payload[k], list) for k in allowed[path])
|
||||
or not any(payload.values())):
|
||||
return "任务补链必须提供计算后的三个数组;未发送查询或空补链"
|
||||
if self._progression_cancel.is_set():
|
||||
return "任务推进已取消"
|
||||
record = self.battle_journal.begin(self.snapshot, intent)
|
||||
if local:
|
||||
self.progression_planner.acknowledge(self.snapshot, intent)
|
||||
self._persist_progression(save=False)
|
||||
self.battle_journal.finish(self.snapshot, record, "local", "已保存普通剧情的本地检查点")
|
||||
return "已推进普通剧情并保存本地检查点"
|
||||
try:
|
||||
self.progression_planner.mark_started(self.snapshot, intent)
|
||||
self._persist_progression(save=False)
|
||||
self.battle_journal.update(record, "request_pending")
|
||||
try:
|
||||
response = self.battles._call(self.client, path, payload, cancel=self._progression_cancel)
|
||||
except CancelledBeforeDispatch:
|
||||
self._cancel_unsent_progression(intent)
|
||||
self.battle_journal.finish(self.snapshot, record, "cancelled", "任务请求尚未发送,已取消")
|
||||
return record["message"]
|
||||
self.battle_journal.update(record, "acknowledged", response=gameplay_response(response), response_confirmed=True)
|
||||
acknowledged = self.progression_planner.acknowledge(self.snapshot, intent, gameplay_response(response))
|
||||
self._persist_progression(save=False)
|
||||
if acknowledged:
|
||||
self.battle_journal.finish(self.snapshot, record, "task", "服务器已确认任务请求,已保存本地检查点")
|
||||
else:
|
||||
self.battle_journal.update(record, "unknown", message="任务成功回包缺少有效状态,等待核对")
|
||||
return value(intent, "description", "任务请求已确认")
|
||||
except Exception as error:
|
||||
self.battle_journal.update(record, "unknown", message="任务请求结果未确认,禁止自动重试", error_type=type(error).__name__)
|
||||
raise
|
||||
|
||||
@account_serial
|
||||
def read_snapshot(self, *, sync_master=True):
|
||||
self.snapshot = self.client.snapshot()
|
||||
self.battle_journal.reconcile(self.snapshot, trusted=True)
|
||||
self.master_sync.apply(self.snapshot)
|
||||
if sync_master:
|
||||
if sync_master and not self._progression_pending():
|
||||
self.master_sync.settle(self.client, self.snapshot)
|
||||
present = self.snapshot.monsters
|
||||
self.growth_cache = {mid: entry for mid, entry in self.growth_cache.items() if mid in present}
|
||||
@@ -79,15 +598,18 @@ class Engine:
|
||||
self.snapshot.raw["monsters"] = rows
|
||||
self.gift_planner.apply_confirmed(self.snapshot)
|
||||
self.sweeper.recover_reward_event(self.snapshot, getattr(getattr(self.client, "trace", None), "path", None))
|
||||
self._refresh_progression_cache()
|
||||
return self.snapshot
|
||||
|
||||
def master_sync_due(self):
|
||||
return not self.demo and bool(self.master_sync.pending(self.snapshot))
|
||||
return not self.demo and not self._progression_pending() and bool(self.master_sync.pending(self.snapshot))
|
||||
|
||||
@account_serial
|
||||
def sync_master(self):
|
||||
self.read_snapshot()
|
||||
return self.snapshot, self.plans(), "已同步等级 / 体力"
|
||||
|
||||
@account_serial
|
||||
def refresh_stages(self):
|
||||
self.auto = False
|
||||
if not self.demo:
|
||||
@@ -118,6 +640,8 @@ class Engine:
|
||||
entry.update({field: row[field] for field in ("gAtk", "gDef", "gHp", "gDex") if row.get(field) is not None})
|
||||
|
||||
def settle_pending_growth(self, force=False):
|
||||
if self._progression_pending():
|
||||
return False
|
||||
pending = self.snapshot.growth_pending(self.catalog)
|
||||
now = time.monotonic()
|
||||
if not pending or not force and all(now - self.growth_attempts.get(key, -1e12) < 60 for key in pending):
|
||||
@@ -130,11 +654,12 @@ class Engine:
|
||||
return True
|
||||
|
||||
def growth_sync_due(self):
|
||||
if self.snapshot is None:
|
||||
if self.snapshot is None or self._progression_pending():
|
||||
return False
|
||||
now = time.monotonic()
|
||||
return any(now - self.growth_attempts.get(key, -1e12) >= 60 for key in self.snapshot.growth_pending(self.catalog))
|
||||
|
||||
@account_serial
|
||||
def sync_growth(self):
|
||||
if self.demo:
|
||||
if self.snapshot is None:
|
||||
@@ -151,6 +676,7 @@ class Engine:
|
||||
message += f";仍有 {len(pending)} 只等待服务器确认阶段或资质"
|
||||
return self.snapshot, self.plans(), message
|
||||
|
||||
@account_serial
|
||||
def keep_alive(self):
|
||||
if self.demo:
|
||||
return "离线演示无需心跳"
|
||||
@@ -158,6 +684,8 @@ class Engine:
|
||||
self.client.call("heartBeatService/keepAlive")
|
||||
return "会话心跳已更新"
|
||||
|
||||
@single_flight
|
||||
@account_serial
|
||||
def poll(self, *, hatch_only=False, defer_hatch=False):
|
||||
self.last_executed = False
|
||||
settled = False
|
||||
@@ -177,6 +705,12 @@ class Engine:
|
||||
self.sweeper.recovered_event = False
|
||||
if self.snapshot.growth_pending(self.catalog):
|
||||
message += ";成长状态等待服务器确认,将自动检查"
|
||||
if self.demo:
|
||||
self._refresh_progression_cache()
|
||||
if self._progression_pending():
|
||||
self.pending_hatches = []
|
||||
pending = self.battle_journal.pending(self.snapshot) or {}
|
||||
return self.snapshot, [], message + ";" + (pending.get("message") or "有待核对的任务 / 战斗,已暂停冲突操作")
|
||||
try:
|
||||
plans = self.plans()
|
||||
except (ValueError, TypeError, KeyError, AttributeError) as error:
|
||||
@@ -188,6 +722,8 @@ class Engine:
|
||||
action = None
|
||||
if self.auto and action is not None:
|
||||
self.last_executed = True
|
||||
if action.kind == "progression":
|
||||
return self._run_progression_intent(action.payload["intent"])
|
||||
if action.kind == "daily":
|
||||
entry = next(row for row in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger) if row.action == action)
|
||||
self.claim_daily_entry(entry)
|
||||
@@ -209,7 +745,7 @@ class Engine:
|
||||
if self.demo:
|
||||
self.apply_demo(action)
|
||||
else:
|
||||
response = self.client.call(action.path, action.payload)
|
||||
response = self._execute_legacy_task(action) if action.kind.startswith("quest_") else self.client.call(action.path, action.payload)
|
||||
if action.kind == "buy":
|
||||
self.record_draw(response.get("eggs") or [])
|
||||
if action.kind == "gift":
|
||||
@@ -241,10 +777,32 @@ class Engine:
|
||||
message += ";" + ";".join(dict.fromkeys(self.planner.notes))
|
||||
return self.snapshot, plans, message
|
||||
|
||||
def _execute_legacy_task(self, action):
|
||||
"""Keep the commission scheduler, with the same durable replay barrier."""
|
||||
payload = action.payload
|
||||
task = next((task for task in self.snapshot.raw.get("currentTasks", [])
|
||||
if str(task.get("id")) == str(payload.get("taskId"))), {})
|
||||
intent = {"kind": action.kind, "description": action.description, "path": action.path, "payload": payload,
|
||||
"task_id": payload.get("taskId"), "task_type_id": payload.get("taskTypeId"), "step_number": task.get("curStep")}
|
||||
record = self.battle_journal.begin(self.snapshot, intent)
|
||||
try:
|
||||
self.battle_journal.update(record, "request_pending")
|
||||
response = self.battles._call(self.client, action.path, payload)
|
||||
self.battle_journal.update(record, "acknowledged", response=gameplay_response(response))
|
||||
return response
|
||||
except Exception as error:
|
||||
self.battle_journal.update(record, "unknown", message="委托请求结果未确认,禁止自动重试", error_type=type(error).__name__)
|
||||
raise
|
||||
|
||||
def plans(self):
|
||||
if self.snapshot is None or self._progression_pending():
|
||||
self.pending_hatches = []
|
||||
return []
|
||||
if self.policy.keep_better_quality or self.policy.gift_auto_representative:
|
||||
self.cultivation.select(self.snapshot)
|
||||
quests = self.tasks.plan(self.snapshot, self.quest_policy, self.policy)
|
||||
# One owner for commission writes; never accept the same offer through
|
||||
# both the legacy planner and the full progression planner.
|
||||
quests = [] if self._commission_planner_available else self.tasks.plan(self.snapshot, self.quest_policy, self.policy)
|
||||
types, eggs = self.tasks.reservations(self.snapshot)
|
||||
reserved = dict(self.policy.reserved_eggs)
|
||||
for key, count in eggs.items():
|
||||
@@ -259,18 +817,26 @@ class Engine:
|
||||
gifts = self.gift_planner.plan(self.snapshot, policy, self.quest_policy)
|
||||
ranch = self.planner.plan(self.snapshot, policy, left)
|
||||
self.planner.notes.extend(self.gift_planner.notes)
|
||||
return daily + quests + gifts + ranch + sweep_actions
|
||||
progression = [Action("progression", value(intent, "description", "推进任务"), "", {"intent": intent})
|
||||
for intent in self._progression_intents if not value(intent, "block_reason") and self._intent_policy(intent).enabled]
|
||||
if quests and quests[0].kind == "quest_reset":
|
||||
return daily + quests + progression[:1] + gifts + ranch + sweep_actions
|
||||
return daily + progression[:1] + quests + gifts + ranch + sweep_actions
|
||||
|
||||
@account_serial
|
||||
def claim_daily_entry(self, entry):
|
||||
self._require_no_battle()
|
||||
self.daily_ledger.record(self.snapshot, entry.key)
|
||||
if not self.demo:
|
||||
self.client.call(entry.action.path, entry.action.payload)
|
||||
self.read_snapshot()
|
||||
|
||||
@account_serial
|
||||
def claim_daily(self):
|
||||
self.auto = False
|
||||
if not self.demo:
|
||||
self.read_snapshot()
|
||||
self._require_no_battle()
|
||||
# Fresh status after every claim, bounded by the initially available IDs.
|
||||
keys = [row.key for row in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger)]
|
||||
done = 0
|
||||
@@ -290,6 +856,7 @@ class Engine:
|
||||
parts = [f"{self.catalog.monster(key).get('name', key)} ×{count}" for key, count in totals.items()]
|
||||
self.last_draw = f"抽蛋完成,共 {sum(totals.values())} 枚:" + "、".join(parts[:8]) + ("…" if len(parts) > 8 else "")
|
||||
|
||||
@account_serial
|
||||
def set_monster_lock(self, monster_ids, locked):
|
||||
self.auto = False
|
||||
ids = list(dict.fromkeys(int(mid) for mid in monster_ids))
|
||||
@@ -297,6 +864,7 @@ class Engine:
|
||||
raise ValueError("请先选择需要锁定 / 解锁的魔物")
|
||||
if not self.demo:
|
||||
self.read_snapshot()
|
||||
self._require_no_battle()
|
||||
monsters = self.snapshot.monsters
|
||||
if any(mid not in monsters for mid in ids):
|
||||
raise ValueError("选中的魔物已不存在,请刷新后重新选择")
|
||||
@@ -317,10 +885,12 @@ class Engine:
|
||||
message = ("[演示] " if self.demo else "") + f"已{'锁定' if locked else '解锁'} {changed} 只魔物;自动执行已暂停"
|
||||
return self.snapshot, self.plans(), message
|
||||
|
||||
@account_serial
|
||||
def manage_monsters(self, kind, monster_ids, target_id=0):
|
||||
self.auto = False
|
||||
if not self.demo:
|
||||
self.read_snapshot()
|
||||
self._require_no_battle()
|
||||
actions = manual_monster_actions(self.catalog, self.snapshot, kind, monster_ids, target_id)
|
||||
for action in actions:
|
||||
if self.demo:
|
||||
@@ -335,10 +905,12 @@ class Engine:
|
||||
raise ValueError("操作已返回,但魔物记录尚未更新;请刷新核对,不会重复提交")
|
||||
return self.snapshot, self.plans(), ("[演示] " if self.demo else "") + ";".join(a.description for a in actions) + ";自动执行已暂停"
|
||||
|
||||
@account_serial
|
||||
def expand(self, quote):
|
||||
self.auto = False
|
||||
if not self.demo:
|
||||
self.read_snapshot()
|
||||
self._require_no_battle()
|
||||
fresh = expansion_quote(self.catalog, self.snapshot, quote.kind, quote.currency, quote.position)
|
||||
if fresh != quote:
|
||||
raise ValueError("扩建费用或次数已变化,请刷新后重新确认")
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
"""Verified, offline progression configuration from the original 1.9.68 APK.
|
||||
|
||||
The application reads derived static files only. Stage battle dictionaries live
|
||||
in a separate archive and are read one stage at a time by a battle worker.
|
||||
Nothing in this module opens an APK, imports the research tools, or uses a
|
||||
network client. The existing commission-only Catalog is deliberately untouched.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from functools import lru_cache
|
||||
import gzip
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import zipfile
|
||||
|
||||
|
||||
DATA_DIR = Path(__file__).with_name("data")
|
||||
MANIFEST_NAME = "progression_manifest.json"
|
||||
DATA_NAME = "progression.json.gz"
|
||||
BATTLES_NAME = "progression_battles.zip"
|
||||
SCHEMA_VERSION = 1
|
||||
ORIGINAL_APK_SHA256 = "01678ee3a8465d818d32cbbd94baa0d8253b04b4c57b70ebc5544ed341f1015d"
|
||||
|
||||
|
||||
class ProgressionDataError(ValueError):
|
||||
"""Missing, inconsistent, or damaged derived configuration."""
|
||||
|
||||
|
||||
class ProgressionData:
|
||||
"""Small task/index data; optional stage battles are loaded lazily.
|
||||
|
||||
Public tables: tasks/task_info, stages/stage_info, scripts, setting,
|
||||
game_setting, npc_info, stage_sp, areas, mines, farming, manifest. ``data`` exposes the index
|
||||
mapping for integrations. This is shared read-only configuration; callers
|
||||
must keep character state and credentials elsewhere.
|
||||
"""
|
||||
|
||||
def __init__(self, data=None, *, directory=None):
|
||||
self.directory = Path(directory or DATA_DIR)
|
||||
self.manifest = {}
|
||||
if data is None:
|
||||
try:
|
||||
self.manifest = json.loads((self.directory / MANIFEST_NAME).read_text(encoding="utf-8"))
|
||||
if self.manifest.get("schema_version") != SCHEMA_VERSION:
|
||||
raise ProgressionDataError("Unsupported progression manifest version")
|
||||
if self.manifest.get("source", {}).get("apk_sha256") != ORIGINAL_APK_SHA256:
|
||||
raise ProgressionDataError("Progression data is not bound to the original APK")
|
||||
artifact = (self.directory / DATA_NAME).read_bytes()
|
||||
expected = self.manifest["artifacts"][DATA_NAME]["sha256"]
|
||||
if hashlib.sha256(artifact).hexdigest() != expected:
|
||||
raise ProgressionDataError("Progression artifact hash mismatch")
|
||||
decoded = gzip.decompress(artifact)
|
||||
if hashlib.sha256(decoded).hexdigest() != self.manifest["artifacts"][DATA_NAME]["decoded_sha256"]:
|
||||
raise ProgressionDataError("Progression decoded data hash mismatch")
|
||||
data = json.loads(decoded)
|
||||
except (OSError, KeyError, ValueError, EOFError) as exc:
|
||||
if isinstance(exc, ProgressionDataError):
|
||||
raise
|
||||
raise ProgressionDataError(f"Cannot load static progression data: {exc}") from exc
|
||||
if not isinstance(data, dict) or not isinstance(data.get("task_info"), dict):
|
||||
raise ProgressionDataError("Progression data must contain a full task_info mapping")
|
||||
if data.get("schema_version", SCHEMA_VERSION) != SCHEMA_VERSION:
|
||||
raise ProgressionDataError("Unsupported progression data version")
|
||||
self.data = data
|
||||
self.tasks = self.task_info = data["task_info"]
|
||||
self.stages = self.stage_info = data.get("stage_info", {})
|
||||
self.scripts = data.get("scripts", {})
|
||||
self.setting = data.get("setting", {})
|
||||
self.game_setting = data.get("game_setting", {})
|
||||
self.npc_info = data.get("npc_info", {})
|
||||
self.stage_sp = data.get("stage_sp", {})
|
||||
self.areas = (data.get("area_info") or {}).get("areaInfo", {})
|
||||
self.area_maps = (data.get("area_info") or {}).get("areaMap", {})
|
||||
self.mines = (data.get("mine_info") or {}).get("mines", {})
|
||||
self.positions = {}
|
||||
self.farming = data.get("farming") or {"kills": {}, "items": {}}
|
||||
for parent, area in self.area_maps.items():
|
||||
for entry in area.get("positions") or []:
|
||||
if entry.get("posId"):
|
||||
self.positions.setdefault(entry["posId"], []).append(entry | {"parent_area": parent})
|
||||
|
||||
def task(self, type_id):
|
||||
return self.tasks.get(str(type_id))
|
||||
|
||||
def stage(self, stage_id):
|
||||
return self.stages.get(str(stage_id))
|
||||
|
||||
def script(self, name):
|
||||
return self.scripts.get(str(name))
|
||||
|
||||
def npc_name(self, key):
|
||||
return self.npc_info.get(str(key), {}).get("name") or str(key or "")
|
||||
|
||||
def stage_battle(self, stage_id, difficulty=1):
|
||||
"""Read one original stage's battle config, never the entire archive.
|
||||
|
||||
Call this from the battle worker, not the GUI thread. The per-member
|
||||
digest is itself covered by the checked index artifact digest.
|
||||
"""
|
||||
stage_id = str(stage_id)
|
||||
stage = self.stage(stage_id) or {}
|
||||
# Injected data can carry full stage dictionaries for offline tests.
|
||||
level = (stage.get("level") or {}).get(str(difficulty), {})
|
||||
if "battle" in level:
|
||||
return level["battle"]
|
||||
record = self.data.get("battle_members", {}).get(stage_id)
|
||||
if not record:
|
||||
raise ProgressionDataError(f"Missing original battle configuration for stage {stage_id}")
|
||||
try:
|
||||
with zipfile.ZipFile(self.directory / BATTLES_NAME) as archive:
|
||||
raw = archive.read(record["member"])
|
||||
if hashlib.sha256(raw).hexdigest() != record["sha256"]:
|
||||
raise ProgressionDataError(f"Stage {stage_id} battle hash mismatch")
|
||||
return json.loads(raw).get(str(difficulty))
|
||||
except (OSError, KeyError, ValueError, zipfile.BadZipFile) as exc:
|
||||
if isinstance(exc, ProgressionDataError):
|
||||
raise
|
||||
raise ProgressionDataError(f"Cannot load stage {stage_id}: {exc}") from exc
|
||||
|
||||
def task_battle(self, type_id, step_number):
|
||||
"""Resolve source battle data; step_number is the one-based wire step."""
|
||||
task = self.task(type_id) or {}
|
||||
steps = task.get("steps") or []
|
||||
if not 1 <= int(step_number) <= len(steps):
|
||||
raise ProgressionDataError("Task battle step is outside the configured task")
|
||||
step = steps[int(step_number) - 1]
|
||||
if step.get("statusType") == "passStage":
|
||||
value = step.get("statusValue") or {}
|
||||
return self.stage_battle(value["stage"], value.get("level", 1))
|
||||
if step.get("statusType") == "battle":
|
||||
return step.get("battle")
|
||||
raise ProgressionDataError("Task step is not a battle")
|
||||
|
||||
|
||||
GameData = ProgressionData
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def load_progression_data():
|
||||
"""Load the packaged static index once; does not parse an APK."""
|
||||
return ProgressionData()
|
||||
+271
-50
@@ -19,7 +19,9 @@ from .login import PasswordLogin, device_id, server_labels
|
||||
from .quests import QuestPolicy
|
||||
from .daily import DailyPolicy
|
||||
from .sweeping import SweepPolicy
|
||||
from .progression import ProgressionPolicy
|
||||
from .activity_gui import ActivityPages
|
||||
from .progression_gui import ProgressionPages, prepare_progression_views
|
||||
from .presentation import Presented, prepare_views, monster_rows
|
||||
from .credentials import CredentialStore
|
||||
from .debug import TraceLog
|
||||
@@ -27,13 +29,13 @@ from .debug_window import DebugWindow
|
||||
from .sessions import SessionStore, identity
|
||||
from .inventory_gui import ITEM_TYPES, InventoryTable
|
||||
from .ranch_gui import RanchView
|
||||
from .policy_io import portable_config, import_config
|
||||
from .policy_io import portable_config, import_config, checked_progression_policy
|
||||
from .table_widgets import table_item
|
||||
from .stage_cache import StageCache
|
||||
from .drop_statistics import SweepStatistics
|
||||
from .statistics_gui import StatisticsPage
|
||||
|
||||
APP_VERSION = "1.1.1"
|
||||
APP_VERSION = "1.2.0.dev1"
|
||||
GAME_VERSION = "1.9.68"
|
||||
|
||||
ROOT = Path(sys.executable).parent if getattr(sys, "frozen", False) else Path(__file__).resolve().parent.parent
|
||||
@@ -109,7 +111,7 @@ def fill_table(widget, rows, sorting=True):
|
||||
widget.setSortingEnabled(sorting)
|
||||
|
||||
|
||||
class Window(ActivityPages, W.QMainWindow):
|
||||
class Window(ProgressionPages, ActivityPages, W.QMainWindow):
|
||||
network_event = C.Signal(object)
|
||||
profile_changed = C.Signal(str)
|
||||
|
||||
@@ -148,7 +150,15 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.busy, self.monitoring = False, False
|
||||
self.active_job = None
|
||||
self.pending_preview = False
|
||||
self.pending_policy = None
|
||||
self.logout_phase = None
|
||||
self.pending_monster_view = False
|
||||
self.monster_data_pending = False
|
||||
self.pending_schedule = False
|
||||
self.monster_view_visible = False
|
||||
self.presentation_active = True
|
||||
self.engine.presentation_active = True
|
||||
self.engine.progression_view_active = False
|
||||
self.latest_render = None
|
||||
self.prepared_views = None
|
||||
self.next_poll = 0
|
||||
@@ -293,6 +303,8 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.policy_page = self.policy_tab(embedded=True)
|
||||
self.gifting_tab()
|
||||
self.automation_tab()
|
||||
self.progression_tab()
|
||||
self.battle_records_tab()
|
||||
self.yield_tab()
|
||||
self.quests_tab()
|
||||
self.maps_tab()
|
||||
@@ -303,7 +315,8 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.plans = table(["操作", "下一步计划(每轮只执行一项,并重新读取状态)"])
|
||||
self.tabs.addTab(self.plans, "执行计划")
|
||||
order = [self.tabs.widget(0), self.slot_page, self.inventory_tabs, self.room_page,
|
||||
self.daily_page, self.automation_page, self.gift_page, self.quests_table.parentWidget(), self.map_page, self.analysis_page,
|
||||
self.daily_page, self.automation_page, self.progression_page, self.battle_records_page, self.gift_page,
|
||||
self.quests_table.parentWidget(), self.map_page, self.analysis_page,
|
||||
self.plans, self.yields.parentWidget()]
|
||||
for page in order:
|
||||
self.tabs.addTab(page, self.tabs.tabText(self.tabs.indexOf(page)))
|
||||
@@ -614,9 +627,13 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
del blocker
|
||||
|
||||
def start_workflow(self):
|
||||
if self.closed or self.logout_phase is not None:
|
||||
return
|
||||
try:
|
||||
policy = self.read_policy()
|
||||
other = self.quest_enabled.isChecked() or self.daily_enabled.isChecked() or self.map_enabled.isChecked() or policy.gift_enabled
|
||||
progression = self.read_progression_policy()
|
||||
other = (self.quest_enabled.isChecked() or self.daily_enabled.isChecked() or self.map_enabled.isChecked()
|
||||
or policy.gift_enabled or progression.enabled)
|
||||
if not (policy.enabled and any((policy.buy, policy.fill, policy.dispatch, policy.collect, policy.feed))) and not other:
|
||||
self.report("请先勾选至少一项功能,并启用对应策略")
|
||||
self.stop_workflow()
|
||||
@@ -627,8 +644,8 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.tabs.setCurrentWidget(self.egg_page)
|
||||
self.stop_workflow()
|
||||
return
|
||||
except ValueError:
|
||||
self.report("请先修正牧场策略中的保留编号和数量")
|
||||
except ValueError as error:
|
||||
self.report("请先修正策略输入:" + str(error))
|
||||
self.stop_workflow()
|
||||
return
|
||||
self.save_config(quiet=True)
|
||||
@@ -646,6 +663,7 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
def stop_workflow(self):
|
||||
self.set_strategy_checked(False)
|
||||
self.engine.auto = False
|
||||
self.cancel_progression()
|
||||
self.pending_execute = False
|
||||
self.next_gift = float("inf")
|
||||
self.update_gift_clock()
|
||||
@@ -687,6 +705,13 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
state = "策略已开启" if active else "策略已关闭"
|
||||
state += " · 状态自动刷新" if self.monitoring else ""
|
||||
self.workflow_status.setText(("演示 · " if self.engine.demo else "已登录 · ") + state)
|
||||
if hasattr(self, "progression_enabled"):
|
||||
enabled = [label for checked, label in ((self.ranch_enabled.isChecked(), "牧场 / 孵蛋"),
|
||||
(self.gift_enabled.isChecked(), "赠礼"), (self.quest_enabled.isChecked(), "委托"),
|
||||
(self.map_enabled.isChecked(), "扫荡"), (self.daily_enabled.isChecked(), "每日事务"),
|
||||
(self.progression_enabled.isChecked(), "主线推进")) if checked]
|
||||
self.workflow_status.setText(self.workflow_status.text() + ";已选功能:" + ("、".join(enabled) or "无"))
|
||||
self.update_progression_status()
|
||||
market = self.catalog.data.get("markets", {}).get(self.market.currentData(), {})
|
||||
snapshot = self.engine.snapshot
|
||||
if snapshot:
|
||||
@@ -1047,6 +1072,10 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.refresh_maps()
|
||||
elif tab is self.analysis_page:
|
||||
self.refresh_analysis()
|
||||
elif tab is self.progression_page:
|
||||
self.refresh_progression()
|
||||
elif tab is self.battle_records_page:
|
||||
self.refresh_progression_records()
|
||||
else:
|
||||
self.refresh()
|
||||
|
||||
@@ -1128,16 +1157,55 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.render_catalog()
|
||||
|
||||
def logout_and_clear(self):
|
||||
if self.busy:
|
||||
self.report("请等待当前操作完成,再清除登录记录")
|
||||
if self.closed or self.logout_phase is not None:
|
||||
return
|
||||
keys = [entry["session_id"] for entry in self.session_store.entries()]
|
||||
engine = self.engine
|
||||
resume_monitoring, resume_heartbeat = self.monitoring, engine.heartbeat_enabled
|
||||
resume_timer = self.timer.isActive()
|
||||
self.logout_phase = "confirming"
|
||||
self.timer.stop()
|
||||
self.monitoring = False
|
||||
engine.heartbeat_enabled = False
|
||||
self.stop_workflow()
|
||||
self.pending_refresh = self.pending_policy = None
|
||||
self.pending_preview = self.pending_monster_view = self.pending_progression_view = False
|
||||
self.pending_schedule = False
|
||||
text = "将退出登录,并删除当前账号页签保存的会话和账号密码。\n培养策略、日志及其他账号的记录不受影响。"
|
||||
if W.QMessageBox.question(self, "清除登录记录", text, W.QMessageBox.StandardButton.Yes | W.QMessageBox.StandardButton.No,
|
||||
W.QMessageBox.StandardButton.No) != W.QMessageBox.StandardButton.Yes:
|
||||
return
|
||||
self.demo()
|
||||
try:
|
||||
confirmed = W.QMessageBox.question(self, "清除登录记录", text,
|
||||
W.QMessageBox.StandardButton.Yes | W.QMessageBox.StandardButton.No,
|
||||
W.QMessageBox.StandardButton.No) == W.QMessageBox.StandardButton.Yes
|
||||
except Exception:
|
||||
self.logout_phase = None
|
||||
if resume_timer and not self.closed:
|
||||
self.timer.start(500)
|
||||
raise
|
||||
if self.closed:
|
||||
return
|
||||
if not confirmed:
|
||||
self.logout_phase = None
|
||||
if self.engine is engine:
|
||||
self.monitoring, engine.heartbeat_enabled = resume_monitoring, resume_heartbeat
|
||||
if resume_timer:
|
||||
self.timer.start(500)
|
||||
return
|
||||
self.logout_phase = "waiting"
|
||||
self.statusBar().showMessage("正在退出登录;当前请求完成后清除登录记录" if self.busy else "正在退出登录")
|
||||
if not self.busy:
|
||||
self.finish_logout()
|
||||
|
||||
def finish_logout(self):
|
||||
if self.busy or self.logout_phase != "waiting":
|
||||
return
|
||||
self.logout_phase = "finishing"
|
||||
try:
|
||||
self.pending_refresh = self.pending_policy = None
|
||||
self.pending_execute = self.pending_preview = self.pending_schedule = False
|
||||
self.pending_monster_view = self.pending_progression_view = False
|
||||
self.demo()
|
||||
if not self.engine.demo or self.engine.client is not None:
|
||||
raise ValueError("原登录连接尚未释放")
|
||||
keys = [entry["session_id"] for entry in self.session_store.entries()]
|
||||
for key in keys:
|
||||
self.session_store.remove(key)
|
||||
self.credentials.save("", "", False)
|
||||
@@ -1148,19 +1216,50 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.reload_saved_sessions()
|
||||
self.login_status.setText("已退出登录并清除当前账号页签的登录记录")
|
||||
self.report("已清除当前账号页签的登录记录")
|
||||
except (OSError, ValueError, KeyError):
|
||||
self.report("部分登录记录未能删除,请检查本地状态目录")
|
||||
except (OSError, ValueError, KeyError, RuntimeError) as error:
|
||||
self.report("退出登录或清除记录未完成:" + str(error) + ";策略保持停止")
|
||||
finally:
|
||||
self.logout_phase = None
|
||||
self.monitoring = False
|
||||
self.engine.auto = self.engine.heartbeat_enabled = False
|
||||
if not self.closed:
|
||||
self.timer.start(500)
|
||||
if self.engine.demo:
|
||||
self.refresh()
|
||||
elif self.close_after_job:
|
||||
C.QTimer.singleShot(0, self.close)
|
||||
|
||||
def run_job(self, kind, function):
|
||||
"""All task requests share the account's existing serial worker."""
|
||||
return self.submit(kind, function)
|
||||
|
||||
def update_policy(self, value=None):
|
||||
"""Apply a whole policy set between requests, never during a worker call."""
|
||||
if value is None:
|
||||
value = self.config_value()
|
||||
policies = {key: cls(**value[key]) for key, cls in (("policy", Policy), ("quest_policy", QuestPolicy),
|
||||
("daily_policy", DailyPolicy), ("sweep_policy", SweepPolicy))}
|
||||
policies["progression_policy"] = checked_progression_policy(value.get("progression_policy", {}))
|
||||
if self.busy:
|
||||
self.pending_policy = policies
|
||||
return False
|
||||
for key, policy in policies.items():
|
||||
setattr(self.engine, key, policy)
|
||||
return True
|
||||
|
||||
def submit(self, kind, function):
|
||||
if self.busy or self.closed:
|
||||
if self.busy or self.closed or self.logout_phase is not None:
|
||||
return
|
||||
self.busy = True
|
||||
self.update_monster_actions()
|
||||
catalog, engine = self.catalog, self.engine
|
||||
self.sync_presentation_visibility()
|
||||
progression_visible = self.presentation_active and self.tabs.currentWidget() is self.progression_page
|
||||
records_visible = self.presentation_active and self.tabs.currentWidget() is self.battle_records_page
|
||||
def background():
|
||||
started = time.perf_counter()
|
||||
value = function()
|
||||
if kind in ("poll", "hatch", "monster_lock", "manual_monsters", "expansion", "growth_sync", "master_sync", "map_refresh", "daily_claim", "connected"):
|
||||
if kind in ("poll", "hatch", "monster_lock", "manual_monsters", "expansion", "growth_sync", "master_sync", "map_refresh", "daily_claim", "connected", "policy_preview", "progression_refresh", "progression_run"):
|
||||
snapshot = value[1] if kind == "connected" else value[0]
|
||||
managed = set() if kind == "connected" else set(engine.planner.managed)
|
||||
preparing = time.perf_counter()
|
||||
@@ -1174,7 +1273,12 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
statistics = SweepStatistics(catalog, folder / "sweep_rewards.sqlite3")
|
||||
client = value[0]
|
||||
statistics.import_log(snapshot.raw["master"]["id"], getattr(getattr(client, "trace", None), "path", None))
|
||||
views = prepare_views(catalog, snapshot, managed, cache, statistics)
|
||||
views = prepare_views(catalog, snapshot, managed, cache, statistics,
|
||||
include_monsters=self.presentation_active and not self.closed and (self.monster_view_visible or kind == "connected"))
|
||||
explicit_progression = kind in ("progression_refresh", "progression_run")
|
||||
if kind != "connected" and (progression_visible or records_visible or explicit_progression):
|
||||
views.progression = prepare_progression_views(engine,
|
||||
tasks=progression_visible or explicit_progression, records=records_visible or explicit_progression)
|
||||
return Presented(value, views, (time.perf_counter() - preparing) * 1000, (time.perf_counter() - started) * 1000)
|
||||
return value
|
||||
job = Job(kind, background)
|
||||
@@ -1189,6 +1293,30 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.busy = False
|
||||
self.update_monster_actions()
|
||||
self.active_job = None
|
||||
if self.logout_phase is not None:
|
||||
if self.logout_phase == "waiting":
|
||||
C.QTimer.singleShot(0, self.finish_logout)
|
||||
elif self.close_after_job:
|
||||
C.QTimer.singleShot(0, self.close)
|
||||
return
|
||||
if not self.presentation_active or self.tabs.currentWidget() not in (self.progression_page, self.battle_records_page):
|
||||
self.pending_progression_view = False
|
||||
if not self.monster_view_visible:
|
||||
self.pending_monster_view = False
|
||||
if self.pending_policy is not None and not self.closed:
|
||||
policies, self.pending_policy = self.pending_policy, None
|
||||
progression_changed = asdict(getattr(self.engine, "progression_policy", ProgressionPolicy())) != asdict(policies["progression_policy"])
|
||||
for key, policy in policies.items():
|
||||
setattr(self.engine, key, policy)
|
||||
if progression_changed:
|
||||
self.progression_views = None
|
||||
if self.presentation_active and self.tabs.currentWidget() in (self.progression_page, self.battle_records_page):
|
||||
self.pending_progression_view = True
|
||||
if self.pending_schedule and not self.closed and not self.close_after_job:
|
||||
self.pending_schedule = False
|
||||
self.schedule()
|
||||
if self.busy:
|
||||
return
|
||||
if self.close_after_job:
|
||||
C.QTimer.singleShot(0, self.close)
|
||||
elif self.pending_refresh is not None:
|
||||
@@ -1196,6 +1324,10 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
C.QTimer.singleShot(0, lambda: self.refresh_page(tab))
|
||||
elif self.pending_preview and not self.closed:
|
||||
C.QTimer.singleShot(0, self.preview_cultivation)
|
||||
elif self.pending_monster_view and not self.closed:
|
||||
self.request_monster_views()
|
||||
elif self.pending_progression_view and not self.closed:
|
||||
C.QTimer.singleShot(0, lambda: self.request_progression_views(force=True))
|
||||
elif self.pending_execute and self.monitoring and self.strategy_toggle.isChecked() and not self.closed:
|
||||
self.pending_execute = False
|
||||
C.QTimer.singleShot(0, lambda: self.refresh(automated=True))
|
||||
@@ -1205,6 +1337,8 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
metrics = None
|
||||
if isinstance(value, Presented):
|
||||
self.prepared_views = value.views
|
||||
if value.views.progression is not None:
|
||||
self.accept_progression_views(value.views.progression)
|
||||
metrics = value
|
||||
value = value.value
|
||||
started = time.perf_counter()
|
||||
@@ -1219,9 +1353,9 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
note="worker总耗时包含网络;大列表在后续短批次更新")
|
||||
|
||||
def apply_result(self, kind, value):
|
||||
if kind in ("poll", "hatch", "monster_lock", "manual_monsters", "expansion", "growth_sync", "master_sync", "map_refresh", "daily_claim", "policy_preview"):
|
||||
if kind in ("poll", "hatch", "monster_lock", "manual_monsters", "expansion", "growth_sync", "master_sync", "map_refresh", "daily_claim", "policy_preview", "progression_refresh", "progression_run"):
|
||||
snapshot, plans, message = value
|
||||
if kind != "policy_preview" and not self.engine.demo and not self.closed:
|
||||
if kind != "policy_preview" and not self.engine.demo and not self.closed and self.logout_phase is None:
|
||||
self.monitoring = True
|
||||
self.engine.heartbeat_enabled = True
|
||||
self.render(snapshot, plans)
|
||||
@@ -1240,6 +1374,13 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.prepared_views.drop_statistics = value
|
||||
self.analysis_page.set_data(self.catalog, value)
|
||||
self.report("已从本地刷新掉落统计")
|
||||
elif kind == "progression_view":
|
||||
self.accept_progression_views(value)
|
||||
self.render_progression()
|
||||
elif kind == "monster_view":
|
||||
if value.snapshot is self.engine.snapshot:
|
||||
self.prepared_views = value
|
||||
self.render_current_page()
|
||||
elif kind == "connected":
|
||||
client, snapshot = value
|
||||
if self.connection_guard and not self.connection_guard(client.session):
|
||||
@@ -1251,6 +1392,8 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
if self.engine.client and self.engine.client is not client:
|
||||
self.engine.client.close()
|
||||
self.engine = Engine(self.catalog, client, self.state / "purchase_budget.json")
|
||||
self.sync_presentation_visibility()
|
||||
self.clear_progression_views()
|
||||
self.engine.snapshot = snapshot
|
||||
if self.prepared_views and self.prepared_views.snapshot is snapshot and self.prepared_views.stage_cache:
|
||||
self.engine.stage_cache = self.prepared_views.stage_cache
|
||||
@@ -1274,16 +1417,15 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.mode.setText("已登录")
|
||||
self.login_status.setText("已进入所选区服并读取角色")
|
||||
self.stop_workflow()
|
||||
self.monitoring = not self.closed
|
||||
self.monitoring = not self.closed and self.logout_phase is None
|
||||
if self.logout_phase is not None:
|
||||
self.engine.heartbeat_enabled = False
|
||||
self.next_poll = 0
|
||||
self.account.setReadOnly(True)
|
||||
self.render(snapshot, [])
|
||||
try:
|
||||
self.engine.policy = self.read_policy()
|
||||
self.engine.quest_policy = self.read_quest_policy()
|
||||
self.engine.daily_policy = self.read_daily_policy()
|
||||
self.engine.sweep_policy = self.read_sweep_policy()
|
||||
fill_table(self.plans, [[action.kind, action.description] for action in self.engine.plans()])
|
||||
self.update_policy()
|
||||
self.pending_preview = True
|
||||
except (ValueError, TypeError, KeyError, AttributeError) as error:
|
||||
self.report("状态已显示;策略暂不可用:" + str(error))
|
||||
self.profile_changed.emit(self.session_label or snapshot.raw["master"].get("roleName", "已连接"))
|
||||
@@ -1326,6 +1468,9 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
|
||||
@C.Slot(str)
|
||||
def error(self, message):
|
||||
self.pending_monster_view = False
|
||||
self.monster_data_pending = False
|
||||
self.monster_render_timer.stop()
|
||||
last = self.trace.events[-1] if self.trace.events else {}
|
||||
if last.get("kind") != "error" or last.get("message") != self.trace.redact(message):
|
||||
self.trace.emit("error", "界面 / 任务处理", scope="local", message=message)
|
||||
@@ -1369,23 +1514,21 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
battle_tasks=self.quest_battles.isChecked(), item_reserves=reserves)
|
||||
|
||||
def refresh(self, checked=False, *, automated=False, hatch_only=False):
|
||||
if self.busy or self.closed:
|
||||
if self.busy or self.closed or self.logout_phase is not None:
|
||||
return
|
||||
try:
|
||||
self.engine.policy = self.read_policy()
|
||||
self.engine.quest_policy = self.read_quest_policy()
|
||||
self.engine.daily_policy = self.read_daily_policy()
|
||||
self.engine.sweep_policy = self.read_sweep_policy()
|
||||
self.update_policy()
|
||||
self.engine.auto = self.strategy_toggle.isChecked() and automated and self.monitoring
|
||||
if hatch_only:
|
||||
self.hatch_timer.stop()
|
||||
self.next_hatch = float("inf")
|
||||
self.submit("hatch" if hatch_only else "poll", lambda: self.engine.poll(hatch_only=hatch_only, defer_hatch=not hatch_only))
|
||||
except ValueError:
|
||||
self.run_job("hatch" if hatch_only else "poll", lambda: self.engine.poll(hatch_only=hatch_only, defer_hatch=not hatch_only))
|
||||
except ValueError as error:
|
||||
self.stop_workflow()
|
||||
self.engine.policy = Policy(enabled=False)
|
||||
self.engine.quest_policy = QuestPolicy()
|
||||
self.report("策略输入尚未完整,已关闭策略;本次继续刷新角色数据")
|
||||
self.engine.progression_policy = ProgressionPolicy()
|
||||
self.report("策略输入尚未完整,已关闭策略;本次继续刷新角色数据:" + str(error))
|
||||
self.submit("poll", self.engine.poll)
|
||||
|
||||
def poll_delay(self):
|
||||
@@ -1435,7 +1578,11 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
|
||||
def schedule(self):
|
||||
self.update_gift_clock()
|
||||
if self.busy or self.closed:
|
||||
if self.closed or self.logout_phase is not None:
|
||||
return
|
||||
if self.busy:
|
||||
if self.active_job and self.active_job.kind == "monster_view":
|
||||
self.pending_schedule = True
|
||||
return
|
||||
now = time.monotonic()
|
||||
if not self.engine.demo and self.engine.heartbeat_enabled and now - self.engine.last_heartbeat >= 240:
|
||||
@@ -1455,6 +1602,7 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
def render(self, snapshot, plans):
|
||||
self.latest_render = (snapshot, plans)
|
||||
self.engine.snapshot = snapshot
|
||||
self.refresh_progression_teams(snapshot)
|
||||
master = snapshot.raw["master"]
|
||||
self.summary.setText(f"{master.get('roleName', '')} | Lv.{master.get('level', '?')} | 经验 {self.catalog.master_experience(master)} | 金币 {master.get('money', '?')} | 氪金 {master.get('ke', '?')} | 体力 {master.get('ti', '?')}")
|
||||
decisions = {int((a.payload.get('monsterId') or a.payload.get('monsterIds') or a.payload.get('foods') or [0])[0]): a.description for a in plans if a.kind in ('sell', 'feed')}
|
||||
@@ -1496,10 +1644,23 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
if self.presentation_active:
|
||||
self.render_current_page()
|
||||
|
||||
def sync_presentation_visibility(self):
|
||||
page = self.tabs.currentWidget()
|
||||
self.engine.presentation_active = bool(self.presentation_active)
|
||||
self.engine.progression_view_active = bool(self.presentation_active and page is self.progression_page)
|
||||
self.monster_view_visible = bool(self.presentation_active and page is self.monster_page)
|
||||
|
||||
def set_presentation_active(self, active):
|
||||
self.presentation_active = active
|
||||
self.presentation_active = bool(active)
|
||||
self.sync_presentation_visibility()
|
||||
if not active:
|
||||
self.pending_monster_view = False
|
||||
if self.prepared_views:
|
||||
self.prepared_views.monsters = self.prepared_views.monster_source = None
|
||||
self.pending_progression_view = False
|
||||
self.analysis_page.row_batch.stop()
|
||||
self.progression_table.row_batch.stop()
|
||||
self.battle_records_table.row_batch.stop()
|
||||
for name in ("map_render_timer", "monster_render_timer"):
|
||||
timer = getattr(self, name, None)
|
||||
if timer:
|
||||
@@ -1512,10 +1673,19 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.render_current_page()
|
||||
|
||||
def render_current_page(self, *args):
|
||||
self.sync_presentation_visibility()
|
||||
if self.closed or not self.presentation_active or not self.latest_render:
|
||||
return
|
||||
snapshot, plans = self.latest_render
|
||||
page = self.tabs.currentWidget()
|
||||
if page not in (self.progression_page, self.battle_records_page):
|
||||
self.pending_progression_view = False
|
||||
if page is not self.monster_page:
|
||||
self.pending_monster_view = False
|
||||
for target, widget in ((self.progression_page, self.progression_table),
|
||||
(self.battle_records_page, self.battle_records_table)):
|
||||
if page is not target:
|
||||
widget.row_batch.stop()
|
||||
if page is not self.analysis_page:
|
||||
self.analysis_page.row_batch.stop()
|
||||
for name, target in (("map_render_timer", self.map_page), ("monster_render_timer", self.monster_page)):
|
||||
@@ -1557,6 +1727,8 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.render_daily()
|
||||
elif page is self.gift_page:
|
||||
self.render_gift_representatives(snapshot)
|
||||
elif page in (self.progression_page, self.battle_records_page):
|
||||
self.render_progression()
|
||||
elif page is self.target.parentWidget() or page is self.automation_page:
|
||||
self.refresh_target_choices(snapshot)
|
||||
except (ValueError, TypeError, KeyError, AttributeError) as error:
|
||||
@@ -1565,11 +1737,35 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
def render_monsters(self, snapshot):
|
||||
views = self.prepared_views
|
||||
managed = self.engine.planner.managed
|
||||
if views and views.snapshot is snapshot and views.monster_source == repr(snapshot.raw["monsters"]) and views.managed == managed:
|
||||
rows = views.monsters
|
||||
if views and views.snapshot is snapshot and views.monsters is not None and views.managed == managed:
|
||||
self.pending_monster_view = False
|
||||
if self.monster_data_pending:
|
||||
self.monster_render_timer.stop()
|
||||
self.monster_data_pending = False
|
||||
self.monsters.set_data(snapshot, views.monsters, self.feed_targets, self.gift_targets)
|
||||
else:
|
||||
rows = monster_rows(self.catalog, snapshot, managed)
|
||||
self.monsters.set_data(snapshot, rows, self.feed_targets, self.gift_targets)
|
||||
self.request_monster_views(snapshot)
|
||||
|
||||
def request_monster_views(self, snapshot=None):
|
||||
if self.closed or self.logout_phase is not None or not self.monster_view_visible:
|
||||
return
|
||||
# Rendering is still pending while the serial worker prepares its data.
|
||||
self.monster_render_timer.stop()
|
||||
self.monster_render_timer.running = True
|
||||
self.monster_data_pending = True
|
||||
if self.busy:
|
||||
self.pending_monster_view = True
|
||||
return
|
||||
snapshot = snapshot or self.engine.snapshot
|
||||
if snapshot is None:
|
||||
self.monster_render_timer.stop()
|
||||
self.monster_data_pending = False
|
||||
return
|
||||
self.pending_monster_view = False
|
||||
engine, catalog = self.engine, self.catalog
|
||||
self.run_job("monster_view", lambda: prepare_views(catalog, snapshot, engine.planner.managed,
|
||||
engine.stage_cache, engine.sweeper.statistics,
|
||||
include_monsters=self.monster_view_visible and self.presentation_active and not self.closed))
|
||||
|
||||
def refresh_target_choices(self, snapshot):
|
||||
self.update_combo(self.target, [("未设置:不自动喂养", 0)] + [(f"{self.catalog.monster(m['typeId']).get('name')} Lv.{m.get('level', 1)}/{self.catalog.max_level(m) or '?'} #{m['id']}", int(m["id"])) for m in snapshot.raw["monsters"] if m.get("process") == 3])
|
||||
@@ -1659,7 +1855,7 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.submit("connected", lambda: (client, client.snapshot()))
|
||||
|
||||
def demo(self):
|
||||
if self.busy:
|
||||
if self.busy or self.logout_phase not in (None, "finishing"):
|
||||
return
|
||||
self.monitoring = False
|
||||
self.stop_workflow()
|
||||
@@ -1669,6 +1865,8 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.engine.client.persist_session()
|
||||
self.engine.client.close()
|
||||
self.engine = Engine(self.catalog)
|
||||
self.sync_presentation_visibility()
|
||||
self.clear_progression_views()
|
||||
self.reset_map_view()
|
||||
self.analysis_page.set_data(self.catalog, {"owner": "", "totals": {}, "drops": {}})
|
||||
self.active_identity = None
|
||||
@@ -1755,6 +1953,7 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
def config_value(self):
|
||||
return {"policy": asdict(self.read_policy()), "quest_policy": asdict(self.read_quest_policy()),
|
||||
"daily_policy": asdict(self.read_daily_policy()), "sweep_policy": asdict(self.read_sweep_policy()),
|
||||
"progression_policy": asdict(self.read_progression_policy()),
|
||||
"overrides": copy.deepcopy(self.catalog.overrides),
|
||||
"log_visible": self.show_log.isChecked(), "log_sizes": self.log_splitter.sizes() if self.show_log.isChecked() else self.log_sizes,
|
||||
"yield_stars": [star for star, check in self.yield_stars.items() if check.isChecked()],
|
||||
@@ -1777,6 +1976,14 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
signal.connect(self.settings_changed)
|
||||
for widget in self.yield_stars.values():
|
||||
widget.toggled.connect(self.settings_changed)
|
||||
for key in asdict(ProgressionPolicy()):
|
||||
if key == "enabled":
|
||||
continue
|
||||
widget = getattr(self, "progression_" + key)
|
||||
signal = (widget.toggled if isinstance(widget, W.QAbstractButton) else
|
||||
widget.currentIndexChanged if isinstance(widget, W.QComboBox) else
|
||||
widget.valueChanged if hasattr(widget, "valueChanged") else widget.textChanged)
|
||||
signal.connect(self.progression_settings_changed)
|
||||
|
||||
def settings_changed(self, *args):
|
||||
if not self.closed and not self.loading_config and hasattr(self, "auto_save_timer"):
|
||||
@@ -1790,12 +1997,15 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
return
|
||||
changed = any(asdict(getattr(self.engine, key)) != value[key]
|
||||
for key in ("policy", "quest_policy", "daily_policy", "sweep_policy"))
|
||||
progression_changed = asdict(getattr(self.engine, "progression_policy", ProgressionPolicy())) != value["progression_policy"]
|
||||
changed = changed or progression_changed
|
||||
local_selection_changed = any(getattr(self.engine.policy, key) != value["policy"][key]
|
||||
for key in ("gift_auto_representative", "keep_better_quality"))
|
||||
self.engine.policy = Policy(**value["policy"])
|
||||
self.engine.quest_policy = QuestPolicy(**value["quest_policy"])
|
||||
self.engine.daily_policy = DailyPolicy(**value["daily_policy"])
|
||||
self.engine.sweep_policy = SweepPolicy(**value["sweep_policy"])
|
||||
self.update_policy(value)
|
||||
if progression_changed:
|
||||
self.progression_views = None
|
||||
if self.presentation_active and self.tabs.currentWidget() in (self.progression_page, self.battle_records_page):
|
||||
self.request_progression_views(force=True)
|
||||
if local_selection_changed:
|
||||
self.pending_preview = True
|
||||
self.preview_cultivation()
|
||||
@@ -1806,7 +2016,7 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.next_poll = 0
|
||||
self.arm_hatching()
|
||||
self.arm_gifting()
|
||||
self.statusBar().showMessage("规则已自动保存并应用", 3000)
|
||||
self.statusBar().showMessage("规则已保存,当前请求完成后应用" if self.pending_policy else "规则已自动保存并应用", 3000)
|
||||
return value
|
||||
|
||||
def preview_cultivation(self):
|
||||
@@ -1837,7 +2047,7 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.statusBar().showMessage("设置尚未保存,请检查输入格式及本地目录", 5000)
|
||||
|
||||
def export_policies(self):
|
||||
path, _ = W.QFileDialog.getSaveFileName(self, "导出全部策略", "ranch-policies-1.1.1.json", "策略文件 (*.json)")
|
||||
path, _ = W.QFileDialog.getSaveFileName(self, "导出全部策略", f"ranch-policies-{APP_VERSION}.json", "策略文件 (*.json)")
|
||||
if not path:
|
||||
return
|
||||
try:
|
||||
@@ -1875,6 +2085,7 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
try:
|
||||
if value is None:
|
||||
value = json.loads(path.read_text(encoding="utf-8"))
|
||||
progression = checked_progression_policy(value.get("progression_policy", {}))
|
||||
sizes = value.get("log_sizes", [420, 140])
|
||||
if isinstance(sizes, list) and len(sizes) == 2 and all(isinstance(v, int) and v >= 0 for v in sizes) and sum(sizes) > 0:
|
||||
self.log_sizes = sizes
|
||||
@@ -1894,6 +2105,7 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.map_enabled.setChecked(sweep.enabled)
|
||||
self.map_keep_ti.setValue(sweep.keep_stamina)
|
||||
self.map_team.setCurrentIndex(max(0, self.map_team.findData(sweep.team)))
|
||||
self.load_progression_policy(progression)
|
||||
self.egg_rules = copy.deepcopy(policy.egg_rules)
|
||||
self.feed_targets = copy.deepcopy(policy.feed_targets)
|
||||
self.gift_targets = copy.deepcopy(policy.gift_targets)
|
||||
@@ -1938,16 +2150,23 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.monsters.render_signature = None
|
||||
if self.latest_render:
|
||||
self.render_current_page()
|
||||
except Exception:
|
||||
self.report("旧设置无法读取,已使用默认设置")
|
||||
except (OSError, ValueError, TypeError, KeyError, AttributeError) as error:
|
||||
self.report("设置无法完整读取,请检查输入:" + str(error))
|
||||
finally:
|
||||
self.loading_config = False
|
||||
|
||||
def closeEvent(self, event):
|
||||
self.closed = True
|
||||
self.cancel_progression()
|
||||
self.timer.stop()
|
||||
self.hatch_timer.stop()
|
||||
self.analysis_page.row_batch.stop()
|
||||
self.progression_table.row_batch.stop()
|
||||
self.battle_records_table.row_batch.stop()
|
||||
self.pending_progression_view = False
|
||||
self.pending_monster_view = False
|
||||
self.pending_schedule = False
|
||||
self.pending_policy = None
|
||||
if hasattr(self, "auto_save_timer"):
|
||||
self.auto_save_timer.stop()
|
||||
if hasattr(self.eggs, "row_batch"):
|
||||
@@ -1964,6 +2183,8 @@ class Window(ActivityPages, W.QMainWindow):
|
||||
self.setEnabled(False)
|
||||
event.ignore()
|
||||
return
|
||||
if self.logout_phase == "waiting":
|
||||
self.finish_logout()
|
||||
self.save_login_info(quiet=True)
|
||||
self.save_config(quiet=True)
|
||||
if self.engine.client:
|
||||
|
||||
@@ -6,6 +6,7 @@ from .model import Policy
|
||||
from .daily import DailyPolicy
|
||||
from .quests import QuestPolicy
|
||||
from .sweeping import SweepPolicy
|
||||
from .progression import ProgressionPolicy
|
||||
|
||||
FORMAT = "ranch-helper-policies"
|
||||
VERSION = 1
|
||||
@@ -31,6 +32,23 @@ def checked_policy(cls, data):
|
||||
raise ValueError("策略字段格式错误") from error
|
||||
|
||||
|
||||
def checked_progression_policy(data):
|
||||
"""Reject ambiguous or unsafe task choices before applying any settings."""
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("主线策略必须是对象")
|
||||
raw = asdict(ProgressionPolicy()) | data
|
||||
for key in ("reserve_ti", "max_money"):
|
||||
if type(raw[key]) is not int or not 0 <= raw[key] <= 1_000_000_000:
|
||||
raise ValueError("主线策略数量超出范围:" + key)
|
||||
if type(raw["stop_after_loss"]) is not int or not 1 <= raw["stop_after_loss"] <= 999:
|
||||
raise ValueError("连续失败停止次数须为1至999")
|
||||
if not isinstance(raw["item_reserves"], dict) or any(not isinstance(key, str) or not key.isdigit() or int(key) <= 0
|
||||
or type(count) is not int or not 0 <= count <= 1_000_000_000
|
||||
for key, count in raw["item_reserves"].items()):
|
||||
raise ValueError("主线保留物品须为正整数编号和非负整数数量")
|
||||
return checked_policy(ProgressionPolicy, data)
|
||||
|
||||
|
||||
def portable_policy(policy, snapshot=None):
|
||||
value = asdict(policy)
|
||||
value["enabled"] = False
|
||||
@@ -45,7 +63,7 @@ def portable_policy(policy, snapshot=None):
|
||||
for key, priority in sorted(value.pop(field).items(), key=lambda pair: pair[1]):
|
||||
mon = snapshot.monsters.get(int(key)) if snapshot else None
|
||||
targets[kind].append({"typeId": str(mon.get("typeId")) if mon else "", "priority": priority})
|
||||
return {"format": FORMAT, "schema": VERSION, "assistantVersion": "1.1.1", "gameVersion": "1.9.68",
|
||||
return {"format": FORMAT, "schema": VERSION, "assistantVersion": "1.2.0.dev1", "gameVersion": "1.9.68",
|
||||
"policy": value, "targetSpecies": targets}
|
||||
|
||||
|
||||
@@ -87,6 +105,7 @@ def portable_config(config, snapshot=None):
|
||||
value["policy"][field] = getattr(policy, field)
|
||||
for key, cls in (("quest_policy", QuestPolicy), ("daily_policy", DailyPolicy), ("sweep_policy", SweepPolicy)):
|
||||
value[key] = asdict(cls(**config.get(key, {})))
|
||||
value["progression_policy"] = asdict(checked_progression_policy(config.get("progression_policy", {})))
|
||||
value["interval"] = config.get("interval", 30)
|
||||
value["overrides"] = copy.deepcopy(config.get("overrides", {}))
|
||||
value["yield_stars"] = list(config.get("yield_stars", [1, 2, 3, 4, 5]))
|
||||
@@ -105,6 +124,9 @@ def import_config(value, snapshot=None):
|
||||
if not isinstance(value.get(key), dict):
|
||||
raise ValueError("策略文件缺少 " + key)
|
||||
config[key] = asdict(checked_policy(cls, value[key]))
|
||||
# An additive section preserves schema-2 compatibility with older bundles.
|
||||
if "progression_policy" in value:
|
||||
config["progression_policy"] = asdict(checked_progression_policy(value["progression_policy"]))
|
||||
interval = value.get("interval", 30)
|
||||
if interval not in (30, 60, 120, 300):
|
||||
raise ValueError("刷新间隔须为30、60、120或300秒")
|
||||
|
||||
@@ -20,14 +20,15 @@ def map_source(snapshot):
|
||||
@dataclass
|
||||
class Views:
|
||||
snapshot: object
|
||||
monster_source: str
|
||||
monster_source: str | None
|
||||
managed: set
|
||||
monsters: list
|
||||
monsters: list | None
|
||||
map_source: str
|
||||
maps: list
|
||||
stage_cache: object = None
|
||||
statistics_store: object = None
|
||||
drop_statistics: dict = None
|
||||
progression: object = None
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -38,7 +39,10 @@ class Presented:
|
||||
worker_ms: float = 0
|
||||
|
||||
|
||||
def prepare_views(catalog, snapshot, managed, stage_cache=None, statistics=None):
|
||||
return Views(snapshot, repr(snapshot.raw["monsters"]), set(managed), monster_rows(catalog, snapshot, managed),
|
||||
def prepare_views(catalog, snapshot, managed, stage_cache=None, statistics=None, *, include_monsters=True):
|
||||
"""Omitted monster rows stay dirty; the default preserves the full view API."""
|
||||
source = repr(snapshot.raw["monsters"]) if include_monsters else None
|
||||
monsters = monster_rows(catalog, snapshot, managed) if include_monsters else None
|
||||
return Views(snapshot, source, set(managed), monsters,
|
||||
str(snapshot.raw["master"]["id"]), stage_cache.get(snapshot) if stage_cache else stages(catalog, snapshot), stage_cache,
|
||||
statistics, statistics.snapshot(snapshot.raw["master"]["id"]) if statistics else None)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,498 @@
|
||||
"""Compact task pages; account workers prepare data, Qt only renders cached rows."""
|
||||
import copy
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import json
|
||||
|
||||
from PySide6 import QtCore as C, QtWidgets as W
|
||||
|
||||
from .native_widgets import ComboBox, IntegerInput, RowBatch
|
||||
from .policy_io import checked_progression_policy
|
||||
from .progression import ProgressionPolicy
|
||||
from .table_widgets import set_value, table_item
|
||||
|
||||
|
||||
CATEGORIES = {"mainline": "主线", "sidequest": "支线", "commission": "委托", "event": "活动(暂不自动)",
|
||||
"bond": "羁绊(暂不自动)", "unknown": "其他 / 未知"}
|
||||
BATTLE_KINDS = {"mainline": "主线战斗", "sidequest": "支线战斗", "commission": "委托战斗",
|
||||
"battle": "普通战斗", "map_battle": "地图战斗", "sweep": "扫荡", "map_reward_event": "地图奖励事件",
|
||||
"ordinary_stage": "普通关卡战斗", "task_battle": "任务战斗", "task_pass_stage": "任务通关战斗", "unknown": "其他 / 未知"}
|
||||
BATTLE_ALIASES = {"task": "task_battle", "passStage": "task_pass_stage", "event": "map_reward_event",
|
||||
"reward_event": "map_reward_event", "normal": "battle"}
|
||||
BATTLE_MODES = {"original": "原版运行时(以能力检查为准)", "experimental": "实验模拟(近似,未完整验证)"}
|
||||
STATES = {"available": "可接取", "unaccepted": "未接取", "active": "进行中", "in_progress": "进行中",
|
||||
"ready": "待交付", "completed": "已完成", "complete": "已完成", "claimed": "已领奖",
|
||||
"received": "进行中", "unlocked": "已解锁 / 待接取", "locked": "未解锁", "finished": "已完成",
|
||||
"ready_to_reward": "待领取任务奖励", "blocked": "受阻", "unsupported": "暂不支持", "unknown": "未知"}
|
||||
CHINA_TIME = timezone(timedelta(hours=8))
|
||||
OUTCOMES = {"win": "胜利", "loss": "战败", "unsupported": "暂不支持", "event": "地图奖励事件",
|
||||
"completed": "已完成", "cancelled": "已取消", "timeout": "超时", "unknown": "结果待核对"}
|
||||
|
||||
|
||||
def category(value):
|
||||
return {"main": "mainline", "side": "sidequest", "sidequests": "sidequest", "commissions": "commission",
|
||||
"主线": "mainline", "支线": "sidequest", "委托": "commission"}.get(value, value) if isinstance(value, str) else "unknown"
|
||||
|
||||
|
||||
def display(value, empty="—"):
|
||||
if value is None or value == "":
|
||||
return empty
|
||||
if isinstance(value, (dict, list, tuple)):
|
||||
return json.dumps(value, ensure_ascii=False, sort_keys=True)
|
||||
return str(value)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ProgressionViews:
|
||||
snapshot: object
|
||||
tasks: list | None
|
||||
records: list | None
|
||||
message: str = ""
|
||||
|
||||
|
||||
def prepare_progression_views(engine, *, tasks=True, records=True):
|
||||
"""Worker boundary: getters may parse task data or read local battle records."""
|
||||
task_reader = getattr(engine, "progression_rows", None)
|
||||
record_reader = getattr(engine, "progression_records", None)
|
||||
task_data = task_reader() if tasks and callable(task_reader) else []
|
||||
record_data = record_reader() if records and callable(record_reader) else []
|
||||
for name, rows in (("progression_rows", task_data), ("progression_records", record_data)):
|
||||
if not isinstance(rows, list) or any(not isinstance(row, dict) for row in rows):
|
||||
raise TypeError(name + "() 必须返回 list[dict]")
|
||||
task_rows, record_rows = [], []
|
||||
for index, source in enumerate(task_data):
|
||||
row = copy.deepcopy(source)
|
||||
kind = category(row.get("category", "unknown"))
|
||||
kind = kind if kind in CATEGORIES else "unknown"
|
||||
state = display(row.get("state"), "未知")
|
||||
reason = display(row.get("blocked_reason") or row.get("block_reason") or row.get("reason"), "")
|
||||
supported = row.get("supported")
|
||||
support = "受阻:" + reason if reason else "已支持" if supported is True else "暂不支持" if supported is False else "支持状态未确认"
|
||||
step = display(row.get("step_number")) + " / " + display(row.get("total_steps"))
|
||||
battle = display(row.get("battle_kind"), "未确认")
|
||||
battle = BATTLE_ALIASES.get(battle, battle)
|
||||
location = row.get("location_text") or row.get("location") or row.get("position")
|
||||
values = [display(row.get("task_type_id")), CATEGORIES[kind], display(row.get("name")), STATES.get(state, state), step,
|
||||
display(location), display(row.get("requirement")), display(row.get("next_action")),
|
||||
BATTLE_KINDS.get(battle, battle), support]
|
||||
dialogue = display(row.get("dialogue") or row.get("dialogue_text") or row.get("dialogue_status"), "当前未提供对话内容")
|
||||
detail = "\n".join(("任务:" + values[2] + " #" + values[0] + ";类别:" + values[1] + ";状态:" + values[3] + ";步骤:" + step,
|
||||
"目标 / 位置:" + values[5] + ";NPC:" + display(row.get("npc_name")), "需求:" + values[6], "对话:" + dialogue,
|
||||
"下一步:" + values[7] + ";战斗:" + values[8] + ";运行状态:" + display(row.get("status"), values[3]),
|
||||
"支持状态 / 阻塞原因:" + support))
|
||||
task_rows.append({"key": str(index), "category": kind, "values": values, "detail": detail,
|
||||
"search": (" ".join(values) + " " + dialogue).casefold()})
|
||||
for index, source in enumerate(record_data):
|
||||
row = copy.deepcopy(source)
|
||||
raw_kind = row.get("battle_kind") or row.get("kind") or row.get("context") or "unknown"
|
||||
kind = BATTLE_ALIASES.get(raw_kind, raw_kind) if isinstance(raw_kind, str) else "unknown"
|
||||
if row.get("outcome") == "event":
|
||||
kind = "map_reward_event"
|
||||
elif row.get("task_id") and kind == "battle":
|
||||
kind = "task_battle"
|
||||
elif row.get("kind") == "sweep":
|
||||
kind = "sweep"
|
||||
stamp = row.get("finished_at") or row.get("started_at") or row.get("timestamp", row.get("time", row.get("at")))
|
||||
if type(stamp) in (int, float) and 0 <= stamp <= 253402271999:
|
||||
stamp = datetime.fromtimestamp(stamp, CHINA_TIME).strftime("%Y-%m-%d %H:%M:%S")
|
||||
outcome = row.get("outcome") or row.get("status") or row.get("phase") or row.get("result")
|
||||
if isinstance(outcome, dict):
|
||||
outcome = outcome.get("outcome") or outcome.get("status")
|
||||
outcome = display(outcome, "未确认")
|
||||
values = [display(stamp), BATTLE_KINDS.get(kind, display(raw_kind)),
|
||||
display(row.get("name") or row.get("task_type_id") or row.get("stage_id") or row.get("stage") or row.get("description")),
|
||||
display(row.get("team")), OUTCOMES.get(outcome, outcome),
|
||||
display(row.get("blocked_reason") or row.get("block_reason") or row.get("message") or row.get("reason"))]
|
||||
mode = row.get("battle_mode") or row.get("execution_mode")
|
||||
mode = mode if isinstance(mode, str) else None
|
||||
if mode == "experimental":
|
||||
values[4] += "(实验近似)"
|
||||
detail = "\n".join(("时间(北京时间):" + values[0], "上下文:" + values[1] + ";任务 / 地图:" + values[2],
|
||||
"战斗模式:" + BATTLE_MODES.get(mode, "记录未标明"),
|
||||
"队伍:" + values[3] + ";结果:" + values[4], "详情 / 阻塞原因:" + values[5], "奖励:" + display(row.get("reward"))))
|
||||
record_rows.append({"key": str(index), "category": kind if kind in BATTLE_KINDS else "unknown", "values": values,
|
||||
"detail": detail, "search": " ".join(values).casefold()})
|
||||
message = "" if callable(task_reader) else "当前引擎尚未提供任务读取;任务只展示,不自动推进"
|
||||
return ProgressionViews(getattr(engine, "snapshot", None), task_rows if tasks else None, record_rows if records else None, message)
|
||||
|
||||
|
||||
class CachedTable(W.QTableWidget):
|
||||
"""Refresh owned items in short batches; never reinsert an existing Qt item."""
|
||||
def __init__(self, headers, left_columns=()):
|
||||
super().__init__(0, len(headers))
|
||||
self.setHorizontalHeaderLabels(headers)
|
||||
self.setEditTriggers(W.QAbstractItemView.EditTrigger.NoEditTriggers)
|
||||
self.setSelectionBehavior(W.QAbstractItemView.SelectionBehavior.SelectRows)
|
||||
self.setSelectionMode(W.QAbstractItemView.SelectionMode.SingleSelection)
|
||||
self.horizontalHeader().setStretchLastSection(True)
|
||||
self.verticalHeader().setMinimumSectionSize(18)
|
||||
self.verticalHeader().setDefaultSectionSize(22)
|
||||
self.row_batch = RowBatch(self)
|
||||
self.signature = None
|
||||
self.details = {}
|
||||
self.left_columns = {0, 1, *left_columns}
|
||||
|
||||
def set_rows(self, rows):
|
||||
if self.signature == rows:
|
||||
return
|
||||
self.row_batch.stop()
|
||||
self.signature = None
|
||||
self.details = {row["key"]: row["detail"] for row in rows}
|
||||
self.setSortingEnabled(False)
|
||||
self.setRowCount(len(rows))
|
||||
|
||||
def apply(entry):
|
||||
index, row = entry
|
||||
for column, value in enumerate(row["values"]):
|
||||
cell = self.item(index, column)
|
||||
if cell is None:
|
||||
cell = table_item(value, column)
|
||||
self.setItem(index, column, cell)
|
||||
else:
|
||||
set_value(cell, column, value)
|
||||
cell.setToolTip(value)
|
||||
if column in self.left_columns:
|
||||
cell.setTextAlignment(C.Qt.AlignmentFlag.AlignVCenter | C.Qt.AlignmentFlag.AlignLeft)
|
||||
if column == 0:
|
||||
cell.setData(C.Qt.ItemDataRole.UserRole, row["key"])
|
||||
|
||||
def finish():
|
||||
self.signature = rows
|
||||
self.setSortingEnabled(True)
|
||||
self.itemSelectionChanged.emit()
|
||||
|
||||
self.row_batch.start(enumerate(rows), apply, finish)
|
||||
|
||||
|
||||
class ProgressionPages:
|
||||
def progression_tab(self):
|
||||
self.progression_views = None
|
||||
self.pending_progression_view = False
|
||||
self.progression_generation = 0
|
||||
self.progression_page = W.QWidget()
|
||||
layout = W.QVBoxLayout(self.progression_page)
|
||||
tools = W.QHBoxLayout()
|
||||
self.progression_enabled = W.QCheckBox("启用自动主线策略")
|
||||
self.progression_refresh_button = W.QPushButton("刷新任务 / 预览")
|
||||
self.progression_refresh_button.clicked.connect(self.refresh_progression)
|
||||
tools.addWidget(self.progression_enabled)
|
||||
tools.addWidget(self.progression_refresh_button)
|
||||
tools.addStretch()
|
||||
layout.addLayout(tools)
|
||||
self.progression_status = W.QLabel()
|
||||
self.progression_status.setWordWrap(True)
|
||||
layout.addWidget(self.progression_status)
|
||||
self.progression_tabs = W.QTabWidget()
|
||||
task_page = W.QWidget()
|
||||
task_layout = W.QVBoxLayout(task_page)
|
||||
filters = W.QHBoxLayout()
|
||||
self.progression_filter = ComboBox()
|
||||
for key, name in (("", "全部类别"), *CATEGORIES.items()):
|
||||
self.progression_filter.addItem(name, key)
|
||||
self.progression_search = W.QLineEdit()
|
||||
self.progression_search.setPlaceholderText("按任务编号、名称、目标或阻塞原因筛选")
|
||||
filters.addWidget(self.progression_filter)
|
||||
filters.addWidget(self.progression_search, 1)
|
||||
task_layout.addLayout(filters)
|
||||
self.progression_table = CachedTable(["编号", "类别", "任务", "状态", "步骤", "目标 / 位置", "需求", "下一步", "战斗类型", "支持状态 / 阻塞原因"],
|
||||
left_columns=(2, 5, 6, 7, 9))
|
||||
self.progression_table.setColumnWidth(2, 180)
|
||||
task_layout.addWidget(self.progression_table, 1)
|
||||
self.progression_detail = W.QPlainTextEdit()
|
||||
self.progression_detail.setReadOnly(True)
|
||||
self.progression_detail.setMaximumHeight(108)
|
||||
self.progression_detail.setPlaceholderText("选择任务,查看步骤、目标、对话、运行状态和阻塞原因")
|
||||
task_layout.addWidget(self.progression_detail)
|
||||
self.progression_tabs.addTab(task_page, "任务状态")
|
||||
settings = W.QWidget()
|
||||
form = W.QFormLayout(settings)
|
||||
defaults = ProgressionPolicy()
|
||||
groups = (("任务类别", (("mainline", "主线"), ("sidequests", "支线"), ("commissions", "委托(仅诊断)"))),
|
||||
("任务流程", (("accept", "接取已确认的任务"), ("auto_dialogue", "自动推进已支持的对话"),
|
||||
("repair_chain", "补全已确认的任务链"))),
|
||||
("交付 / 通关", (("allow_items", "允许提交物品"), ("allow_monsters", "允许提交魔物"),
|
||||
("allow_sweep", "允许用扫荡完成已通关目标"))))
|
||||
for label, choices in groups:
|
||||
line = W.QHBoxLayout()
|
||||
for key, text in choices:
|
||||
check = W.QCheckBox(text)
|
||||
check.setChecked(getattr(defaults, key))
|
||||
setattr(self, "progression_" + key, check)
|
||||
line.addWidget(check)
|
||||
line.addStretch()
|
||||
form.addRow(label, line)
|
||||
if hasattr(defaults, "auto_farm"):
|
||||
self.progression_auto_farm = W.QCheckBox("自动收集任务材料 / 击杀目标")
|
||||
self.progression_auto_farm.setChecked(defaults.auto_farm)
|
||||
self.progression_auto_farm.setToolTip("允许规划器为已识别的材料或击杀缺口选择普通地图。\n"
|
||||
"仍受任务规则、战斗能力、保留体力和顶部“开启 / 停止”限制;无法匹配的目标会显示原因。")
|
||||
form.addRow("任务目标", self.progression_auto_farm)
|
||||
self.progression_commissions.setToolTip("委托交付由“自动委托”页独立配置;此项只纳入任务诊断,不开启委托执行")
|
||||
self.progression_battle_mode = ComboBox()
|
||||
for mode, label in BATTLE_MODES.items():
|
||||
self.progression_battle_mode.addItem(label, mode)
|
||||
self.progression_battle_mode.setToolTip("原版运行时:只执行当前能力检查确认支持的战斗。\n"
|
||||
"实验模拟:近似推演,不保证与原版结果一致,也不代表全部规则已经验证;实际可用范围以能力检查为准。\n"
|
||||
"任务和委托战斗共用此模式,仍由顶部“开启 / 停止”控制。")
|
||||
form.addRow("战斗模式(任务 / 委托)", self.progression_battle_mode)
|
||||
self.progression_team = ComboBox()
|
||||
for team in ("teamA", "teamB", "teamC"):
|
||||
self.progression_team.addItem(team, team)
|
||||
form.addRow("推进战斗队伍", self.progression_team)
|
||||
for key, label, maximum in (("reserve_ti", "保留体力", 1_000_000_000), ("max_money", "单次交付金币上限(0=不交金币)", 1_000_000_000),
|
||||
("stop_after_loss", "连续失败后停止次数", 999)):
|
||||
widget = IntegerInput()
|
||||
widget.setRange(1 if key == "stop_after_loss" else 0, maximum)
|
||||
widget.setValue(getattr(defaults, key))
|
||||
setattr(self, "progression_" + key, widget)
|
||||
form.addRow(label, widget)
|
||||
self.progression_item_reserves = W.QLineEdit()
|
||||
self.progression_item_reserves.setPlaceholderText("物品编号:保留数量,多个用英文逗号分隔")
|
||||
form.addRow("交付后至少保留", self.progression_item_reserves)
|
||||
note = W.QLabel("勾选功能后,使用顶部绿色“开启”运行。支持状态以任务列表为准;未知状态不会自动执行。\n任务列表区分主线 / 支线 / 委托;战斗记录区分普通战斗、扫荡和地图奖励事件。未支持的步骤显示原因。")
|
||||
note.setWordWrap(True)
|
||||
form.addRow(note)
|
||||
scroll = W.QScrollArea()
|
||||
scroll.setWidgetResizable(True)
|
||||
scroll.setFrameShape(W.QFrame.Shape.NoFrame)
|
||||
scroll.setWidget(settings)
|
||||
self.progression_tabs.addTab(scroll, "推进策略")
|
||||
layout.addWidget(self.progression_tabs, 1)
|
||||
self.tabs.addTab(self.progression_page, "自动主线")
|
||||
self.progression_filter.currentIndexChanged.connect(self.render_progression)
|
||||
self.progression_search.textChanged.connect(self.render_progression)
|
||||
self.progression_table.itemSelectionChanged.connect(self.progression_selection_changed)
|
||||
self.progression_enabled.toggled.connect(self.progression_settings_changed)
|
||||
self.update_progression_status()
|
||||
|
||||
def battle_records_tab(self):
|
||||
self.battle_records_page = W.QWidget()
|
||||
layout = W.QVBoxLayout(self.battle_records_page)
|
||||
tools = W.QHBoxLayout()
|
||||
self.battle_records_filter = ComboBox()
|
||||
for key, name in (("", "全部上下文"), *BATTLE_KINDS.items()):
|
||||
self.battle_records_filter.addItem(name, key)
|
||||
self.battle_records_search = W.QLineEdit()
|
||||
self.battle_records_search.setPlaceholderText("按任务、地图、结果或阻塞原因筛选")
|
||||
refresh = W.QPushButton("刷新本地记录")
|
||||
refresh.clicked.connect(self.refresh_progression_records)
|
||||
for widget in (self.battle_records_filter, self.battle_records_search, refresh):
|
||||
tools.addWidget(widget)
|
||||
layout.addLayout(tools)
|
||||
self.battle_records_status = W.QLabel("尚无已读取的战斗记录;地图奖励事件会单独标明,结果以实际记录为准")
|
||||
self.battle_records_status.setWordWrap(True)
|
||||
layout.addWidget(self.battle_records_status)
|
||||
self.battle_records_table = CachedTable(["时间(北京时间)", "上下文", "任务 / 地图", "队伍", "结果", "详情 / 阻塞原因"], left_columns=(2, 5))
|
||||
for column, width in enumerate((158, 124, 140, 70, 95)):
|
||||
self.battle_records_table.setColumnWidth(column, width)
|
||||
layout.addWidget(self.battle_records_table, 1)
|
||||
self.battle_record_detail = W.QPlainTextEdit()
|
||||
self.battle_record_detail.setReadOnly(True)
|
||||
self.battle_record_detail.setMaximumHeight(108)
|
||||
self.battle_record_detail.setPlaceholderText("选择记录查看引擎提供的详情")
|
||||
layout.addWidget(self.battle_record_detail)
|
||||
self.tabs.addTab(self.battle_records_page, "战斗记录")
|
||||
self.battle_records_filter.currentIndexChanged.connect(self.render_progression)
|
||||
self.battle_records_search.textChanged.connect(self.render_progression)
|
||||
self.battle_records_table.itemSelectionChanged.connect(self.progression_selection_changed)
|
||||
|
||||
def progression_settings_changed(self, *args):
|
||||
if self.loading_config or self.closed:
|
||||
return
|
||||
if self.sender() is self.progression_enabled and not self.progression_enabled.isChecked():
|
||||
self.cancel_progression()
|
||||
self.update_progression_status()
|
||||
self.settings_changed()
|
||||
|
||||
def cancel_progression(self):
|
||||
self.progression_generation += 1
|
||||
cancel = getattr(self.engine, "cancel_progression", None)
|
||||
if callable(cancel):
|
||||
cancel()
|
||||
|
||||
def read_progression_policy(self):
|
||||
value = {}
|
||||
for key, default in asdict(ProgressionPolicy()).items():
|
||||
widget = getattr(self, "progression_" + key)
|
||||
if key == "item_reserves":
|
||||
reserves = {}
|
||||
for entry in widget.text().split(","):
|
||||
if entry.strip():
|
||||
item_id, count = entry.split(":")
|
||||
reserves[item_id.strip()] = int(count.strip())
|
||||
value[key] = reserves
|
||||
elif isinstance(widget, W.QComboBox):
|
||||
value[key] = widget.currentData()
|
||||
else:
|
||||
value[key] = widget.isChecked() if type(default) is bool else widget.value()
|
||||
return checked_progression_policy(value)
|
||||
|
||||
def load_progression_policy(self, policy):
|
||||
for key, value in asdict(policy).items():
|
||||
widget = getattr(self, "progression_" + key)
|
||||
blocker = C.QSignalBlocker(widget)
|
||||
if key == "item_reserves":
|
||||
widget.setText(",".join(f"{item_id}:{count}" for item_id, count in value.items()))
|
||||
elif isinstance(widget, W.QComboBox):
|
||||
index = widget.findData(value)
|
||||
if index < 0:
|
||||
if key != "team":
|
||||
raise ValueError("不支持的策略选项:" + key)
|
||||
widget.addItem(value + "(当前账号未找到)", value)
|
||||
index = widget.findData(value)
|
||||
widget.setCurrentIndex(index)
|
||||
elif type(value) is bool:
|
||||
widget.setChecked(value)
|
||||
else:
|
||||
widget.setValue(value)
|
||||
del blocker
|
||||
self.update_progression_status()
|
||||
|
||||
def refresh_progression_teams(self, snapshot):
|
||||
"""Keep imported selections visible until this account confirms a team."""
|
||||
selected = self.progression_team.currentData() or "teamA"
|
||||
names = ["teamA", "teamB", "teamC"]
|
||||
confirmed = set()
|
||||
for team in snapshot.raw.get("teams", []):
|
||||
name = team.get("teamName")
|
||||
if team.get("teamType") == "battleTeam" and isinstance(name, str) and name:
|
||||
confirmed.add(name)
|
||||
if name not in names:
|
||||
names.append(name)
|
||||
if selected not in names:
|
||||
names.append(selected)
|
||||
options = [(name + "(当前账号未找到)" if name == selected and name not in confirmed and name not in ("teamA", "teamB", "teamC") else name, name)
|
||||
for name in names]
|
||||
widget = self.progression_team
|
||||
if [(widget.itemText(i), widget.itemData(i)) for i in range(widget.count())] != options:
|
||||
blocker = C.QSignalBlocker(widget)
|
||||
widget.clear()
|
||||
for label, name in options:
|
||||
widget.addItem(label, name)
|
||||
widget.setCurrentIndex(widget.findData(selected))
|
||||
del blocker
|
||||
|
||||
def update_progression_status(self):
|
||||
if not hasattr(self, "progression_status"):
|
||||
return
|
||||
active = self.strategy_toggle.isChecked() and self.progression_enabled.isChecked()
|
||||
text = "自动主线已开启" if active else "策略已停止;顶部“开启”后执行勾选功能" if self.progression_enabled.isChecked() else "自动主线未启用"
|
||||
mode = self.progression_battle_mode.currentData()
|
||||
text += ";战斗模式:" + BATTLE_MODES.get(mode, "未选择,请检查策略")
|
||||
if not callable(getattr(self.engine, "refresh_progression", None)):
|
||||
text += ";当前引擎尚未接入任务刷新"
|
||||
if not callable(getattr(self.engine, "run_progression_once", None)):
|
||||
text += ";当前引擎尚未接入自动推进"
|
||||
if self.progression_views and self.progression_views.message:
|
||||
text += ";" + self.progression_views.message
|
||||
self.progression_status.setText(text)
|
||||
|
||||
def refresh_progression(self, checked=False):
|
||||
if self.closed:
|
||||
return
|
||||
if self.busy:
|
||||
self.pending_refresh = self.progression_page
|
||||
self.statusBar().showMessage("当前请求完成后刷新任务")
|
||||
return
|
||||
refresh = getattr(self.engine, "refresh_progression", None)
|
||||
if not callable(refresh):
|
||||
self.report("当前引擎尚未提供任务刷新;请等待功能接入")
|
||||
self.request_progression_views(force=True)
|
||||
return
|
||||
try:
|
||||
self.update_policy()
|
||||
except ValueError as error:
|
||||
self.stop_workflow()
|
||||
self.report("主线策略输入有误:" + str(error))
|
||||
return
|
||||
self.run_job("progression_refresh", refresh)
|
||||
|
||||
def run_progression_once(self):
|
||||
"""Explicit one-step entry; it never changes the global execution switch."""
|
||||
if self.closed or self.busy:
|
||||
return
|
||||
if not self.strategy_toggle.isChecked() or not self.progression_enabled.isChecked():
|
||||
self.report("自动主线已停止;请先勾选策略并开启顶部开关")
|
||||
return
|
||||
run = getattr(self.engine, "run_progression_once", None)
|
||||
if not callable(run):
|
||||
self.report("当前引擎尚未提供自动推进")
|
||||
return
|
||||
try:
|
||||
self.update_policy()
|
||||
except ValueError as error:
|
||||
self.stop_workflow()
|
||||
self.report("主线策略输入有误:" + str(error))
|
||||
return
|
||||
self.engine.auto = self.monitoring and self.strategy_toggle.isChecked()
|
||||
engine, generation = self.engine, self.progression_generation
|
||||
def execute():
|
||||
if generation != self.progression_generation or not engine.auto:
|
||||
return engine.snapshot, [], "任务推进已取消;未开始执行"
|
||||
return run()
|
||||
self.run_job("progression_run", execute)
|
||||
|
||||
def refresh_progression_records(self, checked=False):
|
||||
self.request_progression_views(force=True)
|
||||
|
||||
def clear_progression_views(self):
|
||||
self.progression_views = None
|
||||
self.pending_progression_view = False
|
||||
for widget in (self.progression_table, self.battle_records_table):
|
||||
widget.row_batch.stop()
|
||||
widget.set_rows([])
|
||||
self.progression_detail.clear()
|
||||
self.battle_record_detail.clear()
|
||||
self.update_progression_status()
|
||||
|
||||
def accept_progression_views(self, views):
|
||||
previous = self.progression_views
|
||||
if previous and previous.snapshot is views.snapshot:
|
||||
if views.tasks is None:
|
||||
views.tasks = previous.tasks
|
||||
if views.records is None:
|
||||
views.records = previous.records
|
||||
self.progression_views = views
|
||||
|
||||
def request_progression_views(self, *, force=False):
|
||||
if self.closed or self.engine.snapshot is None:
|
||||
return
|
||||
tasks = self.tabs.currentWidget() is not self.battle_records_page
|
||||
cached = self.progression_views
|
||||
if not force and cached and cached.snapshot is self.engine.snapshot and (cached.tasks if tasks else cached.records) is not None:
|
||||
return
|
||||
if self.busy:
|
||||
self.pending_progression_view = True
|
||||
return
|
||||
self.pending_progression_view = False
|
||||
engine = self.engine
|
||||
self.run_job("progression_view", lambda: prepare_progression_views(engine, tasks=tasks, records=not tasks))
|
||||
|
||||
def render_progression(self, *args):
|
||||
if self.closed or not self.presentation_active:
|
||||
return
|
||||
page = self.tabs.currentWidget()
|
||||
if page not in (self.progression_page, self.battle_records_page):
|
||||
return
|
||||
views = self.progression_views
|
||||
tasks = page is self.progression_page
|
||||
if views is None or views.snapshot is not self.engine.snapshot or (views.tasks if tasks else views.records) is None:
|
||||
self.request_progression_views()
|
||||
table = self.progression_table if tasks else self.battle_records_table
|
||||
rows = ((views.tasks if tasks else views.records) or []) if views else []
|
||||
selected = self.progression_filter.currentData() if tasks else self.battle_records_filter.currentData()
|
||||
query = (self.progression_search.text() if tasks else self.battle_records_search.text()).strip().casefold()
|
||||
visible = [row for row in rows if (not selected or row["category"] == selected) and (not query or query in row["search"])]
|
||||
table.set_rows(visible)
|
||||
if not tasks:
|
||||
self.battle_records_status.setText(f"已读取 {len(rows)} 条记录,显示 {len(visible)} 条;战斗、扫荡和地图奖励事件分别标记" if rows else
|
||||
"尚无已读取的战斗记录;未记录结果不代表战斗成功")
|
||||
self.update_progression_status()
|
||||
self.progression_selection_changed()
|
||||
|
||||
def progression_selection_changed(self):
|
||||
for table, detail in ((self.progression_table, self.progression_detail), (self.battle_records_table, self.battle_record_detail)):
|
||||
item = table.item(table.currentRow(), 0)
|
||||
text = table.details.get(item.data(C.Qt.ItemDataRole.UserRole), "") if item else ""
|
||||
if detail.toPlainText() != text:
|
||||
detail.setPlainText(text)
|
||||
@@ -78,7 +78,9 @@ class TaskPlanner:
|
||||
self.guard = Planner(catalog)
|
||||
|
||||
def current(self, snapshot):
|
||||
return [t for t in snapshot.raw.get("currentTasks", []) if str(t.get("typeId")) in self.catalog.data.get("task_info", {})]
|
||||
infos = self.catalog.data.get("task_info", {})
|
||||
return [t for t in snapshot.raw.get("currentTasks", []) if str(t.get("typeId")) in infos
|
||||
and infos[str(t["typeId"])].get("type", 4) == 4]
|
||||
|
||||
def requirement(self, snapshot, step, task, policy, ranch):
|
||||
if not condition_ok(step.get("condition"), snapshot):
|
||||
@@ -146,11 +148,11 @@ class TaskPlanner:
|
||||
continue
|
||||
for type_id in offers:
|
||||
info = self.catalog.data.get("task_info", {}).get(str(type_id), {})
|
||||
if info:
|
||||
if info and info.get("type", 4) == 4:
|
||||
rows.append((str(type_id), info.get("name", ""), f"城市 {city} 可接", info.get("des", ""), {"city": int(city)}))
|
||||
return rows
|
||||
|
||||
def plan(self, snapshot, policy, ranch):
|
||||
def plan(self, snapshot, policy, ranch, *, include_active=True, accept_supported=None):
|
||||
if not policy.enabled:
|
||||
return []
|
||||
history = snapshot.raw.get("history", {})
|
||||
@@ -159,7 +161,7 @@ class TaskPlanner:
|
||||
current_day = int((snapshot.now - 10 + 8 * 3600) // 86400)
|
||||
if old_day < current_day:
|
||||
return [Action("quest_reset", "刷新跨日委托", "taskService/taskLoopFlush", {})]
|
||||
for task in self.current(snapshot):
|
||||
for task in self.current(snapshot) if include_active else []:
|
||||
info = self.catalog.data["task_info"][str(task["typeId"])]
|
||||
index, steps = int(task.get("curStep", 1)) - 1, info.get("steps", [])
|
||||
payload = {"taskId": int(task["id"]), "taskTypeId": str(task["typeId"])}
|
||||
@@ -182,7 +184,8 @@ class TaskPlanner:
|
||||
if info.get("closed") or not condition_ok((info.get("startStep") or {}).get("condition"), snapshot):
|
||||
continue
|
||||
steps = info.get("steps", [])
|
||||
supported = all((s.get("statusType") in ("passStage", "battle") and policy.battle_tasks)
|
||||
supported = accept_supported(type_id) if accept_supported else all(
|
||||
(s.get("statusType") in ("passStage", "battle") and policy.battle_tasks)
|
||||
or self.requirement(snapshot, s, {}, policy, ranch)[0] for s in steps)
|
||||
if supported:
|
||||
return [Action("quest_accept", f"接取委托:{name}", "taskService/taskLoopReceive", {"taskTypeId": type_id, "city": city})]
|
||||
|
||||
@@ -274,6 +274,7 @@ class AccountGuiTests(unittest.TestCase):
|
||||
hub.tabs.setCurrentWidget(first)
|
||||
for page in (first.egg_page, first.monster_page, first.room_page):
|
||||
first.tabs.setCurrentWidget(page)
|
||||
self.wait(windows)
|
||||
self.assertEqual([first.slots.rowCount(), first.eggs.rowCount(), len(first.monsters.monster_items)], [11, 4, 4])
|
||||
self.assertFalse(first.monsters.group_items)
|
||||
self.assertTrue(all(item.parent() is None for item in first.monsters.monster_items.values()))
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
"""AMF3 array shapes and object-reference regressions, entirely offline."""
|
||||
import unittest
|
||||
|
||||
from ranch_assistant.amf import Reader
|
||||
|
||||
|
||||
class ArrayReaderTests(unittest.TestCase):
|
||||
def test_empty_dense_array_is_list_and_occupies_object_reference_slot(self):
|
||||
reader = Reader(b"\x09\x01\x01\x09\x00")
|
||||
value = reader.read()
|
||||
self.assertIs(type(value), list)
|
||||
self.assertEqual(value, [])
|
||||
self.assertIs(reader.read(), value)
|
||||
self.assertIs(reader.objects[0], value)
|
||||
self.assertEqual(reader.pos, len(reader.data))
|
||||
|
||||
def test_pure_associative_array_preserves_self_reference(self):
|
||||
# Array, zero dense entries, property 'x', array reference 0, end keys.
|
||||
reader = Reader(b"\x09\x01\x03x\x09\x00\x01")
|
||||
value = reader.read()
|
||||
self.assertIs(type(value), dict)
|
||||
self.assertIs(value["x"], value)
|
||||
self.assertIs(reader.objects[0], value)
|
||||
|
||||
def test_dense_array_preserves_self_reference(self):
|
||||
reader = Reader(b"\x09\x03\x01\x09\x00")
|
||||
value = reader.read()
|
||||
self.assertIs(type(value), list)
|
||||
self.assertIs(value[0], value)
|
||||
|
||||
def test_nested_empty_array_keeps_parent_and_child_reference_order(self):
|
||||
# [empty array, reference to that array, reference to parent]
|
||||
reader = Reader(b"\x09\x07\x01\x09\x01\x01\x09\x02\x09\x00")
|
||||
value = reader.read()
|
||||
self.assertIs(type(value[0]), list)
|
||||
self.assertIs(value[1], value[0])
|
||||
self.assertIs(value[2], value)
|
||||
self.assertIs(reader.objects[0], value)
|
||||
self.assertIs(reader.objects[1], value[0])
|
||||
|
||||
def test_associative_first_key_can_use_string_reference(self):
|
||||
reader = Reader(b"\x06\x03k\x09\x01\x00\x04\x07\x01")
|
||||
self.assertEqual(reader.read(), "k")
|
||||
self.assertEqual(reader.read(), {"k": 7})
|
||||
self.assertEqual(len(reader.objects), 1)
|
||||
|
||||
def test_dynamic_empty_object_remains_mapping(self):
|
||||
reader = Reader(b"\x0a\x0b\x01\x01\x0a\x00")
|
||||
value = reader.read()
|
||||
self.assertIs(type(value), dict)
|
||||
self.assertEqual(value, {})
|
||||
self.assertIs(reader.read(), value)
|
||||
|
||||
def test_mixed_arrays_still_rejected(self):
|
||||
with self.assertRaisesRegex(ValueError, "Mixed AMF array unsupported"):
|
||||
Reader(b"\x09\x03\x03k\x04\x01\x01\x04\x02").read()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -425,6 +425,7 @@ class AutomationGuiTests(unittest.TestCase):
|
||||
before = len(window.engine.snapshot.raw["monsters"])
|
||||
def select(mid):
|
||||
window.tabs.setCurrentWidget(window.monster_page)
|
||||
self.wait(window)
|
||||
window.monsters.clearSelection()
|
||||
window.monsters.setCurrentItem(window.monsters.monster_items[mid])
|
||||
select(101)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,488 @@
|
||||
from contextlib import ExitStack
|
||||
from copy import deepcopy
|
||||
from dataclasses import asdict, replace
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import zipfile
|
||||
import zlib
|
||||
|
||||
from ranch_assistant.battle_runtime import (
|
||||
BattleRequest, BattleRuntime, ORIGINAL_APK_SHA256, ORIGINAL_MAIN_SHA256, original_fixture_request,
|
||||
)
|
||||
from ranch_assistant.tests.test_core import workspace_temp
|
||||
from tools.battle_runtime.isolation import ProcessResult, run_isolated
|
||||
from tools.battle_runtime.swf_library import encode_tag, library_only, symbols, tags
|
||||
from tools.battle_runtime.trusted import verify_files
|
||||
from tools.battle_runtime.inputs import ADD_FIELDS, MON_FIELDS, validate
|
||||
from tools.battle_runtime.prepare import asset_index, write_atomic
|
||||
|
||||
|
||||
class RuntimeContractTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.stack = ExitStack()
|
||||
self.addCleanup(self.stack.close)
|
||||
self.root = Path(self.stack.enter_context(workspace_temp()))
|
||||
(self.root / "fixture_1.9.68.apk").write_bytes(b"Not an engine; contract tests never execute this")
|
||||
self.stack.enter_context(patch("ranch_assistant.battle_runtime.ROOT", self.root))
|
||||
self.stack.enter_context(patch("ranch_assistant.battle_runtime.LOCAL", self.root / "runtime"))
|
||||
self.stack.enter_context(patch("ranch_assistant.battle_runtime.os", SimpleNamespace(name="nt")))
|
||||
self.stack.enter_context(patch("tools.battle_runtime.trusted.verify_files", return_value=[]))
|
||||
self.request = original_fixture_request()
|
||||
|
||||
def inspect(self, **changes):
|
||||
return BattleRuntime().inspect(replace(self.request, **changes))
|
||||
|
||||
def codes(self, capability):
|
||||
return {row["code"] for row in capability["reasons"]}
|
||||
|
||||
def test_native_fixture_support_never_grants_settlement_or_fidelity(self):
|
||||
capability = self.inspect()
|
||||
self.assertTrue(capability["supported"])
|
||||
self.assertFalse(capability["faithful"])
|
||||
self.assertFalse(capability["settlement_eligible"])
|
||||
self.assertEqual(capability["coverage"]["validated_skills"], [3])
|
||||
|
||||
def test_default_purpose_refuses_before_starting_any_process(self):
|
||||
request = BattleRequest("ordinary_stage", self.request.original_data, self.request.roster, stage_id="0101")
|
||||
with patch("tools.battle_runtime.isolation.run_isolated") as execute:
|
||||
result = BattleRuntime().run(request)
|
||||
execute.assert_not_called()
|
||||
self.assertEqual(result["status"], "unsupported")
|
||||
self.assertIn("settlement_not_validated", self.codes(result["capability"]))
|
||||
self.assertNotIn("outcome", result)
|
||||
self.assertNotIn("offline_result", result)
|
||||
|
||||
def test_dict_contract_matches_dataclass_and_input_is_unchanged(self):
|
||||
request = asdict(self.request)
|
||||
before = json.loads(json.dumps(request))
|
||||
self.assertEqual(BattleRuntime().inspect(request), BattleRuntime().inspect(self.request))
|
||||
self.assertEqual(request, before)
|
||||
|
||||
def test_unknown_context_and_unhashable_context_refuse(self):
|
||||
for context in ("boss", "pve", ["ordinary_stage"], None):
|
||||
with self.subTest(context=context):
|
||||
self.assertIn("unknown_context", self.codes(self.inspect(context=context)))
|
||||
|
||||
def test_task_routes_cannot_reuse_the_ordinary_stage_proof(self):
|
||||
for context in ("task_battle", "task_pass_stage"):
|
||||
capability = self.inspect(context=context, task_id="1001004", step_index=0)
|
||||
self.assertFalse(capability["supported"])
|
||||
self.assertIn("task_route_not_validated", self.codes(capability))
|
||||
|
||||
def test_other_stages_and_difficulties_refuse(self):
|
||||
for changes in ({"stage_id":"0102"}, {"difficulty":2}, {"difficulty":True}, {"difficulty":"1"}):
|
||||
self.assertIn("scene_not_validated", self.codes(self.inspect(**changes)))
|
||||
|
||||
def test_task_fields_are_rejected_even_with_ordinary_context(self):
|
||||
self.assertIn("task_input_not_validated", self.codes(self.inspect(step_index=0)))
|
||||
|
||||
def test_unknown_roster_skills_equipment_and_estimates_refuse(self):
|
||||
for roster in ({"hp":100,"atk":100}, {**self.request.roster,"skills":[9999]},
|
||||
{**self.request.roster,"equipment":[123]}):
|
||||
self.assertIn("roster_not_validated", self.codes(self.inspect(roster=roster)))
|
||||
|
||||
def test_unverified_original_tables_cannot_enable_unknown_mechanics(self):
|
||||
data = {**self.request.original_data, "battle":{"controller":[{"type":"unimplemented"}]}}
|
||||
self.assertIn("external_battle_data_unvalidated", self.codes(self.inspect(original_data=data)))
|
||||
|
||||
def test_claimed_original_identity_must_match_both_pins(self):
|
||||
identity = {**self.request.original_data["resource_identity"], "main_swf_sha256":"0" * 64}
|
||||
self.assertIn("resource_identity_mismatch", self.codes(self.inspect(original_data={
|
||||
"source":"original_apk", "resource_identity":identity})))
|
||||
|
||||
def test_imported_commands_paths_and_unsigned_verified_manifests_never_execute(self):
|
||||
for config in ({"command":["cmd","/c","anything"]}, {"executable":"evil.exe"},
|
||||
{"backend":"original_air","verified":True,"supports":["*"]},
|
||||
{"backend":"original_air","resource_root":"somewhere"}):
|
||||
with self.subTest(config=config), patch("tools.battle_runtime.isolation.run_isolated") as execute:
|
||||
result = BattleRuntime(config).run(self.request)
|
||||
self.assertEqual(result["status"], "unsupported")
|
||||
self.assertIn("untrusted_runtime_config", self.codes(result["capability"]))
|
||||
execute.assert_not_called()
|
||||
|
||||
def test_foreign_backend_refuses(self):
|
||||
result = BattleRuntime({"backend":"basic_estimate"}).inspect(self.request)
|
||||
self.assertIn("unknown_backend", self.codes(result))
|
||||
|
||||
def test_unsigned_result_in_request_is_not_an_engine_result(self):
|
||||
request = {**asdict(self.request), "result":{"win":True}, "verified":True}
|
||||
result = BattleRuntime().run(request)
|
||||
self.assertEqual(result["status"], "unsupported")
|
||||
self.assertIn("unknown_request_fields", self.codes(result["capability"]))
|
||||
|
||||
def test_malformed_nonfinite_and_oversize_inputs_refuse(self):
|
||||
for request in (None, [], {}, {**asdict(self.request),"roster":{"hp":float("nan")}},
|
||||
{**asdict(self.request),"roster":{"payload":"x" * (4 * 1024 * 1024)}}):
|
||||
self.assertFalse(BattleRuntime().inspect(request)["supported"])
|
||||
|
||||
def test_cancellation_before_run_does_not_inspect_or_launch(self):
|
||||
event = threading.Event(); event.set()
|
||||
runtime = BattleRuntime()
|
||||
with patch.object(runtime,"inspect") as inspect:
|
||||
result = runtime.run(self.request,cancel_event=event)
|
||||
inspect.assert_not_called()
|
||||
self.assertEqual(result["status"], "cancelled")
|
||||
|
||||
def test_timeout_must_be_finite_and_positive(self):
|
||||
for value in (0, -1, True, float("nan"), float("inf"), "5"):
|
||||
with self.subTest(value=value), self.assertRaises(ValueError):
|
||||
BattleRuntime().run(self.request, timeout=value)
|
||||
|
||||
def fake_worker(self, mutate):
|
||||
def execute(argv, **kwargs):
|
||||
output = Path(argv[argv.index("--output")+1])
|
||||
nonce = argv[argv.index("--nonce")+1]
|
||||
payload = {"schema":1,"nonce":nonce,"evidence":{
|
||||
"resource_identity":{"apk_sha256":ORIGINAL_APK_SHA256,"main_swf_sha256":ORIGINAL_MAIN_SHA256},
|
||||
"resource_audit":{"all_present_assets_match_apk":True},"process_exit_code":0,
|
||||
"result":{"status":"scene_completed","battle_executed":True,"settlement_eligible":False,
|
||||
"scene_result":{"outcome":"win","battle_data":{"win":True,"cheatNum":0,"battlePosition":{
|
||||
"battleType":"stage","stageLevel":"1","stageId":"0101","taskTypeId":None,"taskStep":0}},
|
||||
"anomaly_records":{"text":"real anomaly","damages":[{"damage":999}]}}}}}
|
||||
mutate(payload)
|
||||
output.write_text(json.dumps(payload),encoding="utf-8")
|
||||
return ProcessResult("completed",0,.1,"","")
|
||||
return execute
|
||||
|
||||
def test_result_protocol_rejects_wrong_nonce_identity_claim_or_missing_execution(self):
|
||||
mutations = [lambda p:p.update(nonce="wrong"),
|
||||
lambda p:p["evidence"]["resource_identity"].update(apk_sha256="0" * 64),
|
||||
lambda p:p["evidence"]["resource_identity"].update(main_swf_sha256="0" * 64),
|
||||
lambda p:p["evidence"]["result"].update(settlement_eligible=True),
|
||||
lambda p:p["evidence"]["result"].update(faithful=True),
|
||||
lambda p:p["evidence"]["result"].update(battle_executed=False),
|
||||
lambda p:p["evidence"]["resource_audit"].update(all_present_assets_match_apk=False),
|
||||
lambda p:p["evidence"]["result"]["scene_result"].update(outcome="invented")]
|
||||
for mutation in mutations:
|
||||
with self.subTest(mutation=mutation), patch("tools.battle_runtime.isolation.run_isolated",side_effect=self.fake_worker(mutation)):
|
||||
result = BattleRuntime().run(self.request)
|
||||
self.assertEqual(result["status"], "error")
|
||||
self.assertNotIn("outcome",result)
|
||||
self.assertFalse(result["settlement_eligible"])
|
||||
|
||||
def test_original_anomaly_records_survive_protocol_without_filtering(self):
|
||||
with patch("tools.battle_runtime.isolation.run_isolated",side_effect=self.fake_worker(lambda p:None)):
|
||||
result = BattleRuntime().run(self.request)
|
||||
self.assertEqual(result["status"],"completed")
|
||||
self.assertEqual(result["offline_result"]["anomaly_records"]["text"],"real anomaly")
|
||||
self.assertEqual(result["offline_result"]["anomaly_records"]["damages"],[{"damage":999}])
|
||||
self.assertFalse(result["faithful"])
|
||||
|
||||
def test_positive_original_anomaly_count_preserves_completed_result(self):
|
||||
def anomaly(payload):
|
||||
payload["evidence"]["result"]["scene_result"]["battle_data"]["cheatNum"] = 4
|
||||
with patch("tools.battle_runtime.isolation.run_isolated",side_effect=self.fake_worker(anomaly)):
|
||||
result = BattleRuntime().run(self.request)
|
||||
self.assertEqual(result["status"],"anomaly")
|
||||
self.assertTrue(result["battle_completed"])
|
||||
self.assertFalse(result["checks_passed"])
|
||||
self.assertEqual(result["offline_result"]["anomaly_records"]["text"],"real anomaly")
|
||||
|
||||
def test_natural_native_time_limit_is_completed_loss_not_watchdog_timeout(self):
|
||||
def expiry(payload):
|
||||
scene = payload["evidence"]["result"]["scene_result"]
|
||||
scene.update(outcome="loss",terminal_reason="time_limit")
|
||||
scene["battle_data"].update(win=False,leftTime=0)
|
||||
with patch("tools.battle_runtime.isolation.run_isolated",side_effect=self.fake_worker(expiry)):
|
||||
result = BattleRuntime().run(self.request)
|
||||
self.assertEqual(result["status"],"completed")
|
||||
self.assertEqual(result["outcome"],"loss")
|
||||
self.assertEqual(result["offline_result"]["terminal_reason"],"time_limit")
|
||||
|
||||
def test_default_deadline_allows_original_300_second_battle_and_explicit_is_preserved(self):
|
||||
runtime=BattleRuntime()
|
||||
with patch.object(runtime,"_execute",return_value={}) as execute:
|
||||
runtime.run(self.request)
|
||||
self.assertGreater(execute.call_args.kwargs["timeout"],600)
|
||||
with patch.object(runtime,"_execute",return_value={}) as execute:
|
||||
runtime.run(self.request,timeout=10)
|
||||
self.assertGreater(execute.call_args.kwargs["timeout"],8)
|
||||
self.assertLessEqual(execute.call_args.kwargs["timeout"],10)
|
||||
|
||||
def test_timed_out_worker_does_not_yield_a_battle_result(self):
|
||||
with patch("tools.battle_runtime.isolation.run_isolated",return_value=ProcessResult("timeout",1,.1,"","")):
|
||||
result = BattleRuntime().run(self.request)
|
||||
self.assertEqual(result["status"],"timeout")
|
||||
self.assertNotIn("outcome",result)
|
||||
self.assertNotIn("offline_result",result)
|
||||
|
||||
|
||||
class OriginalInputTests(unittest.TestCase):
|
||||
"""Data-only preflight tests; no APK, AIR, account, or network is required."""
|
||||
def setUp(self):
|
||||
self.battle={"time":300,"groundType":1,"teams":[],"controller":[],"triggers":[],
|
||||
"battleField":{"mapAreas":[],"mapObjects":[]}}
|
||||
self.tables={"stage_info":{"0101":{"level":{"1":{"battle":self.battle}}}},
|
||||
"task_info":{"original-task":{"steps":[
|
||||
{"statusType":"battle","battle":self.battle},
|
||||
{"statusType":"passStage","statusValue":{"stage":"0101","level":1}}]}},
|
||||
"monster_info":{"1001010":{"skill_1":3,"skill_2":0,"imgFix":{"2":{"x":0,"y":0}}}},
|
||||
"monster_skill":{"3":{}},"skin_info":{},"upstar_info":{},"item_info":{},
|
||||
"team_info":{"battleTeam":{"0":{},"1":{}}},
|
||||
"setting":{"groundType":{"1":{"battleImg":"background.png"}},"groundObject":{}},
|
||||
"game_setting":{"normalBattleTime":300,"maxFeel":200},
|
||||
"potential_info":{"potentialLevelMaxAdd":10}}
|
||||
self.members={self.member(path) for path in ("data/img/bg/background.png","data/img/monster/q/1001010_q_2.png")}
|
||||
mon=dict.fromkeys(MON_FIELDS,0)
|
||||
mon.update(id=1000001,typeId=1001010,level=1,mode=2,process=3,potentialLevel=1,nicName="")
|
||||
self.snapshot={"master":{"id":1,"level":1,"globalAtk":0,"globalDef":0,"globalHp":0,"globalDex":0},
|
||||
"monsters":[mon],"monsterAttributes":[],"items":[],
|
||||
"teams":[{"teamName":"teamB","teamType":"battleTeam","monsters":[1000001,0]}],
|
||||
"history":{**dict.fromkeys(("numAddMoney","numChicken","countBattle"),0),
|
||||
**{k:[] for k in ("monLib","equipLib","passAchi","guide_record","unlockCity")},
|
||||
**{k:{} for k in ("numFeedMonsters","numKillMonsters","historyGacha","passTask","unlockTask","loopTask","unlockStage","passStage","payTypeCount","everyDayBuyProductNum")},
|
||||
"guide_main":""}}
|
||||
self.request={"context":"ordinary_stage","stage_id":"0101","difficulty":1,
|
||||
"original_data":{"battle":self.battle},"roster":self.snapshot,"team":"teamB",
|
||||
"battle_position":{"battleType":"stage","stageId":"0101","stageLevel":"1","taskTypeId":None,"taskStep":0}}
|
||||
|
||||
@staticmethod
|
||||
def member(path):
|
||||
return "assets/codes/"+hashlib.md5(path.encode()).hexdigest()
|
||||
|
||||
def validate(self,request=None):
|
||||
return validate(self.request if request is None else request,source=(self.tables,self.members))
|
||||
|
||||
def codes(self,result):
|
||||
return {r["code"] for r in result["reasons"]}
|
||||
|
||||
def test_raw_roster_contract_preserves_selected_team_b_and_empty_additions(self):
|
||||
before=deepcopy(self.request);result=self.validate()
|
||||
self.assertEqual(result["reasons"],[])
|
||||
self.assertEqual(result["native_request"]["roster"]["team_name"],"teamB")
|
||||
self.assertEqual(result["native_request"]["roster"]["snapshot"]["monsterAttributes"],[])
|
||||
self.assertEqual(self.request,before)
|
||||
|
||||
def test_wrapper_and_raw_contract_produce_identical_native_input(self):
|
||||
raw=self.validate()
|
||||
wrapped=deepcopy(self.request);wrapped.pop("team")
|
||||
wrapped["roster"]={"snapshot":self.snapshot,"team_name":"teamB"}
|
||||
self.assertEqual(self.validate(wrapped)["native_request"],raw["native_request"])
|
||||
|
||||
def test_missing_or_conflicting_team_is_never_defaulted(self):
|
||||
request=deepcopy(self.request);request.pop("team")
|
||||
self.assertIn("invalid_roster",self.codes(self.validate(request)))
|
||||
request["team"]="teamA"
|
||||
self.assertIn("invalid_selected_team",self.codes(self.validate(request)))
|
||||
request["roster"]={"snapshot":self.snapshot,"team_name":"teamB"}
|
||||
self.assertIn("invalid_roster",self.codes(self.validate(request)))
|
||||
|
||||
def test_all_three_contexts_keep_original_position(self):
|
||||
for context,index in (("task_battle",0),("task_pass_stage",1)):
|
||||
request=deepcopy(self.request);request.update(context=context,stage_id=None,
|
||||
task_id="account-instance",step_index=index,battle_position={"battleType":"task",
|
||||
"stageId":None,"stageLevel":None,"taskTypeId":"original-task","taskStep":index})
|
||||
result=self.validate(request)
|
||||
self.assertEqual(result["reasons"],[])
|
||||
self.assertEqual(result["position"],request["battle_position"])
|
||||
request["battle_position"]["battleType"]="stage"
|
||||
self.assertIn("battle_position_mismatch",self.codes(self.validate(request)))
|
||||
|
||||
def test_mismatched_task_status_step_and_authored_config_refuse(self):
|
||||
request=deepcopy(self.request);request.update(context="task_battle",stage_id=None,
|
||||
task_id="original-task",step_index=1,battle_position=None)
|
||||
self.assertIn("invalid_battle_context",self.codes(self.validate(request)))
|
||||
request=deepcopy(self.request);request["original_data"]["battle"]["time"]=1
|
||||
self.assertIn("battle_config_mismatch",self.codes(self.validate(request)))
|
||||
|
||||
def test_unknown_original_mechanics_refuse_even_with_canonical_config(self):
|
||||
for field,value,code in (("controller",[{"type":"unknown"}],"unknown_battle_controller"),
|
||||
("triggers",[{"type":"time","effects":[{"type":"story"}]}],"unsupported_trigger_effect")):
|
||||
with self.subTest(field=field):
|
||||
self.battle[field]=value
|
||||
self.assertIn(code,self.codes(self.validate()))
|
||||
self.battle[field]=[]
|
||||
self.battle["battleField"]["mapAreas"]=[{"type":"block"}]
|
||||
self.assertIn("unknown_battle_area",self.codes(self.validate()))
|
||||
|
||||
def test_missing_assets_and_malformed_arrays_refuse(self):
|
||||
self.members.remove(self.member("data/img/monster/q/1001010_q_2.png"))
|
||||
self.assertIn("original_asset_missing",self.codes(self.validate()))
|
||||
self.battle["teams"]={}
|
||||
self.assertIn("invalid_battle_array",self.codes(self.validate()))
|
||||
|
||||
def test_missing_history_duplicate_slots_and_partial_attributes_refuse(self):
|
||||
request=deepcopy(self.request);del request["roster"]["history"]["passTask"]
|
||||
self.assertIn("incomplete_battle_history",self.codes(self.validate(request)))
|
||||
request=deepcopy(self.request);request["roster"]["teams"][0]["monsters"]=[1000001,1000001]
|
||||
self.assertIn("duplicate_selected_monster",self.codes(self.validate(request)))
|
||||
request=deepcopy(self.request);request["roster"]["monsterAttributes"]=[{"monsterId":1000001,"atk":0}]
|
||||
self.assertIn("incomplete_monster_additions",self.codes(self.validate(request)))
|
||||
|
||||
def test_skin_uses_visual_table_and_original_species_skills(self):
|
||||
self.tables["skin_info"]["1001011"]={"monType":"1001010"}
|
||||
self.tables["monster_info"]["1001011"]={"imgFix":{"2":{}},"skill_1":9999}
|
||||
self.members.add(self.member("data/img/monster/q/1001011_q_2.png"))
|
||||
self.snapshot["monsters"][0]["skin"]=1001011
|
||||
result=self.validate()
|
||||
self.assertEqual(result["reasons"],[])
|
||||
self.assertEqual(result["coverage"]["skill_ids"],[3])
|
||||
|
||||
def test_equipment_requires_original_params_and_its_visible_asset(self):
|
||||
self.snapshot["monsters"][0]["equip1"]=2000001
|
||||
self.snapshot["items"]=[{"id":2000001,"typeId":50001,"num":1,"isUsed":1,
|
||||
"itemClass":3,"equipParams":json.dumps(dict.fromkeys(ADD_FIELDS,0))}]
|
||||
self.tables["item_info"]["50001"]={"position":{"position":1,"img":True}}
|
||||
self.assertIn("original_asset_missing",self.codes(self.validate()))
|
||||
self.members.add(self.member("data/img/item/item_50001_o.png"))
|
||||
self.assertEqual(self.validate()["reasons"],[])
|
||||
self.snapshot["items"][0]["equipParams"]='{}'
|
||||
self.assertIn("incomplete_equipment",self.codes(self.validate()))
|
||||
|
||||
def test_public_dataclass_retains_canonical_raw_roster_fields(self):
|
||||
request=BattleRequest(**self.request)
|
||||
self.assertEqual(asdict(request)["team"],"teamB")
|
||||
self.assertEqual(asdict(request)["battle_position"],self.request["battle_position"])
|
||||
|
||||
def test_public_inspector_routes_engine_raw_roster_to_snapshot_validation(self):
|
||||
with patch("tools.battle_runtime.inputs.original_source",return_value=(self.tables,self.members)), \
|
||||
patch("tools.battle_runtime.trusted.verify_files",return_value=[]), \
|
||||
patch("ranch_assistant.battle_runtime.os",SimpleNamespace(name="nt")):
|
||||
result=BattleRuntime().inspect(self.request)
|
||||
self.assertTrue(result["supported"],result["reasons"])
|
||||
self.assertEqual(result["native_position"],self.request["battle_position"])
|
||||
self.assertEqual(result["watchdog_seconds"],690)
|
||||
self.assertFalse(result["settlement_eligible"])
|
||||
self.assertTrue(result["native_admission_validation_pending"])
|
||||
self.assertTrue(result["faithful"])
|
||||
self.assertFalse(result["server_acceptance_verified"])
|
||||
|
||||
|
||||
class ArtifactIdentityTests(unittest.TestCase):
|
||||
def swf(self, payloads):
|
||||
raw = bytearray(b"FWS\x32\0\0\0\0\0\0\x1e\x01\0")
|
||||
for code,payload in payloads:
|
||||
raw.extend(encode_tag(code,payload))
|
||||
raw.extend(encode_tag(0,b""));struct.pack_into("<I",raw,4,len(raw))
|
||||
return bytes(raw)
|
||||
|
||||
def test_library_copy_cannot_invoke_original_document_and_preserves_abc(self):
|
||||
abc = b"opaque original ABC byte identity fixture"
|
||||
bindings = struct.pack("<H",2)+struct.pack("<H",0)+b"GameStartup\0"+struct.pack("<H",42)+b"BattleAnimation\0"
|
||||
raw = self.swf([(76,bindings),(82,struct.pack("<I",0)+b"main\0"+abc)])
|
||||
converted,identity = library_only(raw)
|
||||
output = dict(tags(converted))
|
||||
self.assertEqual(symbols(output[76]),[(42,b"BattleAnimation")])
|
||||
self.assertEqual(output[82][output[82].index(0,4)+1:],abc)
|
||||
self.assertEqual(struct.unpack_from("<I",output[82])[0],1)
|
||||
self.assertEqual(identity["removed_document_classes"],["GameStartup"])
|
||||
self.assertEqual(identity["abc_sha256"],[hashlib.sha256(abc).hexdigest()])
|
||||
|
||||
def test_compressed_swf_has_same_library_code(self):
|
||||
raw = self.swf([(82,struct.pack("<I",1)+b"main\0abc")])
|
||||
compressed = b"CWS"+raw[3:8]+zlib.compress(raw[8:])
|
||||
self.assertEqual(library_only(raw)[0],library_only(compressed)[0])
|
||||
|
||||
def test_executable_or_import_tags_and_truncation_refuse(self):
|
||||
for tag in (12,59,72,57,71):
|
||||
with self.subTest(tag=tag),self.assertRaises(ValueError):
|
||||
library_only(self.swf([(tag,b"not allowed")]))
|
||||
with self.assertRaises(ValueError):library_only(self.swf([])[:-1])
|
||||
|
||||
def test_digest_validation_ignores_a_local_manifest_claiming_verification(self):
|
||||
with workspace_temp() as directory:
|
||||
root=Path(directory); (root/"runner.exe").write_bytes(b"replaced code")
|
||||
(root/"identity.json").write_text(json.dumps({"verified":True,"files":{"runner.exe":hashlib.sha256(b"replaced code").hexdigest()}}))
|
||||
reasons=verify_files(root,{"runner.exe":hashlib.sha256(b"reviewed code").hexdigest()})
|
||||
self.assertEqual(reasons,[{"code":"dependency_digest_mismatch","detail":"runner.exe"}])
|
||||
|
||||
def test_identical_preparation_does_not_replace_a_resource_open_by_another_job(self):
|
||||
with workspace_temp() as directory:
|
||||
path=Path(directory)/"resource";path.write_bytes(b"verified immutable bytes")
|
||||
with patch.object(Path,"replace",side_effect=PermissionError("shared reader")) as replace_file:
|
||||
write_atomic(path,b"verified immutable bytes")
|
||||
replace_file.assert_not_called()
|
||||
self.assertEqual(path.read_bytes(),b"verified immutable bytes")
|
||||
|
||||
def test_zip_index_ranges_decode_exact_original_stored_and_deflated_bytes(self):
|
||||
with workspace_temp() as directory:
|
||||
path=Path(directory)/"source.zip"
|
||||
originals={"a"*32:b"packed original bytes"*50,"b"*32:bytes(range(256))}
|
||||
with zipfile.ZipFile(path,"w") as archive:
|
||||
for index,(key,data) in enumerate(originals.items()):
|
||||
archive.writestr("assets/codes/"+key,data,compress_type=zipfile.ZIP_DEFLATED if index else zipfile.ZIP_STORED)
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
entries=asset_index(path,archive)
|
||||
with path.open("rb") as stream:
|
||||
for key,entry in entries.items():
|
||||
stream.seek(entry["offset"]);packed=stream.read(entry["compressed_size"])
|
||||
data=zlib.decompress(packed,-15) if entry["method"]==8 else packed
|
||||
self.assertEqual(data,originals[key])
|
||||
self.assertEqual(len(data),entry["size"])
|
||||
self.assertEqual(zlib.crc32(data),entry["crc32"])
|
||||
|
||||
def test_zip_index_refuses_mismatched_local_header_and_unsafe_keys(self):
|
||||
with workspace_temp() as directory:
|
||||
path=Path(directory)/"source.zip"
|
||||
with zipfile.ZipFile(path,"w") as archive:archive.writestr("assets/codes/"+"a"*32,b"data")
|
||||
with path.open("r+b") as stream:stream.seek(8);stream.write(struct.pack("<H",8))
|
||||
with zipfile.ZipFile(path) as archive,self.assertRaisesRegex(ValueError,"metadata"):
|
||||
asset_index(path,archive)
|
||||
with zipfile.ZipFile(path,"w") as archive:archive.writestr("assets/codes/../../escape",b"data")
|
||||
with zipfile.ZipFile(path) as archive,self.assertRaisesRegex(ValueError,"Unsupported"):
|
||||
asset_index(path,archive)
|
||||
|
||||
|
||||
class ProcessIsolationTests(unittest.TestCase):
|
||||
def test_child_executes_in_its_own_directory_and_nonzero_exit_is_error(self):
|
||||
with workspace_temp() as directory:
|
||||
root=Path(directory)
|
||||
result=run_isolated([sys.executable,"-I","-c","from pathlib import Path; print(Path.cwd().name)"],cwd=root,timeout=5)
|
||||
self.assertEqual(result.status,"completed",result.stderr)
|
||||
self.assertEqual(result.stdout.strip(),root.name)
|
||||
result=run_isolated([sys.executable,"-I","-c","raise SystemExit(7)"],cwd=root,timeout=5)
|
||||
self.assertEqual(result.status,"error")
|
||||
self.assertEqual(result.returncode,7)
|
||||
|
||||
def test_wall_timeout_terminates_child_promptly(self):
|
||||
with workspace_temp() as directory:
|
||||
result=run_isolated([sys.executable,"-I","-c","import time; time.sleep(30)"],cwd=Path(directory),timeout=.2)
|
||||
self.assertEqual(result.status,"timeout")
|
||||
self.assertLess(result.duration_seconds,3)
|
||||
|
||||
def test_mid_run_cancellation_terminates_child(self):
|
||||
event=threading.Event();timer=threading.Timer(.2,event.set);timer.start()
|
||||
try:
|
||||
with workspace_temp() as directory:
|
||||
result=run_isolated([sys.executable,"-I","-c","import time; time.sleep(30)"],cwd=Path(directory),timeout=5,cancel_event=event)
|
||||
finally:timer.cancel()
|
||||
self.assertEqual(result.status,"cancelled")
|
||||
self.assertLess(result.duration_seconds,3)
|
||||
|
||||
def test_pre_cancelled_run_does_not_spawn(self):
|
||||
event=threading.Event();event.set()
|
||||
with workspace_temp() as directory,patch("tools.battle_runtime.isolation.subprocess.Popen") as popen:
|
||||
result=run_isolated([sys.executable,"-I","-c","pass"],cwd=Path(directory),timeout=5,cancel_event=event)
|
||||
popen.assert_not_called();self.assertEqual(result.status,"cancelled")
|
||||
|
||||
@unittest.skipUnless(os.name=="nt","Windows Job Object process-tree check")
|
||||
def test_timeout_kills_worker_descendant_not_only_parent(self):
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
with workspace_temp() as directory:
|
||||
root=Path(directory)
|
||||
script="import subprocess,sys,time; from pathlib import Path; p=subprocess.Popen([sys.executable,'-I','-c','import time; time.sleep(30)']); Path('child.pid').write_text(str(p.pid)); time.sleep(30)"
|
||||
result=run_isolated([sys.executable,"-I","-c",script],cwd=root,timeout=.6)
|
||||
self.assertEqual(result.status,"timeout")
|
||||
self.assertTrue((root/"child.pid").exists())
|
||||
pid=int((root/"child.pid").read_text())
|
||||
kernel=ctypes.WinDLL("kernel32",use_last_error=True)
|
||||
kernel.OpenProcess.argtypes=[wintypes.DWORD,wintypes.BOOL,wintypes.DWORD];kernel.OpenProcess.restype=wintypes.HANDLE
|
||||
kernel.GetExitCodeProcess.argtypes=[wintypes.HANDLE,ctypes.POINTER(wintypes.DWORD)];kernel.CloseHandle.argtypes=[wintypes.HANDLE]
|
||||
handle=kernel.OpenProcess(0x1000,False,pid)
|
||||
if handle:
|
||||
try:
|
||||
code=wintypes.DWORD();kernel.GetExitCodeProcess(handle,ctypes.byref(code));self.assertNotEqual(code.value,259)
|
||||
finally:kernel.CloseHandle(handle)
|
||||
|
||||
|
||||
if __name__=="__main__":unittest.main()
|
||||
@@ -0,0 +1,503 @@
|
||||
"""Offline tests use synthetic ids/snapshots and public original static tables."""
|
||||
from copy import deepcopy
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from ranch_assistant.battle_simulator import (
|
||||
ExperimentalBattleRuntime, ORIGINAL_APK_SHA256, Stats, _offline_audit,
|
||||
combat_battles, combat_tables, damage_roll, simulate,
|
||||
)
|
||||
|
||||
|
||||
def monster(mid=101, species=1001010, level=20, **changes):
|
||||
row = combat_tables()["monster_info"][str(species)]
|
||||
result = {"id": mid, "typeId": species, "level": level, "mode": 2,
|
||||
"tpLevel": 0, "feel": 0, "upStar": 0, "pAtk": 0,
|
||||
"pDef": 0, "pHp": 0, "pDex": 0}
|
||||
for name in ("Atk", "Def", "Hp", "Dex"):
|
||||
stat = name.lower()
|
||||
result["g" + name] = (row[stat + "_grow_min"] + row[stat + "_grow_max"]) / 2
|
||||
result.update(changes)
|
||||
return result
|
||||
|
||||
|
||||
def enemy(**changes):
|
||||
result = {"type": "1001010", "team": 2, "mode": 2, "level": 1,
|
||||
"atk": 16, "def": 20, "hp": 101, "dex": 4, "spd_mov": .92,
|
||||
"spd_atk": 1595, "atk_dis": 100, "skill_1": 0, "skill_2": 0,
|
||||
"joinTime": -1, "wave": 1, "teamPos": 1, "ai": 0,
|
||||
"joinPoint": "point_team2_fore2", "controller": []}
|
||||
result.update(changes)
|
||||
return result
|
||||
|
||||
|
||||
def request(*, players=None, enemies=None, seconds=30, seed=0, master_level=43, **changes):
|
||||
players = players if players is not None else [monster()]
|
||||
result = {"context": "ordinary_stage", "seed": seed, "team": "teamA",
|
||||
"battle_position": {"battleType": "stage", "stageId": "fixture", "stageLevel": "1"},
|
||||
"roster": {"master": {"level": master_level}, "monsters": players,
|
||||
"teams": [{"teamName": "teamA", "monsters": [m["id"] for m in players]}],
|
||||
"monsterAttributes": []},
|
||||
"original_data": {"battle": {"time": seconds, "winType": ["1"], "loseType": ["1", "2"],
|
||||
"controller": [], "triggers": [], "teams": [{"team": 2, "numMax": 2, "ap": 80,
|
||||
"mons": enemies if enemies is not None else [enemy()]}],
|
||||
"battleField": {"fieldMode": True, "fieldName": "default", "mapAreas": [], "mapObjects": []}}}}
|
||||
result.update(changes)
|
||||
return result
|
||||
|
||||
|
||||
def battle_of(value):
|
||||
return value["original_data"]["battle"]
|
||||
|
||||
|
||||
class Midpoint:
|
||||
def uniform(self, low, high):
|
||||
return (low + high) / 2
|
||||
|
||||
|
||||
class CombatDataTests(unittest.TestCase):
|
||||
def test_complete_original_data_is_cached_and_recursively_immutable(self):
|
||||
data = combat_tables()
|
||||
self.assertIs(data, combat_tables())
|
||||
self.assertEqual(len(data["monster_info"]), 749)
|
||||
self.assertEqual(len(data["monster_skill"]), 266)
|
||||
self.assertEqual(len(combat_battles()["stage_info"]), 1178)
|
||||
self.assertEqual(len(combat_battles()["task_info"]), 1165)
|
||||
self.assertNotIn("stage_info", data) # Never decode the corpus in a battle worker.
|
||||
with self.assertRaises(TypeError):
|
||||
data["monster_info"]["1001010"]["atk"] = 999
|
||||
self.assertEqual(data["game_setting"]["countDamagePerAtk"], .95)
|
||||
self.assertEqual(data["game_setting"]["critAdd"], 1.5)
|
||||
self.assertEqual(data["monster_skill"]["3"]["lv1"]["para"]["ability"], .4)
|
||||
self.assertEqual(data["attack_profiles"]["43"]["source_class"], "AttackType2")
|
||||
|
||||
def test_manifest_identity_and_artifact_match(self):
|
||||
root = Path(__file__).resolve().parents[1] / "data"
|
||||
manifest = json.loads((root / "combat_manifest.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(manifest["source"]["apk_sha256"], ORIGINAL_APK_SHA256)
|
||||
for name, artifact in manifest["artifacts"].items():
|
||||
self.assertEqual(hashlib.sha256((root / name).read_bytes()).hexdigest(), artifact["sha256"])
|
||||
|
||||
def test_damage_formula_uses_original_numbers_and_no_extra_multiplier(self):
|
||||
defender = Stats(100, 100, 20, 10, 1600, .9, 100, 5)
|
||||
# round(100*.95 - 20*(.25*.75 + .25*.125)) = 91.
|
||||
self.assertEqual(damage_roll(100, 10, defender, combat_tables()["game_setting"], Midpoint()), 91)
|
||||
self.assertEqual(damage_roll(1, 10, defender, combat_tables()["game_setting"], Midpoint()), 1)
|
||||
|
||||
|
||||
class SimulatorTests(unittest.TestCase):
|
||||
def test_snapshot_sanity_records_are_preserved_and_never_repaired(self):
|
||||
mon = monster(mid=100001, pAtk=200000, feel=201, potentialLevel=1)
|
||||
req = request(players=[mon])
|
||||
inspected = ExperimentalBattleRuntime().inspect(req)
|
||||
codes = {a["code"] for a in inspected["anomalies"]}
|
||||
self.assertTrue({"+15overfeel", "+15overgrow", "+15overpoten", "+50overlv"}.issubset(codes))
|
||||
result = simulate(req)
|
||||
for record in inspected["anomalies"]:
|
||||
self.assertIn(record, result["anomalies"])
|
||||
self.assertGreater(result["units"][0]["stats"]["atk"], 200000)
|
||||
self.assertEqual(mon["feel"], 201)
|
||||
self.assertFalse(result["experimental_settlement_eligible"])
|
||||
|
||||
def test_authored_hidden_team_uses_only_original_configured_combatants(self):
|
||||
req = request(enemies=[enemy(hp=10), enemy(team=1, atk=10000)])
|
||||
battle_of(req)["hideTeamMon"] = True
|
||||
result = simulate(req)
|
||||
self.assertEqual(result["outcome"], "win")
|
||||
self.assertTrue(all(not a["id"].startswith("player-") for a in result["units"]))
|
||||
self.assertTrue(any(a["team"] == 1 for a in result["units"]))
|
||||
self.assertEqual(result["battle_data"]["battleMonIds"], [])
|
||||
|
||||
def test_three_routes_preserve_position_and_ordered_roster_ids_including_waiting(self):
|
||||
routes = {
|
||||
"ordinary_stage": {"battleType": "stage", "stageId": "fixture-stage", "stageLevel": "2", "taskTypeId": None, "taskStep": 0},
|
||||
"task_battle": {"battleType": "task", "stageId": None, "stageLevel": None, "taskTypeId": "fixture-task", "taskStep": 1},
|
||||
"task_pass_stage": {"battleType": "task", "stageId": None, "stageLevel": None, "taskTypeId": "fixture-pass", "taskStep": 2},
|
||||
}
|
||||
expected_ids = [202, 105, 301, 101, 111]
|
||||
for context, position in routes.items():
|
||||
req = request(context=context, battle_position=position, seconds=1,
|
||||
players=[monster(mid) for mid in expected_ids])
|
||||
req["roster"]["monsters"].reverse() # Team order wins over inventory order.
|
||||
result = simulate(req)
|
||||
self.assertEqual(result["battle_data"]["battleMonIds"], expected_ids)
|
||||
self.assertEqual(result["battle_data"]["battlePosition"],
|
||||
{k: v for k, v in position.items() if v is not None})
|
||||
self.assertEqual(sum(a["state"] == "waiting" and a["team"] == 1 for a in result["units"]), 1)
|
||||
self.assertNotIn(1001010, result["battle_data"]["battleMonIds"])
|
||||
|
||||
def test_source_boss_points_are_updated_by_actual_damage_and_deaths(self):
|
||||
for marker, expected in ((-1, 10), (7, 7)):
|
||||
result = simulate(request(enemies=[enemy(hp=10, bossPoint=marker)]))
|
||||
self.assertEqual(result["battle_data"]["bossDamage"], expected)
|
||||
self.assertEqual(result["battle_data"]["totalDamage"], 0)
|
||||
|
||||
def test_cancellation_during_simulation_retains_partial_trace(self):
|
||||
class CancelAfterTicks:
|
||||
calls = 0
|
||||
|
||||
def is_set(self):
|
||||
self.calls += 1
|
||||
return self.calls > 10
|
||||
|
||||
result = simulate(request(), cancel_event=CancelAfterTicks())
|
||||
self.assertEqual(result["outcome"], "cancelled")
|
||||
self.assertGreater(result["elapsed_ms"], 0)
|
||||
self.assertTrue(result["events"])
|
||||
self.assertIsNone(result["battle_data"])
|
||||
|
||||
def test_model_failure_keeps_detected_records(self):
|
||||
req = request(players=[monster(mid=100001, feel=201)])
|
||||
with patch("ranch_assistant.battle_simulator._Battle.tick", side_effect=RuntimeError("fixture")):
|
||||
result = simulate(req)
|
||||
self.assertEqual(result["execution_status"], "error")
|
||||
self.assertTrue(result["anomalies"])
|
||||
self.assertIsNone(result["battle_data"])
|
||||
|
||||
def test_known_copy_skills_use_original_factors_and_summons_count_alive(self):
|
||||
for species, skill_id, count, factor in ((1001010, 3, 1, .4), (1030010, 7, 3, .1)):
|
||||
req = request(players=[monster(species=species, pHp=100000)],
|
||||
enemies=[enemy(hp=1000000), enemy(hp=1000000)], seconds=20)
|
||||
result = simulate(req)
|
||||
summons = [u for u in result["units"] if u["summon_of"]]
|
||||
self.assertEqual(len(summons), count)
|
||||
parent = result["units"][0]
|
||||
self.assertEqual(result["battle_data"]["aliveNum"], count + 1)
|
||||
self.assertEqual(result["battle_data"]["battleMonIds"], [101])
|
||||
for child in summons:
|
||||
self.assertFalse(child["count_unit"])
|
||||
self.assertFalse(child["skills"])
|
||||
self.assertEqual(child["stats"]["atk"], int(parent["stats"]["atk"] * factor))
|
||||
self.assertEqual(child["stats"]["defense"], int(parent["stats"]["defense"] * factor))
|
||||
self.assertTrue(any(e["type"] == "skill" and e["skill"] == skill_id for e in result["events"]))
|
||||
ap = result["ap"]["1"]
|
||||
self.assertEqual(ap["current"], ap["initial"] - ap["spent"] + ap["recovered"])
|
||||
self.assertEqual(ap["spent"], 18 if skill_id == 3 else 20)
|
||||
|
||||
def test_area_hit_cleave_uses_original_skill9_and_spatial_neighbors(self):
|
||||
req = request(players=[monster(species=2004010, pHp=100000)],
|
||||
enemies=[enemy(hp=1000000), enemy(hp=1000000)], seconds=20)
|
||||
result = simulate(req)
|
||||
area = [e for e in result["events"] if e.get("reason") == "skill9_area"]
|
||||
self.assertTrue(area)
|
||||
self.assertTrue(all(e["hp_lost"] > 0 for e in area))
|
||||
stats = result["units"][0]["skills"][0]
|
||||
self.assertEqual(stats["id"], 9)
|
||||
self.assertEqual(stats["para"], {"areahurt": 1, "pow": 5})
|
||||
|
||||
def test_flash_move_and_four_hit_combo_are_executed(self):
|
||||
req = request(players=[monster(species=3010010, pHp=100000)],
|
||||
enemies=[enemy(hp=1000000), enemy(hp=1000000)], seconds=30)
|
||||
battle_of(req)["battleField"]["fieldName"] = "longMapDefault"
|
||||
result = simulate(req)
|
||||
used = {e["skill"] for e in result["events"] if e["type"] == "skill"}
|
||||
self.assertTrue({5, 38}.issubset(used))
|
||||
self.assertTrue(any(e["type"] == "dash" for e in result["events"]))
|
||||
casts = [e["at_ms"] for e in result["events"] if e["type"] == "skill" and e["skill"] == 38]
|
||||
attacks = [e for e in result["events"] if e["type"] == "attack" and e["actor"] == "player-1"]
|
||||
for start in casts:
|
||||
burst = [e for e in attacks if start <= e["at_ms"] < start + 1600]
|
||||
self.assertGreaterEqual(len(burst), 4)
|
||||
self.assertEqual(burst[0]["hit_delay_ms"], 100)
|
||||
|
||||
def test_projectile_speed_and_launch_delay_produce_nonzero_travel(self):
|
||||
result = simulate(request(players=[monster(species=1001020)], enemies=[enemy(hp=1000000)], seconds=8))
|
||||
projectiles = [e for e in result["events"] if e["type"] == "projectile" and e["actor"] == "player-1"]
|
||||
self.assertTrue(projectiles)
|
||||
self.assertGreater(projectiles[0]["travel_ms"], 0)
|
||||
attack = next(e for e in result["events"] if e["type"] == "attack" and e["actor"] == "player-1")
|
||||
self.assertEqual(attack["hit_delay_ms"], 100)
|
||||
self.assertGreaterEqual(projectiles[0]["at_ms"], attack["at_ms"] + 100)
|
||||
|
||||
def test_status_effects_healing_and_thorns_are_real_trajectory_events(self):
|
||||
for attributes, event_type, reason in (({"atkStun": 100}, "stun", None),
|
||||
({"atkPoi": 100, "atkPoiDmg": 15}, "damage", "poison"),
|
||||
({"thorns": 100}, "damage", "thorns"),
|
||||
({"atkVim": 50, "selfCure": 10}, "heal", None)):
|
||||
req = request(players=[monster(level=1, pHp=10000)], enemies=[enemy(hp=1000000)], seconds=20)
|
||||
req["roster"]["monsterAttributes"] = [dict(monsterId=101, **attributes)]
|
||||
result = simulate(req)
|
||||
self.assertTrue(any(e["type"] == event_type and (reason is None or e.get("reason") == reason)
|
||||
for e in result["events"]), attributes)
|
||||
if "atkVim" in attributes:
|
||||
self.assertGreater(result["units"][0]["healed"], 0)
|
||||
self.assertTrue(any(e.get("reason") == "selfCure" for e in result["events"]))
|
||||
|
||||
def test_overcure_preserves_exact_source_score_even_when_effective_heal_is_small(self):
|
||||
req = request(seconds=6, trace_limit=0, enemies=[enemy(hp=1000000)])
|
||||
req["roster"]["monsterAttributes"] = [{"monsterId": 101, "selfCure": 20001}]
|
||||
result = simulate(req)
|
||||
self.assertTrue(any(a["code"] == "+15overcure" and a["source_cheat_points"] == 19
|
||||
for a in result["anomalies"]))
|
||||
self.assertEqual(result["battle_data"]["cheatNum"], 19)
|
||||
self.assertFalse(result["experimental_settlement_eligible"])
|
||||
|
||||
def test_experimental_eligibility_is_separate_and_requires_completed_clean_model(self):
|
||||
report = ExperimentalBattleRuntime().inspect(request())
|
||||
self.assertFalse(report["experimental_settlement_eligible"])
|
||||
result = simulate(request())
|
||||
self.assertTrue(result["experimental_settlement_eligible"])
|
||||
self.assertFalse(result["settlement_eligible"])
|
||||
self.assertFalse(result["faithful"])
|
||||
anomaly = simulate(request(players=[monster(pAtk=200000)]))
|
||||
self.assertFalse(anomaly["experimental_settlement_eligible"])
|
||||
self.assertTrue(anomaly["experimental_eligibility_reasons"])
|
||||
|
||||
def test_original_stage_battle_executes_without_apk_or_network_reads(self):
|
||||
req = request()
|
||||
req["original_data"]["battle"] = combat_battles()["stage_info"]["0101"]["level"]["1"]["battle"]
|
||||
with patch("socket.socket", side_effect=AssertionError("No network")), \
|
||||
patch("zipfile.ZipFile", side_effect=AssertionError("No APK access")):
|
||||
result = simulate(req)
|
||||
self.assertEqual(result["outcome"], "win")
|
||||
self.assertGreater(result["kills"], 1)
|
||||
self.assertEqual(result["kill_monster"], {}) # Original stage enemies are mode 1.
|
||||
self.assertTrue(any(e["type"] == "wave" for e in result["events"]))
|
||||
|
||||
def test_full_snapshot_stats_follow_monster_vo_including_server_attributes(self):
|
||||
mon = monster(level=10, gAtk=3.125, gDef=2.5, gHp=30.25, gDex=1.25,
|
||||
tpLevel=2, pAtk=12, pDef=8, pHp=80, pDex=3, feel=120, upStar=1)
|
||||
req = request(players=[mon])
|
||||
req["roster"]["master"].update(globalAtk=7, globalDef=4, globalHp=55, globalDex=2)
|
||||
req["roster"]["monsterAttributes"] = [{"monsterId": 101, "atk": 13, "def": 9,
|
||||
"hp": 45, "dex": 2, "atkSpd": 5, "crit": 4, "apCostSave": 1}]
|
||||
inspected = ExperimentalBattleRuntime().inspect(req)
|
||||
self.assertTrue(inspected["supported"], inspected["reasons"])
|
||||
stats = inspected["units"][0]["stats"]
|
||||
original = combat_tables()["monster_info"]["1001010"]
|
||||
for stat, suffix in (("hp", "Hp"), ("atk", "Atk"), ("def", "Def"), ("dex", "Dex")):
|
||||
expected = int(1.21 * (original[stat] + mon["g" + suffix] * 11 + mon["p" + suffix]
|
||||
+ req["roster"]["master"]["global" + suffix]
|
||||
+ req["roster"]["monsterAttributes"][0][stat]))
|
||||
self.assertEqual(stats["defense" if stat == "def" else stat], expected)
|
||||
self.assertEqual(stats["attack_ms"], 1600 + int(-stats["dex"] * 3 / 4) - 80)
|
||||
self.assertEqual(stats["crit"], 4)
|
||||
self.assertEqual(inspected["units"][0]["ap_cost"], 0)
|
||||
|
||||
def test_inspect_is_honest_and_does_not_mutate_inputs(self):
|
||||
req = request()
|
||||
before = deepcopy(req)
|
||||
result = ExperimentalBattleRuntime().inspect(req)
|
||||
self.assertTrue(result["supported"])
|
||||
self.assertEqual(result["execution_mode"], "experimental")
|
||||
self.assertTrue(result["approximate"])
|
||||
self.assertFalse(result["faithful"])
|
||||
self.assertFalse(result["settlement_eligible"])
|
||||
self.assertTrue(result["requires_realtime_wait"])
|
||||
self.assertTrue(result["ignored_mechanics"])
|
||||
self.assertEqual(req, before)
|
||||
|
||||
def test_all_three_contexts_execute_deterministic_natural_win(self):
|
||||
first = None
|
||||
for context in ("ordinary_stage", "task_battle", "task_pass_stage"):
|
||||
result = simulate(request(context=context))
|
||||
self.assertEqual(result["outcome"], "win")
|
||||
self.assertTrue(result["terminal"])
|
||||
self.assertEqual(result["execution_status"], "completed")
|
||||
self.assertEqual(result["kills"], 1)
|
||||
self.assertEqual(result["battle_data"]["win"], True)
|
||||
if first:
|
||||
self.assertEqual(result["events"], first["events"])
|
||||
first = result
|
||||
|
||||
def test_natural_defeat_retains_actual_state_and_evidence(self):
|
||||
result = simulate(request(players=[monster(level=1)], enemies=[enemy(atk=10000, hp=10000)]))
|
||||
self.assertEqual(result["outcome"], "loss")
|
||||
self.assertEqual(result["terminal_reason"], "elimination")
|
||||
self.assertFalse(result["battle_data"]["win"])
|
||||
self.assertEqual(result["alive_num"], 0)
|
||||
self.assertEqual(result["units"][0]["hp"], 0)
|
||||
self.assertTrue(any(e["type"] == "death" for e in result["events"]))
|
||||
|
||||
def test_battle_clock_expiry_is_completed_loss_not_technical_timeout(self):
|
||||
req = request(seconds=1, enemies=[enemy(hp=100000, moveImmune=True, atk_dis=1)])
|
||||
result = simulate(req)
|
||||
self.assertEqual(result["outcome"], "loss")
|
||||
self.assertEqual(result["execution_status"], "completed")
|
||||
self.assertEqual(result["terminal_reason"], "battle_time_limit")
|
||||
self.assertEqual(result["elapsed_ms"], 1000)
|
||||
self.assertEqual(result["battle_data"]["leftTime"], 0)
|
||||
self.assertFalse(result["battle_data"]["win"])
|
||||
self.assertGreater(result["units"][0]["hp"], 0)
|
||||
|
||||
def test_technical_timeout_and_cancellation_have_no_battle_data(self):
|
||||
event = threading.Event()
|
||||
event.set()
|
||||
for result in (simulate(request(), timeout=0), simulate(request(), cancel_event=event)):
|
||||
self.assertIn(result["execution_status"], ("timed_out", "cancelled"))
|
||||
self.assertFalse(result["terminal"])
|
||||
self.assertIsNone(result["battle_data"])
|
||||
|
||||
def test_source_selective_kill_map_differs_from_all_kills(self):
|
||||
req = request(enemies=[enemy(hp=1, mode=1), enemy(hp=1, mode=2)])
|
||||
result = simulate(req)
|
||||
self.assertEqual(result["outcome"], "win")
|
||||
self.assertEqual(result["kills"], 2)
|
||||
self.assertEqual(result["all_kills"], {"1001010": 2})
|
||||
self.assertEqual(result["battle_data"]["killMonster"], {"1001010": 1})
|
||||
self.assertEqual(result["battle_data"]["totalDamage"], 0)
|
||||
self.assertEqual(result["battle_data"]["killNum"], 0)
|
||||
self.assertEqual(result["battle_data"]["deadNum"], 0)
|
||||
self.assertGreater(result["damage_hp_lost"]["2"], 0)
|
||||
|
||||
def test_waiting_roster_counts_alive_and_respects_source_capacity(self):
|
||||
players = [monster(i, level=1) for i in (101, 102, 103, 104, 105)]
|
||||
result = simulate(request(players=players, seconds=1, master_level=18))
|
||||
player_units = [a for a in result["units"] if a["team"] == 1]
|
||||
self.assertEqual(sum(a["state"] == "active" for a in player_units), 4)
|
||||
self.assertEqual(sum(a["state"] == "waiting" for a in player_units), 1)
|
||||
self.assertEqual(result["battle_data"]["aliveNum"], 5)
|
||||
self.assertTrue(all(e["ap_charged"] == 0 for e in result["events"] if e["type"] == "deploy"))
|
||||
|
||||
def test_order_reinforcements_and_wave_delay(self):
|
||||
req = request(enemies=[enemy(hp=1), enemy(hp=1, wave=2, joinTime=4)])
|
||||
result = simulate(req)
|
||||
self.assertEqual(result["outcome"], "win")
|
||||
wave_wait = next(e for e in result["events"] if e["type"] == "wave_wait")
|
||||
wave = next(e for e in result["events"] if e["type"] == "wave")
|
||||
self.assertEqual(wave["at_ms"] - wave_wait["at_ms"], 700)
|
||||
second = next(e for e in result["events"] if e["type"] == "deploy" and e.get("wave") == 2)
|
||||
self.assertGreaterEqual(second["at_ms"], 4000)
|
||||
|
||||
def test_unimplemented_skills_are_specific_and_explicit(self):
|
||||
req = request(players=[monster(species=1001020)]) # actual skill 10
|
||||
report = ExperimentalBattleRuntime().inspect(req)
|
||||
self.assertTrue(report["supported"])
|
||||
self.assertTrue(any(d["code"] == "unsupported_skill" and "10" in d["message"] for d in report["diagnostics"]))
|
||||
self.assertTrue(any("Skill 10" in x for x in report["ignored_mechanics"]))
|
||||
|
||||
def test_controllers_triggers_and_non_elimination_are_rejected(self):
|
||||
for key, value in (("controller", [{"type": "monMaker"}]),
|
||||
("triggers", [{"type": "dead"}]), ("winType", ["2"])):
|
||||
req = request()
|
||||
battle_of(req)[key] = value
|
||||
result = simulate(req)
|
||||
self.assertEqual(result["outcome"], "unsupported")
|
||||
self.assertFalse(result["supported"])
|
||||
self.assertIsNone(result["battle_data"])
|
||||
self.assertTrue(result["reasons"])
|
||||
|
||||
def test_missing_actual_growth_and_nonpositive_original_speed_are_rejected(self):
|
||||
req = request()
|
||||
req["roster"]["monsters"][0].pop("gAtk")
|
||||
self.assertFalse(ExperimentalBattleRuntime().inspect(req)["supported"])
|
||||
req = request()
|
||||
req["roster"]["monsterAttributes"] = [{"monsterId": 101, "atkSpd": 200}]
|
||||
report = ExperimentalBattleRuntime().inspect(req)
|
||||
self.assertFalse(report["supported"])
|
||||
self.assertTrue(any("nonpositive" in x for x in report["reasons"]))
|
||||
|
||||
def test_enemy_authored_stats_and_authored_scales_are_preserved(self):
|
||||
req = request(enemies=[enemy(atk=31, hp=101, dex=7, spd_atk=1595)])
|
||||
battle_of(req).update(scaleAbility=1.2, scaleHp=1.5)
|
||||
stats = ExperimentalBattleRuntime().inspect(req)["units"][1]["stats"]
|
||||
self.assertEqual(stats["atk"], 37)
|
||||
self.assertEqual(stats["hp"], 151)
|
||||
self.assertEqual(stats["dex"], 8)
|
||||
self.assertEqual(stats["attack_ms"], 1595)
|
||||
|
||||
def test_trace_limit_never_erases_overdamage_anomalies(self):
|
||||
req = request(players=[monster(pAtk=200000)], enemies=[enemy(hp=10)], trace_limit=1)
|
||||
result = simulate(req)
|
||||
self.assertEqual(result["outcome"], "win")
|
||||
self.assertEqual(len(result["events"]), 1)
|
||||
self.assertTrue(result["trace_truncated"])
|
||||
records = [a for a in result["anomalies"] if a["code"] == "+10overdamage"]
|
||||
self.assertTrue(records)
|
||||
self.assertGreater(records[0]["damage"], 80000)
|
||||
self.assertEqual(result["battle_data"]["cheatNum"], 10)
|
||||
self.assertEqual(result["battle_data"]["cheatRecords"], result["anomalies"])
|
||||
|
||||
def test_stats_and_snapshot_never_mutate_across_runs(self):
|
||||
req = request()
|
||||
before = deepcopy(req)
|
||||
a, b = simulate(req), simulate(req)
|
||||
self.assertEqual(a, b)
|
||||
self.assertEqual(req, before)
|
||||
|
||||
|
||||
class WorkerTests(unittest.TestCase):
|
||||
def test_object_request_and_snapshot_raw_have_the_same_contract(self):
|
||||
req = request()
|
||||
req["snapshot"] = SimpleNamespace(raw=req.pop("roster"))
|
||||
result = ExperimentalBattleRuntime().run(SimpleNamespace(**req))
|
||||
self.assertEqual(result["outcome"], "win")
|
||||
self.assertEqual(result["battle_data"]["battlePosition"], req["battle_position"])
|
||||
|
||||
def test_fixed_module_subprocess_equals_direct_model(self):
|
||||
req = request()
|
||||
with patch("socket.socket", side_effect=AssertionError("No network")):
|
||||
result = ExperimentalBattleRuntime().run(req)
|
||||
self.assertEqual(result, simulate(req))
|
||||
|
||||
def test_worker_entrypoint_does_not_import_gui_or_production_engine(self):
|
||||
completed = subprocess.run([sys.executable, "-c",
|
||||
"import sys; import ranch_assistant.battle_simulator; "
|
||||
"assert not any(n in sys.modules for n in "
|
||||
"('ranch_assistant.gui','ranch_assistant.engine','ranch_assistant.__main__',"
|
||||
"'ranch_assistant.battles','ranch_assistant.battle_runtime'))"], capture_output=True)
|
||||
self.assertEqual(completed.returncode, 0, completed.stderr)
|
||||
|
||||
def test_worker_network_guard_rejects_socket_audit_events(self):
|
||||
for event in ("socket.__new__", "socket.connect", "socket.getaddrinfo", "urllib.Request"):
|
||||
with self.assertRaises(PermissionError):
|
||||
_offline_audit(event, ())
|
||||
program = """import socket,sys
|
||||
from ranch_assistant.battle_simulator import _offline_audit
|
||||
sys.addaudithook(_offline_audit)
|
||||
try:
|
||||
socket.socket()
|
||||
except PermissionError:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError('worker socket creation must fail')
|
||||
"""
|
||||
completed = subprocess.run([sys.executable, "-c", program], capture_output=True)
|
||||
self.assertEqual(completed.returncode, 0, completed.stderr)
|
||||
|
||||
def test_cancel_and_wall_timeout_kill_and_reap_worker(self):
|
||||
for cancelled in (True, False):
|
||||
event = threading.Event()
|
||||
processes = []
|
||||
real_popen = subprocess.Popen
|
||||
|
||||
def observe(*args, **kwargs):
|
||||
self.assertEqual(args[0], [sys.executable, "-m", "ranch_assistant.battle_simulator", "--worker"])
|
||||
self.assertNotIn("shell", kwargs)
|
||||
self.assertEqual(kwargs["creationflags"], getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||
process = real_popen(*args, **kwargs)
|
||||
processes.append(process)
|
||||
if cancelled:
|
||||
event.set()
|
||||
return process
|
||||
|
||||
with patch("ranch_assistant.battle_simulator.subprocess.Popen", side_effect=observe):
|
||||
result = ExperimentalBattleRuntime().run(request(), cancel_event=event,
|
||||
timeout=10 if cancelled else .001)
|
||||
self.assertEqual(result["outcome"], "cancelled" if cancelled else "timeout")
|
||||
self.assertFalse(result["terminal"])
|
||||
self.assertIsNone(result["battle_data"])
|
||||
self.assertTrue(processes)
|
||||
self.assertIsNotNone(processes[0].poll())
|
||||
|
||||
def test_keyboard_interrupt_terminates_child(self):
|
||||
process = unittest.mock.MagicMock()
|
||||
process.communicate.side_effect = [KeyboardInterrupt, (b"", b"")]
|
||||
process.poll.return_value = None
|
||||
with patch("ranch_assistant.battle_simulator.subprocess.Popen", return_value=process):
|
||||
result = ExperimentalBattleRuntime().run(request())
|
||||
self.assertEqual(result["outcome"], "cancelled")
|
||||
process.kill.assert_called_once()
|
||||
self.assertIsNone(result["battle_data"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -199,6 +199,11 @@ class GrowthGuiTests(unittest.TestCase):
|
||||
window.engine.snapshot = client.snapshot()
|
||||
window.render(window.engine.snapshot, window.engine.plans())
|
||||
window.tabs.setCurrentWidget(window.monster_page)
|
||||
for _ in range(200):
|
||||
self.app.processEvents()
|
||||
QTest.qWait(5)
|
||||
if not window.busy and 501 in window.monsters.monster_items:
|
||||
break
|
||||
row = next(i for i in range(window.slots.rowCount()) if window.slots.item(i, 1).text() == "1")
|
||||
self.assertIn("待同步", window.slots.item(row, 5).text())
|
||||
self.assertIn("待成熟", window.slots.item(row, 7).text())
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
"""Native AIR integration tests; fixtures contain no account data or networking.
|
||||
|
||||
The tests compile the actual bridge once, then run all cases in a child
|
||||
ApplicationDomain with the pinned original SWFs. Missing local AIR assets skip
|
||||
the suite; compilation/runtime failures with installed assets fail the suite.
|
||||
"""
|
||||
import copy
|
||||
import unittest
|
||||
|
||||
from tools.battle_runtime.snapshot_bridge_check import (
|
||||
dependencies_available, run_checks, synthetic_snapshot,
|
||||
)
|
||||
|
||||
|
||||
@unittest.skipUnless(dependencies_available(), "Prepared local Windows AIR SDK/original libraries required")
|
||||
class NativeSnapshotBridgeTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
plain, rich = synthetic_snapshot(), synthetic_snapshot(rich=True)
|
||||
cases = []
|
||||
|
||||
def case(name, source=plain, *, team="teamA", integrity=False):
|
||||
snapshot = copy.deepcopy(source)
|
||||
cases.append(dict(name=name, snapshot=snapshot, teamName=team, integrity=integrity))
|
||||
return snapshot
|
||||
|
||||
case("plain", integrity=True)
|
||||
case("rich", rich, integrity=True)
|
||||
case("empty_attributes", integrity=True)["monsterAttributes"] = []
|
||||
flat_skin = case("flat_skin_entry", rich, integrity=True)
|
||||
flat_skin["items"] = []
|
||||
flat_skin["monsters"][0].update(equip2=0, pAtk=0, pDef=0, pHp=0, pDex=0)
|
||||
# Keep explicit server attributes independent of skin table abilities.
|
||||
# The bridge must use the supplied values once, not recalculate them.
|
||||
flat_skin["monsterAttributes"][0] = copy.deepcopy(plain["monsterAttributes"][0])
|
||||
flat_skin["monsterAttributes"][1]["def"] = 7
|
||||
case("shuffled_attributes", rich)["monsterAttributes"].reverse()
|
||||
case("low_master_level")["master"]["level"] = 1
|
||||
case("high_master_level")["master"]["level"] = 80
|
||||
case("original_tp_clamp")["monsters"][0]["tpLevel"] = 9
|
||||
case("original_skills")["monsters"][0].update(skill_1=999999, atk=999999, hp=999999)
|
||||
alternate = case("alternate_team", team="teamB")
|
||||
alternate["teams"].append(dict(teamName="teamB", teamType="pveBattleTeam",
|
||||
monsters=[0, 100000002, 100000003, 100000001, 0, 0, 0]))
|
||||
case("empty_padding")["teams"][0]["monsters"].append(0)
|
||||
with_egg = case("unselected_incubator")
|
||||
egg = copy.deepcopy(plain["monsters"][0])
|
||||
egg.update(id=100000004, process=2, mode=0, level=0, potentialLevel=0)
|
||||
with_egg["monsters"].append(egg)
|
||||
case("bad_feel", integrity=True)["monsters"][0]["feel"] = 201
|
||||
|
||||
missing_global = case("missing_global")
|
||||
del missing_global["master"]["globalAtk"]
|
||||
missing_growth = case("missing_growth")
|
||||
del missing_growth["monsters"][0]["gAtk"]
|
||||
case("absent_attribute_row", integrity=True)["monsterAttributes"].pop(0)
|
||||
missing_attribute_field = case("missing_attribute_field")
|
||||
del missing_attribute_field["monsterAttributes"][0]["atk"]
|
||||
missing_attributes = case("missing_attributes")
|
||||
del missing_attributes["monsterAttributes"]
|
||||
case("duplicate_attributes")["monsterAttributes"].append(copy.deepcopy(plain["monsterAttributes"][0]))
|
||||
case("species_as_instance")["teams"][0]["monsters"][0] = 1001010
|
||||
case("duplicate_member")["teams"][0]["monsters"][1] = 100000003
|
||||
case("incubating_member")["monsters"][0]["process"] = 2
|
||||
case("egg_member")["monsters"][0]["mode"] = 0
|
||||
case("exploring_member")["monsters"][0]["inExploreTeam"] = 1
|
||||
case("negative_member")["teams"][0]["monsters"][0] = -1
|
||||
case("empty_team")["teams"][0]["monsters"] = [0] * 7
|
||||
case("missing_team", team="absent")
|
||||
case("occupied_padding")["teams"][0]["monsters"].append(100000002)
|
||||
case("missing_equipment", rich)["items"] = []
|
||||
missing_params = case("missing_equip_params", rich)
|
||||
del missing_params["items"][0]["equipParams"]
|
||||
case("bad_equip_params", rich)["items"][0]["equipParams"] = "{broken"
|
||||
case("wrong_equipment_class", rich)["items"][0]["itemClass"] = 0
|
||||
overflowing_equip = case("equipment_id_overflow", rich)
|
||||
overflowing_equip["items"][0]["id"] = 2147483648
|
||||
overflowing_equip["monsters"][0]["equip2"] = 2147483648
|
||||
case("bad_entangle_json", rich)["monsters"][1]["entangleSkills"] = "null"
|
||||
missing_history = case("missing_history")
|
||||
del missing_history["history"]["monLib"]
|
||||
case("string_stat")["monsters"][0]["gAtk"] = "4.9"
|
||||
case("boolean_stat")["master"]["globalAtk"] = False
|
||||
|
||||
cls.evidence = run_checks(cases)
|
||||
if not cls.evidence["result"].get("ok"):
|
||||
raise AssertionError(cls.evidence["result"])
|
||||
cls.results = {row["name"]: row for row in cls.evidence["result"]["cases"]}
|
||||
|
||||
def accepted(self, name):
|
||||
result = self.results[name]
|
||||
self.assertTrue(result["ok"], result.get("error"))
|
||||
self.assertTrue(result["inputUnchanged"])
|
||||
self.assertTrue(result["installed"])
|
||||
self.assertTrue(result["contextUnchanged"])
|
||||
return result
|
||||
|
||||
def rejected(self, name, code, path=None):
|
||||
result = self.results[name]
|
||||
self.assertFalse(result["ok"], name)
|
||||
self.assertIn(f"SnapshotBridge[{code}]", result["error"], name)
|
||||
if path:
|
||||
self.assertIn(path, result["error"])
|
||||
self.assertTrue(result["inputUnchanged"], name)
|
||||
self.assertTrue(result["previousMasterRestored"], name)
|
||||
|
||||
def test_as3_compiles_and_runs_against_pinned_original_libraries(self):
|
||||
self.assertEqual(self.evidence["compiler_exit_code"], 0)
|
||||
self.assertEqual(self.evidence["process_exit_code"], 0)
|
||||
self.assertEqual(len(self.evidence["source_sha256"]), 64)
|
||||
|
||||
def test_original_values_and_ordered_instance_ids_reach_native_team(self):
|
||||
result = self.accepted("plain")
|
||||
self.assertEqual(result["validation"]["selectedIds"], [100000003, 100000001, 100000002])
|
||||
self.assertEqual(result["selectedSlots"], [100000003, 0, 100000001, 100000002, 0, 0, 0])
|
||||
self.assertEqual(result["nativeMembers"], [dict(mid=100000003, teamPos=1),
|
||||
dict(mid=100000001, teamPos=2),
|
||||
dict(mid=100000002, teamPos=5)])
|
||||
# Pinned original Lv1 slime values, independently of bridge mapping.
|
||||
first = result["units"][0]
|
||||
self.assertEqual(first["battle"], {"atk": 28, "def": 24, "hp": 335, "dex": 6})
|
||||
self.assertEqual(first["skill_1"], 3)
|
||||
|
||||
def test_rich_snapshot_preserves_equipment_potential_skin_and_entangle(self):
|
||||
result = self.accepted("rich")
|
||||
first, second = result["units"][:2]
|
||||
self.assertEqual(first["battle"], {"atk": 31, "def": 27, "hp": 393, "dex": 11})
|
||||
self.assertEqual(first["potential"], 1)
|
||||
self.assertEqual(first["equip2"], 100000101)
|
||||
self.assertEqual(first["special"]["atkPoi"], 2)
|
||||
self.assertEqual(first["special"]["atkPoiType"], 1)
|
||||
self.assertEqual(second["skinVo"], 1003011)
|
||||
self.assertEqual(second["entangleSkill"], {"1": 1001})
|
||||
self.assertTrue(second["entangle"])
|
||||
self.assertEqual(second["skill_1"], 6)
|
||||
self.assertEqual(second["battle"], {"atk": 48, "def": 39, "hp": 209, "dex": 11})
|
||||
self.assertEqual(result["inventory"], [dict(id=100000101, type=50001, num=1,
|
||||
isUsed=True, atk=0, hp=50, atkPoiType=1)])
|
||||
|
||||
def test_attributes_join_by_instance_id_and_are_not_double_counted(self):
|
||||
rich = self.accepted("rich")
|
||||
reordered = self.accepted("shuffled_attributes")
|
||||
self.assertEqual(rich["units"], reordered["units"])
|
||||
# The two slime instances share a species, but only one has equipment.
|
||||
self.assertEqual(rich["units"][0]["additions"]["hp"], 50)
|
||||
self.assertEqual(rich["units"][2]["additions"]["hp"], 0)
|
||||
|
||||
def test_explicit_empty_and_absent_attribute_rows_preserve_original_defaults(self):
|
||||
plain = self.accepted("plain")
|
||||
for name, count in (("empty_attributes", 0), ("absent_attribute_row", 2)):
|
||||
with self.subTest(name=name):
|
||||
result = self.accepted(name)
|
||||
self.assertEqual(result["validation"]["attributeCount"], count)
|
||||
self.assertEqual(result["units"], plain["units"])
|
||||
self.assertEqual(result["integrity"], plain["integrity"])
|
||||
self.assertEqual(result["inventory"], [])
|
||||
self.assertTrue(all(unit["skin"] == 0 for unit in result["units"]))
|
||||
|
||||
def test_flat_skin_table_resolves_original_entry_and_keeps_server_attributes(self):
|
||||
result = self.accepted("flat_skin_entry")
|
||||
skinned = result["units"][1]
|
||||
self.assertEqual(skinned["skinVo"], 1003011)
|
||||
self.assertEqual(skinned["skinEntry"], {"monType": "1003010",
|
||||
"ability": {"def": 15, "atkVim": 2},
|
||||
"sameOriginalEntry": True})
|
||||
self.assertEqual(skinned["additions"]["def"], 7)
|
||||
self.assertEqual(skinned["battle"]["def"], 31)
|
||||
self.assertEqual(self.accepted("rich")["units"][1]["battle"]["def"], 39)
|
||||
self.assertEqual(result["integrity"]["cheatNum"], 0)
|
||||
self.assertEqual(len(result["integrity"]["records"]), 3)
|
||||
|
||||
def test_ap_and_tp_levels_use_original_source_semantics(self):
|
||||
for name, level in (("low_master_level", 1), ("plain", 30), ("high_master_level", 80)):
|
||||
with self.subTest(name=name):
|
||||
result = self.accepted(name)
|
||||
self.assertEqual(result["validation"]["masterLevel"], level)
|
||||
self.assertEqual(result["nativeAP"], result["apFromRawLevel"])
|
||||
self.assertEqual(result["validation"]["ap"], result["nativeAP"])
|
||||
self.assertGreater(self.results["high_master_level"]["nativeAP"], self.results["plain"]["nativeAP"])
|
||||
self.assertEqual(self.accepted("original_tp_clamp")["units"][0]["tplevel"], 4)
|
||||
self.assertEqual(self.accepted("original_skills")["units"], self.accepted("plain")["units"])
|
||||
|
||||
def test_history_uses_original_flag_conversion_api(self):
|
||||
history = self.accepted("rich")["history"]
|
||||
self.assertEqual(history["guide_record"], {"firstOut": True})
|
||||
self.assertEqual(history["unlockCity"], {"1": True})
|
||||
self.assertEqual(history["passStage"], {"0101": {"1": True}})
|
||||
self.assertEqual(history["unlockStage"], {"0101": {"1": True}})
|
||||
self.assertEqual(history["monLib"], [1001010, 1003010])
|
||||
self.assertEqual(self.results["rich"]["validation"]["historyLoader"], "HistoryVo.loadHistoryData")
|
||||
|
||||
def test_selected_team_and_original_loader_padding(self):
|
||||
result = self.accepted("alternate_team")
|
||||
self.assertEqual(result["validation"]["teamName"], "teamB")
|
||||
self.assertEqual(result["validation"]["selectedIds"], [100000002, 100000003, 100000001])
|
||||
padding = self.accepted("empty_padding")
|
||||
self.assertEqual(padding["nativeMembers"], self.results["plain"]["nativeMembers"])
|
||||
self.assertEqual(len(padding["validation"]["rawSlots"]), 8)
|
||||
self.rejected("occupied_padding", "team_slot")
|
||||
|
||||
def test_unselected_incubation_does_not_change_selected_roster(self):
|
||||
result = self.accepted("unselected_incubator")
|
||||
self.assertEqual(result["loadedMonsterIds"], [100000001, 100000002, 100000003, 100000004])
|
||||
self.assertEqual(result["validation"]["monsterCount"], 4)
|
||||
self.assertEqual(result["validation"]["attributeCount"], 3)
|
||||
self.assertEqual(result["units"], self.accepted("plain")["units"])
|
||||
|
||||
def test_real_integrity_checker_records_high_ids_and_detects_invalid_input(self):
|
||||
for name in ("plain", "rich", "empty_attributes", "flat_skin_entry", "absent_attribute_row"):
|
||||
integrity = self.accepted(name)["integrity"]
|
||||
self.assertEqual(integrity["cheatNum"], 0)
|
||||
ids = [int(record["mid"]) for record in integrity["records"]]
|
||||
self.assertEqual(ids, [100000003, 100000001, 100000002])
|
||||
self.assertTrue(all(mid > 100000000 for mid in ids))
|
||||
self.assertIn("+0uneqmon100000001", integrity["text"])
|
||||
self.assertIsNotNone(integrity["records"][0]["skillLevel1"])
|
||||
invalid = self.accepted("bad_feel")
|
||||
self.assertEqual(invalid["units"][0]["feel"], 201)
|
||||
self.assertGreater(invalid["integrity"]["cheatNum"], 0)
|
||||
self.assertIn("overfeel", invalid["integrity"]["text"])
|
||||
self.assertEqual(len(invalid["integrity"]["records"]), 3)
|
||||
self.assertIsNotNone(invalid["integrity"]["master"])
|
||||
|
||||
def test_missing_stats_fail_with_paths_without_zero_defaults(self):
|
||||
for name, code, path in (
|
||||
("missing_global", "missing_number", "master.globalAtk"),
|
||||
("missing_growth", "missing_number", "monsters[0].gAtk"),
|
||||
("missing_attribute_field", "missing_number", "monsterAttributes[0].atk"),
|
||||
("missing_attributes", "missing_array", "monsterAttributes"),
|
||||
("string_stat", "missing_number", "monsters[0].gAtk"),
|
||||
("boolean_stat", "missing_number", "master.globalAtk"),
|
||||
("missing_history", "missing_array", "history.monLib"),
|
||||
):
|
||||
with self.subTest(name=name):
|
||||
self.rejected(name, code, path)
|
||||
|
||||
def test_selected_members_must_exist_and_be_available(self):
|
||||
for name, code in (
|
||||
("species_as_instance", "missing_team_member"), ("duplicate_member", "duplicate_member"),
|
||||
("incubating_member", "incubating_member"), ("egg_member", "incubating_member"),
|
||||
("exploring_member", "exploring_member"), ("negative_member", "team_member_id"),
|
||||
("empty_team", "empty_team"), ("missing_team", "team_missing"),
|
||||
("duplicate_attributes", "duplicate_attributes"),
|
||||
):
|
||||
with self.subTest(name=name):
|
||||
self.rejected(name, code)
|
||||
|
||||
def test_incomplete_equipment_and_entangle_cannot_enter_original_error_fallbacks(self):
|
||||
for name, code in (
|
||||
("missing_equipment", "missing_equipment"), ("missing_equip_params", "json_string"),
|
||||
("bad_equip_params", "json_string"), ("wrong_equipment_class", "equipment_class"),
|
||||
("equipment_id_overflow", "equipment_id"),
|
||||
("bad_entangle_json", "missing_object"),
|
||||
):
|
||||
with self.subTest(name=name):
|
||||
self.rejected(name, code)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,733 @@
|
||||
"""Offline source-derived progression tests; no clients or game servers."""
|
||||
from copy import deepcopy
|
||||
from dataclasses import asdict, replace
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import zipfile
|
||||
|
||||
from ranch_assistant.game_data import (
|
||||
BATTLES_NAME, DATA_DIR, DATA_NAME, MANIFEST_NAME,
|
||||
ORIGINAL_APK_SHA256, ProgressionData, ProgressionDataError, load_progression_data,
|
||||
)
|
||||
from ranch_assistant.model import Catalog, Policy, Snapshot
|
||||
from ranch_assistant.progression import ProgressionPlanner, ProgressionPolicy
|
||||
from ranch_assistant.quests import QuestPolicy
|
||||
from tools.build_progression_data import farming_index, summarize_script
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def step(kind="none", **changes):
|
||||
return {"statusType": kind, "statusValue": {}, "story": "", "afterStory": "",
|
||||
"position": "", "npc": "", "unlockStages": [], "condition": {}, **changes}
|
||||
|
||||
|
||||
def task(type_id="100", *, steps=None, **changes):
|
||||
return {"id": type_id, "name": "离线测试任务", "type": 1, "startStep": step(),
|
||||
"steps": [step()] if steps is None else steps, "closed": False,
|
||||
"nextTasks": [], "unlockTasks": [], "unlockStages": [], **changes}
|
||||
|
||||
|
||||
def snapshot(**changes):
|
||||
return Snapshot({"master": {"id": 1, "level": 20, "money": 2000, "ti": 50},
|
||||
"items": [], "monsters": [], "stacks": [], "rooms": [], "teams": [],
|
||||
"history": {"unlockCity": {"1": True}, "unlockStage": {"0101": [1, 2, 3]},
|
||||
"passStage": {}, "passTask": {}, "unlockTask": {}, "openHardMode": True},
|
||||
"currentTasks": [{"id": 11, "typeId": "100", "curStep": 1, "stepValue": None}],
|
||||
**changes})
|
||||
|
||||
|
||||
def config(tasks=None, **changes):
|
||||
return {"task_info": tasks or {"100": task()}, "scripts": {
|
||||
"linear": {"supported": True, "answer": None, "dialogue_lines": 5},
|
||||
"accept": {"supported": True, "answer": True, "dialogue_lines": 3},
|
||||
"choice": {"supported": False, "answer": None, "block_reasons": ["unsupported command: option"]}},
|
||||
"game_setting": {"cityInfo": {"1": {"name": "莉莉托斯", "cid": "1"}}}, "setting": {},
|
||||
"stage_info": {"0101": {"id": "0101", "name": "王城郊外 1-1", "city": 1, "cost": {"ti": 2},
|
||||
"level": {str(i): {"cost": i, "battle_available": True} for i in (1, 2, 3)}}},
|
||||
"npc_info": {"nina": {"name": "妮娜"}}, "stage_sp": {}, **changes}
|
||||
|
||||
|
||||
class ProgressionTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.catalog = Catalog()
|
||||
|
||||
def setUp(self):
|
||||
self.policy = ProgressionPolicy(enabled=True)
|
||||
self.ranch = Policy(keep_money=1000)
|
||||
self.snapshot = snapshot()
|
||||
self.planner = ProgressionPlanner(self.catalog, config())
|
||||
|
||||
def plan(self):
|
||||
return self.planner.plan(self.snapshot, self.policy, self.ranch)
|
||||
|
||||
def next(self, kind):
|
||||
planned = self.plan()
|
||||
self.assertTrue(planned)
|
||||
self.assertEqual(planned[0].kind, kind, planned[0].description)
|
||||
return planned[0]
|
||||
|
||||
def test_policy_defaults_roundtrip_and_validation(self):
|
||||
policy = ProgressionPolicy()
|
||||
self.assertFalse(policy.enabled)
|
||||
self.assertEqual(ProgressionPolicy.from_dict(json.loads(json.dumps(asdict(policy)))), policy)
|
||||
for changes in ({"enabled": "false"}, {"reserve_ti": -1}, {"stop_after_loss": 0},
|
||||
{"max_money": float("nan")}, {"allow_items": 1}, {"team": ""},
|
||||
{"team": "has\nnewline"}, {"team": " too much space "}, {"team": "x" * 65},
|
||||
{"battle_mode": "faithful_estimate"},
|
||||
{"item_reserves": {"20001": -2}}, {"item_reserves": {"token": 1}}):
|
||||
with self.subTest(changes=changes), self.assertRaises(ValueError):
|
||||
ProgressionPolicy(**changes)
|
||||
with self.assertRaises(ValueError):
|
||||
ProgressionPolicy.from_dict({"session": "must-not-import"})
|
||||
self.assertEqual(ProgressionPolicy(team="自定义编队").team, "自定义编队")
|
||||
self.assertEqual(ProgressionPolicy(team="bonusTeam4").battle_mode, "original")
|
||||
self.assertEqual(ProgressionPolicy(battle_mode="experimental").to_dict()["battle_mode"], "experimental")
|
||||
self.assertEqual(self.planner.plan(self.snapshot, ProgressionPolicy(), self.ranch), [])
|
||||
|
||||
def test_nonbattle_server_ack_then_local_complete_then_reward(self):
|
||||
original = deepcopy(self.snapshot.raw)
|
||||
action = self.next("progression_step")
|
||||
self.assertEqual(action.path, "taskService/taskCompleteStep")
|
||||
self.assertEqual(action.payload, {"taskId": 11, "taskTypeId": "100", "removeIds": None})
|
||||
self.assertNotIn("battleData", action.payload)
|
||||
self.planner.mark_started(self.snapshot, action)
|
||||
self.assertTrue(self.plan()[0].block_reason)
|
||||
self.planner.acknowledge(self.snapshot, action, {"taskStepValue": None})
|
||||
self.assertFalse(self.planner.acknowledge(self.snapshot, action, {}))
|
||||
local = self.next("progression_local_step")
|
||||
self.assertEqual(local.path, "")
|
||||
self.planner.acknowledge(self.snapshot, local)
|
||||
reward = self.next("progression_complete")
|
||||
self.assertEqual(reward.payload, {"taskId": 11, "taskTypeId": "100"})
|
||||
self.planner.acknowledge(self.snapshot, reward, {"reward": {}})
|
||||
self.assertEqual(self.plan(), [])
|
||||
self.assertEqual(self.snapshot.raw, original)
|
||||
|
||||
def test_ordinary_dialogue_and_navigation_are_logical_and_do_not_submit_twice(self):
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"100": task(steps=[
|
||||
step(story="linear", afterStory="linear", position="city1_market", npc="nina"), step()])}))
|
||||
nav = self.next("progression_navigate")
|
||||
self.assertEqual(nav.position, "city1_market")
|
||||
self.assertEqual(nav.payload, {})
|
||||
self.assertEqual(nav.npc_name, "妮娜")
|
||||
self.assertIn("市场", nav.location)
|
||||
self.planner.acknowledge(self.snapshot, nav)
|
||||
before = self.next("progression_dialogue")
|
||||
self.assertEqual(before.phase, "before")
|
||||
self.planner.acknowledge(self.snapshot, before)
|
||||
server = self.next("progression_step")
|
||||
self.assertEqual(self.snapshot.raw["currentTasks"][0]["curStep"], 1)
|
||||
self.planner.acknowledge(self.snapshot, server, {})
|
||||
after = self.next("progression_dialogue")
|
||||
self.assertEqual(after.phase, "after")
|
||||
self.planner.acknowledge(self.snapshot, after)
|
||||
self.planner.acknowledge(self.snapshot, self.next("progression_local_step"))
|
||||
following = self.next("progression_step")
|
||||
self.assertEqual(following.step_number, 2)
|
||||
self.assertEqual(self.snapshot.raw["currentTasks"][0]["curStep"], 1)
|
||||
|
||||
def test_empty_before_story_does_not_skip_after_story(self):
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"100": task(steps=[step(afterStory="linear")])}))
|
||||
self.planner.acknowledge(self.snapshot, self.next("progression_step"), {})
|
||||
self.assertEqual(self.next("progression_dialogue").phase, "after")
|
||||
|
||||
def test_server_step_advance_does_not_skip_unfinished_acknowledged_after_story(self):
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"100": task(steps=[step(afterStory="linear"), step()])}))
|
||||
self.planner.acknowledge(self.snapshot, self.next("progression_step"), {})
|
||||
self.snapshot.raw["currentTasks"][0]["curStep"] = 2
|
||||
self.assertEqual(self.next("progression_dialogue").step_number, 1)
|
||||
|
||||
def test_finished_received_unlocked_states_deduplicate(self):
|
||||
self.snapshot.raw["history"]["unlockTask"] = {"100": True}
|
||||
rows = self.planner.rows(self.snapshot, self.policy, self.ranch)
|
||||
self.assertEqual(len(rows), 1)
|
||||
self.assertEqual(rows[0]["state"], "received")
|
||||
self.assertEqual(self.next("progression_step").task_id, 11)
|
||||
self.snapshot.raw["history"]["passTask"] = {"100": True}
|
||||
self.assertEqual(self.plan(), [])
|
||||
self.assertEqual(self.planner.rows(self.snapshot, self.policy, self.ranch)[0]["state"], "finished")
|
||||
|
||||
def test_task_history_id_lists_are_supported_alongside_flag_mappings(self):
|
||||
self.snapshot.raw["currentTasks"] = []
|
||||
self.snapshot.raw["history"]["unlockTask"] = [100]
|
||||
self.next("progression_accept")
|
||||
self.snapshot.raw["history"]["passTask"] = [100]
|
||||
self.assertEqual(self.plan(), [])
|
||||
|
||||
def test_accept_uses_verified_payload_and_success_instance(self):
|
||||
self.snapshot.raw["currentTasks"] = []
|
||||
self.snapshot.raw["history"]["unlockTask"] = {"100": True}
|
||||
accept = self.next("progression_accept")
|
||||
self.assertEqual(accept.path, "taskService/taskReceive")
|
||||
self.assertEqual(accept.payload, {"taskTypeId": "100"})
|
||||
self.planner.acknowledge(self.snapshot, accept, {"task": {"id": 15, "typeId": "100", "stepValue": None}})
|
||||
self.assertEqual(self.next("progression_step").task_id, 15)
|
||||
|
||||
def test_start_answer_is_required_and_choice_scripts_are_blocked(self):
|
||||
self.snapshot.raw["currentTasks"] = []
|
||||
self.snapshot.raw["history"]["unlockTask"] = {"100": True}
|
||||
for name in ("linear", "choice", "missing"):
|
||||
with self.subTest(name=name):
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"100": task(startStep=step(story=name))}))
|
||||
self.assertTrue(self.plan()[0].block_reason)
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"100": task(startStep=step(story="accept"))}))
|
||||
self.planner.acknowledge(self.snapshot, self.next("progression_dialogue"))
|
||||
self.next("progression_accept")
|
||||
|
||||
def test_missing_accept_response_never_invents_an_instance(self):
|
||||
self.snapshot.raw["currentTasks"] = []
|
||||
self.snapshot.raw["history"]["unlockTask"] = {"100": True}
|
||||
action = self.next("progression_accept")
|
||||
self.assertFalse(self.planner.acknowledge(self.snapshot, action, {}))
|
||||
self.assertIn("禁止自动重发", self.plan()[0].block_reason)
|
||||
|
||||
def test_reward_reply_received_successor_and_unlocked_sidequest(self):
|
||||
self.planner = ProgressionPlanner(self.catalog, config({
|
||||
"100": task(), "101": task("101"), "200": task("200", type=2)}))
|
||||
self.snapshot.raw["currentTasks"][0]["curStep"] = 2
|
||||
action = self.next("progression_complete")
|
||||
self.planner.acknowledge(self.snapshot, action, {
|
||||
"nextTasks": [{"id": 12, "typeId": "101", "curStep": 1}], "unlockTasks": ["200"]})
|
||||
following = self.next("progression_step")
|
||||
self.assertEqual(following.task_type_id, "101")
|
||||
states = {row["task_type_id"]: row["state"] for row in self.planner.rows(self.snapshot, self.policy, self.ranch)}
|
||||
self.assertEqual(states, {"100": "finished", "101": "received", "200": "unlocked"})
|
||||
|
||||
def test_graph_repair_uses_explicit_edges_and_three_exact_arrays(self):
|
||||
self.planner = ProgressionPlanner(self.catalog, config({
|
||||
"100": task(nextTasks=["500", "501"], unlockTasks=["700"]),
|
||||
"500": task("500"), "501": task("501", closed=True), "700": task("700", type=2)}))
|
||||
self.snapshot.raw["currentTasks"] = []
|
||||
self.snapshot.raw["history"]["passTask"] = {"100": True, "unrelated": False}
|
||||
self.policy.sidequests = True
|
||||
action = self.next("progression_update")
|
||||
self.assertEqual(action.path, "taskService/taskUpdate")
|
||||
self.assertEqual(action.payload, {"receiveTasks": [{"prev": "100", "taskTypeId": "500"}],
|
||||
"unlockTasks": [{"prev": "100", "taskTypeId": "700"}], "removeTasks": []})
|
||||
self.snapshot.raw["history"]["unlockTask"] = {"500": True, "700": True}
|
||||
self.policy.accept = False
|
||||
self.assertNotIn("progression_update", [action.kind for action in self.plan()])
|
||||
|
||||
def test_graph_no_guessed_first_task_and_legacy_root_is_respected(self):
|
||||
self.snapshot.raw["currentTasks"] = []
|
||||
self.assertEqual(self.plan(), [])
|
||||
data = config({"999": task("999", nextTasks=["100"]), "100": task()}, setting={"useOldNewTaskFunction": True})
|
||||
self.planner = ProgressionPlanner(self.catalog, data)
|
||||
self.snapshot.raw["history"]["passTask"] = {"999": True}
|
||||
self.assertEqual(self.plan(), [])
|
||||
|
||||
def test_closed_task_removal_ack_is_not_replayed_on_a_stale_snapshot(self):
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"100": task(closed=True)}))
|
||||
action = self.next("progression_update")
|
||||
self.assertEqual(action.payload, {"unlockTasks": [], "receiveTasks": [], "removeTasks": [11]})
|
||||
self.planner.acknowledge(self.snapshot, action, {})
|
||||
self.assertEqual(self.plan(), [])
|
||||
|
||||
def test_declared_conditions_time_and_loader_anomaly_are_conservative(self):
|
||||
self.assertFalse(self.planner.condition({"minLevel": 21}, self.snapshot)[0])
|
||||
self.assertFalse(self.planner.condition({"maxLevel": 19}, self.snapshot)[0])
|
||||
self.assertFalse(self.planner.condition({"close": True}, self.snapshot)[0])
|
||||
self.assertFalse(self.planner.condition({"unfinishTask": ["100"]}, self.snapshot)[0])
|
||||
self.assertFalse(self.planner.condition({"passStage": ["0101"]}, self.snapshot)[0])
|
||||
self.assertTrue(self.planner.condition({"unlockStage": ["0101"]}, self.snapshot)[0])
|
||||
self.assertFalse(self.planner.condition({"lang": "CN"}, self.snapshot)[0])
|
||||
self.snapshot.raw["client_context"] = {"lang": "CN", "platform": "ANDROID", "channel": "DYD"}
|
||||
self.assertTrue(self.planner.condition({"lang": "CN", "platform": "ANDROID"}, self.snapshot)[0])
|
||||
self.assertFalse(self.planner.condition({"futureFlag": True}, self.snapshot)[0])
|
||||
with patch("ranch_assistant.model.time.time", return_value=1794112200):
|
||||
# 2026-11-08 12:30 UTC+8, Sunday == AS3 day 0.
|
||||
self.assertTrue(self.planner.condition({"week": [0], "startTime": 1230, "endTime": 1230}, self.snapshot)[0])
|
||||
self.assertFalse(self.planner.condition({"week": [1]}, self.snapshot)[0])
|
||||
self.assertFalse(self.planner.condition({"endTimestamp": 1}, self.snapshot)[0])
|
||||
|
||||
def test_guide_gates_and_special_gacha_stay_blocked(self):
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"100": task(steps=[step(passGuide="minefail")])}))
|
||||
self.assertTrue(self.plan()[0].block_reason)
|
||||
self.snapshot.raw["history"]["guide_record"] = {"minefail": True}
|
||||
self.next("progression_step")
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"1001006": task("1001006", steps=[step()] * 4)}))
|
||||
self.snapshot.raw["currentTasks"] = [{"id": 12, "typeId": "1001006", "curStep": 4}]
|
||||
self.assertIn("特殊抽蛋", self.plan()[0].block_reason)
|
||||
|
||||
def test_item_reserve_locks_and_exact_remove_ids(self):
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"100": task(steps=[step("getItem", statusValue={"type": 30001, "num": 3, "remove": True})])}))
|
||||
self.snapshot.raw["items"] = [{"id": 1, "typeId": 30001, "num": 2}, {"id": 2, "typeId": 30001, "num": 4},
|
||||
{"id": 3, "typeId": 30001, "num": 100, "lock": True}]
|
||||
self.assertIn("未启用", self.plan()[0].block_reason)
|
||||
self.policy.allow_items = True
|
||||
self.policy.item_reserves = {"30001": 4}
|
||||
self.assertIn("保留", self.plan()[0].block_reason)
|
||||
self.policy.item_reserves = {"30001": 3}
|
||||
action = self.next("progression_step")
|
||||
self.assertEqual(action.payload["removeIds"], [1, 2])
|
||||
self.assertEqual(self.snapshot.raw["items"][1]["num"], 4)
|
||||
|
||||
def test_observation_only_items_still_send_source_ids_without_allowing_consumption(self):
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"100": task(steps=[step("getItem", statusValue={"type": 30001, "num": 2, "remove": False})])}))
|
||||
self.snapshot.raw["items"] = [{"id": 1, "typeId": 30001, "num": 2}]
|
||||
self.policy.item_reserves = {"30001": 100}
|
||||
self.assertEqual(self.next("progression_step").payload["removeIds"], [1])
|
||||
|
||||
def test_money_removal_respects_maximum_and_ranch_reserve(self):
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"100": task(steps=[step("getMoney", statusValue={"money": 1200, "remove": True})])}))
|
||||
self.assertIn("上限", self.plan()[0].block_reason)
|
||||
self.policy.max_money = 1200
|
||||
self.assertIn("保留", self.plan()[0].block_reason)
|
||||
self.snapshot.raw["master"]["money"] = 2200
|
||||
self.next("progression_step")
|
||||
|
||||
def test_monster_submission_never_consumes_team_locked_or_reserved_monsters(self):
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"100": task(steps=[step("getMonster", statusValue={"type": 1001010, "num": 1, "mode": 2, "remove": True})])}))
|
||||
base = self.catalog.monster(1001010)
|
||||
monster = {"id": 1, "typeId": 1001010, "mode": 2, "process": 3, "level": 1,
|
||||
**{"g" + stat.capitalize(): base[stat + "_grow_min"] for stat in ("atk", "def", "hp", "dex")}}
|
||||
self.snapshot.raw["monsters"] = [monster]
|
||||
self.policy.allow_monsters = True
|
||||
self.ranch.protect_quality = 5
|
||||
self.assertEqual(self.next("progression_step").payload["removeIds"], [1])
|
||||
for changes in ({"lock": True}, {"entangle": True}, {"equip1": 3}, {"inExploreTeam": True}):
|
||||
with self.subTest(changes=changes):
|
||||
self.snapshot.raw["monsters"] = [monster | changes]
|
||||
self.assertTrue(self.plan()[0].block_reason)
|
||||
self.snapshot.raw["monsters"] = [monster]
|
||||
self.snapshot.raw["teams"] = [{"monsters": [1]}]
|
||||
self.assertTrue(self.plan()[0].block_reason)
|
||||
self.snapshot.raw["teams"] = []
|
||||
self.ranch.reserved_types = [1001010]
|
||||
self.assertTrue(self.plan()[0].block_reason)
|
||||
|
||||
def test_kill_target_uses_step_value_and_never_configured_relative_count(self):
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"100": task(steps=[step("killMonster", statusValue={"type": 1001010, "num": 2})])}))
|
||||
self.snapshot.raw["currentTasks"][0]["stepValue"] = 150
|
||||
self.snapshot.raw["history"]["numKillMonsters"] = {"1001010": 149}
|
||||
self.assertTrue(self.plan()[0].block_reason)
|
||||
self.snapshot.raw["history"]["numKillMonsters"]["1001010"] = 150
|
||||
self.next("progression_step")
|
||||
self.snapshot.raw["currentTasks"][0]["stepValue"] = None
|
||||
self.assertIn("未同步", self.plan()[0].block_reason)
|
||||
|
||||
def test_pass_stage_and_task_battle_route_are_distinct_and_never_sweeps(self):
|
||||
for kind in ("battle", "passStage"):
|
||||
with self.subTest(kind=kind):
|
||||
value = {"stage": "0101", "level": "1"} if kind == "passStage" else {}
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"100": task(steps=[step(kind, statusValue=value, battle={"teams": [{"mons": []}]})])}))
|
||||
self.snapshot.raw["history"]["passStage"] = {"0101": [1, 2, 3]}
|
||||
action = self.next("progression_battle")
|
||||
self.assertEqual(action.path, "battleService/battleStart")
|
||||
self.assertEqual(action.payload, {"battleType": "task", "taskTypeId": "100"})
|
||||
self.assertEqual(action.battle_kind, "task" if kind == "battle" else "passStage")
|
||||
self.assertEqual(action.stage_id, "" if kind == "battle" else "0101")
|
||||
self.assertNotIn("battleData", action.payload)
|
||||
self.planner.battle_lost(self.snapshot, action)
|
||||
self.assertIn("战败", self.plan()[0].block_reason)
|
||||
|
||||
def test_task_pass_stage_stamina_and_hard_mode_gates(self):
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"100": task(steps=[step("passStage", statusValue={"stage": "0101", "level": 2})])}))
|
||||
self.snapshot.raw["history"]["openHardMode"] = False
|
||||
self.assertIn("高难度", self.plan()[0].block_reason)
|
||||
self.snapshot.raw["history"]["openHardMode"] = True
|
||||
self.policy.reserve_ti = 47
|
||||
self.assertIn("体力", self.plan()[0].block_reason)
|
||||
self.policy.reserve_ti = 46
|
||||
self.next("progression_battle")
|
||||
|
||||
def test_battle_start_or_local_win_is_not_a_step_settlement(self):
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"100": task(steps=[step("battle", battle={"teams": []})])}))
|
||||
action = self.next("progression_battle")
|
||||
for response in ({"resCode": 0}, {"win": True}, {"resCode": 1, "reward": {}}):
|
||||
with self.subTest(response=response), self.assertRaises(ValueError):
|
||||
self.planner.acknowledge(self.snapshot, action, response)
|
||||
|
||||
def test_pass_stage_local_flags_require_confirmed_settlement(self):
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"100": task(steps=[
|
||||
step("passStage", statusValue={"stage": "0101", "level": 1}),
|
||||
step(condition={"passStage": ["0101"]})])}))
|
||||
action = self.next("progression_battle")
|
||||
self.assertFalse(self.planner.condition({"passStage": ["0101"]}, self.snapshot)[0])
|
||||
self.planner.acknowledge(self.snapshot, action, {"costTi": 3, "unlockStage": [], "lockStage": []})
|
||||
self.assertTrue(self.planner.condition({"passStage": ["0101"]}, self.snapshot)[0])
|
||||
self.planner.acknowledge(self.snapshot, self.next("progression_local_step"))
|
||||
self.assertEqual(self.next("progression_step").step_number, 2)
|
||||
|
||||
def test_wrong_account_stale_and_invalid_wire_steps_are_not_accepted(self):
|
||||
action = self.next("progression_step")
|
||||
other = snapshot(master={"id": 2})
|
||||
with self.assertRaises(ValueError):
|
||||
self.planner.acknowledge(other, action, {})
|
||||
with self.assertRaises(ValueError):
|
||||
self.planner.acknowledge(self.snapshot, replace(action, payload={}), {})
|
||||
self.snapshot.raw["currentTasks"][0]["curStep"] = 0
|
||||
self.planner = ProgressionPlanner(self.catalog, config())
|
||||
self.assertIn("一基步骤", self.plan()[0].block_reason)
|
||||
|
||||
def test_pending_request_survives_restore_and_is_not_replayed(self):
|
||||
action = self.next("progression_step")
|
||||
self.planner.mark_started(self.snapshot, action)
|
||||
restored = ProgressionPlanner(self.catalog, config())
|
||||
restored.restore_state(json.loads(json.dumps(self.planner.export_state())))
|
||||
self.assertTrue(restored.plan(self.snapshot, self.policy, self.ranch)[0].block_reason)
|
||||
self.snapshot.raw["currentTasks"][0]["curStep"] = 2
|
||||
planned = restored.plan(self.snapshot, self.policy, self.ranch)[0]
|
||||
self.assertEqual(planned.kind, "progression_local_step")
|
||||
|
||||
def test_local_progress_import_requires_an_actual_step_ack(self):
|
||||
cursor = {"11:100": {"task_id": 11, "task_type_id": "100", "steps": {
|
||||
"1": {"kind": "progression_dialogue", "phase": "before", "acknowledged": True}}}}
|
||||
planned = self.planner.plan(self.snapshot, self.policy, self.ranch, local_progress=cursor)
|
||||
self.assertEqual(planned[0].kind, "progression_step")
|
||||
cursor["11:100"]["steps"]["1"] = {"kind": "progression_step", "acknowledged": True, "response": {"taskStepValue": None}}
|
||||
planned = self.planner.plan(self.snapshot, self.policy, self.ranch, local_progress=cursor)
|
||||
self.assertEqual(planned[0].kind, "progression_local_step")
|
||||
|
||||
def test_unknown_types_are_visible_and_commissions_are_not_duplicated(self):
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"100": task(type=6), "400": task("400", type=4)}))
|
||||
self.snapshot.raw["currentTasks"].append({"id": 12, "typeId": "400", "curStep": 1})
|
||||
rows = self.planner.rows(self.snapshot, self.policy, self.ranch)
|
||||
self.assertEqual({row["category"] for row in rows}, {"unknown", "commission"})
|
||||
self.policy.commissions = True
|
||||
self.assertTrue(all(not action.path for action in self.plan()))
|
||||
self.assertIn("QuestPolicy", next(row for row in rows if row["category"] == "commission")["block_reason"])
|
||||
|
||||
|
||||
class CommissionProgressionTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.catalog = Catalog()
|
||||
|
||||
def setUp(self):
|
||||
self.snapshot = snapshot(currentTasks=[{"id": 40, "typeId": "400", "curStep": 1}])
|
||||
self.snapshot.raw["history"].update(loopTaskTime=int(self.snapshot.now), loopTaskNum=6, loopTask={"1": []})
|
||||
self.quest = QuestPolicy(enabled=True)
|
||||
self.ranch = Policy(keep_money=1000)
|
||||
self.battle_policy = ProgressionPolicy(team="teamB", reserve_ti=5)
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"400": task("400", type=4)}))
|
||||
|
||||
def plans(self):
|
||||
return self.planner.commission_plan(self.snapshot, self.quest, self.ranch, battle_policy=self.battle_policy)
|
||||
|
||||
def next(self, kind):
|
||||
actions = self.plans()
|
||||
self.assertTrue(actions)
|
||||
self.assertEqual(actions[0].kind, kind, actions[0].description)
|
||||
return actions[0]
|
||||
|
||||
def offers(self, values=None):
|
||||
self.snapshot.raw["currentTasks"] = []
|
||||
self.snapshot.raw["history"]["loopTask"] = {"1": ["400"] if values is None else values}
|
||||
|
||||
def test_current_commission_uses_full_nonbattle_acknowledgement_flow(self):
|
||||
self.snapshot.raw["history"]["passTask"] = {"400": True} # Prior day's same type.
|
||||
action = self.next("progression_step")
|
||||
self.planner.acknowledge(self.snapshot, action, {})
|
||||
self.planner.acknowledge(self.snapshot, self.next("progression_local_step"))
|
||||
reward = self.next("progression_complete")
|
||||
self.planner.acknowledge(self.snapshot, reward, {})
|
||||
self.assertEqual(self.plans(), [])
|
||||
self.assertEqual(self.planner.commission_rows(self.snapshot, self.quest, self.ranch)[0]["state"], "finished")
|
||||
|
||||
def test_battle_and_pass_stage_use_quest_battle_switch_and_task_route(self):
|
||||
for kind in ("battle", "passStage"):
|
||||
with self.subTest(kind=kind):
|
||||
value = {"stage": "0101", "level": 1} if kind == "passStage" else {}
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"400": task("400", type=4, steps=[
|
||||
step(kind, battle={"teams": []}, statusValue=value, afterStory="linear")])}))
|
||||
self.quest.battle_tasks = False
|
||||
self.assertIn("战斗开关", self.plans()[0].block_reason)
|
||||
self.quest.battle_tasks = True
|
||||
action = self.next("progression_battle")
|
||||
self.assertEqual(action.payload, {"battleType": "task", "taskTypeId": "400"})
|
||||
self.assertEqual(action.battle_kind, "task" if kind == "battle" else "passStage")
|
||||
self.assertEqual(action.team, "teamB")
|
||||
self.assertEqual(action.battle_mode, "original")
|
||||
self.planner.acknowledge(self.snapshot, action, {"reward": {}})
|
||||
self.assertEqual(self.next("progression_dialogue").phase, "after")
|
||||
|
||||
def test_offer_acceptance_has_exact_loop_payload_and_spends_one_slot_once(self):
|
||||
self.offers()
|
||||
self.snapshot.raw["history"]["loopTaskNum"] = 1
|
||||
action = self.next("progression_loop_accept")
|
||||
self.assertEqual(action.path, "taskService/taskLoopReceive")
|
||||
self.assertEqual(action.payload, {"taskTypeId": "400", "city": 1})
|
||||
response = {"task": {"id": 41, "typeId": "400", "curStep": 1}}
|
||||
self.assertTrue(self.planner.acknowledge(self.snapshot, action, response))
|
||||
self.assertFalse(self.planner.acknowledge(self.snapshot, action, response))
|
||||
account = next(iter(self.planner.export_state()["accounts"].values()))
|
||||
self.assertEqual(account["commissions"]["remaining"], 0)
|
||||
self.assertEqual(self.next("progression_step").task_id, 41)
|
||||
self.planner.acknowledge(self.snapshot, self.next("progression_step"), {})
|
||||
self.planner.acknowledge(self.snapshot, self.next("progression_local_step"))
|
||||
self.planner.acknowledge(self.snapshot, self.next("progression_complete"), {})
|
||||
self.assertEqual(self.plans(), [])
|
||||
|
||||
def test_quest_enabled_accept_city_and_quota_are_authoritative(self):
|
||||
self.offers()
|
||||
self.quest.enabled = False
|
||||
self.assertEqual(self.plans(), [])
|
||||
self.quest.enabled = True
|
||||
self.quest.accept = False
|
||||
self.assertEqual(self.plans(), [])
|
||||
self.quest.accept = True
|
||||
self.quest.city = 2
|
||||
self.assertEqual(self.plans(), [])
|
||||
self.quest.city = 1
|
||||
self.snapshot.raw["history"]["loopTaskNum"] = 0
|
||||
self.assertEqual(self.plans(), [])
|
||||
self.snapshot.raw["history"]["loopTaskNum"] = 1
|
||||
self.next("progression_loop_accept")
|
||||
|
||||
def test_quest_resources_control_offer_acceptance(self):
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"400": task("400", type=4, steps=[
|
||||
step("getItem", statusValue={"type": 30001, "num": 3, "remove": True}, afterStory="linear")])}))
|
||||
self.offers()
|
||||
self.snapshot.raw["items"] = [{"id": 1, "typeId": 30001, "num": 5}]
|
||||
self.assertEqual(self.plans(), [])
|
||||
self.quest.allow_items = True
|
||||
self.quest.item_reserves = {"30001": 3}
|
||||
self.assertEqual(self.plans(), [])
|
||||
row = self.planner.commission_rows(self.snapshot, self.quest, self.ranch)[0]
|
||||
self.assertIn("保留", row["block_reason"])
|
||||
self.assertFalse(row["supported"])
|
||||
self.quest.item_reserves = {"30001": 2}
|
||||
self.next("progression_loop_accept")
|
||||
|
||||
def test_offer_with_linear_stories_is_accepted_and_choice_is_not(self):
|
||||
self.offers()
|
||||
for name, expected in (("linear", True), ("choice", False)):
|
||||
with self.subTest(name=name):
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"400": task("400", type=4, steps=[step(story=name)])}))
|
||||
self.assertEqual(bool(self.plans()), expected)
|
||||
|
||||
def test_battle_offers_need_existing_battle_tasks_opt_in(self):
|
||||
self.offers()
|
||||
self.planner = ProgressionPlanner(self.catalog, config({"400": task("400", type=4, steps=[step("battle", battle={"teams": []})])}))
|
||||
self.assertEqual(self.plans(), [])
|
||||
self.quest.battle_tasks = True
|
||||
self.next("progression_loop_accept")
|
||||
|
||||
def test_reset_expires_old_instance_and_uses_confirmed_new_offers(self):
|
||||
self.snapshot.raw["history"]["loopTaskTime"] -= 86400
|
||||
self.snapshot.raw["history"]["loopTaskNum"] = 0
|
||||
action = self.next("progression_loop_reset")
|
||||
self.assertEqual(action.path, "taskService/taskLoopFlush")
|
||||
self.assertEqual(action.payload, {})
|
||||
self.planner.acknowledge(self.snapshot, action, {"loopTask": {"1": [400]}})
|
||||
following = self.next("progression_loop_accept")
|
||||
self.assertEqual(following.payload, {"taskTypeId": "400", "city": 1})
|
||||
account = next(iter(self.planner.export_state()["accounts"].values()))
|
||||
self.assertIn("40", account["commissions"]["expired_ids"])
|
||||
self.assertEqual(account["commissions"]["remaining"], 6)
|
||||
|
||||
def test_uncertain_loop_accept_reconciles_without_spending_quota_twice(self):
|
||||
self.offers()
|
||||
self.snapshot.raw["history"]["loopTaskNum"] = 1
|
||||
action = self.next("progression_loop_accept")
|
||||
self.planner.mark_uncertain(self.snapshot, action)
|
||||
self.assertTrue(self.plans()[0].block_reason)
|
||||
self.snapshot.raw["currentTasks"] = [{"id": 41, "typeId": "400", "curStep": 1}]
|
||||
self.snapshot.raw["history"]["loopTaskNum"] = 0
|
||||
self.next("progression_step")
|
||||
account = next(iter(self.planner.export_state()["accounts"].values()))
|
||||
self.assertEqual(account["commissions"]["remaining"], 0)
|
||||
|
||||
def test_cn_reset_uses_ten_second_grace(self):
|
||||
midnight = 1794067200 # 2026-11-08 00:00 UTC+8.
|
||||
with patch("ranch_assistant.model.time.time", return_value=midnight + 5):
|
||||
self.snapshot.raw["history"]["loopTaskTime"] = midnight - 100
|
||||
self.assertNotEqual(self.plans()[0].kind, "progression_loop_reset")
|
||||
with patch("ranch_assistant.model.time.time", return_value=midnight + 11):
|
||||
self.assertEqual(self.plans()[0].kind, "progression_loop_reset")
|
||||
|
||||
|
||||
class RecoveredProgressionDataTests(unittest.TestCase):
|
||||
def test_full_original_tasks_static_manifest_and_battle_archive(self):
|
||||
data = load_progression_data()
|
||||
self.assertEqual(len(data.tasks), 1165)
|
||||
self.assertEqual(sum(len(task["steps"]) for task in data.tasks.values()), 3462)
|
||||
self.assertEqual(len(data.stages), 1178)
|
||||
self.assertEqual(len(data.scripts), 4269)
|
||||
self.assertEqual(data.manifest["source"]["apk_sha256"], ORIGINAL_APK_SHA256)
|
||||
self.assertEqual(len(Catalog().data["task_info"]), 83)
|
||||
self.assertEqual(data.task("1001002")["steps"][0]["story"], "task_1001002")
|
||||
self.assertIs(type(data.task("1001001")["unlockTasks"]), list)
|
||||
self.assertEqual(data.manifest["source"]["amf_reader_sha256"], hashlib.sha256((ROOT / "ranch_assistant/amf.py").read_bytes()).hexdigest())
|
||||
self.assertTrue(data.script("task_1001002")["supported"])
|
||||
for name, record in data.manifest["artifacts"].items():
|
||||
self.assertEqual(hashlib.sha256((DATA_DIR / name).read_bytes()).hexdigest(), record["sha256"])
|
||||
self.assertLess((DATA_DIR / BATTLES_NAME).stat().st_size, 3_000_000)
|
||||
with zipfile.ZipFile(DATA_DIR / BATTLES_NAME) as archive:
|
||||
self.assertEqual(len(archive.namelist()), 1178)
|
||||
self.assertTrue(all(name.startswith("stages/") and name.endswith(".json") for name in archive.namelist()))
|
||||
self.assertTrue(all(info.date_time == (1980, 1, 1, 0, 0, 0) for info in archive.infolist()))
|
||||
self.assertTrue(data.stage_battle("0101", 1))
|
||||
self.assertTrue(data.task_battle("1001001", 1))
|
||||
|
||||
def test_loader_never_opens_apk_or_eagerly_reads_battles(self):
|
||||
with patch("ranch_assistant.game_data.zipfile.ZipFile", side_effect=AssertionError("eager archive read")):
|
||||
data = ProgressionData()
|
||||
self.assertEqual(len(data.tasks), 1165)
|
||||
|
||||
def test_artifact_tampering_is_rejected(self):
|
||||
with patch("ranch_assistant.game_data.Path.read_bytes", return_value=b"tampered"):
|
||||
with self.assertRaisesRegex(ProgressionDataError, "hash mismatch"):
|
||||
ProgressionData()
|
||||
|
||||
def test_shared_static_data_is_not_mutated_by_account_planning(self):
|
||||
data = load_progression_data()
|
||||
before = json.dumps(data.data, sort_keys=True, ensure_ascii=True)
|
||||
planner = ProgressionPlanner(Catalog(), data)
|
||||
planner.rows(snapshot(), ProgressionPolicy(), Policy())
|
||||
planner.plan(snapshot(master={"id": 2}), ProgressionPolicy(enabled=True), Policy())
|
||||
self.assertEqual(json.dumps(data.data, sort_keys=True, ensure_ascii=True), before)
|
||||
|
||||
def test_linear_hide_newlines_and_placeholders_are_presentation(self):
|
||||
expressions = [
|
||||
{"key": "text", "para": {"text": "[show]你好 [{gn.myName}][r]下一行\n[hide][cm]"}},
|
||||
{"key": "event", "para": {"event": "GAoEvent", "eventData": "true"}},
|
||||
]
|
||||
summary = summarize_script(json.dumps({"exps": expressions}).encode(), "fixture")
|
||||
self.assertTrue(summary["supported"], summary)
|
||||
self.assertTrue(summary["answer"])
|
||||
self.assertEqual(summary["dialogue_lines"], 1)
|
||||
for expression in ({"key": "option", "para": {"options": []}}, {"key": "jump", "para": {"tag": "x"}},
|
||||
{"key": "event", "para": {"event": "GAoEvent", "eventData": '{"action":"gacha"}'}}):
|
||||
with self.subTest(expression=expression):
|
||||
summary = summarize_script(json.dumps({"exps": [expression]}).encode(), "fixture")
|
||||
self.assertFalse(summary["supported"])
|
||||
|
||||
|
||||
class FarmingAndAreaTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.catalog = Catalog()
|
||||
|
||||
def setUp(self):
|
||||
self.snapshot = snapshot()
|
||||
self.policy = ProgressionPolicy(enabled=True)
|
||||
self.ranch = Policy(keep_money=1000)
|
||||
self.data = config(farming={"kills": {"1001010": [{"stage_id": "0101", "difficulty": 1, "configured_enemies": 2}]},
|
||||
"items": {key: [{"stage_id": "0101", "difficulty": 1}] for key in ("30001", "1001010")}})
|
||||
|
||||
def planner(self, current_step):
|
||||
data = deepcopy(self.data)
|
||||
data["task_info"]["100"]["steps"] = [current_step]
|
||||
return ProgressionPlanner(self.catalog, data)
|
||||
|
||||
def test_kill_farming_has_no_task_wire_context_and_never_uses_sweep(self):
|
||||
planner = self.planner(step("killMonster", statusValue={"type": 1001010, "num": 5}))
|
||||
self.snapshot.raw["currentTasks"][0]["stepValue"] = 5
|
||||
self.snapshot.raw["history"]["numKillMonsters"] = {"1001010": 0}
|
||||
self.snapshot.raw["history"]["passStage"] = {"0101": [1, 2, 3]}
|
||||
action = planner.plan(self.snapshot, self.policy, self.ranch)[0]
|
||||
self.assertEqual(action.kind, "stage_battle")
|
||||
self.assertEqual(action.battle_kind, "ordinary_stage")
|
||||
self.assertEqual((action.task_id, action.task_type_id), (0, ""))
|
||||
self.assertEqual((action.source_task_id, action.source_task_type_id, action.source_step_number), (11, "100", 1))
|
||||
self.assertEqual(action.payload, {"stageTypeId": "0101", "stageLevel": "1"})
|
||||
self.assertEqual(action.path, "stageService/stageStart")
|
||||
with self.assertRaises(ValueError):
|
||||
planner.acknowledge(self.snapshot, action, {"reward": {}})
|
||||
self.assertEqual(self.snapshot.raw["currentTasks"][0]["curStep"], 1)
|
||||
self.snapshot.raw["history"]["numKillMonsters"]["1001010"] = 5
|
||||
self.assertEqual(planner.plan(self.snapshot, self.policy, self.ranch)[0].kind, "progression_step")
|
||||
|
||||
def test_loot_uses_sweep_only_after_three_difficulties_are_cleared(self):
|
||||
planner = self.planner(step("getItem", statusValue={"type": 30001, "num": 3, "remove": False}))
|
||||
self.snapshot.raw["history"]["passStage"] = {"0101": [3]}
|
||||
self.assertEqual(planner.plan(self.snapshot, self.policy, self.ranch)[0].kind, "stage_battle")
|
||||
self.snapshot.raw["history"]["passStage"] = {"0101": [1, 2, 3]}
|
||||
action = planner.plan(self.snapshot, self.policy, self.ranch)[0]
|
||||
self.assertEqual(action.kind, "sweep")
|
||||
self.assertEqual(action.task_id, 0)
|
||||
self.assertEqual(action.source_task_type_id, "100")
|
||||
self.policy.allow_sweep = False
|
||||
self.assertEqual(planner.plan(self.snapshot, self.policy, self.ranch)[0].kind, "stage_battle")
|
||||
|
||||
def test_egg_farming_and_reserves_wait_for_actual_inventory(self):
|
||||
planner = self.planner(step("getMonster", statusValue={"type": 1001010, "num": 2, "mode": 0, "remove": True}))
|
||||
self.policy.allow_items = True
|
||||
self.policy.item_reserves = {"1001010": 2}
|
||||
self.snapshot.raw["items"] = [{"id": 1, "typeId": 1001010, "num": 3}]
|
||||
self.assertEqual(planner.plan(self.snapshot, self.policy, self.ranch)[0].kind, "stage_battle")
|
||||
self.snapshot.raw["items"][0]["num"] = 4
|
||||
self.assertEqual(planner.plan(self.snapshot, self.policy, self.ranch)[0].kind, "progression_step")
|
||||
|
||||
def test_farming_respects_disabled_consumption_stamina_locks_and_premium(self):
|
||||
planner = self.planner(step("getItem", statusValue={"type": 30001, "num": 3, "remove": True}))
|
||||
self.assertTrue(planner.plan(self.snapshot, self.policy, self.ranch)[0].block_reason)
|
||||
self.policy.allow_items = True
|
||||
self.policy.reserve_ti = 48
|
||||
self.assertTrue(planner.plan(self.snapshot, self.policy, self.ranch)[0].block_reason)
|
||||
self.policy.reserve_ti = 0
|
||||
self.snapshot.raw["history"]["unlockStage"] = {}
|
||||
self.assertTrue(planner.plan(self.snapshot, self.policy, self.ranch)[0].block_reason)
|
||||
self.snapshot.raw["history"]["unlockStage"] = {"0101": [1]}
|
||||
self.data["stage_info"]["0101"]["cost"]["ke"] = 1
|
||||
self.assertTrue(self.planner(step("getItem", statusValue={"type": 30001, "num": 1})).plan(self.snapshot, self.policy, self.ranch)[0].block_reason)
|
||||
|
||||
def test_task_interception_and_auto_farm_switch_are_honored(self):
|
||||
current = step("getItem", statusValue={"type": 30001, "num": 3})
|
||||
planner = self.planner(current)
|
||||
self.policy.auto_farm = False
|
||||
self.assertTrue(planner.plan(self.snapshot, self.policy, self.ranch)[0].block_reason)
|
||||
self.policy.auto_farm = True
|
||||
data = deepcopy(self.data)
|
||||
data["task_info"]["100"]["steps"] = [current]
|
||||
data["task_info"]["200"] = task("200", type=2, steps=[step(position="city1_wild_stage0101_level1")])
|
||||
planner = ProgressionPlanner(self.catalog, data)
|
||||
self.snapshot.raw["currentTasks"].append({"id": 12, "typeId": "200", "curStep": 1})
|
||||
self.assertTrue(planner.plan(self.snapshot, self.policy, self.ranch)[0].block_reason)
|
||||
|
||||
def test_farming_ticket_locks_and_gift_reserves_are_protected(self):
|
||||
self.data["stage_info"]["0101"]["cost"]["items"] = [{"typeId": 30002, "num": 1}]
|
||||
self.policy.allow_items = True
|
||||
self.snapshot.raw["items"] = [{"id": 2, "typeId": 30002, "num": 1, "sysLock": True}]
|
||||
planner = self.planner(step("getItem", statusValue={"type": 30001, "num": 2}))
|
||||
self.assertTrue(planner.plan(self.snapshot, self.policy, self.ranch)[0].block_reason)
|
||||
self.snapshot.raw["items"][0]["sysLock"] = False
|
||||
self.ranch.gift_items = {"30002": {"enabled": True, "reserve": 1}}
|
||||
self.assertTrue(planner.plan(self.snapshot, self.policy, self.ranch)[0].block_reason)
|
||||
|
||||
def test_static_index_excludes_juveniles_allies_objects_and_zero_chance(self):
|
||||
monsters = [
|
||||
{"type": "1001010", "team": 2, "mode": 2},
|
||||
{"type": "1001020", "team": 2, "mode": 1},
|
||||
{"type": "1001030", "team": 1, "mode": 2},
|
||||
{"type": "1001040", "team": 2, "mode": 2, "isObject": True},
|
||||
]
|
||||
reward = {"rewards": [
|
||||
{"item_num": 1, "item_chance": 1, "items": [{"name": "30001,1,2", "value": 1}]},
|
||||
{"item_num": 1, "item_chance": 0, "items": [{"name": "30002,1,1", "value": 1}]},
|
||||
{"num": 1, "chance": 1, "monMode": 0, "monsters": [{"name": "1001010", "value": 1}]},
|
||||
{"num": 1, "chance": 1, "monMode": 2, "monsters": [{"name": "1001020", "value": 1}]},
|
||||
]}
|
||||
index = farming_index({"0101": {"level": {"1": {"battle": {"teams": [{"mons": monsters}]}, "reward": reward}}}})
|
||||
self.assertEqual(set(index["kills"]), {"1001010"})
|
||||
self.assertEqual(set(index["items"]), {"30001", "1001010"})
|
||||
|
||||
def test_area_and_dungeon_navigation_use_recovered_conditions_and_labels(self):
|
||||
self.data["area_info"] = {"areaInfo": {"1f": {"name": "森林", "city": "1", "openStage": "0101"}},
|
||||
"areaMap": {"1": {"positions": [
|
||||
{"posId": "city1_wild_1f", "action": "area", "actionPara": {"area": "1f"}, "condition": {"finishTask": ["200"]}},
|
||||
{"posId": "city1_dungeon1", "action": "dungeon", "actionPara": {"dungeon": "dungeon1"}, "condition": {}},
|
||||
]}}}
|
||||
self.data["mine_info"] = {"mines": {"dungeon1": {"pos": "city1_dungeon1", "name": "试炼矿洞"}}}
|
||||
planner = self.planner(step(position="city1_wild_1f", story="linear"))
|
||||
self.assertTrue(planner.plan(self.snapshot, self.policy, self.ranch)[0].block_reason)
|
||||
self.snapshot.raw["history"]["passTask"] = {"200": True}
|
||||
action = planner.plan(self.snapshot, self.policy, self.ranch)[0]
|
||||
self.assertEqual(action.kind, "progression_navigate")
|
||||
self.assertIn("森林", action.location)
|
||||
planner = self.planner(step(position="city1_dungeon1", story="linear"))
|
||||
action = planner.plan(self.snapshot, self.policy, self.ranch)[0]
|
||||
self.assertEqual(action.kind, "progression_navigate")
|
||||
self.assertIn("试炼矿洞", action.location)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,749 @@
|
||||
import os
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
from dataclasses import asdict
|
||||
from types import SimpleNamespace
|
||||
import copy
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from PySide6 import QtCore as C, QtWidgets as W
|
||||
from PySide6.QtTest import QTest
|
||||
|
||||
from ranch_assistant import gui
|
||||
from ranch_assistant.policy_io import import_config, portable_config
|
||||
from ranch_assistant.progression import ProgressionPolicy
|
||||
from ranch_assistant.progression_gui import CachedTable, prepare_progression_views
|
||||
from ranch_assistant.tests.test_core import workspace_temp
|
||||
|
||||
|
||||
def configured_policy():
|
||||
policy = ProgressionPolicy(enabled=True, mainline=True, sidequests=True, commissions=True, accept=False,
|
||||
auto_dialogue=False, team="teamC", reserve_ti=24, allow_sweep=False, max_money=42,
|
||||
allow_items=True, allow_monsters=True, item_reserves={"30001": 17}, stop_after_loss=3, repair_chain=False,
|
||||
battle_mode="experimental")
|
||||
if hasattr(policy, "auto_farm"):
|
||||
policy.auto_farm = False
|
||||
return policy
|
||||
|
||||
|
||||
TASKS = [
|
||||
{"task_type_id": "1001", "name": "主线测试", "category": "mainline", "state": "active", "step_number": 2,
|
||||
"total_steps": 4, "position": "地图0101", "requirement": "与NPC对话", "next_action": "dialogue", "battle_kind": "task_battle",
|
||||
"dialogue": "测试对话内容", "supported": True, "status": "等待对话"},
|
||||
{"task_type_id": "1002", "name": "支线测试", "category": "sidequest", "state": "blocked", "step_number": 1,
|
||||
"total_steps": 2, "position": "地图0102", "requirement": "战斗", "next_action": "", "battle_kind": "task_battle",
|
||||
"supported": False, "blocked_reason": "战斗运行时尚未支持"},
|
||||
{"task_type_id": "1003", "name": "委托测试", "category": "commission", "state": "available", "step_number": 0,
|
||||
"total_steps": 1, "position": "村庄", "requirement": "物品", "next_action": "accept", "battle_kind": ""},
|
||||
{"task_type_id": "1004", "name": "未知测试", "category": "new_category", "state": 999, "step_number": None,
|
||||
"total_steps": None, "position": None, "requirement": None, "next_action": None, "battle_kind": None},
|
||||
]
|
||||
RECORDS = [
|
||||
{"timestamp": 1700000000, "battle_kind": "task_battle", "task_type_id": "1001", "team": "teamC", "outcome": "unsupported", "reason": "未支持"},
|
||||
{"timestamp": 1700000001, "battle_kind": "sweep", "stage_id": "0101", "outcome": "completed", "message": "扫荡记录"},
|
||||
{"timestamp": 1700000002, "battle_kind": "map_reward_event", "stage_id": "0102", "outcome": "event", "message": "奖励事件"},
|
||||
]
|
||||
|
||||
|
||||
class ProgressionPolicyIOTests(unittest.TestCase):
|
||||
def test_round_trip_preserves_choices_without_session_or_runtime_state(self):
|
||||
policy = configured_policy()
|
||||
source = {"progression_policy": asdict(policy), "token": "test-secret", "account": "private-account",
|
||||
"progression_records": RECORDS, "progression_rows": TASKS, "runtime_path": "private-runtime"}
|
||||
exported = portable_config(source)
|
||||
self.assertEqual(exported["assistantVersion"], "1.2.0.dev1")
|
||||
self.assertEqual(import_config(exported)["progression_policy"], asdict(policy))
|
||||
text = json.dumps(exported)
|
||||
for secret in ("test-secret", "private-account", "private-runtime", "progression_records", "progression_rows"):
|
||||
self.assertNotIn(secret, text)
|
||||
self.assertEqual(policy, configured_policy())
|
||||
|
||||
def test_defaults_and_older_bundles_do_not_enable_or_replace_progression(self):
|
||||
exported = portable_config({})
|
||||
self.assertFalse(exported["progression_policy"]["enabled"])
|
||||
self.assertEqual(exported["progression_policy"]["battle_mode"], "original")
|
||||
if hasattr(ProgressionPolicy(), "auto_farm"):
|
||||
self.assertEqual(exported["progression_policy"]["auto_farm"], ProgressionPolicy().auto_farm)
|
||||
del exported["progression_policy"]["auto_farm"]
|
||||
self.assertEqual(import_config(exported)["progression_policy"]["auto_farm"], ProgressionPolicy().auto_farm)
|
||||
del exported["progression_policy"]["battle_mode"]
|
||||
self.assertEqual(import_config(exported)["progression_policy"]["battle_mode"], "original")
|
||||
del exported["progression_policy"]
|
||||
self.assertNotIn("progression_policy", import_config(exported))
|
||||
|
||||
def test_invalid_progression_rejected_atomically(self):
|
||||
exported = portable_config({"progression_policy": asdict(configured_policy())})
|
||||
for field, invalid in (("enabled", 1), ("mainline", "true"), ("reserve_ti", -1), ("reserve_ti", True),
|
||||
("max_money", -1), ("max_money", 1_000_000_001), ("stop_after_loss", 0), ("stop_after_loss", 1000),
|
||||
("team", ""), ("team", None), ("team", True), ("battle_mode", "automatic"), ("battle_mode", True),
|
||||
("battle_mode", ["experimental"]), ("item_reserves", {"30001": -1}), ("item_reserves", {"30001": True}),
|
||||
("item_reserves", {"invalid": 1}), ("item_reserves", {"0": 1}), ("allow_items", "yes"),
|
||||
("auto_farm", "true"), ("auto_farm", 1), ("auto_farm", None)):
|
||||
with self.subTest(field=field, invalid=invalid):
|
||||
value = copy.deepcopy(exported)
|
||||
value["progression_policy"][field] = invalid
|
||||
with self.assertRaises((ValueError, TypeError)):
|
||||
import_config(value)
|
||||
for invalid in (None, [], {"unknown_field": True}):
|
||||
with self.assertRaises((ValueError, TypeError)):
|
||||
import_config(exported | {"progression_policy": invalid})
|
||||
|
||||
|
||||
class ProgressionGuiTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.app = W.QApplication.instance() or W.QApplication([])
|
||||
|
||||
def wait(self, window, predicate=lambda: True):
|
||||
deadline = time.monotonic() + 6
|
||||
while time.monotonic() < deadline:
|
||||
self.app.processEvents()
|
||||
QTest.qWait(5)
|
||||
if (not window.busy and not window.progression_table.row_batch.running
|
||||
and not window.battle_records_table.row_batch.running and predicate()):
|
||||
return
|
||||
self.fail("Offline Qt job did not complete: " + window.log.toPlainText())
|
||||
|
||||
def mock_readers(self, window):
|
||||
threads = []
|
||||
def tasks():
|
||||
threads.append(C.QThread.currentThread())
|
||||
return copy.deepcopy(TASKS)
|
||||
def records():
|
||||
threads.append(C.QThread.currentThread())
|
||||
return copy.deepcopy(RECORDS)
|
||||
task_mock = Mock(side_effect=tasks)
|
||||
record_mock = Mock(side_effect=records)
|
||||
window.engine.progression_rows = task_mock
|
||||
window.engine.progression_records = record_mock
|
||||
return threads, task_mock, record_mock
|
||||
|
||||
def login_fixture(self, window, events):
|
||||
from ranch_assistant.api import Session
|
||||
session = Session("http://127.0.0.1/fixture/", "fixture-token", account_id="fixture-account", server_id=1, role_id=101)
|
||||
client = SimpleNamespace(session=session, trace=None, persist_session=Mock(),
|
||||
close=Mock(side_effect=lambda: events.append("client_closed")))
|
||||
window.engine.client = client
|
||||
window.engine.demo = False
|
||||
window.engine.last_heartbeat = time.monotonic()
|
||||
window.engine.master_sync_due = Mock(return_value=False)
|
||||
window.engine.growth_sync_due = Mock(return_value=False)
|
||||
window.engine.heartbeat_enabled = True
|
||||
window.monitoring = True
|
||||
window.set_strategy_checked(True)
|
||||
window.next_poll = 0
|
||||
window.account.setText("fixture-account")
|
||||
window.password.setText("fixture-password")
|
||||
window.credentials.save("fixture-account", "fixture-password", True)
|
||||
window.session_store.save(session, "fixture account")
|
||||
window.reload_saved_sessions()
|
||||
return client
|
||||
|
||||
def test_logout_nested_confirmation_cannot_report_clear_before_client_release(self):
|
||||
with workspace_temp() as folder:
|
||||
window = gui.Window(folder)
|
||||
window.timer.stop()
|
||||
release = threading.Event()
|
||||
events = []
|
||||
try:
|
||||
self.wait(window)
|
||||
client = self.login_fixture(window, events)
|
||||
def held_poll(**kwargs):
|
||||
if not release.wait(4):
|
||||
raise TimeoutError("logout fixture was not released")
|
||||
return window.engine.snapshot, [], "fixture poll finished"
|
||||
window.engine.poll = Mock(side_effect=held_poll)
|
||||
save = window.credentials.save
|
||||
def record_save(account, password, remember):
|
||||
if not remember and not account and not password:
|
||||
events.append("credentials_cleared")
|
||||
return save(account, password, remember)
|
||||
def confirm(*args):
|
||||
window.schedule() # The real modal runs this nested event loop.
|
||||
self.app.processEvents()
|
||||
return W.QMessageBox.StandardButton.Yes
|
||||
with patch.object(gui.W.QMessageBox, "question", side_effect=confirm), patch.object(window.credentials, "save", side_effect=record_save):
|
||||
window.logout_and_clear()
|
||||
if "credentials_cleared" in events:
|
||||
self.assertIn("client_closed", events, "credentials were cleared while the original client was active")
|
||||
self.assertLess(events.index("client_closed"), events.index("credentials_cleared"))
|
||||
release.set()
|
||||
self.wait(window, lambda: window.engine.demo)
|
||||
client.close.assert_called_once_with()
|
||||
self.assertEqual(window.credentials.load(), (False, "", ""))
|
||||
self.assertEqual(window.session_store.entries(), [])
|
||||
self.assertFalse(window.monitoring)
|
||||
self.assertFalse(window.engine.auto)
|
||||
self.assertFalse(window.strategy_toggle.isChecked())
|
||||
finally:
|
||||
release.set()
|
||||
self.wait(window)
|
||||
window.close()
|
||||
|
||||
def test_logout_cancel_freezes_scheduler_but_preserves_credentials_and_stopped_intent(self):
|
||||
with workspace_temp() as folder:
|
||||
window = gui.Window(folder)
|
||||
window.timer.stop()
|
||||
events, observed = [], []
|
||||
try:
|
||||
self.wait(window)
|
||||
client = self.login_fixture(window, events)
|
||||
engine = window.engine
|
||||
window.ranch_enabled.setChecked(False)
|
||||
window.progression_enabled.setChecked(True)
|
||||
engine.auto = True
|
||||
engine.poll = Mock(return_value=(engine.snapshot, [], "fixture refresh"))
|
||||
def cancel(*args):
|
||||
observed.append((engine.auto, window.monitoring, window.strategy_toggle.isChecked(), engine.heartbeat_enabled))
|
||||
window.schedule()
|
||||
window.start_workflow() # A previously queued start must also stay frozen.
|
||||
self.app.processEvents()
|
||||
observed.append((engine.auto, window.monitoring, window.strategy_toggle.isChecked(), engine.heartbeat_enabled))
|
||||
return W.QMessageBox.StandardButton.No
|
||||
with patch.object(gui.W.QMessageBox, "question", side_effect=cancel):
|
||||
window.logout_and_clear()
|
||||
self.wait(window)
|
||||
self.assertEqual(observed, [(False, False, False, False)] * 2)
|
||||
engine.poll.assert_not_called()
|
||||
self.assertIs(window.engine, engine)
|
||||
client.close.assert_not_called()
|
||||
self.assertEqual(window.credentials.load(), (True, "fixture-account", "fixture-password"))
|
||||
self.assertEqual(len(window.session_store.entries()), 1)
|
||||
self.assertFalse(window.strategy_toggle.isChecked())
|
||||
self.assertFalse(engine.auto)
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_confirmed_busy_logout_waits_for_worker_before_clear(self):
|
||||
with workspace_temp() as folder:
|
||||
window = gui.Window(folder)
|
||||
window.timer.stop()
|
||||
release = threading.Event()
|
||||
events = []
|
||||
try:
|
||||
self.wait(window)
|
||||
client = self.login_fixture(window, events)
|
||||
engine = window.engine
|
||||
def held_poll():
|
||||
if not release.wait(4):
|
||||
raise TimeoutError("logout fixture was not released")
|
||||
return engine.snapshot, [], "fixture poll finished"
|
||||
window.submit("poll", held_poll)
|
||||
with patch.object(gui.W.QMessageBox, "question", return_value=W.QMessageBox.StandardButton.Yes) as question:
|
||||
window.logout_and_clear()
|
||||
question.assert_called_once()
|
||||
self.assertTrue(window.busy)
|
||||
client.close.assert_not_called()
|
||||
self.assertEqual(window.credentials.load(), (True, "fixture-account", "fixture-password"))
|
||||
self.assertNotIn("已清除当前账号页签的登录记录", window.log.toPlainText())
|
||||
release.set()
|
||||
self.wait(window, lambda: window.engine.demo)
|
||||
client.close.assert_called_once_with()
|
||||
self.assertEqual(window.credentials.load(), (False, "", ""))
|
||||
self.assertFalse(window.engine.auto)
|
||||
self.assertFalse(engine.auto)
|
||||
self.assertFalse(engine.heartbeat_enabled)
|
||||
finally:
|
||||
release.set()
|
||||
self.wait(window)
|
||||
window.close()
|
||||
|
||||
def test_failed_client_release_does_not_clear_credentials_or_report_success(self):
|
||||
with workspace_temp() as folder:
|
||||
window = gui.Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
client = self.login_fixture(window, [])
|
||||
client.close.side_effect = RuntimeError("fixture close failed")
|
||||
with patch.object(gui.W.QMessageBox, "question", return_value=W.QMessageBox.StandardButton.Yes):
|
||||
window.logout_and_clear()
|
||||
self.assertEqual(window.credentials.load(), (True, "fixture-account", "fixture-password"))
|
||||
self.assertEqual(len(window.session_store.entries()), 1)
|
||||
self.assertNotIn("已清除当前账号页签的登录记录", window.log.toPlainText())
|
||||
self.assertIn("fixture close failed", window.log.toPlainText())
|
||||
self.assertFalse(window.engine.auto)
|
||||
self.assertFalse(window.engine.heartbeat_enabled)
|
||||
self.assertFalse(window.monitoring)
|
||||
client.close.side_effect = None
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_confirmed_logout_still_clears_sessions_if_window_closes_while_waiting(self):
|
||||
with workspace_temp() as folder:
|
||||
window = gui.Window(folder)
|
||||
window.timer.stop()
|
||||
release = threading.Event()
|
||||
try:
|
||||
self.wait(window)
|
||||
client = self.login_fixture(window, [])
|
||||
window.submit("logout_fixture", lambda: release.wait(4))
|
||||
with patch.object(gui.W.QMessageBox, "question", return_value=W.QMessageBox.StandardButton.Yes):
|
||||
window.logout_and_clear()
|
||||
window.close()
|
||||
release.set()
|
||||
for _ in range(600):
|
||||
self.app.processEvents()
|
||||
QTest.qWait(5)
|
||||
if not window.busy and client.close.called:
|
||||
break
|
||||
self.assertEqual(window.session_store.entries(), [])
|
||||
self.assertEqual(window.credentials.load(), (False, "", ""))
|
||||
client.close.assert_called_once_with()
|
||||
finally:
|
||||
release.set()
|
||||
self.wait(window)
|
||||
window.close()
|
||||
|
||||
def test_tabs_stopped_defaults_and_progression_only_global_start(self):
|
||||
with workspace_temp() as folder:
|
||||
window = gui.Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
labels = [window.tabs.tabText(i) for i in range(window.tabs.count())]
|
||||
self.assertEqual(labels[labels.index("自动孵蛋") + 1], "自动主线")
|
||||
self.assertIn("战斗记录", labels)
|
||||
self.assertEqual(labels[-1], "收益资料")
|
||||
self.assertEqual(window.styleSheet(), "")
|
||||
self.assertFalse(window.progression_enabled.isChecked())
|
||||
self.assertTrue(window.progression_mainline.isChecked())
|
||||
self.assertFalse(window.progression_sidequests.isChecked())
|
||||
self.assertFalse(window.progression_commissions.isChecked())
|
||||
if hasattr(ProgressionPolicy(), "auto_farm"):
|
||||
self.assertEqual(window.progression_auto_farm.isChecked(), ProgressionPolicy().auto_farm)
|
||||
else:
|
||||
self.assertFalse(hasattr(window, "progression_auto_farm"))
|
||||
self.assertEqual(window.progression_battle_mode.currentData(), "original")
|
||||
self.assertIn("近似", window.progression_battle_mode.toolTip())
|
||||
self.assertIn("委托", window.progression_battle_mode.toolTip())
|
||||
self.assertFalse(window.strategy_toggle.isChecked())
|
||||
for widget in (window.ranch_enabled, window.quest_enabled, window.daily_enabled, window.map_enabled, window.gift_enabled):
|
||||
widget.setChecked(False)
|
||||
window.progression_enabled.setChecked(True)
|
||||
window.engine.cancel_progression = Mock()
|
||||
with patch.object(window, "refresh"):
|
||||
window.start_workflow()
|
||||
self.assertTrue(window.strategy_toggle.isChecked())
|
||||
self.assertIn("主线推进", window.workflow_status.text())
|
||||
window.stop_workflow()
|
||||
window.engine.cancel_progression.assert_called_once_with()
|
||||
self.assertFalse(window.strategy_toggle.isChecked())
|
||||
buttons = [b.text() for b in window.findChildren(W.QPushButton)]
|
||||
self.assertEqual(buttons.count("开启"), 1)
|
||||
self.assertNotIn("开始监控", buttons)
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_per_account_autosave_and_restart_round_trip(self):
|
||||
with workspace_temp() as folder:
|
||||
expected = asdict(configured_policy())
|
||||
window = gui.Window(folder / "one")
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
window.load_progression_policy(configured_policy())
|
||||
window.progression_max_money.setValue(43)
|
||||
expected["max_money"] = 43
|
||||
QTest.qWait(350)
|
||||
self.wait(window)
|
||||
self.assertEqual(json.loads((folder / "one" / "settings.json").read_text(encoding="utf-8"))["progression_policy"], expected)
|
||||
self.assertEqual(asdict(window.engine.progression_policy), expected)
|
||||
self.assertFalse(window.engine.auto)
|
||||
finally:
|
||||
window.close()
|
||||
first = gui.Window(folder / "one")
|
||||
second = gui.Window(folder / "two")
|
||||
first.timer.stop()
|
||||
second.timer.stop()
|
||||
try:
|
||||
self.wait(first)
|
||||
self.wait(second)
|
||||
self.assertEqual(asdict(first.read_progression_policy()), expected)
|
||||
self.assertEqual(asdict(second.read_progression_policy()), asdict(ProgressionPolicy()))
|
||||
self.assertFalse(first.strategy_toggle.isChecked())
|
||||
self.assertFalse(second.strategy_toggle.isChecked())
|
||||
finally:
|
||||
first.close()
|
||||
second.close()
|
||||
|
||||
def test_unified_import_keeps_choices_and_execution_stopped(self):
|
||||
with workspace_temp() as folder:
|
||||
window = gui.Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
source = window.config_value() | {"progression_policy": asdict(configured_policy())}
|
||||
path = folder / "policies.json"
|
||||
path.write_text(json.dumps(portable_config(source)), encoding="utf-8")
|
||||
window.set_strategy_checked(True)
|
||||
window.engine.auto = True
|
||||
window.engine.run_progression_once = Mock()
|
||||
with patch.object(gui.W.QFileDialog, "getOpenFileName", return_value=(str(path), "")):
|
||||
window.import_policies()
|
||||
self.assertEqual(asdict(window.read_progression_policy()), asdict(configured_policy()))
|
||||
self.assertEqual(asdict(window.engine.progression_policy), asdict(configured_policy()))
|
||||
self.assertFalse(window.strategy_toggle.isChecked())
|
||||
self.assertFalse(window.engine.auto)
|
||||
window.engine.run_progression_once.assert_not_called()
|
||||
with patch.object(gui.W.QFileDialog, "getSaveFileName", return_value=(str(path), "")):
|
||||
window.export_policies()
|
||||
self.assertEqual(import_config(json.loads(path.read_text(encoding="utf-8")))["progression_policy"], asdict(configured_policy()))
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_battle_mode_autosaves_without_starting_and_reaches_worker_policy(self):
|
||||
with workspace_temp() as folder:
|
||||
window = gui.Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
window.engine.run_progression_once = Mock()
|
||||
self.assertEqual(window.progression_battle_mode.currentData(), "original")
|
||||
window.progression_battle_mode.setCurrentIndex(window.progression_battle_mode.findData("experimental"))
|
||||
QTest.qWait(350)
|
||||
self.wait(window)
|
||||
saved = json.loads((folder / "settings.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(saved["progression_policy"]["battle_mode"], "experimental")
|
||||
self.assertEqual(window.engine.progression_policy.battle_mode, "experimental")
|
||||
self.assertIn("实验模拟", window.progression_status.text())
|
||||
self.assertIn("近似", window.progression_status.text())
|
||||
self.assertFalse(window.strategy_toggle.isChecked())
|
||||
self.assertFalse(window.engine.auto)
|
||||
window.engine.run_progression_once.assert_not_called()
|
||||
observations = []
|
||||
def preview():
|
||||
observations.append((window.engine.progression_policy.battle_mode, C.QThread.currentThread()))
|
||||
return window.engine.snapshot, [], "已预览所选战斗模式"
|
||||
window.engine.refresh_progression = Mock(side_effect=preview)
|
||||
window.refresh_progression()
|
||||
self.wait(window)
|
||||
self.assertEqual(observations[0][0], "experimental")
|
||||
self.assertNotEqual(observations[0][1], self.app.thread())
|
||||
self.assertFalse(window.engine.auto)
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_additional_and_unavailable_teams_round_trip_visibly_without_starting(self):
|
||||
with workspace_temp() as folder:
|
||||
window = gui.Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
policy = configured_policy()
|
||||
policy.team = "Raid42"
|
||||
exported = portable_config(window.config_value() | {"progression_policy": asdict(policy)})
|
||||
value = import_config(exported)
|
||||
self.assertEqual(value["progression_policy"]["team"], "Raid42")
|
||||
window.load_config(window.config_value() | value)
|
||||
self.assertEqual(window.progression_team.currentData(), "Raid42")
|
||||
self.assertIn("当前账号未找到", window.progression_team.currentText())
|
||||
window.engine.snapshot.raw["teams"] = [{"teamType": "battleTeam", "teamName": "Raid42", "monsters": [900]},
|
||||
{"teamType": "battleTeam", "teamName": "teamD", "monsters": [900]}]
|
||||
window.refresh_progression_teams(window.engine.snapshot)
|
||||
self.assertEqual(window.progression_team.currentText(), "Raid42")
|
||||
self.assertGreaterEqual(window.progression_team.findData("teamD"), 0)
|
||||
self.assertEqual(window.read_progression_policy().team, "Raid42")
|
||||
self.assertFalse(window.strategy_toggle.isChecked())
|
||||
self.assertFalse(window.engine.auto)
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
@unittest.skipUnless(hasattr(ProgressionPolicy(), "auto_farm"), "Planner has not exposed ProgressionPolicy.auto_farm yet")
|
||||
def test_auto_farm_autosaves_without_starting_or_duplicate_controls(self):
|
||||
with workspace_temp() as folder:
|
||||
window = gui.Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
checks = [check for check in window.findChildren(W.QCheckBox)
|
||||
if check.text() == "自动收集任务材料 / 击杀目标"]
|
||||
self.assertEqual(checks, [window.progression_auto_farm])
|
||||
window.engine.run_progression_once = Mock()
|
||||
selected = not ProgressionPolicy().auto_farm
|
||||
window.progression_auto_farm.setChecked(selected)
|
||||
QTest.qWait(350)
|
||||
self.wait(window)
|
||||
saved = json.loads((folder / "settings.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(saved["progression_policy"]["auto_farm"], selected)
|
||||
self.assertEqual(window.engine.progression_policy.auto_farm, selected)
|
||||
exported = portable_config(window.config_value())
|
||||
self.assertEqual(import_config(exported)["progression_policy"]["auto_farm"], selected)
|
||||
self.assertFalse(window.strategy_toggle.isChecked())
|
||||
self.assertFalse(window.engine.auto)
|
||||
window.engine.run_progression_once.assert_not_called()
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_hidden_page_and_account_skip_task_getters_and_cached_view_is_lazy(self):
|
||||
with workspace_temp() as folder:
|
||||
window = gui.Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
threads, tasks, records = self.mock_readers(window)
|
||||
window.refresh()
|
||||
self.wait(window)
|
||||
tasks.assert_not_called()
|
||||
records.assert_not_called()
|
||||
window.set_presentation_active(False)
|
||||
window.tabs.setCurrentWidget(window.progression_page)
|
||||
window.refresh()
|
||||
self.wait(window)
|
||||
tasks.assert_not_called()
|
||||
records.assert_not_called()
|
||||
window.set_presentation_active(True)
|
||||
self.wait(window, lambda: window.progression_table.rowCount() == 4)
|
||||
self.assertTrue(all(thread != self.app.thread() for thread in threads))
|
||||
self.assertEqual(tasks.call_count, 1)
|
||||
window.render_progression()
|
||||
window.render_current_page()
|
||||
self.assertEqual(tasks.call_count, 1)
|
||||
records.assert_not_called()
|
||||
window.tabs.setCurrentWidget(window.battle_records_page)
|
||||
self.wait(window, lambda: window.battle_records_table.rowCount() == 3)
|
||||
self.assertEqual(records.call_count, 1)
|
||||
tasks.reset_mock()
|
||||
window.refresh()
|
||||
self.wait(window)
|
||||
tasks.assert_not_called()
|
||||
self.assertEqual(TASKS[0]["state"], "active")
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_account_views_share_static_data_without_mutating_it_or_loading_battles(self):
|
||||
with workspace_temp() as folder:
|
||||
first, second = gui.Window(folder / "one"), gui.Window(folder / "two")
|
||||
first.timer.stop()
|
||||
second.timer.stop()
|
||||
try:
|
||||
self.wait(first)
|
||||
self.wait(second)
|
||||
with patch("ranch_assistant.game_data.zipfile.ZipFile", side_effect=AssertionError("task UI must not load battle archives")):
|
||||
first.refresh_progression()
|
||||
self.wait(first)
|
||||
second.refresh_progression()
|
||||
self.wait(second)
|
||||
data = first.engine.game_data
|
||||
self.assertIsNotNone(data)
|
||||
self.assertIs(data, second.engine.game_data)
|
||||
original = repr(data.tasks)
|
||||
self.assertIsNot(first.progression_views, second.progression_views)
|
||||
self.assertIsNot(first.progression_views.tasks, second.progression_views.tasks)
|
||||
if first.progression_views.tasks:
|
||||
first.progression_views.tasks[0]["values"][2] = "account-one-only"
|
||||
self.assertEqual(repr(data.tasks), original)
|
||||
self.assertFalse(second.progression_views.tasks and second.progression_views.tasks[0]["values"][2] == "account-one-only")
|
||||
finally:
|
||||
first.close()
|
||||
second.close()
|
||||
|
||||
def test_leaving_task_page_drops_its_queued_local_view(self):
|
||||
with workspace_temp() as folder:
|
||||
window = gui.Window(folder)
|
||||
window.timer.stop()
|
||||
release = threading.Event()
|
||||
try:
|
||||
self.wait(window)
|
||||
_, tasks, records = self.mock_readers(window)
|
||||
window.run_job("held_request", lambda: release.wait(4))
|
||||
window.tabs.setCurrentWidget(window.progression_page)
|
||||
self.assertTrue(window.pending_progression_view)
|
||||
window.tabs.setCurrentWidget(window.automation_page)
|
||||
self.assertFalse(window.pending_progression_view)
|
||||
release.set()
|
||||
self.wait(window)
|
||||
tasks.assert_not_called()
|
||||
records.assert_not_called()
|
||||
finally:
|
||||
release.set()
|
||||
self.wait(window)
|
||||
window.close()
|
||||
|
||||
def test_filters_details_unknown_support_and_records_contexts(self):
|
||||
with workspace_temp() as folder:
|
||||
window = gui.Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
self.mock_readers(window)
|
||||
window.tabs.setCurrentWidget(window.progression_page)
|
||||
self.wait(window, lambda: window.progression_table.rowCount() == 4)
|
||||
for kind, expected in (("mainline", "主线测试"), ("sidequest", "支线测试"), ("commission", "委托测试"), ("unknown", "未知测试")):
|
||||
window.progression_filter.setCurrentIndex(window.progression_filter.findData(kind))
|
||||
self.wait(window, lambda: window.progression_table.rowCount() == 1)
|
||||
self.assertEqual(window.progression_table.item(0, 2).text(), expected)
|
||||
window.progression_table.selectRow(0)
|
||||
if kind == "mainline":
|
||||
detail = window.progression_detail.toPlainText()
|
||||
for text in ("测试对话内容", "2 / 4", "地图0101", "等待对话"):
|
||||
self.assertIn(text, detail)
|
||||
elif kind == "sidequest":
|
||||
self.assertIn("战斗运行时尚未支持", window.progression_detail.toPlainText())
|
||||
elif kind == "unknown":
|
||||
self.assertIn("支持状态未确认", window.progression_table.item(0, 9).text())
|
||||
window.tabs.setCurrentWidget(window.battle_records_page)
|
||||
self.wait(window, lambda: window.battle_records_table.rowCount() == 3)
|
||||
for kind, label in (("sweep", "扫荡"), ("map_reward_event", "地图奖励事件"), ("task_battle", "任务战斗")):
|
||||
window.battle_records_filter.setCurrentIndex(window.battle_records_filter.findData(kind))
|
||||
self.wait(window, lambda: window.battle_records_table.rowCount() == 1)
|
||||
self.assertEqual(window.battle_records_table.item(0, 1).text(), label)
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_refresh_and_step_use_worker_prepare_and_result_paths(self):
|
||||
with workspace_temp() as folder:
|
||||
window = gui.Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
threads, tasks, _ = self.mock_readers(window)
|
||||
def refresh():
|
||||
threads.append(C.QThread.currentThread())
|
||||
return window.engine.snapshot, [], "离线任务刷新完成"
|
||||
window.engine.refresh_progression = Mock(side_effect=refresh)
|
||||
window.engine.run_progression_once = Mock(side_effect=refresh)
|
||||
with patch.object(window, "run_job", wraps=window.run_job) as run_job:
|
||||
window.refresh_progression()
|
||||
self.wait(window)
|
||||
self.assertEqual(run_job.call_args[0][0], "progression_refresh")
|
||||
self.assertIsNotNone(window.progression_views)
|
||||
self.assertEqual(tasks.call_count, 1)
|
||||
self.assertIn("离线任务刷新完成", window.log.toPlainText())
|
||||
window.run_progression_once()
|
||||
window.engine.run_progression_once.assert_not_called()
|
||||
window.progression_enabled.setChecked(True)
|
||||
window.monitoring = True
|
||||
window.set_strategy_checked(True)
|
||||
window.run_progression_once()
|
||||
self.wait(window)
|
||||
self.assertEqual(run_job.call_args[0][0], "progression_run")
|
||||
self.assertEqual(window.engine.run_progression_once.call_count, 1)
|
||||
self.assertTrue(all(thread != self.app.thread() for thread in threads))
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_policy_changes_wait_for_serial_request_but_stop_cancels_immediately(self):
|
||||
with workspace_temp() as folder:
|
||||
window = gui.Window(folder)
|
||||
window.timer.stop()
|
||||
release = threading.Event()
|
||||
entered = threading.Event()
|
||||
try:
|
||||
self.wait(window)
|
||||
policy = window.engine.progression_policy
|
||||
def held_request():
|
||||
entered.set()
|
||||
if not release.wait(4):
|
||||
raise TimeoutError("test worker was not released")
|
||||
window.engine.cancel_progression = Mock()
|
||||
window.run_job("held_request", held_request)
|
||||
self.assertTrue(entered.wait(1))
|
||||
window.progression_enabled.setChecked(True)
|
||||
window.progression_reserve_ti.setValue(77)
|
||||
window.progression_battle_mode.setCurrentIndex(window.progression_battle_mode.findData("experimental"))
|
||||
window.persist_settings()
|
||||
self.assertIs(window.engine.progression_policy, policy)
|
||||
self.assertIsNotNone(window.pending_policy)
|
||||
window.stop_workflow()
|
||||
window.engine.cancel_progression.assert_called_once_with()
|
||||
self.assertTrue(window.busy)
|
||||
release.set()
|
||||
self.wait(window)
|
||||
self.assertEqual(window.engine.progression_policy.reserve_ti, 77)
|
||||
self.assertEqual(window.engine.progression_policy.battle_mode, "experimental")
|
||||
self.assertFalse(window.engine.auto)
|
||||
finally:
|
||||
release.set()
|
||||
self.wait(window)
|
||||
window.close()
|
||||
|
||||
def test_stop_before_queued_step_starts_prevents_engine_entry(self):
|
||||
with workspace_temp() as folder:
|
||||
window = gui.Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
window.progression_enabled.setChecked(True)
|
||||
window.monitoring = True
|
||||
window.set_strategy_checked(True)
|
||||
window.engine.run_progression_once = Mock()
|
||||
queued = []
|
||||
with patch.object(window.pool, "start", side_effect=queued.append):
|
||||
window.run_progression_once()
|
||||
self.assertEqual(len(queued), 1)
|
||||
self.assertTrue(window.busy)
|
||||
window.stop_workflow()
|
||||
window.pool.start(queued[0])
|
||||
self.wait(window)
|
||||
window.engine.run_progression_once.assert_not_called()
|
||||
self.assertIn("未开始执行", window.log.toPlainText())
|
||||
self.assertFalse(window.engine.auto)
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_bad_task_contract_errors_are_reported(self):
|
||||
engine = Mock()
|
||||
engine.progression_rows.return_value = [{"task_type_id": "ok"}, None]
|
||||
engine.progression_records.return_value = []
|
||||
with self.assertRaisesRegex(TypeError, r"progression_rows\(\)"):
|
||||
prepare_progression_views(engine)
|
||||
|
||||
def test_journal_timestamps_use_beijing_and_preserve_original_records(self):
|
||||
source = [
|
||||
{"kind": "battle", "task_id": 12, "battle_kind": "passStage", "started_at": 1700000000, "finished_at": 1700000010},
|
||||
{"kind": "battle", "battle_kind": "ordinary_stage", "started_at": 1700000000, "outcome": "event"},
|
||||
{"kind": "sweep", "battle_kind": "normal", "started_at": 1700000000},
|
||||
]
|
||||
original = copy.deepcopy(source)
|
||||
engine = SimpleNamespace(snapshot=object(), progression_rows=lambda: TASKS, progression_records=lambda: source)
|
||||
views = prepare_progression_views(engine)
|
||||
self.assertEqual(views.records[0]["values"][0], "2023-11-15 06:13:30")
|
||||
self.assertEqual(views.records[1]["values"][0], "2023-11-15 06:13:20")
|
||||
self.assertEqual([row["category"] for row in views.records], ["task_pass_stage", "map_reward_event", "sweep"])
|
||||
self.assertEqual(source, original)
|
||||
|
||||
def test_experimental_record_outcomes_keep_their_approximate_label(self):
|
||||
records = [
|
||||
{"battle_mode": "experimental", "faithful": False, "approximate": True, "outcome": "win"},
|
||||
{"battle_mode": "original", "outcome": "win"},
|
||||
{"outcome": "win"},
|
||||
]
|
||||
engine = SimpleNamespace(snapshot=object(), progression_rows=lambda: [], progression_records=lambda: records)
|
||||
rows = prepare_progression_views(engine).records
|
||||
self.assertIn("实验近似", rows[0]["values"][4])
|
||||
self.assertIn("近似,未完整验证", rows[0]["detail"])
|
||||
self.assertEqual(rows[1]["values"][4], "胜利")
|
||||
self.assertIn("原版运行时", rows[1]["detail"])
|
||||
self.assertIn("记录未标明", rows[2]["detail"])
|
||||
self.assertEqual(records[0]["outcome"], "win")
|
||||
|
||||
def test_repeated_sorted_table_updates_do_not_reinsert_owned_items(self):
|
||||
table = CachedTable(["编号", "名称"])
|
||||
messages = []
|
||||
previous = C.qInstallMessageHandler(lambda level, context, message: messages.append(message))
|
||||
try:
|
||||
for count in (80, 4, 35, 80):
|
||||
rows = [{"key": str(i), "values": [str(i), "name " + str(i)], "detail": str(i)} for i in range(count)]
|
||||
table.set_rows(rows)
|
||||
deadline = time.monotonic() + 2
|
||||
while table.row_batch.running and time.monotonic() < deadline:
|
||||
self.app.processEvents()
|
||||
QTest.qWait(2)
|
||||
self.assertFalse(table.row_batch.running)
|
||||
table.sortItems(0, C.Qt.SortOrder.DescendingOrder)
|
||||
self.assertEqual(table.rowCount(), count)
|
||||
self.assertEqual(table.item(0, 0).text(), str(count - 1))
|
||||
self.assertFalse(any("already owned" in message.lower() or "cannot insert" in message.lower() for message in messages), messages)
|
||||
finally:
|
||||
C.qInstallMessageHandler(previous)
|
||||
table.row_batch.stop()
|
||||
table.deleteLater()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -11,6 +11,7 @@ from PySide6 import QtCore as C, QtWidgets as W
|
||||
from PySide6.QtTest import QTest
|
||||
|
||||
from ranch_assistant.gui import Window
|
||||
from ranch_assistant import presentation
|
||||
from ranch_assistant.engine import demo_snapshot
|
||||
from ranch_assistant.engine import Engine
|
||||
from ranch_assistant.api import Client, Session, encode
|
||||
@@ -62,6 +63,134 @@ class ResponsivenessTests(unittest.TestCase):
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_hidden_account_skips_worker_monster_preparation_and_prepares_on_show(self):
|
||||
with workspace_temp() as folder:
|
||||
window = Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
snapshot = demo_snapshot(window.catalog)
|
||||
template = snapshot.raw["monsters"][-1]
|
||||
snapshot.raw["monsters"] = [copy.deepcopy(template) | {"id": 1000 + i} for i in range(500)]
|
||||
window.set_presentation_active(False)
|
||||
window.tabs.setCurrentWidget(window.monster_page)
|
||||
window.engine.poll = lambda **kwargs: (snapshot, [], "fixture poll")
|
||||
threads = []
|
||||
build = presentation.monster_rows
|
||||
def record_build(*args, **kwargs):
|
||||
threads.append(threading.get_ident())
|
||||
return build(*args, **kwargs)
|
||||
with patch.object(presentation, "monster_rows", side_effect=record_build) as preparing, patch("ranch_assistant.gui.monster_rows", side_effect=AssertionError("GUI thread monster fallback")):
|
||||
window.refresh()
|
||||
self.wait(window)
|
||||
self.assertEqual(preparing.call_count, 0, "hidden account formatted monster rows")
|
||||
window.set_presentation_active(True)
|
||||
for _ in range(600):
|
||||
self.app.processEvents()
|
||||
QTest.qWait(5)
|
||||
if not window.busy and len(window.monsters.monster_items) == 500:
|
||||
break
|
||||
self.assertEqual(len(window.monsters.monster_items), 500)
|
||||
self.assertTrue(threads)
|
||||
self.assertTrue(all(tid != threading.get_ident() for tid in threads))
|
||||
self.assertTrue(window.engine.presentation_active)
|
||||
finally:
|
||||
self.wait(window)
|
||||
window.close()
|
||||
|
||||
def test_visible_other_page_skips_monster_preparation_on_poll(self):
|
||||
with workspace_temp() as folder:
|
||||
window = Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
window.tabs.setCurrentIndex(0)
|
||||
with patch.object(presentation, "monster_rows", wraps=presentation.monster_rows) as preparing:
|
||||
window.refresh()
|
||||
self.wait(window)
|
||||
self.assertEqual(preparing.call_count, 0, "another page formatted monster rows")
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_warm_monster_view_finishes_preparation_when_unchanged_after_show(self):
|
||||
with workspace_temp() as folder:
|
||||
window = Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
window.tabs.setCurrentWidget(window.monster_page)
|
||||
for _ in range(500):
|
||||
self.app.processEvents()
|
||||
QTest.qWait(2)
|
||||
if not window.busy and not window.monster_render_timer.running:
|
||||
break
|
||||
original = dict(window.monsters.monster_items)
|
||||
self.assertTrue(original)
|
||||
window.set_presentation_active(False)
|
||||
self.assertIsNone(window.prepared_views.monsters)
|
||||
window.set_presentation_active(True)
|
||||
for _ in range(500):
|
||||
self.app.processEvents()
|
||||
QTest.qWait(2)
|
||||
if not window.busy and not window.monster_render_timer.running:
|
||||
break
|
||||
self.assertFalse(window.busy)
|
||||
self.assertFalse(window.monster_render_timer.running)
|
||||
self.assertEqual(window.monsters.monster_items, original)
|
||||
finally:
|
||||
self.wait(window)
|
||||
window.close()
|
||||
|
||||
def test_prepare_views_default_stays_complete_and_opt_out_marks_monsters_dirty(self):
|
||||
with workspace_temp() as folder:
|
||||
window = Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
snapshot = window.engine.snapshot
|
||||
with patch.object(presentation, "monster_rows", wraps=presentation.monster_rows) as preparing:
|
||||
full = presentation.prepare_views(window.catalog, snapshot, set())
|
||||
self.assertEqual(preparing.call_count, 1)
|
||||
thin = presentation.prepare_views(window.catalog, snapshot, set(), include_monsters=False)
|
||||
self.assertEqual(preparing.call_count, 1)
|
||||
self.assertEqual(len(full.monsters), len(snapshot.raw["monsters"]))
|
||||
self.assertEqual(full.monster_source, repr(snapshot.raw["monsters"]))
|
||||
self.assertIsNone(thin.monsters)
|
||||
self.assertIsNone(thin.monster_source)
|
||||
self.assertIsInstance(full.maps, list)
|
||||
self.assertIsInstance(thin.maps, list)
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_hidden_connection_sets_engine_visibility_before_first_plan(self):
|
||||
from ranch_assistant.model import Snapshot
|
||||
from ranch_assistant.tests.test_accounts import fake_client, role_snapshot
|
||||
with workspace_temp() as folder:
|
||||
window = Window(folder)
|
||||
window.timer.stop()
|
||||
try:
|
||||
self.wait(window)
|
||||
window.set_presentation_active(False)
|
||||
previous = window.engine
|
||||
session = Session("http://127.0.0.1/fixture/", "fixture-token", account_id="fixture", server_id=1, role_id=101)
|
||||
client = fake_client(session, window.catalog, [])
|
||||
window.result("connected", (client, Snapshot(role_snapshot(window.catalog, 101))))
|
||||
engine = window.engine
|
||||
self.assertIsNot(engine, previous)
|
||||
self.assertFalse(engine.presentation_active)
|
||||
self.assertFalse(engine.progression_view_active)
|
||||
observed = []
|
||||
def plan():
|
||||
observed.append((engine.presentation_active, threading.get_ident()))
|
||||
return []
|
||||
with patch.object(engine, "plans", side_effect=plan):
|
||||
window.preview_cultivation()
|
||||
self.wait(window)
|
||||
self.assertEqual([active for active, _ in observed], [False])
|
||||
self.assertTrue(all(tid != threading.get_ident() for _, tid in observed))
|
||||
finally:
|
||||
window.close()
|
||||
|
||||
def test_unchanged_maps_reuse_controls_and_keep_edits(self):
|
||||
with workspace_temp() as folder:
|
||||
window = Window(folder)
|
||||
|
||||
@@ -194,6 +194,7 @@ class ManualGuiTests(unittest.TestCase):
|
||||
self.assertEqual(window.eggs.item(row, 2).text(), "0")
|
||||
self.assertTrue(window.eggs.cellWidget(row, 3).isChecked())
|
||||
window.tabs.setCurrentWidget(window.monster_page)
|
||||
self.wait(window)
|
||||
item = window.monsters.monster_items[900]
|
||||
window.monsters.itemWidget(item, 8).setChecked(True)
|
||||
window.monsters.itemWidget(item, 9).setValue(1)
|
||||
@@ -276,6 +277,7 @@ class ManualGuiTests(unittest.TestCase):
|
||||
self.wait(window)
|
||||
def select(mid):
|
||||
window.tabs.setCurrentWidget(window.monster_page)
|
||||
self.wait(window)
|
||||
window.monsters.clearSelection()
|
||||
window.monsters.setCurrentItem(window.monsters.monster_items[mid])
|
||||
select(101)
|
||||
|
||||
@@ -0,0 +1,421 @@
|
||||
package {
|
||||
import flash.desktop.NativeApplication;
|
||||
import flash.display.Loader;
|
||||
import flash.display.Sprite;
|
||||
import flash.events.Event;
|
||||
import flash.events.IOErrorEvent;
|
||||
import flash.events.InvokeEvent;
|
||||
import flash.events.SecurityErrorEvent;
|
||||
import flash.events.UncaughtErrorEvent;
|
||||
import flash.events.TimerEvent;
|
||||
import flash.filesystem.File;
|
||||
import flash.filesystem.FileMode;
|
||||
import flash.filesystem.FileStream;
|
||||
import flash.system.ApplicationDomain;
|
||||
import flash.system.LoaderContext;
|
||||
import flash.system.System;
|
||||
import flash.utils.ByteArray;
|
||||
import flash.utils.describeType;
|
||||
import flash.utils.getTimer;
|
||||
import flash.utils.setTimeout;
|
||||
import flash.utils.Timer;
|
||||
import flash.utils.Endian;
|
||||
|
||||
/** No game startup, login, update, networking or settlement callbacks. */
|
||||
public class OriginalProbe extends Sprite {
|
||||
private var domain:ApplicationDomain = new ApplicationDomain(ApplicationDomain.currentDomain);
|
||||
private var libraries:Array = ["framework", "main", "baseui", "mainui", "mainui2", "mainui3", "movieclip"];
|
||||
private var loaders:Array = [];
|
||||
private var tables:Object;
|
||||
private var request:Object;
|
||||
private var events:Array = [];
|
||||
private var output:File;
|
||||
private var root:File;
|
||||
private var index:int = 0;
|
||||
private var finished:Boolean = false;
|
||||
private var phase:String = "invoke";
|
||||
private var sceneStarted:Boolean = false;
|
||||
private var sceneResult:Object = null;
|
||||
private var observedFrames:int = 0;
|
||||
private var sceneStartMs:int = 0;
|
||||
private var originalFrameRate:Number;
|
||||
private var engineFrameCallbacks:int = 0;
|
||||
private var assetIndex:Object;
|
||||
private var archiveStream:FileStream;
|
||||
private var crcTable:Array;
|
||||
|
||||
public function OriginalProbe() {
|
||||
System.output("ORIGINAL_PROBE_CONSTRUCTOR\n");
|
||||
loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaught);
|
||||
NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, invoke);
|
||||
}
|
||||
private function invoke(e:InvokeEvent):void {
|
||||
System.output("ORIGINAL_PROBE_INVOKE " + e.arguments.length + "\n");
|
||||
if (output != null) return;
|
||||
try {
|
||||
if (e.arguments.length != 3) throw new Error("Expected original-directory request-json output-json");
|
||||
root = new File(e.arguments[0]);
|
||||
output = new File(e.arguments[2]);
|
||||
request = JSON.parse(readText(new File(e.arguments[1])));
|
||||
assetIndex = JSON.parse(readText(root.resolvePath("asset_index.json")));
|
||||
if (assetIndex.apk_sha256 != "01678ee3a8465d818d32cbbd94baa0d8253b04b4c57b70ebc5544ed341f1015d")
|
||||
throw new Error("Original asset archive identity mismatch");
|
||||
archiveStream = new FileStream(); archiveStream.open(new File(assetIndex.apk_path),FileMode.READ);
|
||||
tables = {};
|
||||
var tableNames:Array = JSON.parse(readText(root.resolvePath("table_index.json"))) as Array;
|
||||
for each (var tableName:String in tableNames) {
|
||||
var bytes:ByteArray = readBytes(root.resolvePath("tables/" + tableName + ".amf.zlib"));
|
||||
bytes.uncompress(); bytes.objectEncoding = 3;
|
||||
tables[tableName] = bytes.readObject();
|
||||
if (bytes.bytesAvailable != 0) throw new Error("Trailing AMF bytes: " + tableName);
|
||||
}
|
||||
var mainBytes:ByteArray = readBytes(root.resolvePath("main.library.swf"));
|
||||
var rectangleBits:uint = uint(mainBytes[8]) >> 3;
|
||||
mainBytes.position = 8 + Math.ceil((5 + 4 * rectangleBits) / 8);
|
||||
mainBytes.endian = Endian.LITTLE_ENDIAN;
|
||||
originalFrameRate = mainBytes.readUnsignedShort() / 256;
|
||||
if (originalFrameRate != 50) throw new Error("Pinned original main SWF frame rate mismatch");
|
||||
stage.frameRate = originalFrameRate;
|
||||
var watchdog:Number = request.watchdog_ms == null ? 690000 : Number(request.watchdog_ms);
|
||||
if (!isFinite(watchdog) || watchdog <= 0) throw new Error("Invalid technical watchdog");
|
||||
setTimeout(function():void { fail(new Error("Technical watchdog exceeded")); },watchdog);
|
||||
loadNext();
|
||||
} catch (error:Error) { fail(error); }
|
||||
}
|
||||
private function readText(file:File):String {
|
||||
var stream:FileStream = new FileStream(); stream.open(file, FileMode.READ);
|
||||
var result:String = stream.readUTFBytes(stream.bytesAvailable); stream.close(); return result;
|
||||
}
|
||||
private function readBytes(file:File):ByteArray {
|
||||
var stream:FileStream = new FileStream(); stream.open(file, FileMode.READ);
|
||||
var result:ByteArray = new ByteArray(); stream.readBytes(result); stream.close(); return result;
|
||||
}
|
||||
private function record(kind:String, data:Object = null):void {
|
||||
var event:Object = {kind:kind, elapsed_ms:getTimer(), phase:phase, data:data};
|
||||
events.push(event); trace("ORIGINAL_PROBE " + JSON.stringify(event));
|
||||
}
|
||||
private function loadNext():void {
|
||||
if (index == libraries.length) { measureClock(); return; }
|
||||
phase = "load_" + libraries[index++];
|
||||
var loader:Loader = new Loader(); loaders.push(loader);
|
||||
loader.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaught);
|
||||
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event):void {
|
||||
record("library_loaded", {name:phase, document_class:String(describeType(loader.content).@name)});
|
||||
loadNext();
|
||||
});
|
||||
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, function(e:IOErrorEvent):void { fail(new Error(e.text)); });
|
||||
loader.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, function(e:SecurityErrorEvent):void { fail(new Error(e.text)); });
|
||||
var context:LoaderContext = new LoaderContext(false, domain); context.allowCodeImport = true;
|
||||
loader.loadBytes(readBytes(root.resolvePath(libraries[index-1] + ".library.swf")), context);
|
||||
}
|
||||
private function cls(name:String):Class { return domain.getDefinition(name) as Class; }
|
||||
private function measureClock():void {
|
||||
phase = "measure_hidden_clock";
|
||||
stage.frameRate = originalFrameRate;
|
||||
// Let startup/loading work drain before measuring the hidden stage.
|
||||
setTimeout(measureClockWindow,300);
|
||||
}
|
||||
private function measureClockWindow():void {
|
||||
var start:int = getTimer(), frames:int = 0, ticks:int = 0;
|
||||
var timer:Timer = new Timer(100);
|
||||
var frame:Function = function(e:Event):void { frames++; };
|
||||
timer.addEventListener(TimerEvent.TIMER, function(e:TimerEvent):void { ticks++; });
|
||||
stage.addEventListener(Event.ENTER_FRAME, frame); timer.start();
|
||||
setTimeout(function():void {
|
||||
timer.stop(); stage.removeEventListener(Event.ENTER_FRAME, frame);
|
||||
var elapsed:int = getTimer() - start;
|
||||
record("clock_measured", {requested_fps:stage.frameRate, observed_frames:frames,
|
||||
elapsed_ms:elapsed, observed_fps:frames * 1000 / elapsed,
|
||||
stage_width:stage.stageWidth,stage_height:stage.stageHeight,
|
||||
timer_period_ms:100, timer_ticks:ticks, native_window_visible:stage.nativeWindow.visible});
|
||||
probe();
|
||||
}, 2500);
|
||||
}
|
||||
private function reflect(name:String):void {
|
||||
var type:XML = describeType(cls(name));
|
||||
var stream:FileStream = new FileStream();
|
||||
stream.open(output.parent.resolvePath(name.replace(/\./g,"_") + ".xml"), FileMode.WRITE);
|
||||
stream.writeUTFBytes(type.toXMLString()); stream.close();
|
||||
record("definition_resolved", {name:name});
|
||||
}
|
||||
private function probe():void {
|
||||
try {
|
||||
phase = "inject_original_tables";
|
||||
var table:Class = cls("net.pixvi.myr.center.Table");
|
||||
for (var key:String in tables) {
|
||||
if (key == "monster_fix") continue;
|
||||
var value:Object = tables[key];
|
||||
if (key != "team_info" && value != null && value.hasOwnProperty("datas")) value = value.datas;
|
||||
table[key] = value;
|
||||
}
|
||||
table["skin_info"] = tables.skin_info.skins;
|
||||
table["upstar_info"] = tables.upstar_info;
|
||||
table["city_info"] = table["game_setting"].cityInfo;
|
||||
table["entangle_skill"] = table["entangle_info"].entangleSkill;
|
||||
table["stage_info"] = cls("net.pixvi.pfw.utils.ObjectUtil")["tableToObject"](tables.stage_info.datas);
|
||||
table["monster_group"] = table["monster_setting"].group;
|
||||
table["monster_element"] = table["monster_setting"].element;
|
||||
record("tables_injected");
|
||||
phase = "initialize_synthetic_master";
|
||||
var gameClass:Class = cls("net.pixvi.myr.center.Game");
|
||||
var masterClass:Class = cls("net.pixvi.myr.element.master.MasterVo");
|
||||
var master:Object = new masterClass();
|
||||
gameClass["getIns"]()["master"] = master; master["init"]();
|
||||
master["history"]["monLib"] = [];
|
||||
record("synthetic_master_initialized", {source:"original MasterVo.init",account:false});
|
||||
phase = "original_framework_bootstrap";
|
||||
addChild(cls("net.pixvi.common.center.StartUpCenter")["startUp"](stage,true,false,false,false));
|
||||
record("original_framework_layers_initialized");
|
||||
var rm:Class = cls("net.pixvi.common.manager.resource.RM");
|
||||
rm["getInstance"]();
|
||||
record("original_resource_managers_initialized");
|
||||
var stringLoader:Class = cls("net.pixvi.pfw.net.PiStringLoader");
|
||||
var cryptor:Class = cls("net.pixvi.myrcryptor.MYRCryptor");
|
||||
stringLoader["globalCryptoMode"] = true;
|
||||
stringLoader["globalJsonCryptoModeFunction"] = cryptor["jsonDecodeHandler"];
|
||||
var resourceClass:Class = cls("net.pixvi.common.net.resource.ResourceVo");
|
||||
for (var tableKey:String in tables) {
|
||||
var resource:Object = new resourceClass("data/table/" + tableKey + ".json");
|
||||
resource["crypto"] = true;
|
||||
resource["data"] = readBytes(root.resolvePath("tables/" + tableKey + ".amf.zlib"));
|
||||
rm["TXT"]["push"](resource);
|
||||
}
|
||||
var netImg:Class = cls("net.pixvi.pfw.display.NetImg");
|
||||
netImg["globalImgCryptoMode"] = true;
|
||||
netImg["globalImgCryptoGetBytes"] = originalAssetBytes;
|
||||
netImg["globalImgSrcHack"] = localAssetPath;
|
||||
var net:Class = cls("net.pixvi.myr.net.NetCenter");
|
||||
var offlineBase:String = output.parent.resolvePath("__offline_game_api_denied__/").url + "/";
|
||||
net["SERVER"] = net["PAY_SERVER"] = net["CENTER_SERVER"] = offlineBase;
|
||||
if (request.scene === true) {
|
||||
bootstrapDisplay();
|
||||
var sceneData:Object = request.original_data != null ? request.original_data.battle :
|
||||
table["stage_info"][request.stage_id].level[String(request.difficulty)].battle;
|
||||
startScene(master,cls("net.pixvi.myr.element.mon.MonsterVo"),sceneData);
|
||||
return;
|
||||
}
|
||||
phase = "original_GameMath";
|
||||
var math:Class = cls("net.pixvi.myr.GameMath");
|
||||
var rolls:Array = [];
|
||||
for (var i:int=0; i<8; i++) rolls.push(math["damage"](100,20,20,30));
|
||||
record("GameMath_executed", {damage_rolls:rolls, ap_cd:math["apCD"], dex_attack_adjustment:math["addAtkSpdByDex"](40)});
|
||||
phase = "reflect_original_framework";
|
||||
for each (var name:String in ["net.pixvi.common.driver.StageDriver", "net.pixvi.common.driver.SecondDriver",
|
||||
"net.pixvi.common.manager.resource.RM", "net.pixvi.common.view.FF", "net.pixvi.pfw.display.BitFactory",
|
||||
"net.pixvi.myr.center.BattleCenter", "net.pixvi.myr.element.mon.MonsterVo",
|
||||
"net.pixvi.myr.element.battle.BattleMonVo", "net.pixvi.myr.element.battle.BattleVo",
|
||||
"net.pixvi.common.utils.StageLocator", "net.pixvi.common.utils.PiFixVo", "net.pixvi.pfw.driver.EnterFrameDriver"]) reflect(name);
|
||||
phase = "original_MonsterVo";
|
||||
var monsterClass:Class = cls("net.pixvi.myr.element.mon.MonsterVo");
|
||||
var monster:Object = new monsterClass(1001010);
|
||||
monster["buildByArea"](); monster["level"] = 1; monster["mode"] = 2;
|
||||
record("MonsterVo_executed", {type:monster["type"],level:monster["level"],hp:monster["hp"],atk:monster["atk"],dex:monster["dex"]});
|
||||
phase = "original_BattleMonVo";
|
||||
var monClass:Class = cls("net.pixvi.myr.element.battle.BattleMonVo");
|
||||
var mon:Object = new monClass(); mon["buildByMonster"](monster);
|
||||
record("BattleMonVo_executed", {hp:mon["hp"],atk:mon["atk"],spd_atk:mon["spd_atk"],spd_mov:mon["spd_mov"],skill_1:mon["skill_1"]});
|
||||
phase = "original_BattleVo";
|
||||
var battleClass:Class = cls("net.pixvi.myr.element.battle.BattleVo");
|
||||
var battle:Object = new battleClass();
|
||||
var stages:Object = table["stage_info"];
|
||||
if (stages is Array) {
|
||||
var mapped:Object = {};
|
||||
for each (var row:Object in stages) mapped[row.id] = row;
|
||||
stages = mapped;
|
||||
}
|
||||
var battleData:Object = stages[request.stage_id].level[String(request.difficulty)].battle;
|
||||
battle["buildByObject"](battleData);
|
||||
record("BattleVo_executed", {time:battle["time"],teams:battle["teams"].length,enemy_count:battle["teams"][0].mons.length});
|
||||
bootstrapDisplay();
|
||||
phase = "original_BattleGround_constructor";
|
||||
reflect("net.pixvi.myr.battle.BattleGround");
|
||||
var groundClass:Class = cls("net.pixvi.myr.battle.BattleGround");
|
||||
groundClass["firstStartUp"]();
|
||||
var ground:Object = new groundClass();
|
||||
record("BattleGround_constructed");
|
||||
finish("probe_completed", null);
|
||||
} catch (error:Error) { fail(error); }
|
||||
}
|
||||
private function bootstrapDisplay():void {
|
||||
phase = "original_display_bootstrap";
|
||||
var fixClass:Class = cls("net.pixvi.common.utils.PiFixVo");
|
||||
var fs1:Object = new fixClass(); fs1["id"] = "fs1"; fs1["maxHWScale"] = 1.775;
|
||||
var fs2:Object = new fixClass(); fs2["id"] = "fs2"; fs2["maxHWScale"] = 1.9125;
|
||||
cls("net.pixvi.common.utils.StageLocator")["autoFull"](720,1136,[fs1,fs2]);
|
||||
// The ORIGINAL constructor calls startup(). Calling it again
|
||||
// creates another ENTER_FRAME source and corrupts delta timing.
|
||||
cls("net.pixvi.pfw.driver.EnterFrameDriver")["getInstance"]()["regist"](countEngineFrame);
|
||||
cls("net.pixvi.common.driver.SecondDriver")["getInstance"]()["startup"]();
|
||||
}
|
||||
private function startScene(master:Object, monsterClass:Class, battleData:Object):void {
|
||||
phase = "original_BattleCenter_startBattle";
|
||||
if (request.roster != null && request.roster.snapshot != null) {
|
||||
phase = "original_snapshot_bridge";
|
||||
var bridge:Class = ApplicationDomain.currentDomain.getDefinition("SnapshotBridge") as Class;
|
||||
var built:Object = bridge["build"](domain,request.roster.snapshot,request.roster.team_name);
|
||||
master = built.master;
|
||||
cls("net.pixvi.myr.center.Game")["getIns"]()["master"] = master;
|
||||
master["curBattleTeam"] = request.roster.team_name;
|
||||
record("snapshot_bridge_built",built.metadata == null ? built.validation : built.metadata);
|
||||
} else {
|
||||
var teamClass:Class = cls("net.pixvi.myr.element.team.TeamVo");
|
||||
var team:Object = new teamClass(); team["monsters"] = [1000001,1000002,1000003,0,0,0,0,0];
|
||||
master["teams"] = [team]; master["name"] = "offline synthetic fixture";
|
||||
for (var i:int = 1; i <= 3; i++) {
|
||||
var mon:Object = new monsterClass(1001010);
|
||||
mon["buildByArea"](); mon["level"] = 1; mon["mode"] = 2; mon["id"] = 1000000+i;
|
||||
master["monsters"].push(mon);
|
||||
}
|
||||
}
|
||||
phase = "original_BattleCenter_startBattle";
|
||||
var sound:Class = cls("net.pixvi.common.center.SoundCenter");
|
||||
sound["getIns"]()["setBgmEnable"](false); sound["getIns"]()["setEffectEnable"](false);
|
||||
var positionClass:Class = cls("net.pixvi.myr.element.battle.BattlePosition");
|
||||
var position:Object = new positionClass();
|
||||
if (request.position != null) {
|
||||
cls("net.pixvi.pfw.utils.Mapper")["fillVariables"](position,request.position);
|
||||
} else {
|
||||
position["battleType"] = "stage"; position["stageId"] = request.stage_id; position["stageLevel"] = String(request.difficulty);
|
||||
}
|
||||
var panelClass:Class = cls("net.pixvi.myr.panel.battle.BattlePanel");
|
||||
var panel:Object = panelClass["getIns"]();
|
||||
panel["onWinCallBack"] = sceneComplete; panel["onLoseCallBack"] = sceneComplete;
|
||||
cls("net.pixvi.myr.center.BattleCenter")["getIns"]()["startBattle"](position,battleData,{},null,null);
|
||||
record("BattleCenter_started", {context:request.context,master_level:master["level"], ap:master["ap"],
|
||||
callbacks:"original BattlePanel checks followed by local result collection only"});
|
||||
setTimeout(function():void {
|
||||
try {
|
||||
phase = "original_battle_ready_animation";
|
||||
panel["battleStartReady"]();
|
||||
stage.addEventListener(Event.ENTER_FRAME, countSceneFrame);
|
||||
sceneStartMs = getTimer();
|
||||
observeScene();
|
||||
} catch (error:Error) { fail(error); }
|
||||
}, 700);
|
||||
}
|
||||
private function countSceneFrame(e:Event):void { observedFrames++; }
|
||||
private function countEngineFrame():void { engineFrameCallbacks++; }
|
||||
private function observeScene():void {
|
||||
if (finished) return;
|
||||
try {
|
||||
var panelClass:Class = cls("net.pixvi.myr.panel.battle.BattlePanel");
|
||||
var panel:Object = panelClass["getIns"]();
|
||||
var ground:Object = panel["ground"];
|
||||
sceneStarted = sceneStarted || ground["battleIsStart"];
|
||||
phase = sceneStarted ? "original_battle_frames" : "original_battle_ready_animation";
|
||||
var units:Array = [];
|
||||
for each (var mon:Object in ground["monsters"]) {
|
||||
units.push({id:mon["monVo"]["mid"],team:mon["team"],x:mon["x"],y:mon["y"],
|
||||
hp:mon["monVo"]["hp"],skill_1:mon["monVo"]["skill_1"],skill_2:mon["monVo"]["skill_2"]});
|
||||
}
|
||||
record("scene_sample", {started:ground["battleIsStart"], paused:ground["paused"],
|
||||
requested_fps:stage.frameRate,
|
||||
engine_frame_callbacks:engineFrameCallbacks,
|
||||
engine_frame_delta_ms:cls("net.pixvi.pfw.driver.EnterFrameDriver")["frameSpaceTime"],
|
||||
left_ms:ground["battleTime"]["leftTime"],ap:ground["vo"]["teamDic"][1]["ap"],
|
||||
units:units, observed_frames:observedFrames, wall_ms:getTimer()-sceneStartMs});
|
||||
if (!sceneStarted) panel["startMovTouchHandler"]();
|
||||
setTimeout(observeScene, 1000);
|
||||
} catch (error:Error) { fail(error); }
|
||||
}
|
||||
private function sceneComplete(data:Object):void {
|
||||
try {
|
||||
phase = "original_BattlePanel_result_callback";
|
||||
sceneStarted = true;
|
||||
var raw:Object = data["cheatRecords"];
|
||||
if (cls("net.pixvi.myr.net.NetCenter")["getIns"]()["reqid"] != 0)
|
||||
throw new Error("Original scene attempted an unavailable offline game API");
|
||||
var unitRecords:Array = [];
|
||||
var panelClass:Class = cls("net.pixvi.myr.panel.battle.BattlePanel");
|
||||
var ground:Object = panelClass["getIns"]()["ground"];
|
||||
var objectUtil:Class = cls("net.pixvi.pfw.utils.ObjectUtil");
|
||||
for each (var team:Object in ground["vo"]["teams"]) {
|
||||
var allUnits:Array = team["mons"].concat(team["stageMons"]).concat(team["deadMons"]);
|
||||
for each (var mon:Object in allUnits) {
|
||||
unitRecords.push({team:mon["team"],mode:mon["monVo"]["mode"],
|
||||
summon:mon["monVo"]["summonUnit"],dead:mon["monVo"]["dead"],hp_left:mon["monVo"]["hp"],
|
||||
original_hurt_record:mon["getTotalHurtRecort"](),
|
||||
original_record:objectUtil["deepClone"](mon["makeRecord"]())});
|
||||
}
|
||||
}
|
||||
sceneResult = {outcome:data["win"] ? "win" : "loss",terminal_reason:data["leftTime"] == 0 ? "time_limit" : (data["win"] ? "victory_condition" : "loss_condition"), battle_data:data["getObj"](),
|
||||
anomaly_records:{mons:raw["mons"],damages:raw["damages"],master:raw["master"],text:raw["text"]},
|
||||
original_unit_records:unitRecords,
|
||||
requested_fps:stage.frameRate,observed_fps:observedFrames*1000/(getTimer()-sceneStartMs),
|
||||
engine_frame_callbacks:engineFrameCallbacks,game_api_requests:0,
|
||||
observed_frames:observedFrames, wall_ms:getTimer()-sceneStartMs};
|
||||
record("original_battle_completed", sceneResult);
|
||||
finish("scene_completed", null);
|
||||
} catch (error:Error) { fail(error); }
|
||||
}
|
||||
private function uncaught(e:UncaughtErrorEvent):void {
|
||||
e.preventDefault(); fail(e.error is Error ? e.error as Error : new Error(String(e.error)));
|
||||
}
|
||||
private function localAssetPath(path:String):String {
|
||||
if (path.indexOf(":") >= 0 || path.indexOf("..") >= 0 || path.indexOf("\\") >= 0 || path.charAt(0) == "/")
|
||||
throw new Error("Offline resource path refused: " + path);
|
||||
return path;
|
||||
}
|
||||
private function originalAssetBytes(path:String):ByteArray {
|
||||
localAssetPath(path);
|
||||
var cryptor:Class = cls("net.pixvi.myrcryptor.MYRCryptor");
|
||||
var hashed:String = cryptor["getHashSrc"](path);
|
||||
var entry:Object = assetIndex.entries[hashed.substr(6)];
|
||||
if (entry == null) {
|
||||
record("original_asset_read", {path:path, member:hashed, crc32:null});
|
||||
// Match MYRCryptor.getHashSrcBytes. NetBitImg then attempts the
|
||||
// relative local file and dispatches its ORIGINAL error/complete
|
||||
// callbacks. Do not manufacture pixels or suppress the record.
|
||||
record("original_asset_missing", {path:path, member:hashed, behavior:"original local IO-error fallback"});
|
||||
var permitted:Array = request.allowed_missing_assets == null ? ["data/img/monster/q/1001010_q_2s.png"] : request.allowed_missing_assets as Array;
|
||||
if (permitted == null || permitted.indexOf(path) < 0) throw new Error("Unknown original asset dependency: " + path);
|
||||
return null;
|
||||
}
|
||||
if (entry.size > 67108864 || entry.compressed_size > 67108864 || entry.offset < 0)
|
||||
throw new Error("Original image resource exceeds supported bounds: " + path);
|
||||
var bytes:ByteArray = new ByteArray();
|
||||
archiveStream.position = entry.offset;
|
||||
archiveStream.readBytes(bytes,0,entry.compressed_size);
|
||||
if (entry.method == 8) bytes.uncompress("deflate");
|
||||
else if (entry.method != 0) throw new Error("Unsupported original ZIP method");
|
||||
var checksum:uint = crc32(bytes);
|
||||
if (bytes.length != entry.size || checksum != uint(entry.crc32))
|
||||
throw new Error("Original asset ZIP content mismatch: " + path);
|
||||
record("original_asset_read", {path:path, member:hashed, crc32:checksum, bytes:bytes.length});
|
||||
bytes.position = 0;
|
||||
return bytes;
|
||||
}
|
||||
private function crc32(bytes:ByteArray):uint {
|
||||
if (crcTable == null) {
|
||||
crcTable = [];
|
||||
for (var n:uint=0; n<256; n++) {
|
||||
var value:uint=n;
|
||||
for (var bit:uint=0; bit<8; bit++) value=(value & 1) ? uint(0xedb88320 ^ (value >>> 1)) : value >>> 1;
|
||||
crcTable.push(value);
|
||||
}
|
||||
}
|
||||
var checksum:uint=0xffffffff;
|
||||
for (var i:uint=0; i<bytes.length; i++) checksum=uint(crcTable[(checksum ^ bytes[i]) & 255]) ^ (checksum >>> 8);
|
||||
return uint(checksum ^ 0xffffffff);
|
||||
}
|
||||
private function fail(error:Error):void {
|
||||
finish("blocked", {phase:phase, name:error.name, message:error.message, stack:error.getStackTrace()});
|
||||
}
|
||||
private function finish(status:String, error:Object):void {
|
||||
if (finished) return; finished = true;
|
||||
if (archiveStream != null) { archiveStream.close(); archiveStream = null; }
|
||||
var result:Object = {schema:1, status:status, scope:request != null && request.scene === true ? "original_scene_experiment" : "original_component_probe",
|
||||
nonce:request == null ? null : request.nonce,
|
||||
application_id:NativeApplication.nativeApplication.applicationID,
|
||||
storage_directory:File.applicationStorageDirectory.nativePath,
|
||||
battle_executed:sceneStarted, scene_result:sceneResult,
|
||||
settlement_eligible:false, events:events, error:error};
|
||||
trace("ORIGINAL_PROBE_RESULT " + JSON.stringify(result));
|
||||
if (output != null) {
|
||||
var stream:FileStream = new FileStream(); stream.open(output, FileMode.WRITE);
|
||||
stream.writeUTFBytes(JSON.stringify(result)); stream.close();
|
||||
}
|
||||
NativeApplication.nativeApplication.exit(status == "probe_completed" || status == "scene_completed" ? 0 : 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,312 @@
|
||||
package {
|
||||
import flash.system.ApplicationDomain;
|
||||
|
||||
/**
|
||||
* Offline adapter for RAW loadMasterData snapshots, never derived stats.
|
||||
*
|
||||
* Contract: after original Table/RM initialization, call
|
||||
* var roster:Object = SnapshotBridge.build(domain, rawSnapshot, "teamA");
|
||||
* Returns {master: original MasterVo, selectedTeam: original TeamVo,
|
||||
* validation: JSON-safe provenance/selection metadata}.
|
||||
* Success installs master in this domain's Game.getIns().master because
|
||||
* original MonsterVo/BagCenter/TeamCenter getters use the Master accessor.
|
||||
* Failure throws Error("SnapshotBridge[code] path: explanation") and leaves
|
||||
* the previous Game.master installed. Input snapshots are never mutated.
|
||||
* Caller owns BattlePosition, battle contexts, resources and result handling.
|
||||
* Required raw roots: master, monsters, items, teams, monsterAttributes,
|
||||
* history. An explicit empty monsterAttributes array is valid: absent rows
|
||||
* leave the ORIGINAL MonsterAdd constructor state unchanged. Present rows
|
||||
* need explicit values for every ADD_FIELDS key; no bonuses are rebuilt.
|
||||
* Equipment requires itemClass 3 and the original JSON-string equipParams.
|
||||
*
|
||||
* Source references below are relative to analysis/as3/scripts/net/pixvi/myr/.
|
||||
* Only the pure loader calls from center/MasterCenter.as:loadMasterData are
|
||||
* used. Do not call loadMasterData itself: its surrounding startup path
|
||||
* accesses SDK, account, persistence, achievements and UI state.
|
||||
*/
|
||||
public class SnapshotBridge {
|
||||
private static const ADD_FIELDS:Array = ["atk", "def", "hp", "dex", "crit", "atkSpd",
|
||||
"atkVim", "selfCure", "deadBoom", "atkStun", "defStun", "atkPoi", "atkPoiDmg",
|
||||
"apCostSave", "skillCooldown", "sunFire", "moonHeal", "thorns"];
|
||||
private static const MON_FIELDS:Array = ["id", "typeId", "level", "exp", "tpLevel", "tpExp",
|
||||
"feel", "process", "mode", "gAtk", "gDef", "gHp", "gDex", "pAtk", "pDef", "pHp",
|
||||
"pDex", "potentialLevel", "equip1", "equip2", "equip3", "equip4", "equip5",
|
||||
"entangleLevel", "skin"];
|
||||
|
||||
public static function build(domain:ApplicationDomain, snapshot:Object, teamName:String):Object {
|
||||
if (domain == null) reject("domain", "domain", "original ApplicationDomain is required");
|
||||
objectAt(snapshot, "snapshot");
|
||||
if (teamName == null || teamName.length == 0)
|
||||
reject("team_name", "teamName", "select an explicit snapshot team");
|
||||
// Copy before calling loaders: BagCenter adds equipPara and HistoryVo
|
||||
// normalizes maps/flags in place (center/BagCenter.as:getItemByItemData;
|
||||
// element/master/HistoryVo.as:loadHistoryData).
|
||||
var data:Object = copy(snapshot);
|
||||
var rawMaster:Object = objectAt(data.master, "master");
|
||||
numbers(rawMaster, ["id", "level", "globalAtk", "globalDef", "globalHp", "globalDex"], "master");
|
||||
positiveId(rawMaster.id, "master.id", 2147483647);
|
||||
positiveId(rawMaster.level, "master.level", 2147483647);
|
||||
var monsters:Array = arrayAt(data.monsters, "monsters");
|
||||
var items:Array = arrayAt(data.items, "items");
|
||||
var teams:Array = arrayAt(data.teams, "teams");
|
||||
var attributes:Array = arrayAt(data.monsterAttributes, "monsterAttributes");
|
||||
validateHistory(data);
|
||||
|
||||
var table:Class = definition(domain, "net.pixvi.myr.center.Table");
|
||||
for each (var tableName:String in ["monster_info", "item_info", "game_setting", "team_info", "task_info"])
|
||||
objectAt(table[tableName], "Table." + tableName);
|
||||
// Table.startUp normally derives city_info from game_setting.cityInfo;
|
||||
// the caller may instead inject it. The history loader tolerates null
|
||||
// city_info; this bridge never rewrites caller resource tables.
|
||||
var monById:Object = {};
|
||||
var attrById:Object = {};
|
||||
var itemById:Object = {};
|
||||
var equipment:Object = {};
|
||||
var rawTeam:Object = null;
|
||||
var names:Object = {};
|
||||
var i:int;
|
||||
var row:Object;
|
||||
var path:String;
|
||||
var key:String;
|
||||
for (i = 0; i < monsters.length; i++) {
|
||||
path = "monsters[" + i + "]"; row = objectAt(monsters[i], path);
|
||||
numbers(row, MON_FIELDS, path);
|
||||
positiveId(row.id, path + ".id"); positiveId(row.typeId, path + ".typeId", 2147483647);
|
||||
// Non-selected eggs may legitimately carry level/potential 0.
|
||||
// Positive combat levels are required below for selected IDs.
|
||||
flag(row.inExploreTeam, path + ".inExploreTeam"); flag(row.entangle, path + ".entangle");
|
||||
if (monById.hasOwnProperty(String(row.id))) reject("duplicate_monster", path + ".id", "duplicate instance ID");
|
||||
monById[String(row.id)] = row;
|
||||
if (table["monster_info"][row.typeId] == null)
|
||||
reject("monster_type", path + ".typeId", "missing original monster table row");
|
||||
if (row.skin > 0) {
|
||||
// center/Table.as:startUp assigns RM.TXT.getJson("skin_info").skins.
|
||||
// element/mon/SkinVo.as:table indexes that FLAT map by typeId.
|
||||
var skins:Object = objectAt(table["skin_info"], "Table.skin_info");
|
||||
if (skins[row.skin] == null || Number(skins[row.skin].monType) != row.typeId)
|
||||
reject("skin", path + ".skin", "skin must exist for this monster species");
|
||||
}
|
||||
// MonsterCenter itself supplies table skills, up-star skills,
|
||||
// potential PointLockers, SkinVo and decoded entangleSkills.
|
||||
if (row.upStar != null && Number(row.upStar) > 0) {
|
||||
numbers(row, ["upStar"], path);
|
||||
if (table["upstar_info"] == null || table["upstar_info"][row.typeId] == null)
|
||||
reject("upstar", path + ".upStar", "missing original up-star table row");
|
||||
}
|
||||
if (row.entangleSkills != null) {
|
||||
var entangleSkills:Object = jsonObject(row.entangleSkills, path + ".entangleSkills");
|
||||
for (key in entangleSkills) {
|
||||
if (Number(entangleSkills[key]) > 0 && (table["entangle_info"] == null ||
|
||||
table["entangle_info"].entangleSkill == null ||
|
||||
table["entangle_info"].entangleSkill[entangleSkills[key]] == null))
|
||||
reject("entangle_skill", path + ".entangleSkills", "missing original entangle skill");
|
||||
}
|
||||
}
|
||||
}
|
||||
for (i = 0; i < attributes.length; i++) {
|
||||
path = "monsterAttributes[" + i + "]"; row = objectAt(attributes[i], path);
|
||||
positiveId(row.monsterId, path + ".monsterId");
|
||||
key = String(row.monsterId);
|
||||
if (attrById.hasOwnProperty(key)) reject("duplicate_attributes", path + ".monsterId", "ambiguous instance attributes");
|
||||
if (!monById.hasOwnProperty(key)) reject("orphan_attributes", path + ".monsterId", "monster instance is absent");
|
||||
numbers(row, ADD_FIELDS, path);
|
||||
attrById[key] = row;
|
||||
}
|
||||
var itemVoClass:Class = definition(domain, "net.pixvi.myr.element.bag.ItemVo");
|
||||
var itemTypeClass:Class = definition(domain, "net.pixvi.myr.element.bag.ItemType");
|
||||
for (i = 0; i < items.length; i++) {
|
||||
path = "items[" + i + "]"; row = objectAt(items[i], path);
|
||||
numbers(row, ["id", "typeId", "num"], path);
|
||||
positiveId(row.id, path + ".id"); positiveId(row.typeId, path + ".typeId", 2147483647);
|
||||
if (itemById.hasOwnProperty(String(row.id))) reject("duplicate_item", path + ".id", "duplicate inventory instance ID");
|
||||
itemById[String(row.id)] = row;
|
||||
if (table["item_info"][row.typeId] == null && table["monster_info"][row.typeId] == null)
|
||||
reject("item_type", path + ".typeId", "missing original item/egg table row");
|
||||
if (itemVoClass["getItemType"](row.typeId) == itemTypeClass["TYPE_EQUIP"]) {
|
||||
numbers(row, ["itemClass", "isUsed"], path);
|
||||
if (row.itemClass != 3) reject("equipment_class", path + ".itemClass", "original equipment loader requires itemClass 3");
|
||||
// Preflight avoids BagCenter's missing-params Alert/fake-zero
|
||||
// error branch. The original loader still decodes equipParams.
|
||||
var equip:Object = jsonObject(row.equipParams, path + ".equipParams");
|
||||
numbers(equip, ADD_FIELDS, path + ".equipParams");
|
||||
if (equip.atkPoi > 0) numbers(equip, ["atkPoiType"], path + ".equipParams");
|
||||
equipment[String(row.id)] = row;
|
||||
}
|
||||
}
|
||||
for (i = 0; i < monsters.length; i++) {
|
||||
row = monsters[i];
|
||||
for (var slot:int = 1; slot <= 5; slot++) {
|
||||
var equipId:Number = Number(row["equip" + slot]);
|
||||
if (equipId < 0 || equipId > 2147483647 || equipId != Math.floor(equipId))
|
||||
reject("equipment_id", "monsters[" + i + "].equip" + slot, "expected zero or inventory instance ID within original equip:int range");
|
||||
if (equipId > 0 && !equipment.hasOwnProperty(String(equipId)))
|
||||
reject("missing_equipment", "monsters[" + i + "].equip" + slot, "equipped inventory instance is absent or is not equipment");
|
||||
}
|
||||
}
|
||||
var selectedIds:Array = [];
|
||||
var selectedSlots:Array = [];
|
||||
var selectedSeen:Object = {};
|
||||
for (i = 0; i < teams.length; i++) {
|
||||
path = "teams[" + i + "]"; row = objectAt(teams[i], path);
|
||||
if (!(row.teamName is String) || row.teamName.length == 0 || !(row.teamType is String))
|
||||
reject("team_fields", path, "original teamName and teamType are required");
|
||||
if (names.hasOwnProperty(row.teamName)) reject("duplicate_team", path + ".teamName", "ambiguous team name");
|
||||
names[row.teamName] = true;
|
||||
var rawSlots:Array = arrayAt(row.monsters, path + ".monsters");
|
||||
var slotInfo:Object = objectAt(table["team_info"][row.teamType], "Table.team_info." + row.teamType);
|
||||
for (var pos:int = 0; pos < rawSlots.length; pos++) {
|
||||
var mid:Number = numberAt(rawSlots[pos], path + ".monsters[" + pos + "]");
|
||||
if (mid < 0 || mid != Math.floor(mid)) reject("team_member_id", path + ".monsters[" + pos + "]", "expected zero or positive monster instance ID");
|
||||
// Original loaders may discard trailing empty padding. An
|
||||
// occupied unsupported position must never be discarded.
|
||||
if (slotInfo[pos] == null && mid > 0) reject("team_slot", path + ".monsters[" + pos + "]", "occupied position is absent from the original team table");
|
||||
if (mid > 0 && !monById.hasOwnProperty(String(mid)))
|
||||
reject("missing_team_member", path + ".monsters[" + pos + "]", "reference must be a supplied monster instance ID, not a species ID");
|
||||
if (row.teamName == teamName && mid > 0) {
|
||||
var member:Object = monById[String(mid)];
|
||||
if (selectedSeen.hasOwnProperty(String(mid))) reject("duplicate_member", path, "monster instance occupies multiple selected slots");
|
||||
selectedSeen[String(mid)] = true;
|
||||
if (member.process != 3 || (member.mode != 1 && member.mode != 2))
|
||||
reject("incubating_member", path + ".monsters[" + pos + "]", "selected monster must be out of incubation (process 3, mode 1 or 2)");
|
||||
if (member.inExploreTeam == true)
|
||||
reject("exploring_member", path + ".monsters[" + pos + "]", "selected monster is exploring");
|
||||
positiveId(member.level, path + ".monsters[" + pos + "].level", 2147483647);
|
||||
positiveId(member.potentialLevel, path + ".monsters[" + pos + "].potentialLevel", 2147483647);
|
||||
selectedIds.push(mid); selectedSlots.push(pos);
|
||||
}
|
||||
}
|
||||
if (row.teamName == teamName) rawTeam = row;
|
||||
}
|
||||
if (rawTeam == null) reject("team_missing", "teams", "requested teamName is absent");
|
||||
if (selectedIds.length == 0) reject("empty_team", "teams", "selected team has no positive monster instance IDs");
|
||||
|
||||
var game:Object = definition(domain, "net.pixvi.myr.center.Game")["getIns"]();
|
||||
var previous:Object = game["master"];
|
||||
var masterClass:Class = definition(domain, "net.pixvi.myr.element.master.MasterVo");
|
||||
var monsterCenter:Class = definition(domain, "net.pixvi.myr.center.MonsterCenter");
|
||||
var bagCenter:Class = definition(domain, "net.pixvi.myr.center.BagCenter");
|
||||
var teamCenter:Class = definition(domain, "net.pixvi.myr.center.TeamCenter");
|
||||
var master:Object = new masterClass();
|
||||
try {
|
||||
game["master"] = master; master["init"]();
|
||||
// center/MasterCenter.as:loadMasterData scalar mapping. AP is
|
||||
// read-only MasterVo.ap -> GameMath.apByLevel(raw level).
|
||||
for each (key in ["id", "createTime", "level", "farmName", "avatar", "exp", "money", "ti", "ke"])
|
||||
if (rawMaster.hasOwnProperty(key)) master[key] = rawMaster[key];
|
||||
if (rawMaster.hasOwnProperty("roleName")) master["name"] = rawMaster.roleName;
|
||||
if (rawMaster.hasOwnProperty("timeTi")) master["timeTi"] = rawMaster.timeTi / 1000;
|
||||
master["curBattleTeam"] = teamName;
|
||||
// Native reflection confirms HistoryVo.loadHistoryData(Object,
|
||||
// Object); there is no HistoryVo.onData API in this SWF.
|
||||
master["history"]["loadHistoryData"](data.history, data.data2);
|
||||
if (data.activityHistory != null) {
|
||||
master["activityHistory"]["loadActivityData"](data.activityHistory);
|
||||
master["vipTime"] = data.activityHistory.vipInfo.vipTime;
|
||||
}
|
||||
if (data.payInfo != null) {
|
||||
if (data.payInfo.payPoint != null) master["history"]["payPoint"] = data.payInfo.payPoint;
|
||||
var giftTypes:Object = data.payInfo.payGiftTypes == null ? data.payInfo.payGitfTypes : data.payInfo.payGiftTypes;
|
||||
if (giftTypes != null) for each (key in String(giftTypes).split(",")) master["history"]["payGiftTypes"][key] = true;
|
||||
}
|
||||
master["globalAdd"]["update"](rawMaster);
|
||||
if (data.masterEventTimer != null) master["randomEventTimer"] = data.masterEventTimer;
|
||||
if (data.masterCurrentEvent != null) master["randomEvent"] = data.masterCurrentEvent;
|
||||
for each (row in monsters) {
|
||||
var mon:Object = monsterCenter["getMonByMonData"](row);
|
||||
// center/MasterCenter.as:loadMasterData only updates an
|
||||
// existing allMbs[mon.id]; [] and absent per-instance rows
|
||||
// intentionally preserve the original MonsterAdd defaults.
|
||||
if (attrById.hasOwnProperty(String(row.id))) mon["abilityAdd"]["update"](attrById[String(row.id)]);
|
||||
master["monsters"].push(mon);
|
||||
}
|
||||
for each (row in items) master["bag"]["items"].push(bagCenter["getItemByItemData"](row));
|
||||
var selectedTeam:Object = null;
|
||||
for each (row in teams) {
|
||||
var team:Object = teamCenter["getTeamVoByData"](row);
|
||||
master["teams"].push(team);
|
||||
if (row.teamName == teamName) selectedTeam = team;
|
||||
}
|
||||
for each (pos in selectedSlots)
|
||||
if (selectedTeam.monsters[pos] != rawTeam.monsters[pos])
|
||||
reject("team_slot", "teams", "original loader shifted an occupied selected slot");
|
||||
return {master:master, selectedTeam:selectedTeam, validation:{schema:1,
|
||||
source:"original_loadMasterData", teamName:teamName, teamType:rawTeam.teamType,
|
||||
selectedIds:selectedIds, selectedSlots:selectedSlots, rawSlots:rawTeam.monsters.concat(),
|
||||
monsterCount:monsters.length, attributeCount:attributes.length, itemCount:items.length,
|
||||
masterLevel:master["level"], ap:master["ap"], apSource:"MasterVo.ap/GameMath.apByLevel",
|
||||
historyLoader:"HistoryVo.loadHistoryData", installed:true}};
|
||||
} catch (error:Error) {
|
||||
game["master"] = previous;
|
||||
reject("original_loader", "snapshot", error.name + ": " + error.message);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static function validateHistory(data:Object):void {
|
||||
var h:Object = objectAt(data.history, "history");
|
||||
// Exact required shapes read by HistoryVo.loadHistoryData. Original
|
||||
// conversions produce guide/unlock/pass boolean maps, not arrays.
|
||||
for each (var name:String in ["monLib", "equipLib", "passAchi", "guide_record", "unlockCity"])
|
||||
arrayAt(h[name], "history." + name);
|
||||
for each (name in ["numFeedMonsters", "numKillMonsters", "historyGacha", "passTask", "unlockTask",
|
||||
"loopTask", "unlockStage", "passStage", "payTypeCount", "everyDayBuyProductNum"])
|
||||
objectAt(h[name], "history." + name);
|
||||
numbers(h, ["numAddMoney", "numChicken", "countBattle"], "history");
|
||||
for each (name in ["unlockStage", "passStage"])
|
||||
for (var key:String in h[name]) if (key != "") arrayAt(h[name][key], "history." + name + "." + key);
|
||||
if (data.data2 != null) {
|
||||
objectAt(data.data2, "data2"); arrayAt(data.data2.unlockSkins, "data2.unlockSkins");
|
||||
}
|
||||
if (data.activityHistory != null) {
|
||||
var activity:Object = objectAt(data.activityHistory, "activityHistory");
|
||||
var daily:Object = objectAt(activity.dailyGift, "activityHistory.dailyGift");
|
||||
numbers(daily, ["dailyGiftCheckTime", "dailyGiftLevel", "dailyGiftCount", "signCount"], "activityHistory.dailyGift");
|
||||
}
|
||||
}
|
||||
|
||||
private static function definition(domain:ApplicationDomain, name:String):Class {
|
||||
if (!domain.hasDefinition(name)) reject("definition", name, "original library definition is missing");
|
||||
return domain.getDefinition(name) as Class;
|
||||
}
|
||||
private static function objectAt(value:Object, path:String):Object {
|
||||
if (value == null || typeof(value) != "object" || value is Array)
|
||||
reject("missing_object", path, "expected an explicit object");
|
||||
return value;
|
||||
}
|
||||
private static function arrayAt(value:Object, path:String):Array {
|
||||
if (!(value is Array)) reject("missing_array", path, "expected an explicit array, including when empty");
|
||||
return value as Array;
|
||||
}
|
||||
private static function numberAt(value:Object, path:String):Number {
|
||||
if (value == null || typeof(value) != "number" || !isFinite(Number(value)))
|
||||
reject("missing_number", path, "expected an explicit finite number; no stat defaults are supplied");
|
||||
return Number(value);
|
||||
}
|
||||
private static function numbers(row:Object, names:Array, path:String):void {
|
||||
for each (var name:String in names) numberAt(row[name], path + "." + name);
|
||||
}
|
||||
private static function positiveId(value:Object, path:String, max:Number = 9007199254740991):void {
|
||||
var n:Number = numberAt(value, path);
|
||||
if (n < 1 || n != Math.floor(n) || n > max) reject("positive_integer", path, "expected an exact positive integer within the original field range");
|
||||
}
|
||||
private static function flag(value:Object, path:String):void {
|
||||
if (!(value is Boolean) && !(value === 0 || value === 1)) reject("missing_flag", path, "expected explicit boolean or 0/1 flag");
|
||||
}
|
||||
private static function jsonObject(value:Object, path:String):Object {
|
||||
if (!(value is String)) reject("json_string", path, "original loader requires a JSON object string");
|
||||
var decoded:Object;
|
||||
try { decoded = JSON.parse(String(value)); }
|
||||
catch (error:Error) { reject("json_string", path, "invalid JSON object string"); }
|
||||
return objectAt(decoded, path);
|
||||
}
|
||||
private static function copy(value:Object):Object {
|
||||
if (value == null || typeof(value) != "object") return value;
|
||||
var result:Object = value is Array ? [] : {};
|
||||
for (var key:String in value) result[key] = copy(value[key]);
|
||||
return result;
|
||||
}
|
||||
private static function reject(code:String, path:String, message:String):void {
|
||||
throw new Error("SnapshotBridge[" + code + "] " + path + ": " + message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Fetch only compiler/desktop-runtime members from the official AIR SDK ZIP.
|
||||
|
||||
Opt-in dependency acquisition, never imported by the offline adapter. Everything
|
||||
is scoped to ignored local_state; the SDK is not installed or placed on PATH.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import http.cookiejar
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import urllib.request
|
||||
import zipfile
|
||||
import zlib
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
BASE = "https://airsdk.wxlift.com"
|
||||
SDK_VERSION = "51.5.1.1" # Must match the reviewed executable hashes in trusted.py.
|
||||
|
||||
|
||||
class RemoteZip(io.RawIOBase):
|
||||
def __init__(self, opener, url):
|
||||
self.opener, self.url, self.position = opener, url, 0
|
||||
self.cached_start, self.cached_data = 0, b""
|
||||
with self.fetch(0, 1) as response:
|
||||
self.size = int(response.headers["Content-Range"].split("/")[-1])
|
||||
|
||||
def fetch(self, start, size):
|
||||
return self.opener.open(urllib.request.Request(self.url, headers={
|
||||
"Range": f"bytes={start}-{start + size - 1}",
|
||||
"Referer": BASE + "/download"}), timeout=45)
|
||||
|
||||
def seekable(self):
|
||||
return True
|
||||
|
||||
def seek(self, offset, whence=0):
|
||||
self.position = offset + (0 if whence == 0 else self.position if whence == 1 else self.size)
|
||||
return self.position
|
||||
|
||||
def tell(self):
|
||||
return self.position
|
||||
|
||||
def read(self, size=-1):
|
||||
size = min(self.size - self.position, size if size >= 0 else self.size)
|
||||
if size <= 0:
|
||||
return b""
|
||||
if self.cached_start <= self.position and self.position + size <= self.cached_start + len(self.cached_data):
|
||||
offset = self.position - self.cached_start
|
||||
self.position += size
|
||||
return self.cached_data[offset:offset + size]
|
||||
requested = min(self.size - self.position, max(size, 128 * 1024))
|
||||
with self.fetch(self.position, requested) as response:
|
||||
if response.status != 206:
|
||||
raise ValueError("Official SDK server did not honor byte range")
|
||||
fetched = response.read()
|
||||
if len(fetched) != requested:
|
||||
raise ValueError("Truncated SDK byte range")
|
||||
self.cached_start, self.cached_data = self.position, fetched
|
||||
data = fetched[:size]
|
||||
self.position += size
|
||||
return data
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--list", action="store_true")
|
||||
parser.add_argument("--runtime-only", action="store_true")
|
||||
args = parser.parse_args()
|
||||
root = ROOT / "local_state/battle_runtime"
|
||||
acquisition = root / "acquisition"
|
||||
acquisition.mkdir(parents=True, exist_ok=True)
|
||||
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar()))
|
||||
with opener.open(BASE + "/api/config-settings/download", timeout=30) as response:
|
||||
settings = json.load(response)
|
||||
link = f"/api/versions/{SDK_VERSION}/sdks/AIRSDK_Windows.zip"
|
||||
url = BASE + link + "?id=" + str(settings["id"])
|
||||
remote = RemoteZip(opener, url)
|
||||
with zipfile.ZipFile(remote) as archive:
|
||||
inventory = [{"name": item.filename, "bytes": item.file_size,
|
||||
"compressed": item.compress_size, "crc32": item.CRC}
|
||||
for item in archive.infolist()]
|
||||
(acquisition / "sdk_inventory.json").write_text(json.dumps(inventory, indent=2), encoding="utf-8")
|
||||
selected = [item for item in archive.infolist() if not item.is_dir() and (
|
||||
item.filename.startswith("runtimes/air/win64/")
|
||||
or (item.filename.startswith("lib/") and item.filename.count("/") == 1)
|
||||
or (item.filename.startswith("frameworks/") and not item.filename.startswith(("frameworks/projects/", "frameworks/locale/")))
|
||||
or item.filename in ("bin/adl.exe", "bin/adl64.exe", "air-sdk-description.xml"))]
|
||||
if args.runtime_only:
|
||||
selected = [item for item in selected if item.filename.startswith("runtimes/") or item.filename == "bin/adl64.exe"]
|
||||
print(json.dumps({"version": SDK_VERSION, "archive_bytes": remote.size,
|
||||
"selected_files": len(selected), "selected_compressed_bytes": sum(i.compress_size for i in selected)}), flush=True)
|
||||
if args.list:
|
||||
for item in selected:
|
||||
print(item.filename, item.file_size)
|
||||
return
|
||||
destination = root / "air_sdk"
|
||||
identity = {"version": SDK_VERSION, "source": BASE + link, "files": {}}
|
||||
for item in selected:
|
||||
path = (destination / item.filename).resolve()
|
||||
if not path.is_relative_to(destination.resolve()):
|
||||
raise ValueError("SDK path escapes local destination")
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
existing = path.read_bytes() if path.is_file() else b""
|
||||
data = existing if len(existing) == item.file_size and zlib.crc32(existing) == item.CRC else archive.read(item)
|
||||
path.write_bytes(data)
|
||||
identity["files"][item.filename] = hashlib.sha256(data).hexdigest()
|
||||
print(item.filename, len(data), flush=True)
|
||||
(acquisition / "sdk_identity.json").write_text(json.dumps(identity, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,390 @@
|
||||
"""Validate original scene/snapshot provenance and dependencies, without combat math."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar
|
||||
from functools import lru_cache
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import time
|
||||
import zipfile
|
||||
import zlib
|
||||
|
||||
from ranch_assistant.amf import Reader
|
||||
from tools.battle_runtime.prepare import APK_SHA256, MAIN_SHA256, ROOT
|
||||
from tools.battle_runtime.trusted import TABLE_FILES
|
||||
|
||||
MON_FIELDS = frozenset("id typeId level exp tpLevel tpExp feel process mode gAtk gDef gHp gDex lock sysLock nicName timeGet timeStart roomId inExploreTeam equip1 equip2 equip3 equip4 equip5 pAtk pDef pHp pDex potentialLevel giftTime skin entangle entangleLevel".split())
|
||||
GLOBAL_FIELDS = frozenset(("globalAtk","globalDef","globalHp","globalDex"))
|
||||
ADD_FIELDS = frozenset("atk def hp dex crit atkSpd atkVim selfCure deadBoom atkStun defStun atkPoi atkPoiDmg apCostSave skillCooldown sunFire moonHeal thorns".split())
|
||||
CONTROLLERS = frozenset(("base","none","monMaker","monBuff","buff"))
|
||||
MON_CONTROLLERS = frozenset("none add monMaker showFace monSteps hp skill hunluanBoom deadBoom hpArea buffMovie buffMon buff statusMov fixHurt lockTarget".split())
|
||||
TRIGGERS = frozenset(("event","useSkill","time","monDead","waveStart"))
|
||||
EFFECTS = frozenset("none monSkill buff monBuff buffMov event monJoin unlockWave shake showFace startController stopController".split())
|
||||
# BattleAreaType advertises block in its editor dictionary, but its native
|
||||
# factory returns null. Do not advertise that scene as executable.
|
||||
AREAS = frozenset(("none","hp","movespd","pow","speed","powdef"))
|
||||
KNOWN_ORIGINAL_IMAGE_FALLBACKS = frozenset(("data/img/monster/q/1001010_q_2s.png",))
|
||||
_INSPECTION_BUDGET = ContextVar("original_runtime_inspection_budget",default=None)
|
||||
|
||||
|
||||
class InspectionInterrupted(RuntimeError):
|
||||
def __init__(self,status):
|
||||
super().__init__(status)
|
||||
self.status=status
|
||||
|
||||
|
||||
def _check_budget():
|
||||
budget=_INSPECTION_BUDGET.get()
|
||||
if budget is not None:
|
||||
cancel_event,deadline=budget
|
||||
if cancel_event is not None and cancel_event.is_set(): raise InspectionInterrupted("cancelled")
|
||||
if deadline is not None and time.monotonic() >= deadline: raise InspectionInterrupted("timeout")
|
||||
|
||||
|
||||
@contextmanager
|
||||
def inspection_budget(cancel_event=None,deadline=None):
|
||||
"""Make the large source hash cancellable without a background thread."""
|
||||
token=_INSPECTION_BUDGET.set((cancel_event,deadline))
|
||||
try:
|
||||
_check_budget()
|
||||
yield
|
||||
finally:
|
||||
_INSPECTION_BUDGET.reset(token)
|
||||
|
||||
|
||||
def _source_key():
|
||||
candidates = list(ROOT.glob("*_1.9.68.apk"))
|
||||
if len(candidates) != 1:
|
||||
raise ValueError("Expected exactly one original *_1.9.68.apk")
|
||||
path = candidates[0]
|
||||
stat = path.stat()
|
||||
return str(path.resolve()), stat.st_size, stat.st_mtime_ns
|
||||
|
||||
|
||||
@lru_cache(maxsize=2)
|
||||
def _load_source(path: str, size: int, modified: int):
|
||||
with Path(path).open("rb") as stream:
|
||||
hasher=hashlib.sha256()
|
||||
while True:
|
||||
_check_budget()
|
||||
chunk=stream.read(4*1024*1024)
|
||||
if not chunk: break
|
||||
hasher.update(chunk)
|
||||
if hasher.hexdigest() != APK_SHA256:
|
||||
raise ValueError("Original APK SHA-256 mismatch")
|
||||
tables = {}
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
if hashlib.sha256(archive.read("assets/MYRMain.app")).hexdigest() != MAIN_SHA256:
|
||||
raise ValueError("Original main SWF SHA-256 mismatch")
|
||||
for name, expected in TABLE_FILES.items():
|
||||
_check_budget()
|
||||
member = "assets/codes/" + hashlib.md5(f"data/table/{name}.json".encode()).hexdigest()
|
||||
compressed = archive.read(member)
|
||||
if hashlib.sha256(compressed).hexdigest() != expected:
|
||||
raise ValueError("Original table identity mismatch: " + name)
|
||||
raw = zlib.decompress(compressed)
|
||||
reader = Reader(raw); value = reader.read()
|
||||
if reader.pos != len(raw):
|
||||
raise ValueError("Trailing original AMF table bytes")
|
||||
if name == "skin_info": value = value["skins"]
|
||||
elif name not in ("setting","game_setting","monster_setting","team_info","potential_info","entangle_info","upstar_info"):
|
||||
value = value["datas"]
|
||||
if name == "stage_info" and isinstance(value,list): value = {str(row["id"]):row for row in value}
|
||||
tables[name] = value
|
||||
members = frozenset(archive.namelist())
|
||||
return tables, members
|
||||
|
||||
|
||||
def original_source():
|
||||
_check_budget()
|
||||
return _load_source(*_source_key())
|
||||
|
||||
|
||||
def _number(value):
|
||||
if isinstance(value,bool) or not isinstance(value,(str,int,float)):
|
||||
return None
|
||||
try:
|
||||
result = float(value)
|
||||
return result if math.isfinite(result) else None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _list(value):
|
||||
return value if isinstance(value,list) else None
|
||||
|
||||
|
||||
def _id(value):
|
||||
number = _number(value)
|
||||
return str(int(number)) if number is not None and number == int(number) else ""
|
||||
|
||||
|
||||
def _positive_id(value):
|
||||
key = _id(value)
|
||||
return bool(key) and 0 < int(key) <= 9007199254740991
|
||||
|
||||
|
||||
def validate(request: Mapping, *, source=None) -> dict:
|
||||
"""Return a native data-only request or precise refusal reasons.
|
||||
|
||||
Tables are read from the independently hashed APK, never an imported support
|
||||
manifest. Supplied battle objects must equal their original context's config.
|
||||
SnapshotBridge performs the original native construction and checks again.
|
||||
"""
|
||||
reasons, gaps, required, unit_types, skill_ids = [], [], set(), set(), set()
|
||||
def refuse(code, detail): reasons.append({"code":code,"detail":detail})
|
||||
try:
|
||||
tables, members = original_source() if source is None else source
|
||||
except (OSError,ValueError,KeyError,zipfile.BadZipFile) as error:
|
||||
return {"reasons":[{"code":"original_source_unavailable","detail":str(error)}]}
|
||||
context = request.get("context")
|
||||
data = request.get("original_data")
|
||||
roster = request.get("roster")
|
||||
supplied_position = request.get("battle_position")
|
||||
if supplied_position is not None and (not isinstance(supplied_position,Mapping) or set(supplied_position)-{"battleType","stageId","stageLevel","taskTypeId","taskStep"}):
|
||||
return {"reasons":[{"code":"invalid_battle_position","detail":"Expected the original five-field battle position"}]}
|
||||
if not isinstance(data,Mapping) or set(data)-{"source","resource_identity","battle"}:
|
||||
return {"reasons":[{"code":"external_battle_data_unvalidated","detail":"Expected original_data.battle and original resource identity only"}]}
|
||||
if data.get("source","original_apk") != "original_apk": refuse("resource_identity_mismatch","Expected original_apk source")
|
||||
identity = data.get("resource_identity",{"apk_sha256":APK_SHA256,"main_swf_sha256":MAIN_SHA256})
|
||||
if identity != {"apk_sha256":APK_SHA256,"main_swf_sha256":MAIN_SHA256}:
|
||||
refuse("resource_identity_mismatch","Expected pinned original APK/main SWF")
|
||||
battle = None
|
||||
position = {"battleType":"stage","stageId":request.get("stage_id"),"stageLevel":str(request.get("difficulty")),"taskTypeId":None,"taskStep":0}
|
||||
stage_id, difficulty = request.get("stage_id"), request.get("difficulty")
|
||||
try:
|
||||
if context == "ordinary_stage":
|
||||
if not isinstance(stage_id,str) or type(difficulty) is not int or difficulty < 1: raise ValueError("Stage ID and integer difficulty required")
|
||||
battle = tables["stage_info"][stage_id]["level"][str(difficulty)]["battle"]
|
||||
if request.get("task_id") is not None or request.get("step_index") is not None: raise ValueError("Ordinary stage cannot carry task position")
|
||||
elif context in ("task_battle","task_pass_stage"):
|
||||
# Canonical orchestration carries the account task-instance ID in
|
||||
# task_id. Its original task TYPE is explicitly in BattlePosition.
|
||||
task_id = supplied_position.get("taskTypeId") if supplied_position is not None else request.get("task_id")
|
||||
step_index = request.get("step_index")
|
||||
if supplied_position is not None:
|
||||
if step_index is not None and step_index != supplied_position.get("taskStep"):
|
||||
raise ValueError("Task step selector conflicts with BattlePosition")
|
||||
step_index = supplied_position.get("taskStep")
|
||||
if not isinstance(task_id,str) or type(step_index) is not int or step_index < 0: raise ValueError("Task type ID and zero-based step_index required")
|
||||
step = tables["task_info"][task_id]["steps"][step_index]
|
||||
expected_status = "battle" if context == "task_battle" else "passStage"
|
||||
if step["statusType"] != expected_status: raise ValueError("Task step statusType does not match context")
|
||||
position = {"battleType":"task","stageId":None,"stageLevel":None,"taskTypeId":task_id,"taskStep":step_index}
|
||||
if context == "task_battle":
|
||||
if stage_id is not None: raise ValueError("Embedded task battle cannot carry an ordinary stage selector")
|
||||
battle = step["battle"]
|
||||
else:
|
||||
stage_id, difficulty = str(step["statusValue"]["stage"]), int(step["statusValue"]["level"])
|
||||
battle = tables["stage_info"][stage_id]["level"][str(difficulty)]["battle"]
|
||||
if request.get("stage_id") is not None and request["stage_id"] != stage_id: raise ValueError("passStage stage selector mismatch")
|
||||
else: raise ValueError("Unknown battle context")
|
||||
if not isinstance(battle,dict) or not battle: raise ValueError("Original context has no battle")
|
||||
except (KeyError,IndexError,TypeError,ValueError) as error:
|
||||
return {"reasons":reasons+[{"code":"invalid_battle_context","detail":str(error)}]}
|
||||
if "battle" not in data or data["battle"] != battle:
|
||||
refuse("battle_config_mismatch","Supplied battle must equal the original config selected by its stage/task context")
|
||||
if supplied_position is not None and dict(supplied_position) != position:
|
||||
refuse("battle_position_mismatch","Supplied BattlePosition does not match the original selected context")
|
||||
if not isinstance(roster,Mapping):
|
||||
return {"reasons":reasons+[{"code":"roster_not_validated","detail":"Expected a raw original snapshot or roster.snapshot wrapper"}]}
|
||||
team_name = request.get("team")
|
||||
if "snapshot" in roster:
|
||||
if set(roster)-{"snapshot","team_name","team_id"}:
|
||||
refuse("invalid_roster","Unknown snapshot-wrapper fields")
|
||||
wrapper_team = roster.get("team_name",roster.get("team_id"))
|
||||
if "team_id" in roster and "team_name" in roster and roster["team_id"] != roster["team_name"]:
|
||||
refuse("invalid_roster","Conflicting wrapper team selectors")
|
||||
if team_name is not None and wrapper_team is not None and team_name != wrapper_team:
|
||||
refuse("invalid_roster","Top-level and wrapper team selectors conflict")
|
||||
if team_name is None: team_name = wrapper_team
|
||||
snapshot = roster.get("snapshot")
|
||||
else:
|
||||
snapshot = roster
|
||||
if isinstance(snapshot,Mapping) and set(snapshot)=={"time","body"}: snapshot = snapshot["body"]
|
||||
if not isinstance(snapshot,Mapping) or not isinstance(team_name,str) or not team_name:
|
||||
return {"reasons":reasons+[{"code":"invalid_roster","detail":"Snapshot and team_name required"}]}
|
||||
for name in ("master","history","monsters","monsterAttributes","items","teams"):
|
||||
if name not in snapshot: refuse("incomplete_snapshot","Missing " + name)
|
||||
if reasons: return {"reasons":reasons}
|
||||
master, history = snapshot["master"], snapshot["history"]
|
||||
if not isinstance(master,Mapping) or not GLOBAL_FIELDS.issubset(master) or any(_number(master.get(k)) is None for k in GLOBAL_FIELDS|{"level","id"}):
|
||||
refuse("incomplete_global_attributes","Original master level/id and all four global attributes are required")
|
||||
elif not _positive_id(master["id"]) or not _positive_id(master["level"]):
|
||||
refuse("invalid_master","Original master ID and level must be positive integers")
|
||||
if not isinstance(history,Mapping) or not isinstance(history.get("monLib"),list) or not isinstance(history.get("guide_record"),(list,dict)) or "guide_main" not in history:
|
||||
refuse("incomplete_battle_history","Original monLib, guide_main and guide_record required")
|
||||
if isinstance(history,Mapping):
|
||||
for name in ("monLib","equipLib","passAchi","guide_record","unlockCity"):
|
||||
if not isinstance(history.get(name),list): refuse("incomplete_battle_history","Original history array required: "+name)
|
||||
for name in ("numFeedMonsters","numKillMonsters","historyGacha","passTask","unlockTask","loopTask","unlockStage","passStage","payTypeCount","everyDayBuyProductNum"):
|
||||
if not isinstance(history.get(name),dict): refuse("incomplete_battle_history","Original history object required: "+name)
|
||||
for name in ("numAddMoney","numChicken","countBattle"):
|
||||
if _number(history.get(name)) is None: refuse("incomplete_battle_history","Original history number required: "+name)
|
||||
for name in ("unlockStage","passStage"):
|
||||
if isinstance(history.get(name),dict) and any(not isinstance(value,list) for key,value in history[name].items() if key):
|
||||
refuse("incomplete_battle_history","Original stage history arrays required: "+name)
|
||||
for name in ("monsters","monsterAttributes","items","teams"):
|
||||
if not isinstance(snapshot[name],list): refuse("invalid_snapshot_array",name)
|
||||
if reasons: return {"reasons":reasons}
|
||||
monsters, items = {}, {}
|
||||
for row in snapshot["monsters"]:
|
||||
if not isinstance(row,dict) or not MON_FIELDS.issubset(row):
|
||||
refuse("incomplete_monster_snapshot","Original MonsterCenter fields are missing"); continue
|
||||
key = _id(row["id"])
|
||||
if not _positive_id(row["id"]) or key in monsters: refuse("invalid_monster_id","Missing or duplicate monster instance"); continue
|
||||
if any(_number(row[field]) is None for field in MON_FIELDS-{"nicName","entangle","lock","sysLock","inExploreTeam","timeStart","giftTime","roomId"}): refuse("invalid_monster_fields","Original numeric monster fields required")
|
||||
monsters[key] = row
|
||||
if _id(row["typeId"]) not in tables["monster_info"]: refuse("unknown_monster_type","Snapshot requires a different resource version")
|
||||
for row in snapshot["items"]:
|
||||
if not isinstance(row,dict) or not {"id","typeId","num"}.issubset(row): refuse("incomplete_item_snapshot","Original item id/typeId/num required"); continue
|
||||
key = _id(row["id"])
|
||||
if not _positive_id(row["id"]) or key in items: refuse("invalid_item_id","Missing or duplicate item instance"); continue
|
||||
items[key] = row
|
||||
attribute_ids = set()
|
||||
for row in snapshot["monsterAttributes"]:
|
||||
if not isinstance(row,dict) or "monsterId" not in row or set(row)-ADD_FIELDS-{"monsterId","id","masterId"}:
|
||||
refuse("unknown_monster_additions","Unsupported independent monster attribute fields")
|
||||
continue
|
||||
key = _id(row["monsterId"])
|
||||
if key in attribute_ids or key not in monsters: refuse("invalid_monster_additions","Duplicate or orphan original attribute row")
|
||||
attribute_ids.add(key)
|
||||
if not ADD_FIELDS.issubset(row) or any(_number(row.get(field)) is None for field in ADD_FIELDS):
|
||||
refuse("incomplete_monster_additions","Supplied original attribute rows must be complete")
|
||||
teams = [row for row in snapshot["teams"] if isinstance(row,dict) and row.get("teamName")==team_name]
|
||||
if len(teams)!=1 or not isinstance(teams[0].get("monsters"),list):
|
||||
return {"reasons":reasons+[{"code":"invalid_selected_team","detail":"Exactly one original team with monster slots is required"}]}
|
||||
selected, equipment_types = [], set()
|
||||
selected_seen = set()
|
||||
slots = tables["team_info"].get(teams[0].get("teamType"))
|
||||
if not isinstance(slots,dict):
|
||||
return {"reasons":reasons+[{"code":"unknown_team_type","detail":"Selected formation requires an original team table"}]}
|
||||
for position_index,value in enumerate(teams[0]["monsters"]):
|
||||
if _number(value)==0: continue
|
||||
if not _positive_id(value): refuse("invalid_team_member","Expected zero or a positive original instance ID"); continue
|
||||
if str(position_index) not in slots: refuse("unknown_team_slot","Occupied selected slot is absent from the original formation")
|
||||
if _id(value) in selected_seen: refuse("duplicate_selected_monster","A monster cannot occupy multiple selected slots")
|
||||
selected_seen.add(_id(value))
|
||||
mon = monsters.get(_id(value))
|
||||
if mon is None: refuse("missing_selected_monster","Selected team instance is absent from snapshot"); continue
|
||||
selected.append(mon)
|
||||
if _number(mon["process"]) != 3 or _number(mon["mode"]) not in (1,2): refuse("monster_unavailable","Selected monster must be out of incubation")
|
||||
if not _positive_id(mon["level"]) or not _positive_id(mon["potentialLevel"]): refuse("invalid_combat_level","Selected original level and potentialLevel must be positive integers")
|
||||
if _number(mon["level"]) > _number(mon["potentialLevel"]) * float(tables["potential_info"]["potentialLevelMaxAdd"]):
|
||||
refuse("+50overlv","Selected level exceeds original GameMath.getMonMaxLevel(potentialLevel)")
|
||||
# BattlePanel.cheatCheck uses literal 200 (not GameMath.maxFeel, whose
|
||||
# optional table setting is absent from this APK).
|
||||
if _number(mon["feel"]) > 200:
|
||||
refuse("+15overfeel","Selected feel exceeds original BattlePanel's 200 check")
|
||||
if request.get("purpose","settlement")=="settlement" and int(_id(mon["id"])) <= 100000:
|
||||
refuse("player_check_exemption","Selected instance ID would bypass original player integrity checks")
|
||||
if mon["inExploreTeam"] not in (0,False,"0"): refuse("monster_unavailable","Selected original monster is exploring")
|
||||
for field in ("equip1","equip2","equip3","equip4","equip5"):
|
||||
if _number(mon[field]) != 0:
|
||||
item = items.get(_id(mon[field]))
|
||||
if item is None: refuse("missing_equipment","Selected equipment instance is absent"); continue
|
||||
if _id(item["typeId"]) not in tables["item_info"]: refuse("unknown_item_type","Selected equipment requires a different original item table"); continue
|
||||
equipment_types.add(_id(item["typeId"]))
|
||||
if item.get("itemClass") != 3 or "isUsed" not in item or not isinstance(item.get("equipParams"),str): refuse("incomplete_equipment","Original equipParams/itemClass/isUsed required"); continue
|
||||
try:
|
||||
parameters = json.loads(item["equipParams"])
|
||||
if not ADD_FIELDS.issubset(parameters) or any(_number(parameters[k]) is None for k in ADD_FIELDS): raise ValueError()
|
||||
if _number(parameters["atkPoi"]) > 0 and _number(parameters.get("atkPoiType")) is None: raise ValueError()
|
||||
except (ValueError,TypeError): refuse("incomplete_equipment","Incomplete original equipment parameters")
|
||||
if not selected: refuse("empty_selected_team","Original selected team contains no available monsters")
|
||||
def image(path, *, native_empty_frame=False):
|
||||
required.add(path)
|
||||
member = "assets/codes/"+hashlib.md5(path.encode()).hexdigest()
|
||||
if member not in members:
|
||||
if path in KNOWN_ORIGINAL_IMAGE_FALLBACKS or native_empty_frame: gaps.append(path)
|
||||
else: refuse("original_asset_missing",path)
|
||||
for equip_type in equipment_types:
|
||||
item_row = tables["item_info"][equip_type]
|
||||
item_position = item_row.get("position")
|
||||
if not isinstance(item_position,dict) or "position" not in item_position:
|
||||
refuse("unknown_equipment_appearance","Original equipment position is missing")
|
||||
elif str(item_position["position"]) != "0":
|
||||
ornament = "_o" if item_position.get("img") else ""
|
||||
image(f"data/img/item/item_{equip_type}{ornament}.png")
|
||||
def unit(type_id, mode, skills=None, appearance=None):
|
||||
key = _id(type_id); row = tables["monster_info"].get(key)
|
||||
if row is None: refuse("unknown_monster_type",str(type_id)); return
|
||||
unit_types.add(key)
|
||||
image_key = _id(appearance) if appearance is not None else key
|
||||
visual = tables["monster_info"].get(image_key)
|
||||
if visual is None: refuse("unknown_monster_appearance",str(appearance)); return
|
||||
for tag in ("","m","a","ab","s"):
|
||||
fix = visual.get("imgFix",{}).get(str(int(float(mode)))+tag)
|
||||
if fix is not None and not (isinstance(fix,dict) and fix.get("close") is True):
|
||||
image(f"data/img/monster/q/{image_key}_q_{int(float(mode))}{tag}.png",native_empty_frame=bool(tag) and fix in ({},[]))
|
||||
for skill in skills if skills is not None else [row.get("skill_1",0),row.get("skill_2",0)]:
|
||||
if _number(skill) is not None and int(float(skill)) > 0:
|
||||
skill_ids.add(int(float(skill)))
|
||||
if _id(skill) not in tables["monster_skill"]: refuse("unknown_skill",str(skill))
|
||||
for mon in selected:
|
||||
appearance = mon["typeId"]
|
||||
if _number(mon.get("skin",0)):
|
||||
skin = tables["skin_info"].get(_id(mon["skin"]))
|
||||
if skin is None: refuse("unknown_skin","Skin is not present in the pinned original resources")
|
||||
elif _id(skin.get("monType")) != _id(mon["typeId"]): refuse("invalid_skin","Original skin belongs to another monster species")
|
||||
else: appearance = mon["skin"]
|
||||
base = tables["monster_info"].get(_id(mon["typeId"]),{})
|
||||
skills = [base.get("skill_1",0),base.get("skill_2",0)]
|
||||
if _number(mon.get("upStar",0)):
|
||||
upstar = tables["upstar_info"].get(_id(mon["typeId"]))
|
||||
if not isinstance(upstar,dict): refuse("unknown_upstar","Missing original up-star table")
|
||||
else: skills = [upstar.get("skill",{}).get(str(i+1),skill) for i,skill in enumerate(skills)]
|
||||
unit(mon["typeId"],mon["mode"],skills,appearance)
|
||||
def rows(owner,field):
|
||||
value = _list(owner.get(field,[]))
|
||||
if value is None: refuse("invalid_battle_array",field); return []
|
||||
return value
|
||||
for team in rows(battle,"teams"):
|
||||
if not isinstance(team,dict): refuse("invalid_battle_team","Original team object required"); continue
|
||||
for mon in rows(team,"mons"):
|
||||
if not isinstance(mon,dict) or "type" not in mon or _number(mon.get("mode")) is None:
|
||||
refuse("invalid_battle_unit","Original enemy type/mode required"); continue
|
||||
row = tables["monster_info"].get(_id(mon["type"]),{})
|
||||
skills = [row.get("skill_1",0) if _number(mon.get("skill_1",-1))==-1 else mon["skill_1"],row.get("skill_2",0) if _number(mon.get("skill_2",-1))==-1 else mon["skill_2"]]
|
||||
unit(mon["type"],mon["mode"],skills)
|
||||
for controller in rows(mon,"controller"):
|
||||
if controller.get("type") not in MON_CONTROLLERS: refuse("unknown_mon_controller",str(controller.get("type")))
|
||||
for controller in rows(battle,"controller"):
|
||||
if controller.get("type") not in CONTROLLERS: refuse("unknown_battle_controller",str(controller.get("type")))
|
||||
if controller.get("type")=="monMaker":
|
||||
para=controller.get("para",{});unit(para.get("monType"),para.get("mode",2))
|
||||
for trigger in rows(battle,"triggers"):
|
||||
if trigger.get("type") not in TRIGGERS: refuse("unknown_trigger",str(trigger.get("type")))
|
||||
for effect in rows(trigger,"effects"):
|
||||
if effect.get("type") not in EFFECTS: refuse("unsupported_trigger_effect",str(effect.get("type")))
|
||||
field=battle.get("battleField",{})
|
||||
if field.get("fieldMode"):
|
||||
field = tables["setting"]["defaultField"].get(field.get("fieldName"),{}) | {"mapObjects":field.get("mapObjects",[])}
|
||||
for area in rows(field,"mapAreas"):
|
||||
if area.get("type","none") not in AREAS: refuse("unknown_battle_area",str(area.get("type")))
|
||||
for obj in rows(field,"mapObjects"):
|
||||
ground=tables["setting"]["groundObject"].get(obj.get("type"))
|
||||
if ground is None: refuse("unknown_ground_object",str(obj.get("type")))
|
||||
elif ground.get("img"): image(str(ground["img"]))
|
||||
ground = tables["setting"]["groundType"].get(str(battle.get("groundType","1")))
|
||||
if ground is None: refuse("unknown_ground_type",str(battle.get("groundType")))
|
||||
else: image("data/img/bg/"+ground["battleImg"])
|
||||
selected_ids = {_id(mon["id"]) for mon in selected}
|
||||
equipment_ids = {_id(mon[field]) for mon in selected for field in ("equip1","equip2","equip3","equip4","equip5") if _number(mon[field]) != 0}
|
||||
projection = dict(snapshot)
|
||||
projection["monsters"] = selected
|
||||
projection["items"] = [item for key,item in items.items() if key in equipment_ids]
|
||||
projection["monsterAttributes"] = [row for row in snapshot["monsterAttributes"] if _id(row["monsterId"]) in selected_ids]
|
||||
projection["teams"] = teams
|
||||
native = {"scene":True,"context":context,"stage_id":stage_id,"difficulty":difficulty,
|
||||
"position":position,"original_data":{"battle":battle},
|
||||
"roster":{"snapshot":projection,"team_name":team_name},"allowed_missing_assets":sorted(set(gaps))}
|
||||
return {"reasons":reasons,"native_request":native,"position":position,
|
||||
"expected_battle_mon_ids":[] if battle.get("hideTeamMon") else [int(_id(value)) for value in teams[0]["monsters"] if _number(value) != 0],
|
||||
"battle_seconds":float(battle["time"]) if float(battle.get("time",-1)) >= 0 else float(tables["game_setting"]["normalBattleTime"]),
|
||||
"coverage":{"unit_type_count":len(unit_types),"skill_ids":sorted(skill_ids),"required_image_count":len(required),
|
||||
"original_image_fallbacks":sorted(set(gaps)),"full_original_swf":True}}
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Bounded child-process supervision. No runner command comes from a policy file."""
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
from dataclasses import dataclass
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import subprocess
|
||||
import time
|
||||
from typing import Sequence
|
||||
|
||||
|
||||
class _WindowsJob:
|
||||
"""Close a private job to kill the worker and any ADL/compiler descendants."""
|
||||
def __init__(self, process):
|
||||
class Basic(ctypes.Structure):
|
||||
_fields_ = [("process_time", ctypes.c_longlong), ("job_time", ctypes.c_longlong),
|
||||
("flags", wintypes.DWORD), ("minimum_working_set", ctypes.c_size_t),
|
||||
("maximum_working_set", ctypes.c_size_t), ("active_processes", wintypes.DWORD),
|
||||
("affinity", ctypes.c_size_t), ("priority", wintypes.DWORD),
|
||||
("scheduling", wintypes.DWORD)]
|
||||
|
||||
class IO(ctypes.Structure):
|
||||
_fields_ = [(name, ctypes.c_ulonglong) for name in (
|
||||
"read_ops", "write_ops", "other_ops", "read_bytes", "write_bytes", "other_bytes")]
|
||||
|
||||
class Extended(ctypes.Structure):
|
||||
_fields_ = [("basic", Basic), ("io", IO), ("process_memory", ctypes.c_size_t),
|
||||
("job_memory", ctypes.c_size_t), ("peak_process_memory", ctypes.c_size_t),
|
||||
("peak_job_memory", ctypes.c_size_t)]
|
||||
|
||||
self.kernel = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
self.kernel.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]
|
||||
self.kernel.CreateJobObjectW.restype = wintypes.HANDLE
|
||||
self.kernel.SetInformationJobObject.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD]
|
||||
self.kernel.SetInformationJobObject.restype = wintypes.BOOL
|
||||
self.kernel.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
|
||||
self.kernel.AssignProcessToJobObject.restype = wintypes.BOOL
|
||||
self.kernel.CloseHandle.argtypes = [wintypes.HANDLE]
|
||||
self.kernel.CloseHandle.restype = wintypes.BOOL
|
||||
self.handle = self.kernel.CreateJobObjectW(None, None)
|
||||
if not self.handle:
|
||||
raise ctypes.WinError(ctypes.get_last_error())
|
||||
limits = Extended()
|
||||
limits.basic.flags = 0x2000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
||||
if not self.kernel.SetInformationJobObject(self.handle, 9, ctypes.byref(limits), ctypes.sizeof(limits)):
|
||||
code = ctypes.get_last_error(); self.close(); raise ctypes.WinError(code)
|
||||
if not self.kernel.AssignProcessToJobObject(self.handle, wintypes.HANDLE(int(process._handle))):
|
||||
code = ctypes.get_last_error(); self.close(); raise ctypes.WinError(code)
|
||||
|
||||
def close(self):
|
||||
if self.handle:
|
||||
self.kernel.CloseHandle(self.handle)
|
||||
self.handle = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProcessResult:
|
||||
status: str
|
||||
returncode: int | None
|
||||
duration_seconds: float
|
||||
stdout: str
|
||||
stderr: str
|
||||
|
||||
|
||||
def run_isolated(argv: Sequence[str], *, cwd: Path, timeout: float, cancel_event=None,
|
||||
output_limit: int = 2 * 1024 * 1024) -> ProcessResult:
|
||||
"""Use only with bundled fixed commands; never forward imported argv/config.
|
||||
|
||||
Separate cwd/logs, shell=False, no inherited stdin, no visible helper window,
|
||||
a wall-clock deadline, and a kill-on-close process tree on Windows. This is
|
||||
process/lifetime isolation, not an OS network sandbox.
|
||||
"""
|
||||
if isinstance(timeout, bool) or not isinstance(timeout, (float, int)) or not math.isfinite(timeout) or timeout <= 0:
|
||||
raise ValueError("timeout must be a finite positive number")
|
||||
if cancel_event is not None and cancel_event.is_set():
|
||||
return ProcessResult("cancelled", None, 0.0, "", "")
|
||||
cwd.mkdir(parents=True, exist_ok=True)
|
||||
stdout_path, stderr_path = cwd / "worker.stdout.log", cwd / "worker.stderr.log"
|
||||
started = time.monotonic()
|
||||
process, job, status = None, None, "error"
|
||||
with stdout_path.open("wb") as stdout, stderr_path.open("wb") as stderr:
|
||||
try:
|
||||
process = subprocess.Popen(list(argv), cwd=cwd, stdin=subprocess.DEVNULL, stdout=stdout,
|
||||
stderr=stderr, shell=False, close_fds=True,
|
||||
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
||||
start_new_session=os.name != "nt")
|
||||
if os.name == "nt":
|
||||
job = _WindowsJob(process)
|
||||
while process.poll() is None:
|
||||
if cancel_event is not None and cancel_event.is_set():
|
||||
status = "cancelled"; break
|
||||
if time.monotonic() - started >= timeout:
|
||||
status = "timeout"; break
|
||||
if stdout_path.stat().st_size + stderr_path.stat().st_size > output_limit:
|
||||
status = "output_limit"; break
|
||||
time.sleep(.025)
|
||||
else:
|
||||
status = "completed" if process.returncode == 0 else "error"
|
||||
except OSError as error:
|
||||
stderr.write(str(error).encode("utf-8", errors="replace"))
|
||||
finally:
|
||||
if job is not None:
|
||||
job.close()
|
||||
elif process is not None and os.name != "nt":
|
||||
try:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
if process is not None:
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.wait(timeout=5)
|
||||
def bounded(path):
|
||||
with path.open("rb") as stream:
|
||||
return stream.read(output_limit).decode("utf-8", errors="replace")
|
||||
return ProcessResult(status, process.returncode if process is not None else None,
|
||||
time.monotonic() - started, bounded(stdout_path), bounded(stderr_path))
|
||||
@@ -0,0 +1,168 @@
|
||||
"""Recover original offline libraries and tables from the pinned local APK."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import struct
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import uuid
|
||||
import zipfile
|
||||
import zlib
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from ranch_assistant.amf import Reader
|
||||
from tools.battle_runtime.swf_library import digest, library_only
|
||||
|
||||
APK_SHA256 = "01678ee3a8465d818d32cbbd94baa0d8253b04b4c57b70ebc5544ed341f1015d"
|
||||
MAIN_SHA256 = "c6838331a198a22ffa486cbf61cc74c97619e011bc3364c8bb8dc99e269036cf"
|
||||
TABLES = ("setting", "game_setting", "monster_info", "monster_skill", "monster_setting",
|
||||
"monster_level", "monster_fix", "team_info", "stage_info", "task_info",
|
||||
"item_info", "potential_info", "entangle_info", "skin_info", "upstar_info")
|
||||
|
||||
|
||||
def write_atomic(path: Path, data: bytes):
|
||||
# Prepared resources are immutable for the pinned APK. Reusing identical
|
||||
# bytes also avoids Windows rename failures while another AIR job reads a
|
||||
# shared resource (each job still has its own application/storage/cwd).
|
||||
if path.is_file() and path.read_bytes() == data:
|
||||
return
|
||||
temporary = path.with_name(path.name + "." + uuid.uuid4().hex + ".tmp")
|
||||
try:
|
||||
temporary.write_bytes(data)
|
||||
try:
|
||||
temporary.replace(path)
|
||||
except PermissionError:
|
||||
# Another preparer may have published the exact same bytes after
|
||||
# our first check. Never accept a different or partially read file.
|
||||
if not path.is_file() or path.read_bytes() != data:
|
||||
raise
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def write_json(path: Path, data):
|
||||
write_atomic(path, json.dumps(data, ensure_ascii=False, allow_nan=False, indent=2).encode("utf-8"))
|
||||
|
||||
|
||||
def asset_index(apk: Path, archive: zipfile.ZipFile) -> dict:
|
||||
"""Bind original packed-resource keys to their verified ZIP byte ranges."""
|
||||
entries = {}
|
||||
archive_size = apk.stat().st_size
|
||||
with apk.open("rb") as source:
|
||||
for item in archive.infolist():
|
||||
if not item.filename.startswith("assets/codes/") or item.is_dir():
|
||||
continue
|
||||
key = item.filename.removeprefix("assets/codes/")
|
||||
if len(key) != 32 or any(c not in "0123456789abcdef" for c in key) or item.flag_bits & 1 or item.compress_type not in (0,8):
|
||||
raise ValueError("Unsupported original asset ZIP member")
|
||||
if key in entries:
|
||||
raise ValueError("Duplicate original asset ZIP member")
|
||||
source.seek(item.header_offset)
|
||||
header = source.read(30)
|
||||
if len(header) != 30 or header[:4] != b"PK\x03\x04":
|
||||
raise ValueError("Original ZIP local header mismatch")
|
||||
flags, method = struct.unpack_from("<HH",header,6)
|
||||
if flags != item.flag_bits or method != item.compress_type:
|
||||
raise ValueError("Original ZIP local metadata mismatch")
|
||||
filename_size, extra_size = struct.unpack_from("<HH", header, 26)
|
||||
encoded_name = source.read(filename_size)
|
||||
if encoded_name.decode("utf-8" if flags & 0x800 else "cp437") != item.filename:
|
||||
raise ValueError("Original ZIP local filename mismatch")
|
||||
offset = item.header_offset + 30 + filename_size + extra_size
|
||||
if offset < 0 or offset + item.compress_size > archive_size:
|
||||
raise ValueError("Original asset ZIP member escapes archive")
|
||||
entries[key] = {"offset":offset,"compressed_size":item.compress_size,
|
||||
"size":item.file_size,"method":item.compress_type,"crc32":item.CRC}
|
||||
return entries
|
||||
|
||||
|
||||
def prepare(apk: Path | None = None, *, assets: bool = False) -> dict:
|
||||
if apk is None:
|
||||
candidates = list(ROOT.glob("*_1.9.68.apk"))
|
||||
if len(candidates) != 1:
|
||||
raise ValueError("Expected exactly one original *_1.9.68.apk")
|
||||
apk = candidates[0]
|
||||
with apk.open("rb") as stream:
|
||||
sha = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
if sha != APK_SHA256:
|
||||
raise ValueError("Original APK SHA-256 mismatch")
|
||||
root = ROOT / "local_state/battle_runtime/original"
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
manifest = {"apk_sha256": sha, "main_swf_sha256": MAIN_SHA256, "libraries": {}, "tables": {}}
|
||||
with zipfile.ZipFile(apk) as archive:
|
||||
entries = asset_index(apk,archive)
|
||||
write_json(root / "asset_index.json", {"apk_path":str(apk.resolve()),"apk_sha256":sha,"entries":entries})
|
||||
manifest["asset_index_sha256"] = digest((root / "asset_index.json").read_bytes())
|
||||
for member, filename in (("assets/MYRDyd.swf", "framework.library.swf"),
|
||||
("assets/MYRMain.app", "main.library.swf")):
|
||||
original = archive.read(member)
|
||||
if member.endswith("MYRMain.app") and digest(original) != MAIN_SHA256:
|
||||
raise ValueError("Original main SWF SHA-256 mismatch")
|
||||
library, identity = library_only(original)
|
||||
write_atomic(root / filename, library)
|
||||
manifest["libraries"][filename] = identity
|
||||
tables = {}
|
||||
(root / "tables").mkdir(exist_ok=True)
|
||||
for name in TABLES:
|
||||
member = "assets/codes/" + hashlib.md5(f"data/table/{name}.json".encode()).hexdigest()
|
||||
if member not in archive.namelist():
|
||||
manifest["tables"][name] = {"missing": True}
|
||||
continue
|
||||
compressed = archive.read(member)
|
||||
write_atomic(root / "tables" / (name + ".amf.zlib"), compressed)
|
||||
decoded = zlib.decompress(compressed)
|
||||
reader = Reader(decoded)
|
||||
value = reader.read()
|
||||
if reader.pos != len(decoded):
|
||||
raise ValueError(f"Trailing original table bytes: {name}")
|
||||
tables[name] = value
|
||||
manifest["tables"][name] = {"member": member, "sha256": digest(compressed)}
|
||||
write_json(root / "tables.json", tables)
|
||||
write_json(root / "table_index.json", list(tables))
|
||||
manifest["tables_json_sha256"] = digest((root / "tables.json").read_bytes())
|
||||
# Preserve actual libraries/assets locally. No APK is rebuilt or installed.
|
||||
for member in ("assets/baseui.swf", "assets/ui/mainui.swf", "assets/ui/mainui2.swf",
|
||||
"assets/ui/mainui3.swf", "assets/ui/movieclip.swf"):
|
||||
original = archive.read(member)
|
||||
library, identity = library_only(original)
|
||||
path = root / (Path(member).stem + ".library.swf")
|
||||
write_atomic(path, library)
|
||||
manifest["libraries"][path.name] = identity
|
||||
if assets:
|
||||
asset_count = asset_bytes = 0
|
||||
destination = root / "codes"
|
||||
destination.mkdir(exist_ok=True)
|
||||
for item in archive.infolist():
|
||||
if item.filename.startswith("assets/codes/") and not item.is_dir():
|
||||
basename = item.filename.removeprefix("assets/codes/")
|
||||
if len(basename) != 32 or any(c not in "0123456789abcdef" for c in basename):
|
||||
raise ValueError("Unexpected original asset member")
|
||||
path = destination / basename
|
||||
if not path.exists() or path.stat().st_size != item.file_size:
|
||||
write_atomic(path, archive.read(item))
|
||||
asset_count += 1
|
||||
asset_bytes += item.file_size
|
||||
write_json(root / "assets_prepared.json", {"count":asset_count,"bytes":asset_bytes,
|
||||
"source_apk_sha256":sha})
|
||||
manifest["asset_count"] = asset_count
|
||||
write_json(root / "identity.json", manifest)
|
||||
return manifest
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--apk", type=Path)
|
||||
parser.add_argument("--assets", action="store_true")
|
||||
args = parser.parse_args()
|
||||
manifest = prepare(args.apk, assets=args.assets)
|
||||
print(json.dumps({"main_swf_sha256": manifest["main_swf_sha256"],
|
||||
"libraries": {name: {k: v for k, v in row.items() if k in (
|
||||
"removed_document_classes", "abc_count", "lazy_flags_changed", "abc_bytes_preserved")}
|
||||
for name, row in manifest["libraries"].items()}}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<application xmlns="http://ns.adobe.com/air/application/51.1">
|
||||
<id>local.ranchassistant.originalprobe</id>
|
||||
<versionNumber>0.0.1</versionNumber>
|
||||
<filename>OriginalProbe</filename>
|
||||
<initialWindow>
|
||||
<content>OriginalProbe.swf</content>
|
||||
<visible>false</visible>
|
||||
<width>640</width><height>960</height>
|
||||
<systemChrome>none</systemChrome>
|
||||
<renderMode>cpu</renderMode>
|
||||
</initialWindow>
|
||||
<supportedProfiles>extendedDesktop</supportedProfiles>
|
||||
</application>
|
||||
@@ -0,0 +1,160 @@
|
||||
"""Compile and execute the fixed original-library probe (no network imports)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SOURCE = Path(__file__).resolve().parent
|
||||
LOCAL = ROOT / "local_state/battle_runtime"
|
||||
|
||||
|
||||
def compile_probe(build_directory: Path | None = None) -> dict:
|
||||
sdk = LOCAL / "air_sdk"
|
||||
build = build_directory if build_directory is not None else LOCAL / "build"
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
captured_source = build / "source"
|
||||
captured_source.mkdir(exist_ok=True)
|
||||
source_bytes = (SOURCE / "OriginalProbe.as").read_bytes()
|
||||
(captured_source / "OriginalProbe.as").write_bytes(source_bytes)
|
||||
bridge = SOURCE / "SnapshotBridge.as"
|
||||
bridge_bytes = bridge.read_bytes() if bridge.is_file() else None
|
||||
if bridge_bytes is not None:
|
||||
(captured_source / "SnapshotBridge.as").write_bytes(bridge_bytes)
|
||||
config = build / "compiler-config.xml"
|
||||
config.write_text("<flex-config/>", encoding="utf-8")
|
||||
command = [shutil.which("java") or "java", "-Duser.language=en", "-Duser.country=US", "-jar", str(sdk / "lib/mxmlc-cli.jar"),
|
||||
"-load-config=" + str(config), "-compiler.external-library-path=" + str(sdk / "frameworks/libs/air/airglobal.swc"),
|
||||
"-compiler.library-path=" + str(sdk / "frameworks/libs/core.swc"),
|
||||
"-swf-version=50", "-debug=true", "-default-frame-rate=50", "-default-size=640,960",
|
||||
"-output=" + str(build / "OriginalProbe.swf"), str(captured_source / "OriginalProbe.as")]
|
||||
if bridge_bytes is not None:
|
||||
command.insert(-1, "-source-path=" + str(captured_source))
|
||||
command.insert(-1, "-includes=SnapshotBridge")
|
||||
result = subprocess.run(command, cwd=ROOT, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=60,
|
||||
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||
evidence = {"command": command, "exit_code": result.returncode, "stdout": result.stdout, "stderr": result.stderr,
|
||||
"source_sha256": hashlib.sha256(source_bytes).hexdigest()}
|
||||
(build / "compile.json").write_text(json.dumps(evidence, indent=2), encoding="utf-8")
|
||||
if result.returncode != 0:
|
||||
raise RuntimeError("AIR harness compile failed: " + result.stdout + result.stderr)
|
||||
shutil.copyfile(SOURCE / "probe-app.xml", build / "probe-app.xml")
|
||||
descriptor = build / "probe-app.xml"
|
||||
descriptor.write_text(descriptor.read_text(encoding="utf-8").replace(
|
||||
"local.ranchassistant.originalprobe", "local.ranchassistant.originalprobe.j" + uuid.uuid4().hex), encoding="utf-8")
|
||||
evidence["swf_sha256"] = hashlib.sha256((build / "OriginalProbe.swf").read_bytes()).hexdigest()
|
||||
if bridge_bytes is not None:
|
||||
evidence["snapshot_bridge_sha256"] = hashlib.sha256(bridge_bytes).hexdigest()
|
||||
return evidence
|
||||
|
||||
|
||||
def execute_probe(*, timeout: float = 690.0, cancel_event=None, scene: bool = False, source_request: dict | None = None) -> dict:
|
||||
# Re-derive all original libraries rather than accepting imported manifest claims.
|
||||
from tools.battle_runtime.prepare import prepare
|
||||
from tools.battle_runtime.trusted import SDK_FILES, LIBRARY_FILES, verify_files
|
||||
dependency_errors = verify_files(LOCAL / "air_sdk", SDK_FILES)
|
||||
if dependency_errors:
|
||||
raise RuntimeError("Untrusted/missing AIR dependencies: " + json.dumps(dependency_errors))
|
||||
identity = prepare()
|
||||
validation = None
|
||||
if source_request is not None:
|
||||
from tools.battle_runtime.inputs import validate
|
||||
validation = validate(source_request)
|
||||
if validation["reasons"]:
|
||||
raise ValueError("Original request refused: " + json.dumps(validation["reasons"]))
|
||||
attempt = LOCAL / "experiments" / uuid.uuid4().hex
|
||||
attempt.mkdir(parents=True)
|
||||
compiler = compile_probe(attempt / "build")
|
||||
library_errors = verify_files(LOCAL / "original", LIBRARY_FILES)
|
||||
if library_errors:
|
||||
raise RuntimeError("Original library identity mismatch: " + json.dumps(library_errors))
|
||||
request = attempt / "request.json"
|
||||
nonce = uuid.uuid4().hex
|
||||
native_request = validation["native_request"] if validation is not None else {"stage_id":"0101","difficulty":1,"scene":scene}
|
||||
native_request = dict(native_request,nonce=nonce,watchdog_ms=int(timeout*1000))
|
||||
request.write_text(json.dumps(native_request,ensure_ascii=False,allow_nan=False), encoding="utf-8")
|
||||
sdk = LOCAL / "air_sdk"
|
||||
command = [str(sdk / "bin/adl64.exe"), "-runtime", str(sdk / "runtimes/air/win64"), "-nodebug",
|
||||
"-profile", "extendedDesktop", str(attempt / "build/probe-app.xml"),
|
||||
"--", str(LOCAL / "original"), str(request), str(attempt / "result.json")]
|
||||
started = time.monotonic()
|
||||
with (attempt / "stdout.log").open("wb") as stdout, (attempt / "stderr.log").open("wb") as stderr:
|
||||
process = subprocess.Popen(command, cwd=attempt, stdout=stdout, stderr=stderr,
|
||||
creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
|
||||
interrupted = None
|
||||
try:
|
||||
while process.poll() is None:
|
||||
if cancel_event is not None and cancel_event.is_set():
|
||||
interrupted = "cancelled"; break
|
||||
if time.monotonic() - started >= timeout:
|
||||
interrupted = "timeout"; break
|
||||
time.sleep(.05)
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.wait(timeout=5)
|
||||
result_file = attempt / "result.json"
|
||||
result = json.loads(result_file.read_text(encoding="utf-8")) if result_file.exists() and not interrupted else {
|
||||
"status": interrupted or "process_failed", "battle_executed": None, "settlement_eligible": False}
|
||||
if result_file.exists() and not interrupted and result.get("nonce") != nonce:
|
||||
raise ValueError("Native AIR result nonce mismatch")
|
||||
audit = audit_resources(result)
|
||||
evidence = {"command": command, "compiler": compiler, "process_exit_code": process.returncode,
|
||||
"duration_seconds": time.monotonic() - started, "result": result,
|
||||
"resource_identity": {"apk_sha256": identity["apk_sha256"],
|
||||
"main_swf_sha256": identity["main_swf_sha256"]},
|
||||
"resource_audit": audit,
|
||||
"input_sha256":hashlib.sha256(json.dumps(source_request,ensure_ascii=True,allow_nan=False,sort_keys=True,separators=(",", ":")).encode("ascii")).hexdigest() if source_request is not None else None,
|
||||
"directory": str(attempt)}
|
||||
(attempt / "evidence.json").write_text(json.dumps(evidence, indent=2), encoding="utf-8")
|
||||
return evidence
|
||||
|
||||
|
||||
def audit_resources(result: dict) -> dict:
|
||||
"""Compare every read image with the pinned APK; retain genuine absences."""
|
||||
import zipfile
|
||||
reads = [event["data"] for event in result.get("events", []) if event.get("kind") == "original_asset_read"]
|
||||
members = {read["member"] for read in reads}
|
||||
candidates = list(ROOT.glob("*_1.9.68.apk"))
|
||||
if len(candidates) != 1:
|
||||
raise ValueError("Ambiguous original APK during resource audit")
|
||||
missing, mismatched = [], []
|
||||
with zipfile.ZipFile(candidates[0]) as archive:
|
||||
names = set(archive.namelist())
|
||||
for member in sorted(members):
|
||||
if not member.startswith("codes/") or len(member) != 38 or any(c not in "0123456789abcdef" for c in member[6:]):
|
||||
raise ValueError("Invalid resource identity in original trace")
|
||||
if "assets/" + member not in names:
|
||||
missing.append(member)
|
||||
if any(read.get("crc32") is not None for read in reads if read["member"] == member):
|
||||
mismatched.append(member)
|
||||
else:
|
||||
info = archive.getinfo("assets/" + member)
|
||||
if any(read.get("crc32") != info.CRC or read.get("bytes") != info.file_size for read in reads if read["member"] == member):
|
||||
mismatched.append(member)
|
||||
return {"used_asset_count":len(members), "original_missing_members":missing,
|
||||
"mismatched_members":mismatched, "all_present_assets_match_apk":not mismatched}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--compile-only", action="store_true")
|
||||
parser.add_argument("--scene", action="store_true")
|
||||
args = parser.parse_args()
|
||||
if args.compile_only:
|
||||
print(json.dumps(compile_probe(), indent=2))
|
||||
else:
|
||||
print(json.dumps(execute_probe(scene=args.scene), indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.path.insert(0, str(ROOT))
|
||||
main()
|
||||
@@ -0,0 +1,376 @@
|
||||
"""Offline, synthetic-only AIR checks for SnapshotBridge; never starts the game.
|
||||
|
||||
Generated AS3, SWFs, requests and results stay in the ignored local runtime
|
||||
directory. The harness only loads the already prepared library SWFs and tables.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SOURCE = Path(__file__).resolve().parent
|
||||
LOCAL = ROOT / "local_state/battle_runtime"
|
||||
|
||||
HARNESS = r'''
|
||||
package {
|
||||
import flash.desktop.NativeApplication;
|
||||
import flash.display.Loader;
|
||||
import flash.display.Sprite;
|
||||
import flash.events.Event;
|
||||
import flash.events.IOErrorEvent;
|
||||
import flash.events.InvokeEvent;
|
||||
import flash.events.UncaughtErrorEvent;
|
||||
import flash.filesystem.File;
|
||||
import flash.filesystem.FileMode;
|
||||
import flash.filesystem.FileStream;
|
||||
import flash.system.ApplicationDomain;
|
||||
import flash.system.LoaderContext;
|
||||
import flash.utils.ByteArray;
|
||||
import flash.utils.describeType;
|
||||
public class SnapshotBridgeCheck extends Sprite {
|
||||
private var domain:ApplicationDomain = new ApplicationDomain(ApplicationDomain.currentDomain);
|
||||
private var names:Array = ["framework", "main", "baseui", "mainui", "mainui2", "mainui3", "movieclip"];
|
||||
private var loaders:Array = [];
|
||||
private var index:int = 0;
|
||||
private var root:File;
|
||||
private var output:File;
|
||||
private var request:Object;
|
||||
private var finished:Boolean = false;
|
||||
private var frameworkReady:Boolean = false;
|
||||
public function SnapshotBridgeCheck() {
|
||||
loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR,
|
||||
function(e:UncaughtErrorEvent):void {
|
||||
e.preventDefault(); finish({ok:false, error:String(e.error)});
|
||||
});
|
||||
NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, invoke);
|
||||
}
|
||||
private function invoke(e:InvokeEvent):void {
|
||||
try {
|
||||
root = new File(e.arguments[0]); output = new File(e.arguments[2]);
|
||||
request = JSON.parse(readText(new File(e.arguments[1])));
|
||||
loadNext();
|
||||
} catch (error:Error) { finish({ok:false,error:error.getStackTrace() || error.toString()}); }
|
||||
}
|
||||
private function readText(file:File):String {
|
||||
var s:FileStream = new FileStream(); s.open(file,FileMode.READ);
|
||||
var text:String = s.readUTFBytes(s.bytesAvailable); s.close(); return text;
|
||||
}
|
||||
private function readBytes(file:File):ByteArray {
|
||||
var s:FileStream = new FileStream(); s.open(file,FileMode.READ);
|
||||
var bytes:ByteArray = new ByteArray(); s.readBytes(bytes); s.close(); return bytes;
|
||||
}
|
||||
private function cls(name:String):Class { return domain.getDefinition(name) as Class; }
|
||||
private function loadNext():void {
|
||||
if (index == names.length) { check(); return; }
|
||||
var loader:Loader = new Loader(); loaders.push(loader);
|
||||
loader.contentLoaderInfo.addEventListener(Event.COMPLETE,function(e:Event):void { loadNext(); });
|
||||
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,
|
||||
function(e:IOErrorEvent):void { finish({ok:false,error:e.text}); });
|
||||
var context:LoaderContext = new LoaderContext(false,domain); context.allowCodeImport = true;
|
||||
loader.loadBytes(readBytes(root.resolvePath(names[index++] + ".library.swf")),context);
|
||||
}
|
||||
private function check():void {
|
||||
try {
|
||||
var table:Class = cls("net.pixvi.myr.center.Table");
|
||||
var names:Array = JSON.parse(readText(root.resolvePath("table_index.json"))) as Array;
|
||||
var rm:Class = cls("net.pixvi.common.manager.resource.RM"); rm["getInstance"]();
|
||||
var stringLoader:Class = cls("net.pixvi.pfw.net.PiStringLoader");
|
||||
stringLoader["globalCryptoMode"] = true;
|
||||
stringLoader["globalJsonCryptoModeFunction"] = cls("net.pixvi.myrcryptor.MYRCryptor")["jsonDecodeHandler"];
|
||||
var resourceClass:Class = cls("net.pixvi.common.net.resource.ResourceVo");
|
||||
for each (var name:String in names) {
|
||||
var packed:ByteArray = readBytes(root.resolvePath("tables/" + name + ".amf.zlib"));
|
||||
var resource:Object = new resourceClass("data/table/" + name + ".json");
|
||||
resource["crypto"] = true; resource["data"] = packed; rm["TXT"]["push"](resource);
|
||||
var bytes:ByteArray = readBytes(root.resolvePath("tables/" + name + ".amf.zlib"));
|
||||
bytes.uncompress(); bytes.objectEncoding = 3;
|
||||
var value:Object = bytes.readObject();
|
||||
table[name] = name != "team_info" && value.hasOwnProperty("datas") ? value.datas : value;
|
||||
// ORIGINAL Table.startUp flattens the skin resource wrapper.
|
||||
if (name == "skin_info") table[name] = value.skins;
|
||||
}
|
||||
table["monster_group"] = table["monster_setting"].group;
|
||||
table["monster_element"] = table["monster_setting"].element;
|
||||
__ACTION__
|
||||
} catch (error:Error) { finish({ok:false,error:error.getStackTrace() || error.toString()}); }
|
||||
}
|
||||
private function initializeFramework():void {
|
||||
if (!frameworkReady) {
|
||||
addChild(cls("net.pixvi.common.center.StartUpCenter")["startUp"](stage,true,false,false,false));
|
||||
var fixClass:Class = cls("net.pixvi.common.utils.PiFixVo");
|
||||
var fs1:Object = new fixClass(); fs1.id = "fs1"; fs1.maxHWScale = 1.775;
|
||||
var fs2:Object = new fixClass(); fs2.id = "fs2"; fs2.maxHWScale = 1.9125;
|
||||
cls("net.pixvi.common.utils.StageLocator")["autoFull"](720,1136,[fs1,fs2]);
|
||||
cls("net.pixvi.myr.battle.BattleGround")["firstStartUp"](); frameworkReady = true;
|
||||
}
|
||||
}
|
||||
private function integrity(roster:Object):Object {
|
||||
// Exercise BattlePanel's private cheatCheck through its ORIGINAL
|
||||
// public completion handler. Native units come from TeamCenter;
|
||||
// skip movie loading and install only local result callbacks.
|
||||
initializeFramework();
|
||||
var panelClass:Class = cls("net.pixvi.myr.panel.battle.BattlePanel");
|
||||
var panel:Object = panelClass["getIns"]();
|
||||
var groundClass:Class = cls("net.pixvi.myr.battle.BattleGround");
|
||||
var ground:Object = new groundClass(); panel.ground = ground;
|
||||
var battleClass:Class = cls("net.pixvi.myr.element.battle.BattleVo");
|
||||
var battle:Object = new battleClass(); ground.vo = battle; panel.battle = battle;
|
||||
var table:Class = cls("net.pixvi.myr.center.Table");
|
||||
var authored:Object = table["stage_info"];
|
||||
if (authored is Array) for each (var stageRow:Object in authored) {
|
||||
if (stageRow.id == "0101") { authored = {"0101":stageRow}; break; }
|
||||
}
|
||||
battle["buildByObject"](authored["0101"].level["1"].battle);
|
||||
var nativeTeam:Object = cls("net.pixvi.myr.center.TeamCenter")["getIns"]()["getBattleTeamVo"](roster.selectedTeam.teamName);
|
||||
battle.teamDic[1] = nativeTeam; battle.teams = [nativeTeam];
|
||||
var viewClass:Class = cls("net.pixvi.myr.battle.view.BattleMon");
|
||||
var skillClass:Class = cls("net.pixvi.myr.view.skill.SkillType");
|
||||
for (var i:int = 0; i < nativeTeam.mons.length; i++) {
|
||||
var nativeVo:Object = nativeTeam.mons[i];
|
||||
var view:Object = new viewClass();
|
||||
view.vo = nativeVo.monsterVo; view.monVo = nativeVo; view.teamVo = nativeTeam;
|
||||
// The pure skill portion of BattleMon.init, without buildView
|
||||
// or image/movie loading. Skill parameters stay in original code.
|
||||
view.skill_1 = skillClass["getSkill"](view.vo.skill_1,view.vo.skill_1_lv);
|
||||
view.skill_2 = skillClass["getSkill"](view.vo.skill_2,view.vo.skill_2_lv);
|
||||
if (view.skill_1 != null) view.skill_1["init"](view);
|
||||
if (view.skill_2 != null) view.skill_2["init"](view);
|
||||
nativeTeam.mons[i] = view;
|
||||
}
|
||||
var cooldownClass:Class = cls("net.pixvi.common.utils.Cooldowner");
|
||||
ground.battleTime = new cooldownClass(1000); ground.winnerTeam = 1;
|
||||
var dataClass:Class = cls("net.pixvi.myr.element.battle.BattleData");
|
||||
panelClass["battleData"] = new dataClass();
|
||||
panel.battlePosition = null;
|
||||
var result:Object = null;
|
||||
var completed:Function = function(data:Object):void {
|
||||
result = {cheatNum:data.cheatNum, text:data.cheatRecords.text,
|
||||
records:data.cheatRecords.mons, master:data.cheatRecords.master};
|
||||
};
|
||||
panel.onWinCallBack = completed; panel.onLoseCallBack = completed;
|
||||
panel["battleCompleteHandler"]();
|
||||
return result;
|
||||
}
|
||||
private function finish(result:Object):void {
|
||||
if (finished) return; finished = true;
|
||||
var s:FileStream = new FileStream(); s.open(output,FileMode.WRITE);
|
||||
s.writeUTFBytes(JSON.stringify(result)); s.close();
|
||||
NativeApplication.nativeApplication.exit(result.ok ? 0 : 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
REFLECT = r'''
|
||||
var masterClass:Class = cls("net.pixvi.myr.element.master.MasterVo");
|
||||
var master:Object = new masterClass();
|
||||
cls("net.pixvi.myr.center.Game")["getIns"]()["master"] = master; master["init"]();
|
||||
finish({ok:true, master:describeType(master).toXMLString(),
|
||||
history:describeType(master.history).toXMLString(),
|
||||
activity:describeType(master.activityHistory).toXMLString()});
|
||||
'''
|
||||
|
||||
CHECK = r'''
|
||||
var outcomes:Array = [];
|
||||
var game:Object = cls("net.pixvi.myr.center.Game")["getIns"]();
|
||||
initializeFramework();
|
||||
var panel:Object = cls("net.pixvi.myr.panel.battle.BattlePanel")["getIns"]();
|
||||
var positionClass:Class = cls("net.pixvi.myr.element.battle.BattlePosition");
|
||||
for each (var test:Object in request.cases) {
|
||||
var before:String = JSON.stringify(test.snapshot);
|
||||
var previous:Object = game.master;
|
||||
var position:Object = new positionClass(); panel.battlePosition = position;
|
||||
var outcome:Object = {name:test.name};
|
||||
try {
|
||||
var roster:Object = SnapshotBridge.build(domain,test.snapshot,test.teamName);
|
||||
var nativeTeam:Object = cls("net.pixvi.myr.center.TeamCenter")["getIns"]()["getBattleTeamVo"](test.teamName);
|
||||
var units:Array = [];
|
||||
var loadedIds:Array = [];
|
||||
for each (var mon:Object in roster.master.monsters) {
|
||||
loadedIds.push(mon.id);
|
||||
if (roster.validation.selectedIds.indexOf(mon.id) < 0) continue;
|
||||
var native:Object = cls("net.pixvi.myr.center.MonsterCenter")["getIns"]()["getBattleMonVoByMid"](mon.id);
|
||||
units.push({id:mon.id,type:mon.type,level:mon.level,tplevel:mon.tplevel,
|
||||
feel:mon.feel,skin:mon.skin,skinVo:mon.skinVo == null ? null : mon.skinVo.typeId,
|
||||
skinEntry:mon.skinVo == null ? null : {monType:mon.skinVo.table().monType,
|
||||
ability:mon.skinVo.ability,
|
||||
sameOriginalEntry:mon.skinVo.table() === table["skin_info"][String(mon.skin)]},
|
||||
entangle:mon.entangle,entangleLevel:mon.entangleLevel,entangleSkill:mon.entangleSkill,
|
||||
potential:mon.potential_atk.val,skill_1:mon.skill_1,skill_2:mon.skill_2,
|
||||
atk:mon.atk,def:mon.def,hp:mon.hp,dex:mon.dex,equip1:mon.equip1,equip2:mon.equip2,
|
||||
additions:mon.abilityAdd.getRecord(),special:{atkPoi:native.atkPoi,
|
||||
atkPoiType:native.atkPoiType,crit:native.crit,thorns:native.thorns},
|
||||
battle:{atk:native.atk,def:native.def,hp:native.hpMax,dex:native.dex}});
|
||||
}
|
||||
var inventory:Array = [];
|
||||
for each (var item:Object in roster.master.bag.items) {
|
||||
var itemRecord:Object = {id:item.id,type:item.type,num:item.num};
|
||||
if ("isUsed" in item) {
|
||||
itemRecord.isUsed = item.isUsed; itemRecord.atk = item.atk.val;
|
||||
itemRecord.hp = item.hp.val; itemRecord.atkPoiType = item.atkPoiType;
|
||||
}
|
||||
inventory.push(itemRecord);
|
||||
}
|
||||
var members:Array = [];
|
||||
for each (native in nativeTeam.mons) members.push({mid:native.mid,teamPos:native.teamPos});
|
||||
outcome.ok = true; outcome.validation = roster.validation;
|
||||
outcome.contextUnchanged = panel.battlePosition === position;
|
||||
outcome.installed = game.master === roster.master;
|
||||
outcome.selectedSlots = roster.selectedTeam.monsters;
|
||||
outcome.nativeAP = nativeTeam.ap; outcome.nativeMembers = members;
|
||||
outcome.apFromRawLevel = cls("net.pixvi.myr.GameMath")["apByLevel"](test.snapshot.master.level);
|
||||
outcome.units = units; outcome.inventory = inventory;
|
||||
outcome.loadedMonsterIds = loadedIds;
|
||||
outcome.history = {monLib:roster.master.history.monLib,
|
||||
guide_record:roster.master.history.guide_record,unlockStage:roster.master.history.unlockStage,
|
||||
passStage:roster.master.history.passStage,unlockCity:roster.master.history.unlockCity};
|
||||
if (test.integrity === true) outcome.integrity = integrity(roster);
|
||||
} catch (error:Error) {
|
||||
outcome.ok = false; outcome.error = error.getStackTrace() || error.toString();
|
||||
outcome.previousMasterRestored = game.master === previous;
|
||||
}
|
||||
outcome.inputUnchanged = before == JSON.stringify(test.snapshot);
|
||||
outcomes.push(outcome);
|
||||
}
|
||||
finish({ok:true,cases:outcomes});
|
||||
'''
|
||||
|
||||
|
||||
def synthetic_snapshot(*, rich: bool = False) -> dict:
|
||||
"""Explicit fake-account INPUTS; all derived stats remain in original AS3."""
|
||||
tables = json.loads((LOCAL / "original/tables.json").read_text(encoding="utf-8"))
|
||||
monster_table = tables["monster_info"].get("datas", tables["monster_info"])
|
||||
fields = ("atk", "def", "hp", "dex", "crit", "atkSpd", "atkVim", "selfCure", "deadBoom",
|
||||
"atkStun", "defStun", "atkPoi", "atkPoiDmg", "apCostSave", "skillCooldown",
|
||||
"sunFire", "moonHeal", "thorns")
|
||||
monsters, attributes = [], []
|
||||
for i in range(3):
|
||||
type_id = 1003010 if rich and i == 1 else 1001010
|
||||
row = monster_table[str(type_id)]
|
||||
monsters.append(dict(id=100000001 + i, typeId=type_id, level=1 + i, exp=0,
|
||||
tpLevel=0, tpExp=0, feel=0, upStar=0, process=3, mode=2,
|
||||
gAtk=row["atk_grow_min"], gDef=row["def_grow_min"],
|
||||
gHp=row["hp_grow_min"], gDex=row["dex_grow_min"],
|
||||
lock=0, sysLock=0, nicName="", timeGet=0, timeStart=0, roomId=0,
|
||||
inExploreTeam=0, equip1=0, equip2=0, equip3=0, equip4=0, equip5=0,
|
||||
pAtk=0, pDef=0, pHp=0, pDex=0, potentialLevel=1, giftTime=0,
|
||||
skin=0, entangle=0, entangleLevel=0, entangleSkills=None))
|
||||
attributes.append(dict(monsterId=100000001 + i, **dict.fromkeys(fields, 0)))
|
||||
items = []
|
||||
if rich:
|
||||
monsters[0].update(equip2=100000101, pAtk=1, pDef=2, pHp=3, pDex=1)
|
||||
monsters[1].update(skin=1003011, entangle=1, entangleLevel=1,
|
||||
entangleSkills='{"1":1001}')
|
||||
# Aggregate supplied attributes are authoritative, exactly as the server
|
||||
# snapshot represents them. Do not recalculate equipment/skin bonuses.
|
||||
attributes[0].update(hp=50, dex=3, atkPoi=2, atkPoiDmg=3)
|
||||
attributes[1].update({"atk": 13, "def": 15, "atkVim": 2})
|
||||
params = dict.fromkeys(fields, 0)
|
||||
params.update(hp=50, dex=3, atkPoi=2, atkPoiDmg=3, atkPoiType=1)
|
||||
items = [dict(id=100000101, typeId=50001, num=1, isUsed=1, itemClass=3,
|
||||
equipParams=json.dumps(params))]
|
||||
return dict(
|
||||
master=dict(id=1, level=30, roleName="Offline fixture", farmName="", avatar=0,
|
||||
createTime=0, exp=0, money=0, ti=0, ke=0, timeTi=0,
|
||||
globalAtk=2 if rich else 0, globalDef=1 if rich else 0,
|
||||
globalHp=5 if rich else 0, globalDex=1 if rich else 0),
|
||||
monsters=monsters, monsterAttributes=attributes, items=items,
|
||||
teams=[dict(teamName="teamA", teamType="battleTeam",
|
||||
monsters=[100000003, 0, 100000001, 100000002, 0, 0, 0])],
|
||||
history=dict(numAddMoney=0, numFeedMonsters={}, numKillMonsters={}, numChicken=0,
|
||||
countBattle=0, historyGacha={}, passAchi=[], passTask={}, unlockTask={},
|
||||
loopTask={}, guide_main="", guide_record=["firstOut"], unlockCity=[1],
|
||||
unlockStage={"0101": [1]}, passStage={"0101": [1]},
|
||||
monLib=[1001010, 1003010], equipLib=["50001"], payTypeCount={},
|
||||
everyDayBuyProductNum={}),
|
||||
data2=dict(unlockSkins=[1003011], timeEggItems=[]),
|
||||
activityHistory=dict(dailyGift=dict(dailyGiftCheckTime=0, dailyGiftLevel=1,
|
||||
dailyGiftCount=0, signCount=0),
|
||||
vipInfo=dict(vipTime=0, getTime=0)))
|
||||
|
||||
|
||||
def dependencies_available() -> bool:
|
||||
return (os.name == "nt" and shutil.which("java") is not None
|
||||
and (LOCAL / "air_sdk/lib/mxmlc-cli.jar").is_file()
|
||||
and (LOCAL / "original/main.library.swf").is_file())
|
||||
|
||||
|
||||
def run_harness(request: dict, *, action: str = REFLECT) -> dict:
|
||||
# Match the existing probe's reviewed, pinned dependencies, without prepare(),
|
||||
# network acquisition, account caches, or writes into another owner's build.
|
||||
from tools.battle_runtime.trusted import LIBRARY_FILES, SDK_FILES, verify_files
|
||||
|
||||
for root, pins in ((LOCAL / "air_sdk", SDK_FILES), (LOCAL / "original", LIBRARY_FILES)):
|
||||
errors = verify_files(root, pins)
|
||||
if errors:
|
||||
raise RuntimeError(f"Untrusted local snapshot-check dependencies: {errors}")
|
||||
build = LOCAL / "snapshot_bridge_checks" / uuid.uuid4().hex
|
||||
build.mkdir(parents=True)
|
||||
(build / "SnapshotBridgeCheck.as").write_text(HARNESS.replace("__ACTION__", action), encoding="utf-8")
|
||||
(build / "compiler-config.xml").write_text("<flex-config/>", encoding="utf-8")
|
||||
sdk = LOCAL / "air_sdk"
|
||||
command = [shutil.which("java") or "java", "-Duser.language=en", "-Duser.country=US", "-jar",
|
||||
str(sdk / "lib/mxmlc-cli.jar"), "-load-config=" + str(build / "compiler-config.xml"),
|
||||
"-compiler.external-library-path=" + str(sdk / "frameworks/libs/air/airglobal.swc"),
|
||||
"-compiler.library-path=" + str(sdk / "frameworks/libs/core.swc"),
|
||||
"-compiler.source-path=" + str(SOURCE), "-swf-version=50", "-debug=true",
|
||||
"-default-frame-rate=50", "-output=" + str(build / "SnapshotBridgeCheck.swf"),
|
||||
str(build / "SnapshotBridgeCheck.as")]
|
||||
compiler = subprocess.run(command, cwd=ROOT, capture_output=True, text=True, encoding="utf-8",
|
||||
errors="replace", timeout=60, creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
evidence = {"compiler_exit_code": compiler.returncode, "compiler_stdout": compiler.stdout,
|
||||
"compiler_stderr": compiler.stderr,
|
||||
"source_sha256": hashlib.sha256((SOURCE / "SnapshotBridge.as").read_bytes()).hexdigest()
|
||||
if (SOURCE / "SnapshotBridge.as").is_file() else None}
|
||||
if compiler.returncode:
|
||||
raise RuntimeError("Snapshot bridge compilation failed: " + compiler.stdout + compiler.stderr)
|
||||
(build / "check-app.xml").write_text('''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<application xmlns="http://ns.adobe.com/air/application/51.1">
|
||||
<id>local.snapshotbridge.c''' + uuid.uuid4().hex + '''</id><versionNumber>0.0.1</versionNumber>
|
||||
<filename>SnapshotBridgeCheck</filename><initialWindow><content>SnapshotBridgeCheck.swf</content>
|
||||
<visible>false</visible><systemChrome>none</systemChrome><renderMode>cpu</renderMode>
|
||||
</initialWindow><supportedProfiles>extendedDesktop</supportedProfiles></application>''', encoding="utf-8")
|
||||
(build / "request.json").write_text(json.dumps(request), encoding="utf-8")
|
||||
command = [str(sdk / "bin/adl64.exe"), "-runtime", str(sdk / "runtimes/air/win64"), "-nodebug",
|
||||
"-profile", "extendedDesktop", str(build / "check-app.xml"), "--", str(LOCAL / "original"),
|
||||
str(build / "request.json"), str(build / "result.json")]
|
||||
runtime = subprocess.run(command, cwd=build, capture_output=True, timeout=45,
|
||||
creationflags=subprocess.CREATE_NO_WINDOW)
|
||||
result_path = build / "result.json"
|
||||
evidence.update(process_exit_code=runtime.returncode,
|
||||
result=json.loads(result_path.read_text(encoding="utf-8")) if result_path.exists() else None,
|
||||
directory=str(build))
|
||||
(build / "evidence.json").write_text(json.dumps(evidence, indent=2), encoding="utf-8")
|
||||
if evidence["result"] is None:
|
||||
raise RuntimeError(f"AIR snapshot check produced no result (exit {runtime.returncode})")
|
||||
return evidence
|
||||
|
||||
|
||||
def run_checks(cases: list[dict] | None = None) -> dict:
|
||||
if cases is None:
|
||||
cases = [dict(name=name, snapshot=synthetic_snapshot(rich=rich),
|
||||
teamName="teamA", integrity=True)
|
||||
for name, rich in (("plain", False), ("equipment_skin_entangle", True))]
|
||||
empty = synthetic_snapshot()
|
||||
empty["monsterAttributes"] = []
|
||||
cases.append(dict(name="empty_attributes", snapshot=empty, teamName="teamA", integrity=True))
|
||||
return run_harness({"cases": cases}, action=CHECK)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
sys.path.insert(0, str(ROOT))
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--reflect", action="store_true")
|
||||
args = parser.parse_args()
|
||||
evidence = run_harness({}) if args.reflect else run_checks()
|
||||
print(json.dumps(evidence, indent=2))
|
||||
sys.exit(0 if evidence["result"].get("ok") and
|
||||
all(c["ok"] for c in evidence["result"].get("cases", [])) else 1)
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Prepare library-only copies without changing any original AVM2 code bytes."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter
|
||||
import hashlib
|
||||
import struct
|
||||
import zlib
|
||||
|
||||
|
||||
def digest(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def unpack_swf(data: bytes) -> bytes:
|
||||
if len(data) < 13 or data[:3] not in (b"FWS", b"CWS"):
|
||||
raise ValueError("Expected FWS/CWS SWF")
|
||||
result = data if data[:3] == b"FWS" else b"FWS" + data[3:8] + zlib.decompress(data[8:])
|
||||
if len(result) != struct.unpack_from("<I", result, 4)[0]:
|
||||
raise ValueError("SWF declared length mismatch")
|
||||
return result
|
||||
|
||||
|
||||
def tags(data: bytes):
|
||||
start = 8 + (5 + 4 * (data[8] >> 3) + 7) // 8 + 4
|
||||
position = start
|
||||
while position < len(data):
|
||||
if position + 2 > len(data):
|
||||
raise ValueError("Truncated SWF tag")
|
||||
header = struct.unpack_from("<H", data, position)[0]
|
||||
code, size = header >> 6, header & 63
|
||||
position += 2
|
||||
if size == 63:
|
||||
if position + 4 > len(data):
|
||||
raise ValueError("Truncated long SWF tag")
|
||||
size = struct.unpack_from("<I", data, position)[0]
|
||||
position += 4
|
||||
if position + size > len(data):
|
||||
raise ValueError("Truncated SWF tag payload")
|
||||
yield code, data[position:position + size]
|
||||
position += size
|
||||
if code == 0:
|
||||
if size != 0 or position != len(data):
|
||||
raise ValueError("Invalid SWF end tag")
|
||||
return
|
||||
raise ValueError("Missing SWF end tag")
|
||||
|
||||
|
||||
def encode_tag(code: int, data: bytes) -> bytes:
|
||||
size = len(data)
|
||||
return (struct.pack("<H", (code << 6) | min(size, 63))
|
||||
+ (struct.pack("<I", size) if size >= 63 else b"") + data)
|
||||
|
||||
|
||||
def symbols(data: bytes) -> list[tuple[int, bytes]]:
|
||||
if len(data) < 2:
|
||||
raise ValueError("Truncated SymbolClass tag")
|
||||
count = struct.unpack_from("<H", data)[0]
|
||||
position, result = 2, []
|
||||
for _ in range(count):
|
||||
if position + 3 > len(data):
|
||||
raise ValueError("Truncated SymbolClass entry")
|
||||
symbol_id = struct.unpack_from("<H", data, position)[0]
|
||||
end = data.index(0, position + 2)
|
||||
result.append((symbol_id, data[position + 2:end]))
|
||||
position = end + 1
|
||||
if position != len(data):
|
||||
raise ValueError("Trailing SymbolClass bytes")
|
||||
return result
|
||||
|
||||
|
||||
def library_only(original: bytes) -> tuple[bytes, dict]:
|
||||
"""Drop document bindings, make DoABC lazy, reject executable timelines.
|
||||
|
||||
DoABC's flags/name are SWF metadata, outside the ABC payload. All ABC bytes
|
||||
(including checks, methods, skills, callbacks and static initializers) remain
|
||||
identical and ordered. Lazy loading prevents unrelated script initializers
|
||||
from running just because a library was loaded.
|
||||
"""
|
||||
raw = unpack_swf(original)
|
||||
start = 8 + (5 + 4 * (raw[8] >> 3) + 7) // 8 + 4
|
||||
output = bytearray(raw[:start])
|
||||
roots, code_hashes, lazy_changed = [], [], 0
|
||||
counts = Counter()
|
||||
for code, payload in tags(raw):
|
||||
counts[code] += 1
|
||||
if code in (12, 59, 72, 57, 71):
|
||||
raise ValueError(f"Unsupported executable/import SWF tag {code}")
|
||||
if code == 76:
|
||||
entries = symbols(payload)
|
||||
roots.extend(name.decode("utf-8") for sid, name in entries if sid == 0)
|
||||
entries = [(sid, name) for sid, name in entries if sid != 0]
|
||||
payload = struct.pack("<H", len(entries)) + b"".join(
|
||||
struct.pack("<H", sid) + name + b"\0" for sid, name in entries)
|
||||
elif code == 82:
|
||||
if len(payload) < 6:
|
||||
raise ValueError("Truncated DoABC")
|
||||
end = payload.index(0, 4)
|
||||
code_hashes.append(digest(payload[end + 1:]))
|
||||
flags = struct.unpack_from("<I", payload)[0]
|
||||
if flags not in (0, 1):
|
||||
raise ValueError("Unknown DoABC flags")
|
||||
lazy_changed += flags == 0
|
||||
payload = struct.pack("<I", 1) + payload[4:]
|
||||
output.extend(encode_tag(code, payload))
|
||||
struct.pack_into("<I", output, 4, len(output))
|
||||
result = bytes(output)
|
||||
return result, {"original_sha256": digest(original), "library_sha256": digest(result),
|
||||
"removed_document_classes": roots, "abc_sha256": code_hashes,
|
||||
"abc_count": len(code_hashes), "lazy_flags_changed": lazy_changed,
|
||||
"tag_counts": dict(counts), "abc_bytes_preserved": True}
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Reviewed identities, never extended by an imported runtime manifest.
|
||||
|
||||
SDK bytes were acquired from the official Wipro AIR SDK 51.5.1.1 distribution.
|
||||
The original libraries are deterministic library-only transforms of APK 1.9.68.
|
||||
These hashes bind execution to those bytes; they are not vendor signatures or
|
||||
proof of complete gameplay fidelity.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
SDK_FILES = {
|
||||
"bin/adl64.exe": "e22cc43b97d15ed8794f2a4eb838976413945d8e066ac0ada82fe48d1cd38069",
|
||||
"runtimes/air/win64/Adobe AIR/Versions/1.0/Adobe AIR.dll": "181d076176f76b8060c7bcaa5e9a98909b86e25b03bd994036f841614c668041",
|
||||
"lib/mxmlc-cli.jar": "fceb2e3fe9493b37f6df88d7ea3ed2644e3f19bc8a12ec78338674be17704a1a",
|
||||
"lib/compiler.jar": "5c858003d2f5711924e3a3a842f59283cbe627b6a815d6e5209da4ba0be3d03f",
|
||||
"lib/antlr.jar": "4febf283a01fa7a895ce3b91f9f2d1dd1f4d223d8ed8b799c13aaa7aaf502aec",
|
||||
"lib/guava-r08.jar": "d54f64a15314d87c811d845692c790a11ef4aaabd2c5f12de50ba634cddaf971",
|
||||
"lib/aglj40.jar": "d2339b8a1992cc934072c9fa676b33b92e1c2734267ba0745ba6e0660dd44022",
|
||||
"lib/afe.jar": "8b27d1457846380187fecd9d0e28e7d3a409fb2f761fbefe61eb93bc496c27b3",
|
||||
"lib/commons-io-2.0.1.jar": "2a3f5a206480863aae9dff03f53c930c3add6912f8785498d59442c7ebb98c5c",
|
||||
"lib/commons-cli-1.2.jar": "e7cd8951956d349b568b7ccfd4f5b2529a8c113e67c32b028f52ffda371259d9",
|
||||
"lib/lzma-sdk-9.2.jar": "ba9ae4079c05b6132f8445d0b5d9bf9564191d47393977dc29c3d083d8c6b6e6",
|
||||
"lib/rideau.jar": "ca16f52610cca6da007a71df514d403fab6757720b0a24f94e40a39aa6ee2bd3",
|
||||
"frameworks/libs/air/airglobal.swc": "e0f81fdb2029d2bb16e6987c8d85d4eba5eedfa3a23ed6e7f780bf6eb67b0546",
|
||||
"frameworks/libs/core.swc": "193bc3a54aae57424def160d1cd6f62b73d06e028d785f125ef35a91a0af4e8a",
|
||||
}
|
||||
LIBRARY_FILES = {
|
||||
"framework.library.swf": "680e9055da1ec1916af0f2526ba53e73c8e5e299c4f2b5d2061a8903c71133c1",
|
||||
"main.library.swf": "a53afc2fceb6e9592291d4e579b31fdc54f2edd827cbe6adab6b89ee5adc7b40",
|
||||
"baseui.library.swf": "31879090afb49f821646e8b8e36b1469ee9df9e1c57d3f020245e4e780360c29",
|
||||
"mainui.library.swf": "315be2c5bc2b7be0644ef16b9a0ae3c22478a8f98957d83a4361f497de7bf3f2",
|
||||
"mainui2.library.swf": "a544277d3d308178f669289da13f02ae3403f9ddd46a730f21885d0c8be4e766",
|
||||
"mainui3.library.swf": "e2f1977cfbf5acaa09b1bdec281954eb32a56c3d2340f09ffe6526dbb6094c58",
|
||||
"movieclip.library.swf": "3e7967c4dff48c64e61b6c2cfeaa4dd49e279ea644096e948bcd1926f9a4dc8d",
|
||||
}
|
||||
TABLE_FILES = {
|
||||
"setting":"68bb8d2ee882a1c14b98315eb61dfb3545dc633173b53409b1dec3af68fb7af3",
|
||||
"game_setting":"8810981688414e3cef520976911d16e2847df0a435dccd792e2dd527695283e3",
|
||||
"monster_info":"081747ddc5b7afba03f69e65f5eba6af815b9fbd3ea7e0821c7f8807d9486921",
|
||||
"monster_skill":"0fea0eb8553a4868ff704210e9adfd09c6e2b2c3b2730e9ebe25642fa478bf9b",
|
||||
"monster_setting":"49388d221e3d4461fede3b176526d593ec0f1647a8b93a8d2b33a712761febab",
|
||||
"monster_level":"1e435fb320b66c19152216e16159ad04c677e8dc970f32534e50b59363b71340",
|
||||
"team_info":"21254655b6966ab67d5b3f1105568ab6ed13e2eecc4f05d27ef016de0e34ced2",
|
||||
"stage_info":"47ccef41d460f4ef23732624cf302e863a22ca33148dc02629841d764c38b487",
|
||||
"task_info":"b833985c54e11f3079a3ccc53709f87d25b1f8301699b3eb99613a826a469744",
|
||||
"item_info":"9beeab37d107b09d02c4491a052594390c874c92328f524752080f5a7fab21e2",
|
||||
"potential_info":"cf43bde8204ed1e13c555cfc48df5a54ea7f2df7813e017a04ba02f0453d7895",
|
||||
"entangle_info":"9be02321151385379b0992053a41f2df6e911d6e3a9474701c118faad386e8b0",
|
||||
"skin_info":"80841c945544b8b6db87c480ca194cf59c9e7da18718cea66585328d4d18edd2",
|
||||
"upstar_info":"b53db40bd0c94e0c0fff7e6c1bc5519b05c0aa353f4ba384cd3062ad5865c350",
|
||||
}
|
||||
|
||||
|
||||
def verify_files(root: Path, expected: dict[str, str]) -> list[dict]:
|
||||
reasons = []
|
||||
for name, sha in expected.items():
|
||||
path = root / name
|
||||
if not path.is_file():
|
||||
reasons.append({"code": "dependency_missing", "detail": name})
|
||||
else:
|
||||
with path.open("rb") as stream:
|
||||
actual = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
if actual != sha:
|
||||
reasons.append({"code": "dependency_digest_mismatch", "detail": name})
|
||||
return reasons
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Opt-in offline native validation; full evidence stays in ignored local_state.
|
||||
|
||||
The default runs canonical original configs in all three contexts with fake
|
||||
account INPUTS. --request accepts a data-only BattleRequest JSON file. This tool
|
||||
never imports a runner command, downloads dependencies, or calls game services.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
from pathlib import Path
|
||||
import uuid
|
||||
|
||||
from ranch_assistant.battle_runtime import BattleRuntime, CONTEXTS
|
||||
from tools.battle_runtime.inputs import original_source
|
||||
from tools.battle_runtime.probe import LOCAL
|
||||
|
||||
|
||||
def summarize(result: dict) -> dict:
|
||||
scene=result.get("offline_result",{})
|
||||
battle=scene.get("battle_data",{})
|
||||
native=result.get("evidence",{}).get("result",{})
|
||||
elapsed=scene.get("wall_ms",0)
|
||||
return {"status":result["status"],"outcome":result.get("outcome"),
|
||||
"terminal_reason":scene.get("terminal_reason"),"cheatNum":battle.get("cheatNum"),
|
||||
"original_player_checks":len(scene.get("anomaly_records",{}).get("mons",[])),
|
||||
"original_unit_records":len(scene.get("original_unit_records",[])),
|
||||
"battle_left_ms":battle.get("leftTime"),"scene_wall_ms":elapsed,
|
||||
"scene_observed_fps":scene.get("observed_frames",0)*1000/elapsed if elapsed else None,
|
||||
"assets":result.get("evidence",{}).get("resource_audit"),
|
||||
"error_phase":native.get("error",{}).get("phase") if native.get("error") else None,
|
||||
"refusal_codes":[reason["code"] for reason in result.get("reasons",[])],
|
||||
"settlement_eligible":result.get("settlement_eligible",False)}
|
||||
|
||||
|
||||
def synthetic_request(context: str, *, rich=False) -> dict:
|
||||
from tools.battle_runtime.snapshot_bridge_check import synthetic_snapshot
|
||||
tables,_=original_source()
|
||||
position={"battleType":"stage","stageId":"0101","stageLevel":"1","taskTypeId":None,"taskStep":0}
|
||||
battle=tables["stage_info"]["0101"]["level"]["1"]["battle"]
|
||||
request={"context":context,"roster":synthetic_snapshot(rich=rich),"team":"teamA",
|
||||
"battle_position":position,"stage_id":"0101","difficulty":1}
|
||||
if context != "ordinary_stage":
|
||||
task_id,step=("2002014",2) if context=="task_battle" else ("1001004",0)
|
||||
request.update(stage_id=None,task_id="offline-synthetic-instance",step_index=step)
|
||||
position.update(battleType="task",stageId=None,stageLevel=None,taskTypeId=task_id,taskStep=step)
|
||||
if context=="task_battle":battle=tables["task_info"][task_id]["steps"][step]["battle"]
|
||||
request["original_data"]={"battle":battle}
|
||||
return request
|
||||
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--request",type=Path)
|
||||
parser.add_argument("--contexts",choices=sorted(CONTEXTS),nargs="*",default=sorted(CONTEXTS))
|
||||
parser.add_argument("--rich",action="store_true",help="Synthetic original equipment/skin/global/addition inputs")
|
||||
parser.add_argument("--concurrent",action="store_true",help="Also verify two simultaneous component processes/storage/nonces")
|
||||
parser.add_argument("--timeout",type=float,help="Optional explicit deadline for each run")
|
||||
args=parser.parse_args()
|
||||
directory=LOCAL/"validations"/uuid.uuid4().hex
|
||||
directory.mkdir(parents=True)
|
||||
runtime=BattleRuntime();summaries=[];success=True
|
||||
if args.request is not None:
|
||||
if args.request.stat().st_size > 4*1024*1024:raise ValueError("Request exceeds 4 MiB")
|
||||
requests=[json.loads(args.request.read_text(encoding="utf-8"))]
|
||||
else:
|
||||
requests=[synthetic_request(context,rich=args.rich) for context in args.contexts]
|
||||
for index,request in enumerate(requests):
|
||||
result=runtime.run(request,timeout=args.timeout)
|
||||
(directory/f"run-{index}.local.json").write_text(json.dumps(result,ensure_ascii=True,allow_nan=False,indent=2),encoding="utf-8")
|
||||
summary={"context":request.get("context"),**summarize(result)}
|
||||
summaries.append(summary);print(json.dumps(summary),flush=True)
|
||||
success=success and result["status"]=="completed"
|
||||
if args.concurrent:
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
results=list(pool.map(lambda _:runtime.probe_original_components(timeout=args.timeout or 100),range(2)))
|
||||
(directory/"concurrent.local.json").write_text(json.dumps(results,indent=2),encoding="utf-8")
|
||||
native=[result.get("evidence",{}).get("result",{}) for result in results]
|
||||
isolated=all(result["status"]=="completed" for result in results) and all(
|
||||
all(result.get(field) for result in native) and len({result[field] for result in native})==2
|
||||
for field in ("application_id","storage_directory","nonce"))
|
||||
summary={"concurrent_isolation_verified":isolated,"statuses":[result["status"] for result in results]}
|
||||
summaries.append(summary);print(json.dumps(summary),flush=True);success=success and isolated
|
||||
(directory/"summary.json").write_text(json.dumps(summaries,indent=2),encoding="utf-8")
|
||||
raise SystemExit(0 if success else 1)
|
||||
|
||||
|
||||
if __name__=="__main__":
|
||||
main()
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Fixed native runner entrypoint, invoked only in an isolated offline process."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from tools.battle_runtime.probe import LOCAL, execute_probe
|
||||
from tools.battle_runtime.trusted import SDK_FILES, verify_files
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--action", choices=("scene", "components"), required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--nonce", required=True)
|
||||
parser.add_argument("--input",type=Path)
|
||||
parser.add_argument("--timeout",type=float,default=690.0)
|
||||
args = parser.parse_args()
|
||||
# No executable, command, Python import, environment, or plugin-manifest
|
||||
# options exist. Verify the code-bearing SDK before starting Java or ADL.
|
||||
reasons = verify_files(LOCAL / "air_sdk", SDK_FILES)
|
||||
if reasons:
|
||||
raise RuntimeError("AIR dependency validation failed: " + json.dumps(reasons))
|
||||
source_request = None
|
||||
if args.input is not None:
|
||||
if args.input.stat().st_size > 4*1024*1024: raise ValueError("Oversized original request")
|
||||
source_request = json.loads(args.input.read_text(encoding="utf-8"))
|
||||
evidence = execute_probe(scene=args.action == "scene",source_request=source_request,timeout=args.timeout)
|
||||
payload = {"schema": 1, "nonce": args.nonce, "evidence": evidence}
|
||||
args.output.write_text(json.dumps(payload, ensure_ascii=True, allow_nan=False), encoding="utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,141 @@
|
||||
"""Reproducibly bundle original, public combat configuration. No account inputs.
|
||||
|
||||
Run from the repo root: python tools/build_battle_simulation_data.py
|
||||
Only this build tool opens the supplied, hash-checked original APK. Runtime
|
||||
loads a small immutable cache from combat_tables.json.gz instead.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import gzip
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
import zipfile
|
||||
import zlib
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from tools.research_battle_v12 import recover_table
|
||||
|
||||
ORIGINAL_APK_SHA256 = "01678ee3a8465d818d32cbbd94baa0d8253b04b4c57b70ebc5544ed341f1015d"
|
||||
TABLES = ("monster_info", "monster_skill", "monster_setting", "game_setting",
|
||||
"team_info", "setting", "potential_info", "entangle_info", "upstar_info",
|
||||
"item_info", "stage_info", "task_info")
|
||||
# HitAction1..10, verified at the sendHit callbacks, not sound/visual timing.
|
||||
ACTION_HIT_MS = {"JUMP_HIT": 200, "Y_SCALE_SHOOT": 100, "HORIZON_HIT": 200,
|
||||
"DOWN_HIT": 200, "NONE": 0, "HORIZON_HIT_DELAY": 0,
|
||||
"HORIZON_HIT_QUICK": 100, "FRONT_HIT": 200,
|
||||
"JUMP_HIT2": 200, "X_SCALE_SHOOT": 200}
|
||||
|
||||
|
||||
def compact(value):
|
||||
if isinstance(value, dict):
|
||||
return {str(k): compact(v) for k, v in value.items() if not str(k).startswith("c_")}
|
||||
if isinstance(value, list):
|
||||
return [compact(v) for v in value]
|
||||
return value
|
||||
|
||||
|
||||
def attack_profiles(sources):
|
||||
folder = sources / "net/pixvi/myr/view/attack"
|
||||
factory = (folder / "type/AttackType.as").read_text(encoding="utf-8")
|
||||
profiles, fingerprints = {}, {}
|
||||
paths = list(folder.glob("AttackType*.as")) + list((folder / "action").rglob("*.as"))
|
||||
paths += [folder / "type/AttackType.as", folder / "BaseAttack.as"]
|
||||
for path in sorted(paths):
|
||||
fingerprints[path.relative_to(sources).as_posix()] = hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
for key, cls in re.findall(r'case "(\d+)":\s*attack = new (AttackType\d+)\(\);', factory):
|
||||
source = (folder / (cls + ".as")).read_text(encoding="utf-8")
|
||||
action = re.search(r"type_action\s*=\s*HitActionType\.(\w+)", source)
|
||||
speed = re.search(r"spd_bullet\s*=\s*([\d.]+)", source)
|
||||
if not action or action.group(1) not in ACTION_HIT_MS:
|
||||
raise ValueError(f"Unreviewed attack timing: {cls}")
|
||||
profiles[key] = {"source_class": cls,
|
||||
"projectile": bool(re.search(r"shotter\s*=\s*true", source)),
|
||||
"projectile_speed": float(speed.group(1)) if speed else 6,
|
||||
"hit_delay_ms": ACTION_HIT_MS[action.group(1)],
|
||||
"action": action.group(1)}
|
||||
return profiles, fingerprints
|
||||
|
||||
|
||||
def build(apk, output, *, sources=None):
|
||||
apk, output = Path(apk), Path(output)
|
||||
source_hash = hashlib.sha256(apk.read_bytes()).hexdigest()
|
||||
if source_hash != ORIGINAL_APK_SHA256:
|
||||
raise ValueError("Expected the unmodified original 1.9.68 APK (SHA-256 mismatch)")
|
||||
data, table_meta = {"schema_version": 1}, {}
|
||||
with zipfile.ZipFile(apk) as archive:
|
||||
swf = archive.read("assets/MYRMain.app")
|
||||
swf_body = zlib.decompress(swf[8:]) if swf[:3] == b"CWS" else swf[8:]
|
||||
rect_bytes = (5 + 4 * (swf_body[0] >> 3) + 7) // 8
|
||||
fps = struct.unpack_from("<H", swf_body, rect_bytes)[0] / 256
|
||||
if fps != 50:
|
||||
raise ValueError("Unreviewed original frame rate")
|
||||
for name in TABLES:
|
||||
value, meta = recover_table(archive, name)
|
||||
if isinstance(value, dict):
|
||||
value = value.get("datas", value)
|
||||
if name == "stage_info":
|
||||
value = {str(row["id"]): {"id": row["id"], "level": row.get("level", {})}
|
||||
for row in value}
|
||||
if name == "task_info":
|
||||
value = {str(k): {"id": row["id"], "type": row.get("type"),
|
||||
"steps": [{k: v for k, v in step.items()
|
||||
if k in ("type", "battle", "stage", "level", "value", "statusType", "statusValue")}
|
||||
for step in row.get("steps", [])]}
|
||||
for k, row in value.items()}
|
||||
data[name] = compact(value)
|
||||
table_meta[name] = dict(meta, record_count=len(value))
|
||||
# Preserve all combat values; discard images, descriptions and quest rewards.
|
||||
data["monster_info"] = {k: {f: v for f, v in row.items() if f in (
|
||||
"type", "name", "atk", "def", "hp", "dex", "star", "element", "job",
|
||||
"pow", "powdef", "spd_atk", "spd_move", "atk_dis", "atk_type1", "atk_type2",
|
||||
"skill_1", "skill_2", "move_1", "move_2", "entangleSkills") or "_grow_" in f}
|
||||
for k, row in data["monster_info"].items()}
|
||||
data["setting"] = {k: data["setting"][k] for k in ("defaultField", "groundObject", "groundType")}
|
||||
data["attack_profiles"], source_files = attack_profiles(sources or ROOT / "analysis/as3/scripts")
|
||||
data["clock"] = {"fps": fps, "frame_ms": 1000 / fps}
|
||||
battles = {k: data.pop(k) for k in ("stage_info", "task_info")}
|
||||
battles["schema_version"] = 1
|
||||
# Simulation already receives one battle config. Do not decode all original
|
||||
# stage battles in each worker merely to compute species stats.
|
||||
artifacts = {}
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
for name, value in (("combat_tables.json.gz", data), ("combat_battles.json.gz", battles)):
|
||||
encoded = json.dumps(value, ensure_ascii=False, allow_nan=False,
|
||||
sort_keys=True, separators=(",", ":")).encode("utf-8")
|
||||
artifact = gzip.compress(encoded, mtime=0)
|
||||
artifacts[name] = {"name": name, "bytes": len(artifact),
|
||||
"sha256": hashlib.sha256(artifact).hexdigest(),
|
||||
"decoded_sha256": hashlib.sha256(encoded).hexdigest()}
|
||||
(output / name).write_bytes(artifact)
|
||||
manifest = {"schema_version": 1, "source": {"apk_sha256": source_hash,
|
||||
"main_swf_sha256": "c6838331a198a22ffa486cbf61cc74c97619e011bc3364c8bb8dc99e269036cf"},
|
||||
"tables": table_meta, "attack_sources": source_files, "original_frame_rate": fps,
|
||||
"artifact": artifacts["combat_tables.json.gz"], "artifacts": artifacts,
|
||||
"scope": "Public original combat tables; experimental simulator, not engine fidelity."}
|
||||
(output / "combat_manifest.json").write_text(json.dumps(manifest, ensure_ascii=True,
|
||||
sort_keys=True, indent=2) + "\n", encoding="utf-8")
|
||||
return manifest
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--apk", type=Path)
|
||||
parser.add_argument("--output", type=Path, default=ROOT / "ranch_assistant/data")
|
||||
args = parser.parse_args(argv)
|
||||
candidates = list(ROOT.glob("*_1.9.68.apk"))
|
||||
apk = args.apk or (candidates[0] if len(candidates) == 1 else None)
|
||||
if apk is None:
|
||||
parser.error("Supply exactly one original APK with --apk")
|
||||
manifest = build(apk, args.output)
|
||||
print(json.dumps({"artifact": manifest["artifact"],
|
||||
"table_counts": {k: v["record_count"] for k, v in manifest["tables"].items()}}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -12,7 +12,6 @@ from repack_apk import repack_members
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
ANALYSIS = ROOT / "analysis"
|
||||
BUILD_TOOLS = Path(r"C:\Users\11789\AppData\Local\Android\Sdk\build-tools\36.0.0")
|
||||
|
||||
|
||||
def sha256(path: Path) -> str:
|
||||
@@ -27,7 +26,7 @@ def run(*args: str) -> None:
|
||||
subprocess.run(list(map(str, args)), cwd=ROOT, check=True)
|
||||
|
||||
|
||||
def build(mode_filter: str = "both", revision: str = "V3", refresh_air_cache: bool = False) -> None:
|
||||
def build(mode_filter: str = "both", revision: str = "V3", refresh_air_cache: bool = False, *, build_tools: Path) -> None:
|
||||
source = ROOT / "\u7267\u7f8a\u4eba\u4e4b\u5fc3_1.9.68.apk"
|
||||
expected = "01678ee3a8465d818d32cbbd94baa0d8253b04b4c57b70ebc5544ed341f1015d"
|
||||
if sha256(source) != expected:
|
||||
@@ -61,17 +60,17 @@ def build(mode_filter: str = "both", revision: str = "V3", refresh_air_cache: bo
|
||||
print(f"New AIR extracted-code cache ID: {cache_id}", flush=True)
|
||||
print(f"Repacking {mode}", flush=True)
|
||||
repack_members(source, replacements, unsigned)
|
||||
run(BUILD_TOOLS / "zipalign.exe", "-f", "-p", "4", unsigned, aligned)
|
||||
run(build_tools / "zipalign.exe", "-f", "-p", "4", unsigned, aligned)
|
||||
if refresh_air_cache:
|
||||
xmltree = subprocess.check_output([str(BUILD_TOOLS / "aapt.exe"), "dump", "xmltree", str(aligned), "AndroidManifest.xml"]).decode("utf-8", errors="replace")
|
||||
xmltree = subprocess.check_output([str(build_tools / "aapt.exe"), "dump", "xmltree", str(aligned), "AndroidManifest.xml"]).decode("utf-8", errors="replace")
|
||||
if cache_id not in xmltree or '"uniqueappversionid"' not in xmltree or '"MYRDyd.swf"' not in xmltree:
|
||||
raise ValueError("Compiled Android manifest validation failed")
|
||||
(ANALYSIS / f"{revision.lower()}_manifest_dump.txt").write_text(xmltree, encoding="utf-8")
|
||||
run(BUILD_TOOLS / "apksigner.bat", "sign", "--ks", ANALYSIS / "myrzx-local-test.p12",
|
||||
run(build_tools / "apksigner.bat", "sign", "--ks", ANALYSIS / "myrzx-local-test.p12",
|
||||
"--ks-key-alias", "myrzx-local", "--ks-pass", "pass:myrzx-local-test",
|
||||
"--key-pass", "pass:myrzx-local-test", "--out", output, aligned)
|
||||
run(BUILD_TOOLS / "zipalign.exe", "-c", "-p", "4", output)
|
||||
run(BUILD_TOOLS / "apksigner.bat", "verify", "--verbose", "--print-certs", output)
|
||||
run(build_tools / "zipalign.exe", "-c", "-p", "4", output)
|
||||
run(build_tools / "apksigner.bat", "verify", "--verbose", "--print-certs", output)
|
||||
with zipfile.ZipFile(output) as apk, zipfile.ZipFile(source) as original:
|
||||
bad = apk.testzip()
|
||||
if bad is not None:
|
||||
@@ -104,5 +103,6 @@ if __name__ == "__main__":
|
||||
parser.add_argument("--mode", choices=("both", "damage", "stats"), default="both")
|
||||
parser.add_argument("--revision", choices=("V3", "V4"), default="V3")
|
||||
parser.add_argument("--refresh-air-cache", action="store_true")
|
||||
parser.add_argument("--build-tools", type=Path, required=True, help="Android SDK build-tools directory")
|
||||
args = parser.parse_args()
|
||||
build(args.mode, args.revision, args.refresh_air_cache)
|
||||
build(args.mode, args.revision, args.refresh_air_cache, build_tools=args.build_tools)
|
||||
|
||||
@@ -0,0 +1,303 @@
|
||||
"""Build deterministic progression artifacts from the original APK, offline.
|
||||
|
||||
Usage: python tools/build_progression_data.py [--apk PATH] [--output DIRECTORY]
|
||||
The manifest binds every recovered table, script summary, retained AS3 source,
|
||||
and output artifact to SHA-256. No account data or network calls are used.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from collections import Counter
|
||||
import gzip
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import zipfile
|
||||
import re
|
||||
import zlib
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from tools.research_battle_v12 import recover_table
|
||||
from ranch_assistant.game_data import (
|
||||
BATTLES_NAME, DATA_NAME, MANIFEST_NAME, ORIGINAL_APK_SHA256, SCHEMA_VERSION,
|
||||
)
|
||||
|
||||
TABLES = ("task_info", "stage_info", "stage_sp", "setting", "game_setting", "npc_info", "area_info", "mine_info")
|
||||
SOURCES = (
|
||||
"center/TaskCenter.as", "center/PosCenter.as", "center/GuideCenter.as",
|
||||
"center/MonsterCenter.as", "center/BagCenter.as", "center/StageCenter.as",
|
||||
"element/task/TaskStepVo.as", "element/task/TaskVo.as", "element/task/TaskType.as",
|
||||
"element/task/TaskStatusType.as", "element/npc/ConditionVo.as",
|
||||
"element/stage/StageVo.as", "element/city/CityVo.as", "net/NetTask.as",
|
||||
"net/NetBattle.as", "panel/taskstartpanel/TaskStartPanel.as",
|
||||
"panel/story/StoryPanel.as", "panel/stage/StageStartPanel.as",
|
||||
"panel/story/GAoNanoEventVo.as", "center/LibCenter.as",
|
||||
"panel/wild/AreaVo.as", "panel/wild/AreaIconUI.as", "panel/wild/AreaPositionIconUI.as",
|
||||
"panel/wild/WildPanel.as", "panel/wild/StageMap.as", "panel/loopStagePanel/LoopStagePanel.as",
|
||||
"battle/BattleGround.as", "panel/battle/BattlePanel.as", "element/reward/RewardPieceVo.as",
|
||||
"panel/stage/StagePanel.as", "panel/task/TaskViewPanel.as",
|
||||
)
|
||||
# These commands affect presentation only. Control-flow and arbitrary events
|
||||
# are rejected, even though the original player supports additional commands.
|
||||
PRESENTATION_COMMANDS = frozenset({
|
||||
"tag", "text", "wait", "top", "setLayer", "moveLayer", "playSound",
|
||||
"stopSound", "shake", "flash", "localBgm", "end",
|
||||
})
|
||||
|
||||
|
||||
def digest(value):
|
||||
return hashlib.sha256(value).hexdigest()
|
||||
|
||||
|
||||
def encode(value):
|
||||
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode("utf-8")
|
||||
|
||||
|
||||
def repair_text(value):
|
||||
"""Same reversible legacy-text repair as the existing catalog builder."""
|
||||
if isinstance(value, dict):
|
||||
return {str(key): repair_text(item) for key, item in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [repair_text(item) for item in value]
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
return value.encode("latin1").decode("gbk")
|
||||
except (UnicodeEncodeError, UnicodeDecodeError):
|
||||
pass
|
||||
return value
|
||||
|
||||
|
||||
def summarize_script(raw, member):
|
||||
script = json.loads(raw)
|
||||
expressions = script.get("exps")
|
||||
blocked, events, commands, lines = [], [], Counter(), 0
|
||||
if not isinstance(expressions, list):
|
||||
expressions = []
|
||||
blocked.append("missing expression list")
|
||||
ended = False
|
||||
for expression in expressions:
|
||||
if ended:
|
||||
break
|
||||
key, para = expression.get("key"), expression.get("para") or {}
|
||||
commands[str(key)] += 1
|
||||
if key == "event":
|
||||
events.append(para)
|
||||
if para.get("event") != "GAoEvent" or str(para.get("eventData", "")).strip() not in ("true", "false"):
|
||||
blocked.append("special event")
|
||||
elif key not in PRESENTATION_COMMANDS:
|
||||
blocked.append(f"unsupported command: {key}")
|
||||
if key == "text":
|
||||
lines += 1
|
||||
# Inline GAo commands can contain their own branching/event code.
|
||||
tags = re.findall(r"\[([^\]]*)\]", para.get("text", ""))
|
||||
supported = {"show", "hide", "l", "r", "cm", "color", "colorEnd", "wait", "br", "b", "bEnd", "i", "iEnd", "size", "sizeEnd", "align", "alignEnd"}
|
||||
for tag in tags:
|
||||
if re.fullmatch(r"\{gn\.[A-Za-z_][A-Za-z0-9_]*\}", tag):
|
||||
continue # Escaped dialogue placeholders, not script commands.
|
||||
if tag.split("=", 1)[0] not in supported:
|
||||
blocked.append(f"unsupported inline command: {tag.split('=', 1)[0]}")
|
||||
if key == "end":
|
||||
if para.get("end") is True:
|
||||
ended = True
|
||||
else:
|
||||
blocked.append("unverified end command")
|
||||
answer = None
|
||||
if events:
|
||||
answer = str(events[-1].get("eventData", "")).startswith("true")
|
||||
return {"member": member, "sha256": digest(raw), "commands": dict(commands),
|
||||
"dialogue_lines": lines, "events": events, "answer": answer,
|
||||
"supported": not blocked, "block_reasons": sorted(set(blocked))}
|
||||
|
||||
|
||||
def support_report(tasks, scripts):
|
||||
uses, mainline = {}, set()
|
||||
special_acceptance, conditions, guides = [], [], []
|
||||
for key, task in sorted(tasks.items()):
|
||||
for number, step in enumerate([task.get("startStep") or {}] + (task.get("steps") or [])):
|
||||
for phase in ("story", "afterStory"):
|
||||
name = step.get(phase)
|
||||
if name:
|
||||
uses.setdefault(name, []).append({"task_type_id": key, "step_number": number, "phase": phase})
|
||||
if task.get("type") == 1:
|
||||
mainline.add(name)
|
||||
if step.get("passGuide"):
|
||||
guides.append({"task_type_id": key, "step_number": number, "record": step["passGuide"]})
|
||||
condition = step.get("condition") or {}
|
||||
if condition.get("passStage") or condition.get("lang") not in (None, "", "all"):
|
||||
conditions.append({"task_type_id": key, "step_number": number,
|
||||
"condition": condition, "reason": "Retained ConditionVo loader anomaly; declared conditions checked conservatively"})
|
||||
start = task.get("startStep") or {}
|
||||
if (task.get("type") in (1, 2) and start.get("position") and start.get("npc")
|
||||
and (not start.get("story") or scripts[start["story"]].get("answer") is not True)):
|
||||
special_acceptance.append(key)
|
||||
return {
|
||||
"source_apk_sha256": ORIGINAL_APK_SHA256,
|
||||
"scope": "Static planning support only; no game server calls or combat execution.",
|
||||
"script_classification_basis": "Original GAo expression keys and literal text formatting; StoryPanel/GAoNanoEventVo event handlers. Bundled GAo renderer implementation is not retained.",
|
||||
"counts": {"referenced_scripts": len(scripts), "linear_scripts": sum(item["supported"] for item in scripts.values()),
|
||||
"mainline_referenced_scripts": len(mainline), "mainline_linear_scripts": sum(scripts[name]["supported"] for name in mainline)},
|
||||
"unsupported_scripts": {name: {"reasons": item["block_reasons"], "uses": uses[name]}
|
||||
for name, item in sorted(scripts.items()) if not item["supported"]},
|
||||
"special_acceptance_task_types": special_acceptance,
|
||||
"guide_gates": guides,
|
||||
"condition_loader_anomalies": conditions,
|
||||
"unknown_task_types": {key: task.get("type") for key, task in sorted(tasks.items()) if task.get("type") not in (1, 2, 3, 4, 5)},
|
||||
"special_local_hooks": [{"task_type_id": "1001006", "step_number": 4, "action": "GachaPanel.popInGacha('task1')", "supported": False}],
|
||||
"delegated_categories": {"3": "event", "4": "commission_plan driven by existing QuestPolicy", "5": "bond"},
|
||||
"supported_nonbattle_statuses": ["none", "getItem", "getMonster", "getMoney", "killMonster", "passLevel", "unlockMonster", "sysLock"],
|
||||
"battle_routing": {"battle": "battleStart(task) -> real battle -> taskCompleteStep", "passStage": "same task route; stage configuration; never a sweep"},
|
||||
}
|
||||
|
||||
|
||||
def farming_index(stages):
|
||||
"""Potential sources, never fabricated rewards/kills or drop guarantees."""
|
||||
index = {"kills": {}, "items": {}}
|
||||
def number(value, default=0):
|
||||
try:
|
||||
return float(value)
|
||||
except (ValueError, TypeError):
|
||||
return default
|
||||
for stage_id, stage in sorted(stages.items()):
|
||||
for difficulty, level in (stage.get("level") or {}).items():
|
||||
battle = level.get("battle") or {}
|
||||
if not isinstance(battle, dict) or not battle:
|
||||
continue
|
||||
counts = Counter()
|
||||
for team in battle.get("teams") or []:
|
||||
for monster in team.get("mons") or []:
|
||||
# BattleGround.deadHandler: team != 1, !isObject, mode==2.
|
||||
key = str(monster.get("type", ""))
|
||||
if ("team" in monster and number(monster["team"]) != 1 and not monster.get("isObject")
|
||||
and number(monster.get("mode")) == 2 and key.isdigit()):
|
||||
counts[key] += 1
|
||||
record = {"stage_id": str(stage_id), "difficulty": int(difficulty)}
|
||||
for key, count in sorted(counts.items()):
|
||||
index["kills"].setdefault(key, []).append(record | {"configured_enemies": count})
|
||||
items = set()
|
||||
for group in (level.get("reward") or {}).get("rewards") or []:
|
||||
if number(group.get("item_num")) > 0 and number(group.get("item_chance"), 1) > 0:
|
||||
for item in group.get("items") or []:
|
||||
parts = str(item.get("name", "")).split(",")
|
||||
maximum = number(parts[2] if len(parts) > 2 else 1)
|
||||
if parts[0].isdigit() and maximum > 0 and number(item.get("value"), 1) > 0:
|
||||
items.add(parts[0])
|
||||
if number(group.get("monMode")) == 0 and number(group.get("num")) > 0 and number(group.get("chance"), 1) > 0:
|
||||
for monster in group.get("monsters") or []:
|
||||
key = str(monster.get("name", ""))
|
||||
if key.isdigit() and number(monster.get("value"), 1) > 0:
|
||||
items.add(key)
|
||||
for key in sorted(items):
|
||||
index["items"].setdefault(key, []).append(record)
|
||||
return index
|
||||
|
||||
|
||||
def build(apk, output):
|
||||
apk, output = Path(apk), Path(output)
|
||||
with apk.open("rb") as stream:
|
||||
apk_sha256 = hashlib.file_digest(stream, "sha256").hexdigest()
|
||||
if apk_sha256 != ORIGINAL_APK_SHA256:
|
||||
raise ValueError("Only the verified original 1.9.68 APK is accepted")
|
||||
tables, table_manifest = {}, {}
|
||||
with zipfile.ZipFile(apk) as archive:
|
||||
main_bytes = archive.read("assets/MYRMain.app")
|
||||
for name in TABLES:
|
||||
original, metadata = recover_table(archive, name)
|
||||
value = original.get("datas", original) if isinstance(original, dict) else original
|
||||
metadata["record_count"] = len(value)
|
||||
metadata["recovered_sha256"] = digest(encode(original))
|
||||
tables[name] = repair_text(value)
|
||||
table_manifest[name] = metadata
|
||||
tasks = tables["task_info"]
|
||||
references = {str(step[key]) for task in tasks.values()
|
||||
for step in [task.get("startStep") or {}] + (task.get("steps") or [])
|
||||
for key in ("story", "afterStory") if step.get(key)}
|
||||
scripts = {}
|
||||
for name in sorted(references):
|
||||
member = f"assets/GAoNano/script/{name}.json"
|
||||
scripts[name] = summarize_script(archive.read(member), member)
|
||||
stages = {str(row["id"]): row for row in tables["stage_info"]}
|
||||
farm_sources = farming_index(stages)
|
||||
tables["stage_info"] = {}
|
||||
members = {}
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
with zipfile.ZipFile(output / BATTLES_NAME, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
|
||||
for key, stage in sorted(stages.items()):
|
||||
battles = {str(level): value.get("battle") for level, value in (stage.get("level") or {}).items()}
|
||||
raw = encode(battles)
|
||||
member = f"stages/{key}.json"
|
||||
info = zipfile.ZipInfo(member, date_time=(1980, 1, 1, 0, 0, 0))
|
||||
info.create_system = 3
|
||||
info.external_attr = 0o100644 << 16
|
||||
info.compress_type = zipfile.ZIP_DEFLATED
|
||||
archive.writestr(info, raw, compresslevel=9)
|
||||
members[key] = {"member": member, "sha256": digest(raw)}
|
||||
tables["stage_info"][key] = {field: value for field, value in stage.items() if field != "level"}
|
||||
tables["stage_info"][key]["level"] = {
|
||||
str(level): {field: item for field, item in value.items() if field != "battle"}
|
||||
| {"battle_available": bool(value.get("battle"))}
|
||||
for level, value in (stage.get("level") or {}).items()}
|
||||
data = {"schema_version": SCHEMA_VERSION, **tables, "scripts": scripts, "battle_members": members, "farming": farm_sources}
|
||||
raw = encode(data)
|
||||
compressed_stream = io.BytesIO()
|
||||
with gzip.GzipFile(filename="", fileobj=compressed_stream, mode="wb", compresslevel=9, mtime=0) as stream:
|
||||
stream.write(raw)
|
||||
compressed = compressed_stream.getvalue()
|
||||
(output / DATA_NAME).write_bytes(compressed)
|
||||
support_name = "progression_support.json"
|
||||
support = support_report(tasks, scripts)
|
||||
support["farming"] = {"kill_species": len(farm_sources["kills"]), "item_or_egg_types": len(farm_sources["items"]),
|
||||
"kill_rule": "team != 1 and !isObject and mode == 2; declared battle teams only",
|
||||
"sweep_kill_credit": False, "loot": "Configured potential rewards; actual inventory and kills must be refreshed after settlement",
|
||||
"unindexed": "Dynamic controller/skill spawns and external reward sources"}
|
||||
support_bytes = (json.dumps(support, ensure_ascii=False, indent=2, sort_keys=True) + "\n").encode("utf-8")
|
||||
(output / support_name).write_bytes(support_bytes)
|
||||
source_root = ROOT / "analysis/as3/scripts/net/pixvi/myr"
|
||||
manifest = {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"builder": {"sha256": digest(Path(__file__).read_bytes()), "python": sys.version.split()[0], "zlib": zlib.ZLIB_VERSION},
|
||||
"source": {"apk_version": "1.9.68", "apk_sha256": apk_sha256,
|
||||
"main_swf_sha256": digest(main_bytes),
|
||||
"amf_reader_sha256": digest((ROOT / "ranch_assistant/amf.py").read_bytes())},
|
||||
"tables": table_manifest,
|
||||
"as3_sources": {str((source_root / name).relative_to(ROOT)).replace("\\", "/"):
|
||||
digest((source_root / name).read_bytes()) for name in SOURCES},
|
||||
"artifacts": {DATA_NAME: {"sha256": digest(compressed), "bytes": len(compressed),
|
||||
"decoded_sha256": digest(raw), "decoded_bytes": len(raw)},
|
||||
BATTLES_NAME: {"sha256": digest((output / BATTLES_NAME).read_bytes()),
|
||||
"bytes": (output / BATTLES_NAME).stat().st_size},
|
||||
support_name: {"sha256": digest(support_bytes), "bytes": len(support_bytes)}},
|
||||
"counts": {"tasks": len(tasks), "steps": sum(len(task.get("steps") or []) for task in tasks.values()),
|
||||
"task_types": dict(Counter(str(task.get("type")) for task in tasks.values())),
|
||||
"stages": len(stages), "scripts": len(scripts),
|
||||
"areas": len(tables["area_info"].get("areaInfo", {})), "mines": len(tables["mine_info"].get("mines", {})),
|
||||
"supported_scripts": sum(script["supported"] for script in scripts.values()),
|
||||
**support["counts"]},
|
||||
"task_update_mode": "legacy" if tables["setting"].get("useOldNewTaskFunction") is True else "new",
|
||||
"limitations": ["Static original APK baseline; live resource version not verified.",
|
||||
"Script support means linear dialogue/presentation and boolean GAoEvent only.",
|
||||
"ConditionVo passStage loading and lang assignment anomalies require conservative checks.",
|
||||
"No account data, network operations, combat execution, or battle results."],
|
||||
}
|
||||
(output / MANIFEST_NAME).write_text(json.dumps(manifest, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
||||
return manifest
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--apk", type=Path)
|
||||
parser.add_argument("--output", type=Path, default=ROOT / "ranch_assistant/data")
|
||||
args = parser.parse_args()
|
||||
if args.apk is None:
|
||||
candidates = list(ROOT.glob("*_1.9.68.apk"))
|
||||
if len(candidates) != 1:
|
||||
parser.error("Pass --apk with the original 1.9.68 APK")
|
||||
args.apk = candidates[0]
|
||||
manifest = build(args.apk, args.output)
|
||||
print(json.dumps({"counts": manifest["counts"], "artifacts": manifest["artifacts"]}, ensure_ascii=True))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,32 +1,69 @@
|
||||
"""Read packaged assets through ADB; do not access private saves or change the device."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import shutil
|
||||
import subprocess
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parent.parent
|
||||
adb = r"C:\Program Files\adb_tools\adb.exe"
|
||||
device = "3B15C400HGV00000"
|
||||
prefix = [adb, "-s", device]
|
||||
paths = subprocess.check_output(prefix + ["shell", "pm", "path", "air.net.pixvi.myrzx"], timeout=15).decode().strip().splitlines()
|
||||
if len(paths) != 1 or not paths[0].startswith("package:"):
|
||||
raise RuntimeError("Expected one installed base APK")
|
||||
installed = paths[0][len("package:"):].strip()
|
||||
members = {"assets/MYRDyd.swf": "device_latest_loader.swf", "assets/MYRMain.app": "device_latest_main.app"}
|
||||
observed = {}
|
||||
for member, filename in members.items():
|
||||
result = subprocess.run(prefix + ["exec-out", "unzip", "-p", installed, member], capture_output=True, timeout=60, check=True)
|
||||
data = result.stdout
|
||||
if data[:3] not in (b"FWS", b"CWS", b"ZWS"):
|
||||
raise RuntimeError(f"Unexpected asset format for {member}")
|
||||
(root / "analysis" / filename).write_bytes(data)
|
||||
observed[member] = {"sha256": hashlib.sha256(data).hexdigest(), "size": len(data)}
|
||||
matches = []
|
||||
for apk in root.glob("*.apk"):
|
||||
with zipfile.ZipFile(apk) as archive:
|
||||
if all(hashlib.sha256(archive.read(member)).hexdigest() == record["sha256"] for member, record in observed.items()):
|
||||
matches.append(apk.name)
|
||||
report = {"installed_packaged_assets": observed, "matching_local_apks": matches}
|
||||
(root / "analysis" / "device_latest_identity.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(json.dumps(report, ensure_ascii=False, indent=2))
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def select_serial(adb: str, serial: str | None = None) -> str:
|
||||
output = subprocess.check_output([adb, "devices"], timeout=15, text=True)
|
||||
authorized = []
|
||||
for line in output.splitlines():
|
||||
fields = line.split()
|
||||
if len(fields) >= 2 and fields[1] == "device":
|
||||
authorized.append(fields[0])
|
||||
if serial is not None:
|
||||
if serial not in authorized:
|
||||
raise RuntimeError("Selected ADB device must be connected and authorized")
|
||||
return serial
|
||||
if not authorized:
|
||||
raise RuntimeError("No authorized ADB device is connected")
|
||||
if len(authorized) != 1:
|
||||
raise RuntimeError("Multiple authorized ADB devices are connected; pass --serial")
|
||||
return authorized[0]
|
||||
|
||||
|
||||
def read_assets(*, adb: str | None = None, serial: str | None = None) -> dict:
|
||||
adb = adb or shutil.which("adb")
|
||||
if adb is None:
|
||||
raise FileNotFoundError("ADB not found; add it to PATH or pass --adb")
|
||||
prefix = [adb, "-s", select_serial(adb, serial)]
|
||||
paths = subprocess.check_output(prefix + ["shell", "pm", "path", "air.net.pixvi.myrzx"], timeout=15).decode().strip().splitlines()
|
||||
if len(paths) != 1 or not paths[0].startswith("package:"):
|
||||
raise RuntimeError("Expected one installed base APK")
|
||||
installed = paths[0][len("package:"):].strip()
|
||||
members = {"assets/MYRDyd.swf": "device_latest_loader.swf", "assets/MYRMain.app": "device_latest_main.app"}
|
||||
observed = {}
|
||||
for member, filename in members.items():
|
||||
result = subprocess.run(prefix + ["exec-out", "unzip", "-p", installed, member], capture_output=True, timeout=60, check=True)
|
||||
data = result.stdout
|
||||
if data[:3] not in (b"FWS", b"CWS", b"ZWS"):
|
||||
raise RuntimeError(f"Unexpected asset format for {member}")
|
||||
(ROOT / "analysis" / filename).write_bytes(data)
|
||||
observed[member] = {"sha256": hashlib.sha256(data).hexdigest(), "size": len(data)}
|
||||
matches = []
|
||||
for apk in ROOT.glob("*.apk"):
|
||||
with zipfile.ZipFile(apk) as archive:
|
||||
if all(hashlib.sha256(archive.read(member)).hexdigest() == record["sha256"] for member, record in observed.items()):
|
||||
matches.append(apk.name)
|
||||
report = {"installed_packaged_assets": observed, "matching_local_apks": matches}
|
||||
(ROOT / "analysis" / "device_latest_identity.json").write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
return report
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--adb", help="ADB executable; defaults to adb on PATH")
|
||||
parser.add_argument("--serial", help="Authorized device serial; required when multiple authorized devices are connected")
|
||||
args = parser.parse_args()
|
||||
print(json.dumps(read_assets(adb=args.adb, serial=args.serial), ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
Reference in New Issue
Block a user