From 001ed9d36db8783805178797171093faaf37fbeb Mon Sep 17 00:00:00 2001 From: AttilaNet Date: Sun, 8 Nov 2026 20:07:26 +0800 Subject: [PATCH] Prioritize commission rewards and fix built-in battle simulation flow --- README.md | 4 +- analysis/V1_2_PLAN.md | 8 ++ ranch_assistant/README.md | 8 +- ranch_assistant/battle_simulator.py | 13 +++- ranch_assistant/engine.py | 22 ++++-- ranch_assistant/gui.py | 4 +- ranch_assistant/progression.py | 33 +++++---- ranch_assistant/progression_gui.py | 19 +++-- ranch_assistant/quests.py | 18 ++++- .../tests/test_battle_simulator.py | 46 +++++++++++- .../tests/test_commission_priority.py | 73 +++++++++++++++++++ ranch_assistant/tests/test_progression_gui.py | 71 ++++++++++++++---- 12 files changed, 260 insertions(+), 59 deletions(-) create mode 100644 ranch_assistant/tests/test_commission_priority.py diff --git a/README.md b/README.md index 648e3ff..fca3db1 100644 --- a/README.md +++ b/README.md @@ -42,8 +42,8 @@ 在“自动主线 → 任务状态”点击“刷新任务 / 预览”,查看下一步和阻塞原因;到“推进策略”选择任务范围、推进战斗队伍、保留体力和交付限制,再勾选“启用自动主线策略”,用顶部绿色“开启”运行、红色“停止”暂停。规则自动保存,重启、恢复会话或导入配置后仍需手动开启。委托接取、交付和“也接取需要实战的委托”继续在“自动委托”配置。 -- **原版运行时(默认)**:原 AIR 引擎已通过原始战斗面板自然完成合成阵容的 1-1 离线实验,读取实际战场统计与检查结果,样例 `cheatNum=0`。任意实际阵容的输入桥接仍在完善,当前能力检查会阻止尚未验证的开战;该样例不代表全部原版战斗可用。 -- **实验模拟(需显式选择)**:使用原始数值资料,在独立进程中计算 AP、出场、移动、攻击和部分技能,记录实际模型轨迹。它包含机制近似与遗漏,可能和原版胜负不同;完整集成 QA、原引擎对拍及真实账号验证尚未完成。 +- **内置战斗模拟**:无需选择运行时,程序使用原始数值资料,在独立进程中计算 AP、出场、移动、攻击和部分技能,等待计算出的战斗时长后提交结果。模型仍有机制近似与遗漏,可能和原版胜负不同,未支持的战斗会显示原因。 +- **委托优先**:按奖励氪金数量20→15→10接取可处理的委托,优先执行委托步骤和材料补缺,再处理主线及普通牧场策略。缺少材料时使用现有扫荡/挑战来源;按委托缺口自动购买并孵化魔物蛋的联动留待后续实现。 - **地图与扫荡**:普通地图可能直接发放探索奖励,此时记录为奖励事件;进入战斗的分支才调用所选运行时。扫荡仍要求普通关卡三个难度全部通关。任务专属战斗和任务通关目标按任务路线处理,击杀缺口不靠扫荡计数。 - **中断恢复**:请求结果不明、开战后停止或运行超时时,保留本账号的待核对记录,暂停冲突操作。恢复后先刷新角色与任务;仅在新状态足以确认结果时继续,不重放未知写请求。 diff --git a/analysis/V1_2_PLAN.md b/analysis/V1_2_PLAN.md index 2b3ea60..0734df2 100644 --- a/analysis/V1_2_PLAN.md +++ b/analysis/V1_2_PLAN.md @@ -1,5 +1,13 @@ # v1.2 方案与实施状态:主线任务、普通挑战与战斗委托 +## 2026-11-08 增量收尾与下次待办 + +按用户剩余额度限制,本轮只完成短路径修改:桌面程序统一使用内置实验模拟并等待计算出的战斗时长,移除运行时选择;修复任务1002002(再次出发,0201难度1)纯显示 `buffMovie` 控制器造成的阻塞;委托按奖励氪金20→15→10排序,委托执行优先于普通策略,材料不足时接通现有扫荡/挑战来源。保留原属性、资源保护和未知结果核对机制,未执行真实游戏请求。 + +本轮定向验证:任务/编排/委托优先级141项、最终界面及配置/原自动化回归51项、战斗模型40项通过。未运行长时间原AIR试验,也未重新执行全量回归。 + +**下次继续:按委托缺口购买魔物蛋、孵化并交付的完整联动。** 先按种类统计未保护的可交付成熟魔物、正在孵化的魔物和可用蛋,库存已够时不买;仅为剩余缺口抽蛋,按服务器实际返回重新核对,够数即停。金币市场不能保证每次抽中指定蛋,需要遵守金币保留、每日额度、VIP坑位、牧场容量及保护规则,并覆盖重启恢复与普通孵蛋之间的优先级测试。此功能尚未实现,不应将本轮委托排序误解为已能自动买蛋补齐所有魔物委托。 + 状态更新: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。 diff --git a/ranch_assistant/README.md b/ranch_assistant/README.md index 2697427..82ae13b 100644 --- a/ranch_assistant/README.md +++ b/ranch_assistant/README.md @@ -91,8 +91,8 @@ 1. 登录或恢复当前角色后,进入“自动主线”,点击“刷新任务 / 预览”。“任务状态”显示类别、步骤、目标位置、需求、下一步和支持状态;选择一行可查看 NPC、对话与阻塞原因。刷新用于同步与预览,不执行任务交付或开战。 2. 打开“推进策略”,选择主线或支线、自动接取、已支持对话和补链选项。需要补齐材料、蛋或击杀时,勾选“自动收集任务材料 / 击杀目标”;来源必须符合当前位置、地图解锁、资源保护及运行时能力。 -3. 在“战斗模式(任务 / 委托)”明确选择模式,默认是“原版运行时(以能力检查为准)”。“实验模拟(近似,未完整验证)”需要手动选择;任务和委托共用此模式。选择推进战斗队伍,设置保留体力、单次交付金币上限、物品保留量和连续失败停止次数。物品、魔物交付默认关闭,金币上限默认 0。 -4. 委托仍在“自动委托”单独配置启用、接取、城市、交付限制及“也接取需要实战的委托”。“自动主线”中的“委托(仅诊断)”用于查看状态;委托执行遵循“自动委托”的规则。接取前会检查已知后续条件与战斗能力,避免接下当前无法处理的委托。 +3. 任务和委托统一使用内置模拟,无需选择运行时;保留原始属性,计算战斗过程并等待相应时长后再提交。选择推进战斗队伍,设置保留体力、单次交付金币上限、物品保留量和连续失败停止次数。物品、魔物交付默认关闭,金币上限默认 0。 +4. 委托仍在“自动委托”单独配置启用、接取、城市、交付限制及“也接取需要实战的委托”。按奖励氪金20→15→10优先接取可处理的委托,已有委托优先完成,委托步骤及材料补缺优先于普通孵蛋、赠礼、主线和刷图。缺少材料时自动选择已支持的扫荡/挑战来源,并遵守保留设置;已有足够库存则直接交付。按委托缺口买蛋、孵化、交付的完整联动尚待实现。 5. 勾选“启用自动主线策略”,再点击顶部绿色“开启”。修改规则会自动保存并应用;菜单“策略配置”可立即保存、导入或导出当前账号规则,包含任务策略与战斗模式。重启、恢复会话和导入后,顶部策略开关保持关闭,核对后再开启。 6. 在“战斗记录”查看上下文、队伍、胜负和原因;“刷新本地记录”只读取本机记录。点击顶部红色“停止”可取消后续推进和可取消的运行/时钟等待;已经发出的请求仍须等待确认,开战后的未知状态会保留待核对记录。 @@ -102,8 +102,8 @@ | 开图与收集 | 随任务目标和地图前置推进,缺少材料、蛋或已识别的成年目标击杀时规划普通地图;可能掉落只用于选择来源,实际库存与击杀仍需结算后刷新。扫荡不计作击杀来源。 | | 扫荡 | 普通、非特殊、无当前任务截获的关卡,三个难度全部通关后才可扫荡。“允许用扫荡完成已通关目标”受此条件限制;任务专属战斗和任务通关战斗仍走各自任务路线。逐关次数与难度在“自动扫荡”配置。 | | 地图奖励事件 | 普通地图开始时若已经发放探索奖励,单独记录奖励并刷新;该分支不运行战斗,也不重复提交战斗奖励。隐藏战斗重新检查能力,未知事件保留待处理。 | -| 原版运行时(默认) | 原 AIR 的合成 1-1 已通过原始战斗面板自然完成,读取实际统计与检查,样例 `cheatNum=0`。任意实际阵容桥接仍在完善;当前只允许能力检查确认的范围,尚未验证的开战会被阻止。 | -| 实验模拟(显式选择) | 独立进程使用原始数值资料计算 AP、出场、移动、攻击及技能 3、5、7、9、38 的部分机制,保留轨迹、胜负和异常。物理、随机、时序、装备及其他技能存在近似或遗漏,结果可能与原版不同。 | +| 原版内核研究工具 | 保留原 AIR 离线验证工具,不再要求桌面用户选择;最终原版集成尚待完成。 | +| 内置模拟 | 独立进程使用原始数值资料计算 AP、出场、移动、攻击及技能 3、5、7、9、38 的部分机制,保留轨迹、胜负和异常,并等待计算出的战斗时长。物理、随机、时序、装备及其他技能存在近似或遗漏,结果可能与原版不同。任务1002002所需的纯显示 `buffMovie` 控制器已支持。 | 任务资料包含 1165 个任务、1178 个关卡、337 个 NPC 和 4269 份脚本;4239 份属于已支持的线性脚本,主线引用中为 718/720。这些是资料与脚本分类数量,不是整条主线通关率。30 份特殊选择等脚本(含 2 份主线)、4 类特殊接取入口、任务1001006第4步的特殊抽蛋钩子尚不支持;活动、羁绊和未知任务类别也不承诺自动推进。 diff --git a/ranch_assistant/battle_simulator.py b/ranch_assistant/battle_simulator.py index 0706ec8..b208e30 100644 --- a/ranch_assistant/battle_simulator.py +++ b/ranch_assistant/battle_simulator.py @@ -39,7 +39,7 @@ LIMITATIONS = ( "Skill presentation callbacks are replaced with immediate model activation; AI checks use modeled cadence.", "Knockback, cosmetic equipment animations and special equipment words are omitted.", "Python seeded RNG is not the original Random helper or Math.random stream.", - "Only elimination objectives are supported; authored controllers, triggers and active field areas are rejected.", + "Only elimination objectives are supported; authored combat controllers, triggers and active field areas are rejected.", "Original cheat-check execution is incomplete; detected model anomalies are preserved, not a clean-engine verdict.", ) @@ -424,7 +424,16 @@ def _prepare(request, tables): if not isinstance(mon, Mapping): raise SimulationInputError("Enemy configuration contains a non-object monster") for controller in mon.get("controller", ()) or (): - diagnostic("unit_controller", f"Unsupported monster controller: {_get(controller, 'type', 'unknown')}", blocking=True) + kind = _get(controller, "type", "unknown") + para = _get(controller, "para") + # MonControllerBuffMovie.start -> BattleMonBuff.addBuffMov: + # a standalone aura only draws a clip; stopMove pauses the + # monster's legs. Other buff slots may share status visuals. + if (kind == "buffMovie" and isinstance(para, Mapping) + and para.get("type") == "none" and not para.get("stopMove", False)): + diagnostic("cosmetic_controller", "Cosmetic monster buffMovie animation is omitted", ignored=True) + else: + diagnostic("unit_controller", f"Unsupported monster controller: {kind}", blocking=True) if mon.get("protectTarget") or mon.get("destroyTarget"): diagnostic("unit_objective", "Protected/destroy objective units are unsupported", blocking=True) unit = _enemy(mon, dict(team, team=team_id), tables, f"configured-{ti + 1}-{mi + 1}", battle, diagnostic, master) diff --git a/ranch_assistant/engine.py b/ranch_assistant/engine.py index dd6e5f8..46b55fe 100644 --- a/ranch_assistant/engine.py +++ b/ranch_assistant/engine.py @@ -392,7 +392,7 @@ class Engine: 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, + commissions=True, accept=quest.accept, auto_farm=True, 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): @@ -417,10 +417,13 @@ class Engine: 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) + policy = self._intent_policy({"task_type_id": str(type_id)}) + ready, _, _ = self.progression_planner.requirement(self.snapshot, step, {}, policy, self.policy) if not ready: - return False + sources = self.progression_planner.farming_intents(self.snapshot, step, + {"id": 0, "typeId": str(type_id), "curStep": number}, policy, self.policy) + if not any(self._is_sweep_intent(source) or self._battle_capability(source)[0] for source in sources): + return False return bool(info.get("steps")) def _refresh_progression_cache(self, *, force=False): @@ -443,6 +446,7 @@ class Engine: 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) + intents.sort(key=lambda intent: not self._is_commission(intent)) 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), @@ -716,7 +720,9 @@ class Engine: except (ValueError, TypeError, KeyError, AttributeError) as error: self.auto = False return self.snapshot, [], "状态已读取;策略暂不可用:" + str(error) - actions = self.pending_hatches if hatch_only else plans + commission_actions = [action for action in plans if action.kind.startswith("quest_") or + action.kind == "progression" and self._is_commission(action.payload["intent"])] + actions = (commission_actions or self.pending_hatches) if hatch_only else plans action = actions[0] if actions else None if action and defer_hatch and action.kind == "hatch": action = None @@ -819,9 +825,11 @@ class Engine: self.planner.notes.extend(self.gift_planner.notes) 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] + commission = [action for action in progression if self._is_commission(action.payload["intent"])] + progression = [action for action in progression if not self._is_commission(action.payload["intent"])] 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 + return quests + commission[:1] + daily + progression[:1] + gifts + ranch + sweep_actions + return commission[:1] + quests + daily + progression[:1] + gifts + ranch + sweep_actions @account_serial def claim_daily_entry(self, entry): diff --git a/ranch_assistant/gui.py b/ranch_assistant/gui.py index c8ce896..6ca6bb5 100644 --- a/ranch_assistant/gui.py +++ b/ranch_assistant/gui.py @@ -832,7 +832,7 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow): tab.setLayout(layout) form = W.QFormLayout() self.quest_enabled = W.QCheckBox("启用委托自动接取 / 推进 / 领奖") - self.quest_accept = W.QCheckBox("自动接取条件已满足的委托") + self.quest_accept = W.QCheckBox("按氪金奖励优先接取(20 → 15 → 10)") self.quest_accept.setChecked(True) self.quest_city = spin(0, 99, 0) self.quest_items = W.QCheckBox("允许提交道具(遵守保留数量)") @@ -847,7 +847,7 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow): layout.addLayout(form) self.quest_summary = W.QLabel() layout.addWidget(self.quest_summary) - note = W.QLabel("当前支持按实际库存/等级/击杀进度推进非战斗步骤并领奖;战斗和剧情步骤会显示所需内容。\n实战委托须由游戏正常完成战斗;程序不会提交虚构胜利。每日接取次数来自角色数据。") + note = W.QLabel("优先完成已接委托,按奖励氪金数量从高到低接取可完成的委托。缺少材料时优先从已支持的扫荡或挑战来源获取,遵守体力和物品保留设置。\n需要战斗的委托使用内置模拟计算,当前未支持的战斗会显示原因。按委托缺口自动购买并孵化魔物蛋的联动尚待实现。每日接取次数来自角色数据。") note.setWordWrap(True) layout.addWidget(note) self.quests_table = table(["委托编号", "名称", "状态", "奖励金币", "奖励氪金", "需求 / 进度"]) diff --git a/ranch_assistant/progression.py b/ranch_assistant/progression.py index a13ca94..a601121 100644 --- a/ranch_assistant/progression.py +++ b/ranch_assistant/progression.py @@ -45,7 +45,7 @@ import uuid from .game_data import ProgressionData, load_progression_data from .model import Planner, seconds -from .quests import indexed, stage_has_level +from .quests import commission_priority, indexed, stage_has_level CATEGORIES = {1: ("mainline", "主线"), 2: ("sidequest", "支线"), @@ -765,7 +765,7 @@ class ProgressionPlanner: def _commission_policy(self, quest_policy, battle_policy=None): base = battle_policy or ProgressionPolicy() return replace(base, enabled=bool(quest_policy.enabled), mainline=False, sidequests=False, - commissions=True, accept=bool(quest_policy.accept), repair_chain=False, + commissions=True, accept=bool(quest_policy.accept), repair_chain=False, auto_farm=True, allow_items=bool(quest_policy.allow_items), allow_monsters=bool(quest_policy.allow_monsters), max_money=quest_policy.max_money, item_reserves=dict(quest_policy.item_reserves)) @@ -878,7 +878,7 @@ class ProgressionPlanner: return [action] active, _, finished = self._tasks(snapshot, account) blocked = [] - for key, task in active.items(): + for key, task in sorted(active.items(), key=lambda pair: commission_priority(self.data.task(pair[0]) or {})): info = self.data.task(key) if not info or info.get("type") != 4 or key in finished: continue @@ -889,23 +889,24 @@ class ProgressionPlanner: self._issued[candidate.token] = candidate.to_dict() return actions blocked.append(action) - if not quest_policy.accept or remaining <= 0: + if blocked or not quest_policy.accept or remaining <= 0: return blocked - for city, values in sorted(offers.items()): + ranked_offers = sorted(((city, key) for city, values in offers.items() for key in _values(values)), + key=lambda pair: commission_priority(self.data.task(str(pair[1])) or {})) + for city, offered_key in ranked_offers: city = _integer(city) if city <= 0 or quest_policy.city and city != quest_policy.city or not snapshot.city_unlocked(city): continue - for key in _values(values): - key, info = str(key), self.data.task(key) - if key in active or key in finished or not info or info.get("type") != 4: - continue - if not self._commission_offer_ready(snapshot, quest_policy, policy, ranch_policy, info)[0]: - continue - action = self._intent(scope, {"id": 0, "typeId": key}, 0, info.get("startStep") or {}, - "progression_loop_accept", "接取城市委托:" + info.get("name", key), policy, - path="taskService/taskLoopReceive", payload={"taskTypeId": key, "city": city}, phase=str(today)) - self._issued[action.token] = action.to_dict() - return [action] + key, info = str(offered_key), self.data.task(offered_key) + if key in active or key in finished or not info or info.get("type") != 4: + continue + if not self._commission_offer_ready(snapshot, quest_policy, policy, ranch_policy, info)[0]: + continue + action = self._intent(scope, {"id": 0, "typeId": key}, 0, info.get("startStep") or {}, + "progression_loop_accept", "接取城市委托:" + info.get("name", key), policy, + path="taskService/taskLoopReceive", payload={"taskTypeId": key, "city": city}, phase=str(today)) + self._issued[action.token] = action.to_dict() + return [action] return blocked def commission_rows(self, snapshot, quest_policy, ranch_policy, *, battle_policy=None): diff --git a/ranch_assistant/progression_gui.py b/ranch_assistant/progression_gui.py index 24112d5..d9165da 100644 --- a/ranch_assistant/progression_gui.py +++ b/ranch_assistant/progression_gui.py @@ -228,13 +228,12 @@ class ProgressionPages: "仍受任务规则、战斗能力、保留体力和顶部“开启 / 停止”限制;无法匹配的目标会显示原因。") form.addRow("任务目标", self.progression_auto_farm) self.progression_commissions.setToolTip("委托交付由“自动委托”页独立配置;此项只纳入任务诊断,不开启委托执行") - self.progression_battle_mode = ComboBox() + # Keep the combo for existing config/autosave glue; the GUI always simulates. + self.progression_battle_mode = ComboBox(settings) 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_battle_mode.setCurrentIndex(self.progression_battle_mode.findData("experimental")) + self.progression_battle_mode.hide() self.progression_team = ComboBox() for team in ("teamA", "teamB", "teamC"): self.progression_team.addItem(team, team) @@ -314,7 +313,10 @@ class ProgressionPages: value = {} for key, default in asdict(ProgressionPolicy()).items(): widget = getattr(self, "progression_" + key) - if key == "item_reserves": + if key == "battle_mode": + # Legacy GUI glue may restore the hidden combo after loading. + value[key] = "experimental" + elif key == "item_reserves": reserves = {} for entry in widget.text().split(","): if entry.strip(): @@ -329,6 +331,8 @@ class ProgressionPages: def load_progression_policy(self, policy): for key, value in asdict(policy).items(): + if key == "battle_mode": + value = "experimental" widget = getattr(self, "progression_" + key) blocker = C.QSignalBlocker(widget) if key == "item_reserves": @@ -377,8 +381,7 @@ class ProgressionPages: 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, "未选择,请检查策略") + text += ";战斗按原始属性进行实验模拟,等待计算出的战斗时长后提交(近似推演,结果以实际记录为准)" if not callable(getattr(self.engine, "refresh_progression", None)): text += ";当前引擎尚未接入任务刷新" if not callable(getattr(self.engine, "run_progression_once", None)): diff --git a/ranch_assistant/quests.py b/ranch_assistant/quests.py index 2837179..1c44b74 100644 --- a/ranch_assistant/quests.py +++ b/ranch_assistant/quests.py @@ -7,6 +7,14 @@ from .model import Action, Planner, seconds CN = timezone(timedelta(hours=8)) +def commission_priority(info): + try: + reward = int((info.get("reward") or {}).get("ke") or 0) + except (TypeError, ValueError): + reward = 0 + return -reward + + def indexed(value, key, default=None): if isinstance(value, dict): return value.get(str(key), value.get(key, default)) @@ -161,7 +169,9 @@ 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) if include_active else []: + current_tasks = sorted(self.current(snapshot), key=lambda task: commission_priority( + self.catalog.data["task_info"][str(task["typeId"])])) if include_active else [] + for task in current_tasks: 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"])} @@ -171,10 +181,12 @@ class TaskPlanner: ready, ids, _ = self.requirement(snapshot, steps[index], task, policy, ranch) if ready: return [Action("quest_step", f"推进委托:{info['name']}", "taskService/taskCompleteStep", payload | {"removeIds": ids or None})] - if not policy.accept or int(history.get("loopTaskNum", 0)) <= 0: + if current_tasks or not policy.accept or int(history.get("loopTaskNum", 0)) <= 0: return [] current = {str(t["typeId"]) for t in self.current(snapshot)} - for type_id, name, state, _, meta in self.rows(snapshot, policy, ranch): + offers = sorted(self.rows(snapshot, policy, ranch), key=lambda row: commission_priority( + self.catalog.data["task_info"][row[0]])) + for type_id, name, state, _, meta in offers: if "city" not in meta or type_id in current: continue city = meta["city"] diff --git a/ranch_assistant/tests/test_battle_simulator.py b/ranch_assistant/tests/test_battle_simulator.py index b71b6da..8127af6 100644 --- a/ranch_assistant/tests/test_battle_simulator.py +++ b/ranch_assistant/tests/test_battle_simulator.py @@ -12,7 +12,7 @@ import unittest from unittest.mock import patch from ranch_assistant.battle_simulator import ( - ExperimentalBattleRuntime, ORIGINAL_APK_SHA256, Stats, _offline_audit, + ExperimentalBattleRuntime, ORIGINAL_APK_SHA256, Stats, _offline_audit, _plain, combat_battles, combat_tables, damage_roll, simulate, ) @@ -262,6 +262,50 @@ class SimulatorTests(unittest.TestCase): self.assertEqual(result["kill_monster"], {}) # Original stage enemies are mode 1. self.assertTrue(any(e["type"] == "wave" for e in result["events"])) + def test_task1002002_lianlake_admits_original_cosmetic_controllers(self): + corpus = combat_battles() + step = corpus["task_info"]["1002002"]["steps"][0] + self.assertEqual(step["statusType"], "passStage") + stage, level = step["statusValue"]["stage"], step["statusValue"]["level"] + self.assertEqual((stage, level), ("0201", "1")) + req = request(context="task_pass_stage", battle_position={ + "battleType": "stage", "stageId": stage, "stageLevel": level, + "taskTypeId": "1002002", "taskStep": 0}) + req["original_data"]["battle"] = _plain(corpus["stage_info"][stage]["level"][level]["battle"]) + before = deepcopy(req) + baseline = deepcopy(req) + for team in battle_of(baseline)["teams"]: + for mon in team["mons"]: + mon["controller"] = [] + with patch("socket.socket", side_effect=AssertionError("No network")), \ + patch("zipfile.ZipFile", side_effect=AssertionError("No APK access")): + report = ExperimentalBattleRuntime().inspect(req) + self.assertTrue(report["supported"], report["reasons"]) + result, reference = simulate(req), simulate(baseline) + self.assertEqual(result["execution_status"], "completed") + self.assertTrue(result["requires_realtime_wait"]) + self.assertTrue(any(d["code"] == "cosmetic_controller" for d in result["diagnostics"])) + for key in ("events", "elapsed_ms", "units", "battle_data", "anomalies"): + self.assertEqual(result[key], reference[key], key) + self.assertEqual(report["units"][1]["stats"]["atk"], 80) + self.assertEqual(report["units"][1]["stats"]["hp"], 1100) + self.assertEqual(req, before) + + def test_buff_movie_cannot_bypass_substantive_or_unknown_controller_rejection(self): + for controller in ( + {"type": "buffMovie", "para": {"type": "none", "stopMove": True}}, + {"type": "buffMovie", "para": {"type": "stun"}}, + {"type": "buffMovie", "para": None}, + {"type": "buffMovie"}, + {"type": "buff", "para": {"type": "none"}}, + {"type": "unknown", "para": {"type": "none"}}, + ): + with self.subTest(controller=controller): + result = simulate(request(enemies=[enemy(controller=[controller])])) + self.assertEqual(result["outcome"], "unsupported") + self.assertIsNone(result["battle_data"]) + self.assertIn("Unsupported monster controller: " + controller["type"], result["reasons"]) + 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) diff --git a/ranch_assistant/tests/test_commission_priority.py b/ranch_assistant/tests/test_commission_priority.py new file mode 100644 index 0000000..1356f45 --- /dev/null +++ b/ranch_assistant/tests/test_commission_priority.py @@ -0,0 +1,73 @@ +from types import SimpleNamespace +import unittest +from unittest.mock import Mock + +from ranch_assistant.engine import Engine, demo_snapshot +from ranch_assistant.model import Catalog, Policy +from ranch_assistant.progression import ProgressionPlanner +from ranch_assistant.quests import QuestPolicy, TaskPlanner +from ranch_assistant.tests.test_progression import config, snapshot, step, task + + +class CommissionPriorityTests(unittest.TestCase): + def setUp(self): + self.catalog = Catalog() + self.tasks = {str(400 + i): task(str(400 + i), type=4, reward={"ke": reward}) + for i, reward in enumerate((10, 15, 20))} + self.snapshot = snapshot(currentTasks=[]) + self.snapshot.raw["history"].update(loopTaskTime=self.snapshot.now, loopTaskNum=6, + loopTask={"1": ["400", "401"], "2": ["402"]}, unlockCity={"1": True, "2": True}) + self.quest = QuestPolicy(enabled=True) + self.ranch = Policy() + + def test_reward_ranking_across_cities_and_fallback_when_unavailable(self): + planner = ProgressionPlanner(self.catalog, config(self.tasks)) + self.assertEqual(planner.commission_plan(self.snapshot, self.quest, self.ranch)[0].task_type_id, "402") + self.tasks["402"]["closed"] = True + planner = ProgressionPlanner(self.catalog, config(self.tasks)) + self.assertEqual(planner.commission_plan(self.snapshot, self.quest, self.ranch)[0].task_type_id, "401") + self.quest.city = 1 + self.assertEqual(planner.commission_plan(self.snapshot, self.quest, self.ranch)[0].payload["city"], 1) + + def test_legacy_planner_uses_same_reward_order(self): + self.catalog.data["task_info"] = self.tasks + action = TaskPlanner(self.catalog).plan(self.snapshot, self.quest, self.ranch)[0] + self.assertEqual(action.payload["taskTypeId"], "402") + + def test_active_commission_precedes_new_offer(self): + self.tasks["400"]["steps"] = [step("passLevel", statusValue={"level": 99})] + self.snapshot.raw["currentTasks"] = [{"id": 50, "typeId": "400", "curStep": 1}] + planner = ProgressionPlanner(self.catalog, config(self.tasks)) + actions = planner.commission_plan(self.snapshot, self.quest, self.ranch) + self.assertTrue(actions[0].blocked) + self.assertFalse(any(action.kind == "progression_loop_accept" for action in actions)) + + def test_commission_execution_precedes_mainline_and_ranch(self): + engine = Engine(self.catalog) + engine.snapshot = demo_snapshot(self.catalog) + engine.progression_policy.enabled = engine.quest_policy.enabled = True + engine._commission_planner_available = True + engine.game_data = SimpleNamespace(task=lambda key: {"type": 4 if key == "400" else 1}) + engine._progression_intents = [ + {"kind": "progression_step", "task_type_id": key, "description": key} + for key in ("100", "400")] + self.assertEqual(engine.plans()[0].payload["intent"]["task_type_id"], "400") + self.assertTrue(engine._intent_policy({"task_type_id": "400"}).auto_farm) + + def test_material_shortage_uses_supported_farming_source(self): + self.quest.allow_items = True + self.tasks["400"]["steps"] = [step("getItem", statusValue={"type": "30001", "num": 3, "remove": True})] + engine = Engine(self.catalog) + engine.snapshot = self.snapshot + engine.quest_policy = self.quest + engine.game_data = SimpleNamespace(task=self.tasks.get) + engine.progression_planner = Mock() + engine.progression_planner.requirement.return_value = (False, [], "missing") + engine.progression_planner.farming_intents.return_value = [{"kind": "sweep"}] + self.assertTrue(engine._commission_offer_supported("400")) + engine.progression_planner.farming_intents.return_value = [] + self.assertFalse(engine._commission_offer_supported("400")) + + +if __name__ == "__main__": + unittest.main() diff --git a/ranch_assistant/tests/test_progression_gui.py b/ranch_assistant/tests/test_progression_gui.py index 6e93425..00d045b 100644 --- a/ranch_assistant/tests/test_progression_gui.py +++ b/ranch_assistant/tests/test_progression_gui.py @@ -318,9 +318,14 @@ class ProgressionGuiTests(unittest.TestCase): 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.assertEqual(window.progression_battle_mode.currentData(), "experimental") + self.assertEqual(window.engine.progression_policy.battle_mode, "experimental") + self.assertTrue(window.progression_battle_mode.isHidden()) + settings = window.progression_tabs.widget(1).widget() + self.assertEqual(settings.layout().indexOf(window.progression_battle_mode), -1) + self.assertFalse(any("战斗模式" in label.text() for label in settings.findChildren(W.QLabel))) + for text in ("原始属性", "实验模拟", "战斗时长后提交", "近似", "实际记录"): + self.assertIn(text, window.progression_status.text()) 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) @@ -364,7 +369,7 @@ class ProgressionGuiTests(unittest.TestCase): self.wait(first) self.wait(second) self.assertEqual(asdict(first.read_progression_policy()), expected) - self.assertEqual(asdict(second.read_progression_policy()), asdict(ProgressionPolicy())) + self.assertEqual(asdict(second.read_progression_policy()), asdict(ProgressionPolicy()) | {"battle_mode": "experimental"}) self.assertFalse(first.strategy_toggle.isChecked()) self.assertFalse(second.strategy_toggle.isChecked()) finally: @@ -396,15 +401,21 @@ class ProgressionGuiTests(unittest.TestCase): finally: window.close() - def test_battle_mode_autosaves_without_starting_and_reaches_worker_policy(self): + def test_legacy_original_mode_normalizes_for_autosave_and_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")) + legacy = asdict(configured_policy()) | {"battle_mode": "original"} + window.load_config(window.config_value() | {"progression_policy": legacy}) + self.assertEqual(window.progression_battle_mode.currentData(), "experimental") + self.assertEqual(asdict(window.read_progression_policy()), asdict(configured_policy())) + self.assertEqual(legacy["battle_mode"], "original") + # Older GUI glue can write the hidden field again after load_config. + window.progression_battle_mode.setCurrentIndex(window.progression_battle_mode.findData("original")) + self.assertEqual(window.read_progression_policy().battle_mode, "experimental") QTest.qWait(350) self.wait(window) saved = json.loads((folder / "settings.json").read_text(encoding="utf-8")) @@ -418,7 +429,7 @@ class ProgressionGuiTests(unittest.TestCase): observations = [] def preview(): observations.append((window.engine.progression_policy.battle_mode, C.QThread.currentThread())) - return window.engine.snapshot, [], "已预览所选战斗模式" + return window.engine.snapshot, [], "已预览模拟战斗策略" window.engine.refresh_progression = Mock(side_effect=preview) window.refresh_progression() self.wait(window) @@ -428,6 +439,33 @@ class ProgressionGuiTests(unittest.TestCase): finally: window.close() + def test_saved_original_and_missing_modes_load_as_experimental_without_starting(self): + for mode in ("original", None): + with self.subTest(mode=mode), workspace_temp() as folder: + legacy = asdict(configured_policy()) + if mode is None: + del legacy["battle_mode"] + else: + legacy["battle_mode"] = mode + path = folder / "settings.json" + path.write_text(json.dumps({"progression_policy": legacy}), encoding="utf-8") + window = gui.Window(folder) + window.timer.stop() + try: + window.engine.run_progression_once = Mock() + self.wait(window) + self.assertEqual(window.progression_battle_mode.currentData(), "experimental") + self.assertTrue(window.progression_battle_mode.isHidden()) + self.assertEqual(asdict(window.read_progression_policy()), asdict(configured_policy())) + self.assertEqual(asdict(window.engine.progression_policy), asdict(configured_policy())) + window.persist_settings() + self.assertEqual(json.loads(path.read_text(encoding="utf-8"))["progression_policy"], asdict(configured_policy())) + self.assertFalse(window.strategy_toggle.isChecked()) + self.assertFalse(window.engine.auto) + window.engine.run_progression_once.assert_not_called() + finally: + window.close() + def test_additional_and_unavailable_teams_round_trip_visibly_without_starting(self): with workspace_temp() as folder: window = gui.Window(folder) @@ -710,17 +748,22 @@ class ProgressionGuiTests(unittest.TestCase): def test_experimental_record_outcomes_keep_their_approximate_label(self): records = [ {"battle_mode": "experimental", "faithful": False, "approximate": True, "outcome": "win"}, + {"battle_mode": "experimental", "outcome": "loss"}, + {"execution_mode": "experimental", "outcome": "unsupported", "reason": "能力检查未通过"}, {"battle_mode": "original", "outcome": "win"}, {"outcome": "win"}, ] + original = copy.deepcopy(records) 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") + for row, outcome in zip(rows, ("胜利", "战败", "暂不支持")): + self.assertEqual(row["values"][4], outcome + "(实验近似)") + self.assertIn("近似,未完整验证", row["detail"]) + self.assertIn("能力检查未通过", rows[2]["detail"]) + self.assertEqual(rows[3]["values"][4], "胜利") + self.assertIn("原版运行时", rows[3]["detail"]) + self.assertIn("记录未标明", rows[4]["detail"]) + self.assertEqual(records, original) def test_repeated_sorted_table_updates_do_not_reinsert_owned_items(self): table = CachedTable(["编号", "名称"])