Add simulated challenges to selected uncleared maps

This commit is contained in:
AttilaNet
2026-11-09 08:11:57 +08:00
parent df0259febf
commit f9631c3363
11 changed files with 628 additions and 47 deletions
+2 -2
View File
@@ -31,7 +31,7 @@
| 自动主线 | 展示主线、支线、委托的状态、位置、NPC、需求、对话和阻塞原因;推进已支持的接取、线性对话、交付、领奖与任务补链。材料、蛋或击杀不足时,按已知来源规划普通地图收集;开图受前置、资源和战斗能力限制。 | | 自动主线 | 展示主线、支线、委托的状态、位置、NPC、需求、对话和阻塞原因;推进已支持的接取、线性对话、交付、领奖与任务补链。材料、蛋或击杀不足时,按已知来源规划普通地图收集;开图受前置、资源和战斗能力限制。 |
| 自动委托 | 根据每日剩余次数、城市与库存接取委托,推进已支持的步骤并领奖;显示金币和氪金奖励,金币、道具及魔物提交可分别限制。实战委托已接入任务战斗调度,须开启对应选项并通过所选模式的能力检查;设置仍在“自动委托”。 | | 自动委托 | 根据每日剩余次数、城市与库存接取委托,推进已支持的步骤并领奖;显示金币和氪金奖励,金币、道具及魔物提交可分别限制。实战委托已接入任务战斗调度,须开启对应选项并通过所选模式的能力检查;设置仍在“自动委托”。 |
| 战斗模式与记录 | “自动主线 → 推进策略”显式选择原版运行时(默认)或实验模拟(近似);按普通地图、任务专属战斗、任务通关战斗分别编排。记录胜负、模式、地图奖励事件和待核对原因,支持停止与中断恢复;局部能力不代表全部关卡可用。 | | 战斗模式与记录 | “自动主线 → 推进策略”显式选择原版运行时(默认)或实验模拟(近似);按普通地图、任务专属战斗、任务通关战斗分别编排。记录胜负、模式、地图奖励事件和待核对原因,支持停止与中断恢复;局部能力不代表全部关卡可用。 |
| 自动扫荡 | 按地区折叠显示关卡、难度、通关星级及可能掉落;账号地图首次读取后本地缓存,仅手动刷新关卡时重新获取。逐关勾选、选择已解锁难度和本日次数上限,配置保留体力与战队;处理普通扫荡及探索奖励事件,记录实际奖励。 | | 自动扫荡与挑战 | 按地区折叠显示关卡、难度、通关星级及可能掉落;账号地图本地缓存,手动刷新或挑战结束后同步进度。逐关勾选、选择已解锁难度和本日次数上限,配置保留体力与战队;满足扫荡条件时扫荡,未满星时可自动模拟挑战,战败显示“打不过”,支持探索奖励事件。 |
| 掉落数据分析 | 按账号、关卡与难度在本地保存扫荡记录,分别统计普通扫荡、奖励事件或合计;展示样本数、出现次数、总数量、实测掉落率、平均数量和95%区间。支持掉落率/每点体力获得数量的条形图,不额外请求游戏服务器。 | | 掉落数据分析 | 按账号、关卡与难度在本地保存扫荡记录,分别统计普通扫荡、奖励事件或合计;展示样本数、出现次数、总数量、实测掉落率、平均数量和95%区间。支持掉落率/每点体力获得数量的条形图,不额外请求游戏服务器。 |
| 收益资料与执行计划 | 内置749种魔物的培育时间、派遣金币、强化经验及每小时收益,支持名称/星级筛选和CSV/XLSX覆盖;执行计划显示下一步操作与等待原因。 | | 收益资料与执行计划 | 内置749种魔物的培育时间、派遣金币、强化经验及每小时收益,支持名称/星级筛选和CSV/XLSX覆盖;执行计划显示下一步操作与等待原因。 |
| 统一策略配置 | 规则修改后自动保存并应用;通过原生菜单保存、导入或导出当前账号的孵蛋、牧场、喂养、赠礼、委托、每日事务、扫荡、主线推进、战斗模式、刷新间隔及自定义收益资料。跨账号按魔物种类匹配培养目标,导出文件不包含账号凭据或服务器进度。 | | 统一策略配置 | 规则修改后自动保存并应用;通过原生菜单保存、导入或导出当前账号的孵蛋、牧场、喂养、赠礼、委托、每日事务、扫荡、主线推进、战斗模式、刷新间隔及自定义收益资料。跨账号按魔物种类匹配培养目标,导出文件不包含账号凭据或服务器进度。 |
@@ -44,7 +44,7 @@
- **内置战斗模拟**:无需选择运行时,程序使用原始数值资料,在独立进程中计算 AP、出场、移动、攻击和部分技能,等待计算出的战斗时长后提交结果。模型仍有机制近似与遗漏,可能和原版胜负不同,未支持的战斗会显示原因。 - **内置战斗模拟**:无需选择运行时,程序使用原始数值资料,在独立进程中计算 AP、出场、移动、攻击和部分技能,等待计算出的战斗时长后提交结果。模型仍有机制近似与遗漏,可能和原版胜负不同,未支持的战斗会显示原因。
- **委托优先**:按奖励氪金数量20→15→10接取可处理的委托,优先执行委托步骤和材料补缺,再处理主线及普通牧场策略。缺少材料时使用现有扫荡/挑战来源;按委托缺口自动购买并孵化魔物蛋的联动留待后续实现。 - **委托优先**:按奖励氪金数量20→15→10接取可处理的委托,优先执行委托步骤和材料补缺,再处理主线及普通牧场策略。缺少材料时使用现有扫荡/挑战来源;按委托缺口自动购买并孵化魔物蛋的联动留待后续实现。
- **地图与扫荡**:普通地图可能直接发放探索奖励,此时记录为奖励事件;进入战斗的分支才调用所选运行时。扫荡仍要求普通关卡三个难度全部通关。任务专属战斗和任务通关目标按任务路线处理,击杀缺口不靠扫荡计数。 - **地图与扫荡**:在“自动扫荡”勾选“未满星时自动挑战”,已解锁普通关卡可使用内置模拟首次挑战,无需开启自动主线;满足三个难度全部通关的条件后自动使用扫荡。普通地图直接发放探索奖励时按事件处理;当前任务占用的关卡交由自动主线处理。
- **中断恢复**:后台最长每2分钟自动核对角色与任务。模型已完成、等待时长被中断且结算从未发出的记录,在策略开启后自动续交保存的胜利结果;不重新开战或模拟。已经发出但结果不明的写请求不重发,继续核对服务器状态。 - **中断恢复**:后台最长每2分钟自动核对角色与任务。模型已完成、等待时长被中断且结算从未发出的记录,在策略开启后自动续交保存的胜利结果;不重新开战或模拟。已经发出但结果不明的写请求不重发,继续核对服务器状态。
详细设置、能力限制与恢复方法见[辅助使用说明](ranch_assistant/README.md#v12-自动主线与战斗设置);阶段证据及待验收事项见[v1.2 实施与交接](analysis/V1_2_IMPLEMENTATION.md)。当前仍为开发版,尚未发布 v1.2 正式标签。 详细设置、能力限制与恢复方法见[辅助使用说明](ranch_assistant/README.md#v12-自动主线与战斗设置);阶段证据及待验收事项见[v1.2 实施与交接](analysis/V1_2_IMPLEMENTATION.md)。当前仍为开发版,尚未发布 v1.2 正式标签。
+8
View File
@@ -1,5 +1,13 @@
# v1.2 方案与实施状态:主线任务、普通挑战与战斗委托 # v1.2 方案与实施状态:主线任务、普通挑战与战斗委托
## 2026-11-09 自动扫荡页接入普通挑战
新增默认开启的“未满星时自动挑战”开关,沿用勾选关卡、所选战队、保留体力与本日次数上限。满足原有扫荡条件时继续扫荡,其余已解锁、开放且无当前任务拦截的普通关卡接入现有内置模拟、战斗时钟及普通结算流程,不需要自动主线策略。未实现新的保护/摧毁目标或特殊控制器;未支持原因保持中文显示,实际战败显示“打不过”。
战败结果按账号、日期、关卡难度和队伍属性摘要持久保存,暂停同阵容的重复尝试,阵容或属性改变后允许重试;地图挑战战败不增加自动主线的失败计数。每日次数在开战前记账,确定未发出的取消退回次数。普通挑战保存结果的时钟中断,以及结算已确认但尚未写战果记录的重启场景可恢复,不重复开战、模拟、结算或次数记账;未知写请求仍只查询核对。普通轮询继续使用地图缓存,已确认的挑战或奖励事件完成后更新实际进度。
新增14项普通挑战调度测试,覆盖胜负、事件、次数、资源和当前任务拦截、停止与恢复、不确定结算及多关卡候选跳过,并通过已有战斗编排、扫荡、地图缓存、策略配置和界面定向回归。验证使用本地模拟服务及运行时替身,未执行真实游戏账号请求。
## 2026-11-08 增量收尾与下次待办 ## 2026-11-08 增量收尾与下次待办
委托调度修复:实际战斗能力检查移入奖励排序的候选选择过程,跳过不支持的高奖励委托后继续查找其他可完成候选,避免首个候选阻塞全部接取。自动委托页同步显示缓存的中文阻塞原因。两个本地账号快照在全启用配置下离线回放,分别选择到可处理的10氪金与20氪金委托,未执行真实接取请求。 委托调度修复:实际战斗能力检查移入奖励排序的候选选择过程,跳过不支持的高奖励委托后继续查找其他可完成候选,避免首个候选阻塞全部接取。自动委托页同步显示缓存的中文阻塞原因。两个本地账号快照在全启用配置下离线回放,分别选择到可处理的10氪金与20氪金委托,未执行真实接取请求。
+4 -2
View File
@@ -70,7 +70,7 @@
- 自动扫荡:按地区分组,默认折叠显示关卡、难度、掉落及账号解锁/通关记录。 - 自动扫荡:按地区分组,默认折叠显示关卡、难度、掉落及账号解锁/通关记录。
首次读取后按账号/角色保存本地地图缓存,重启、切换页面或普通监控刷新均复用缓存,仅“刷新关卡”(或本页右键刷新)更新列表。 首次读取后按账号/角色保存本地地图缓存,重启、切换页面或普通监控刷新均复用缓存,仅“刷新关卡”(或本页右键刷新)更新列表。
每关可勾选、选择已解锁难度和本日上限;满足游戏原有条件的普通关卡可接口扫荡, 每关可勾选、选择已解锁难度和本日上限;满足游戏原有条件的普通关卡可接口扫荡,
首次挑战由任务与战斗调度按能力检查处理;未支持内容等待用户在游戏内处理。 “未满星时自动挑战”默认开启,勾选已解锁普通关卡后可模拟首次挑战;符合三个难度全部通关条件后使用扫荡。打不过会暂停同一队伍的重复尝试,换队或提升属性后再试;未支持的规则显示中文原因。
- 战斗记录:按上下文筛选普通地图、主线、任务与委托战斗、扫荡和地图奖励事件;实验模型结果标明“实验近似”,未知结果保留待核对原因。 - 战斗记录:按上下文筛选普通地图、主线、任务与委托战斗、扫荡和地图奖励事件;实验模型结果标明“实验近似”,未知结果保留待核对原因。
- 扫荡奖励:普通扫荡读取 `battleEnd.reward`,奖励事件读取 `stageEvent.result`,日志列出本次实际获得的物品、魔物蛋、金币和经验。 - 扫荡奖励:普通扫荡读取 `battleEnd.reward`,奖励事件读取 `stageEvent.result`,日志列出本次实际获得的物品、魔物蛋、金币和经验。
- 数据分析:紧邻“自动扫荡”的独立页签。左侧按地区选择关卡和难度,右侧显示条形图与掉落明细;关卡和可能掉落来自本地静态配置。 - 数据分析:紧邻“自动扫荡”的独立页签。左侧按地区选择关卡和难度,右侧显示条形图与掉落明细;关卡和可能掉落来自本地静态配置。
@@ -300,7 +300,9 @@
普通、非剧情定位关卡的三个难度全部通关后才开放扫荡,无需本地战斗演算或手机截图。首次挑战、任务专属战斗与扫荡分别处理,当前可执行范围见上方能力表。客户端调用链与字段证据见[地图及每日事务研究](../analysis/STAGES_DAILY.md)和[战斗路线说明](../analysis/V1_2_IMPLEMENTATION.md#调度与恢复约定)。 普通、非剧情定位关卡的三个难度全部通关后才开放扫荡,无需本地战斗演算或手机截图。首次挑战、任务专属战斗与扫荡分别处理,当前可执行范围见上方能力表。客户端调用链与字段证据见[地图及每日事务研究](../analysis/STAGES_DAILY.md)和[战斗路线说明](../analysis/V1_2_IMPLEMENTATION.md#调度与恢复约定)。
在“自动扫荡”展开地区,每关勾选“刷图”、选择难度、输入“本日上限”,勾选该页功能,再开启顶部策略开关。 在“自动扫荡”展开地区,每关勾选“刷图”、选择已解锁的难度、输入“本日上限”,勾选该页功能,再开启顶部策略开关。需要挑战未通关普通关卡时保留“未满星时自动挑战”勾选;关闭后只执行符合条件的扫荡,无需开启自动主线。
挑战沿用原始属性和内置模拟,等待计算出的战斗时长后按普通关卡流程结算,战果与奖励在“战斗记录”查看。实际战败显示“打不过”,本日内相同阵容及属性不会反复尝试该难度;更换战队、升级或属性变化后允许再试。每日次数与扫荡共用,开战前占用次数,确定未发送的取消会退回次数;未知回包不重复请求。暂停或重启后可续交已完成并保存的模型结果,保持原始开战和每日计数。地图列表保存在本地,普通轮询不重建;挑战已确认结束后同步账号实际通关进度。
星级是服务器通关进度计算出来的,只读。未解锁难度不能选;特殊关卡、未全通关、剧情任务、 星级是服务器通关进度计算出来的,只读。未解锁难度不能选;特殊关卡、未全通关、剧情任务、
体力/金币/门票不足的关卡会显示原因并跳过。次数按角色、日期、关卡和难度保存, 体力/金币/门票不足的关卡会显示原因并跳过。次数按角色、日期、关卡和难度保存,
是本地已开始次数,不冒充服务器每日限制。 是本地已开始次数,不冒充服务器每日限制。
+27 -7
View File
@@ -34,12 +34,15 @@ class ActivityPages:
line.addWidget(button) line.addWidget(button)
layout.addLayout(line) layout.addLayout(line)
line = W.QHBoxLayout() line = W.QHBoxLayout()
self.map_enabled = W.QCheckBox("启用勾选关卡的自动扫荡") self.map_enabled = W.QCheckBox("启用勾选关卡自动刷图")
self.map_allow_challenge = W.QCheckBox("未满星时自动挑战")
self.map_allow_challenge.setChecked(True)
self.map_keep_ti = number(0) self.map_keep_ti = number(0)
self.map_team = ComboBox() self.map_team = ComboBox()
for name in ("teamA", "teamB", "teamC"): for name in ("teamA", "teamB", "teamC"):
self.map_team.addItem(name, name) self.map_team.addItem(name, name)
line.addWidget(self.map_enabled) line.addWidget(self.map_enabled)
line.addWidget(self.map_allow_challenge)
line.addWidget(W.QLabel("保留体力")) line.addWidget(W.QLabel("保留体力"))
line.addWidget(self.map_keep_ti) line.addWidget(self.map_keep_ti)
line.addWidget(W.QLabel("使用战队")) line.addWidget(W.QLabel("使用战队"))
@@ -53,7 +56,7 @@ class ActivityPages:
self.maps_summary.setWordWrap(True) self.maps_summary.setWordWrap(True)
layout.addWidget(self.maps_summary) layout.addWidget(self.maps_summary)
self.maps_tree = W.QTreeWidget() self.maps_tree = W.QTreeWidget()
self.maps_tree.setHeaderLabels(["刷图", "关卡", "名称", "难度", "星级", "扫荡状态", "体力 / 门票", "可能掉落", "本日上限", "本日已开始"]) self.maps_tree.setHeaderLabels(["刷图", "关卡", "名称", "难度", "星级", "扫荡 / 挑战状态", "体力 / 门票", "可能掉落", "本日上限", "本日已开始"])
self.maps_tree.setAlternatingRowColors(True) self.maps_tree.setAlternatingRowColors(True)
self.maps_tree.setUniformRowHeights(False) self.maps_tree.setUniformRowHeights(False)
self.maps_tree.setEditTriggers(W.QAbstractItemView.EditTrigger.NoEditTriggers) self.maps_tree.setEditTriggers(W.QAbstractItemView.EditTrigger.NoEditTriggers)
@@ -63,19 +66,21 @@ class ActivityPages:
for col, width in enumerate((100, 82, 160, 130, 70, 210, 120, 340, 100, 92)): for col, width in enumerate((100, 82, 160, 130, 70, 210, 120, 340, 100, 92)):
self.maps_tree.setColumnWidth(col, width) self.maps_tree.setColumnWidth(col, width)
layout.addWidget(self.maps_tree, 1) layout.addWidget(self.maps_tree, 1)
note = W.QLabel("地图按账号保存在本地,点击“刷新关卡”才更新列表。星级来自实际通关难度,不能手动修改。\n普通关卡三个难度全部通关后可扫荡;未满足条件的关卡请在游戏内手动战斗。每行勾选、选择难度并输入本日次数上限,使用所选战队。随机掉落并非必得。") note = W.QLabel("地图按账号保存在本地,点击“刷新关卡”可更新完整列表;挑战结束后同步实际进度。星级来自实际通关难度,不能手动修改。\n普通关卡三个难度全部通关后可扫荡;开启“未满星时自动挑战”后,其余已解锁且开放的勾选普通关卡使用内置模拟挑战,共用所选战队、保留体力和本日上限。实际战败显示“打不过”,未支持的内容显示具体原因;未解锁、特殊关卡和当前任务拦截的关卡仍不可刷图。随机掉落并非必得。")
note.setWordWrap(True) note.setWordWrap(True)
layout.addWidget(note) layout.addWidget(note)
self.tabs.addTab(self.map_page, "自动扫荡") self.tabs.addTab(self.map_page, "自动扫荡")
self.map_search.textChanged.connect(self.render_maps) self.map_search.textChanged.connect(self.render_maps)
self.only_unlocked.toggled.connect(self.render_maps) self.only_unlocked.toggled.connect(self.render_maps)
self.map_enabled.toggled.connect(self.activity_settings_changed) self.map_enabled.toggled.connect(self.activity_settings_changed)
self.map_allow_challenge.toggled.connect(self.activity_settings_changed)
self.map_keep_ti.valueChanged.connect(self.activity_settings_changed) self.map_keep_ti.valueChanged.connect(self.activity_settings_changed)
self.map_team.currentIndexChanged.connect(self.activity_settings_changed) self.map_team.currentIndexChanged.connect(self.activity_settings_changed)
def read_sweep_policy(self): def read_sweep_policy(self):
import copy import copy
return SweepPolicy(self.map_enabled.isChecked(), copy.deepcopy(self.map_rules), self.map_keep_ti.value(), self.map_team.currentData()) return SweepPolicy(self.map_enabled.isChecked(), copy.deepcopy(self.map_rules), self.map_keep_ti.value(),
self.map_team.currentData(), allow_challenge=self.map_allow_challenge.isChecked())
def reset_map_view(self): def reset_map_view(self):
if hasattr(self, "map_render_timer"): if hasattr(self, "map_render_timer"):
@@ -98,9 +103,20 @@ class ActivityPages:
# Stop takes effect immediately, even if the current request is in flight. # Stop takes effect immediately, even if the current request is in flight.
if hasattr(self, "map_enabled") and not self.map_enabled.isChecked(): if hasattr(self, "map_enabled") and not self.map_enabled.isChecked():
self.engine.sweep_policy.enabled = False self.engine.sweep_policy.enabled = False
sender = self.sender()
if sender in (self.map_enabled, self.map_allow_challenge) and not sender.isChecked():
field = "enabled" if sender is self.map_enabled else "allow_challenge"
setattr(self.engine.sweep_policy, field, False)
if self.pending_policy is not None:
setattr(self.pending_policy["sweep_policy"], field, False)
pending = self.engine.battle_journal.pending(self.engine.snapshot) if self.engine.snapshot is not None else None
if pending and pending.get("kind") == "map_battle":
self.cancel_progression()
if hasattr(self, "daily_enabled") and not self.daily_enabled.isChecked(): if hasattr(self, "daily_enabled") and not self.daily_enabled.isChecked():
self.engine.daily_policy.enabled = False self.engine.daily_policy.enabled = False
self.settings_changed() self.settings_changed()
if sender is self.map_allow_challenge:
self.render_maps()
def map_item_changed(self, item, column): def map_item_changed(self, item, column):
key = item.data(0, C.Qt.ItemDataRole.UserRole) key = item.data(0, C.Qt.ItemDataRole.UserRole)
@@ -143,7 +159,7 @@ class ActivityPages:
chosen = next((s for s in options if s.level == str(rule.get("level"))), None) if rule else None chosen = next((s for s in options if s.level == str(rule.get("level"))), None) if rule else None
chosen = chosen or next((s for s in reversed(options) if s.unlocked), first) chosen = chosen or next((s for s in reversed(options) if s.unlocked), first)
self.map_rules.setdefault(key, {"enabled": False, "level": chosen.level, "limit": 3}) self.map_rules.setdefault(key, {"enabled": False, "level": chosen.level, "limit": 3})
reason = self.engine.sweeper.reason(snapshot, chosen, policy, team_ids=team_ids) reason = self.engine.map_stage_reason(snapshot, chosen, policy, team_ids=team_ids)
visible.append((key, options, chosen, dict(self.map_rules[key]), reason)) visible.append((key, options, chosen, dict(self.map_rules[key]), reason))
self._map_items = getattr(self, "_map_items", {}) self._map_items = getattr(self, "_map_items", {})
self._map_cities = getattr(self, "_map_cities", {}) self._map_cities = getattr(self, "_map_cities", {})
@@ -181,7 +197,7 @@ class ActivityPages:
self.maps_tree.setItemWidget(item, 8, limit) self.maps_tree.setItemWidget(item, 8, limit)
item.setSizeHint(0, C.QSize(90, max(difficulty.sizeHint().height(), limit.sizeHint().height()) + 4)) item.setSizeHint(0, C.QSize(90, max(difficulty.sizeHint().height(), limit.sizeHint().height()) + 4))
self._map_items[key] = item self._map_items[key] = item
values = ["", first.number, first.name, "", "★" * first.stars + "☆" * (3 - first.stars), reason or "可扫荡", values = ["", first.number, first.name, "", "★" * first.stars + "☆" * (3 - first.stars), reason or ("可扫荡" if chosen.sweep else "将模拟挑战"),
str(chosen.stamina) + (" / " + chosen.tickets if chosen.tickets else ""), chosen.drops, "", str(self.engine.sweeper.used(snapshot, chosen))] str(chosen.stamina) + (" / " + chosen.tickets if chosen.tickets else ""), chosen.drops, "", str(self.engine.sweeper.used(snapshot, chosen))]
for col, text in enumerate(values): for col, text in enumerate(values):
if item.text(col) != text: if item.text(col) != text:
@@ -218,7 +234,7 @@ class ActivityPages:
pending = self.engine.sweeper.state.get("pending") pending = self.engine.sweeper.state.get("pending")
self.maps_summary.setText(f"已解锁 {sum(s.unlocked for s in all_rows)} 个难度;显示 {len(visible)} 关;勾选 {sum(bool(r.get('enabled')) for r in self.map_rules.values())} 关。" + self.maps_summary.setText(f"已解锁 {sum(s.unlocked for s in all_rows)} 个难度;显示 {len(visible)} 关;勾选 {sum(bool(r.get('enabled')) for r in self.map_rules.values())} 关。" +
(f" 待处理:{pending['stage']} / {pending['phase']}" if pending else "") + (f" 待处理:{pending['stage']} / {pending['phase']}" if pending else "") +
(" 扫荡策略运行中。" if self.map_enabled.isChecked() and self.strategy_toggle.isChecked() else " 开启顶部策略开关后运行已勾选关卡。")) (" 刷图策略运行中。" if self.map_enabled.isChecked() and self.strategy_toggle.isChecked() else " 开启顶部策略开关后运行已勾选关卡。"))
def clear_sweep_pending(self): def clear_sweep_pending(self):
if self.busy: if self.busy:
@@ -226,6 +242,10 @@ class ActivityPages:
return return
pending = self.engine.sweeper.state.get("pending") pending = self.engine.sweeper.state.get("pending")
if not pending: if not pending:
battle = self.engine.battle_journal.pending(self.engine.snapshot) if self.engine.snapshot is not None else None
if battle and battle.get("kind") == "map_battle":
self.report("普通挑战记录由后台每2分钟自动核对;开启策略后续交已保存的结果,详细状态可查看战斗记录。")
return
self.report("没有未完成的扫荡记录") self.report("没有未完成的扫荡记录")
return return
if W.QMessageBox.question(self, "清除本地待处理记录", f"{pending['stage']}:{pending['phase']}\n请先在游戏内确认并处理该关卡。确认已处理后清除记录?") == W.QMessageBox.StandardButton.Yes: if W.QMessageBox.question(self, "清除本地待处理记录", f"{pending['stage']}:{pending['phase']}\n请先在游戏内确认并处理该关卡。确认已处理后清除记录?") == W.QMessageBox.StandardButton.Yes:
+46 -21
View File
@@ -184,9 +184,9 @@ class BattleJournal:
record.update(phase="done", outcome=outcome, message=message, finished_at=time.time()) record.update(phase="done", outcome=outcome, message=message, finished_at=time.time())
if state["pending"] == record["attempt_id"]: if state["pending"] == record["attempt_id"]:
state["pending"] = None state["pending"] = None
if outcome == "loss": if outcome == "loss" and record.get("kind") != "map_battle":
state["losses"] += 1 state["losses"] += 1
elif outcome == "win": elif outcome == "win" and record.get("kind") != "map_battle":
state["losses"] = 0 state["losses"] = 0
self.save() self.save()
@@ -365,7 +365,7 @@ class BattleOrchestrator:
if base.get("ke"): if base.get("ke"):
return "入场需要氪金,未启用" return "入场需要氪金,未启用"
money = float(base.get("money") or 0) 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)): if money and (money > policy.max_money or float(master.get("money") or 0) - money < max(0, value(ranch, "keep_money", 0))):
return "入场金币超过上限或保留金币不足" return "入场金币超过上限或保留金币不足"
for item in base.get("items") or []: for item in base.get("items") or []:
key, count = str(item["typeId"]), int(item["num"]) key, count = str(item["typeId"]), int(item["num"])
@@ -451,21 +451,28 @@ class BattleOrchestrator:
@staticmethod @staticmethod
def resumable_task_clock(record): def resumable_task_clock(record):
return bool(record and record.get("kind") == "progression_battle" and record.get("task_id") common = bool(record and ((record.get("kind") == "progression_battle" and record.get("task_id"))
and record.get("phase") in ("unknown", "waiting_for_battle_clock") or (record.get("kind") == "map_battle" and not record.get("task_id")))
and record.get("path") in ("", "battleService/battleStart")
and not record.get("settlement_confirmed") and not record.get("settlement_dispatched")
and (record.get("resume_clock_ready") is True or
record.get("message") == "等待战斗时钟期间已取消,开战记录保留待核对")
and record.get("execution_mode") == "experimental" and record.get("execution_status") == "completed" and record.get("execution_mode") == "experimental" and record.get("execution_status") == "completed"
and record.get("experimental_settlement_eligible") is True and record.get("terminal") is True and record.get("experimental_settlement_eligible") is True and record.get("terminal") is True
and record.get("approximate") is True and record.get("faithful") is False and record.get("approximate") is True and record.get("faithful") is False
and not record.get("anomalies") and not any(row.get("blocking") is True and not record.get("anomalies") and not any(row.get("blocking") is True
for row in record.get("diagnostics") or [] if isinstance(row, dict)) for row in record.get("diagnostics") or [] if isinstance(row, dict))
and isinstance(record.get("battle_data"), dict) and record["battle_data"].get("win") is True) and isinstance(record.get("battle_data"), dict) and type(record["battle_data"].get("win")) is bool)
if not common:
return False
if (record.get("kind") == "map_battle" and record.get("phase") == "settlement_acknowledged"
and record.get("settlement_confirmed") is True):
return (record["battle_data"]["win"] is True and isinstance(record.get("response"), dict)
and record["response"].get("resCode", 0) in (0, "0"))
return (record.get("phase") in ("unknown", "waiting_for_battle_clock")
and record.get("path") in ("", "battleService/battleStart", "stageService/stageStart")
and not record.get("settlement_confirmed") and not record.get("settlement_dispatched")
and (record.get("resume_clock_ready") is True or
record.get("message") == "等待战斗时钟期间已取消,开战记录保留待核对"))
def resume_task_clock(self, client, snapshot, intent, policy, *, cancel): def resume_task_clock(self, client, snapshot, intent, policy, *, cancel):
"""Continue a saved result only when no settlement was ever dispatched.""" """Resume an unsent result, or finish recording a confirmed map settlement."""
with self.journal.lock: with self.journal.lock:
record = self.journal.pending(snapshot) record = self.journal.pending(snapshot)
if not policy.enabled or cancel.is_set() or not self.resumable_task_clock(record): if not policy.enabled or cancel.is_set() or not self.resumable_task_clock(record):
@@ -475,19 +482,24 @@ class BattleOrchestrator:
if any(str(record.get(key)) != str(value(intent, key)) for key in if any(str(record.get(key)) != str(value(intent, key)) for key in
("kind", "task_id", "task_type_id", "step_number")): ("kind", "task_id", "task_type_id", "step_number")):
return "" return ""
task_battle = bool(record.get("task_id"))
if task_battle:
task = next((row for row in snapshot.raw.get("currentTasks", []) task = next((row for row in snapshot.raw.get("currentTasks", [])
if str(row.get("id")) == str(record["task_id"]) if str(row.get("id")) == str(record["task_id"])
and str(row.get("typeId")) == str(record["task_type_id"])), None) and str(row.get("typeId")) == str(record["task_type_id"])), None)
if not task or int(task.get("curStep", 1)) != int(record["step_number"]): if not task or int(task.get("curStep", 1)) != int(record["step_number"]):
return "" return ""
expected = {"battleType": "task", "stageId": None, "stageLevel": None, expected = {"battleType": "task" if task_battle else "stage",
"taskTypeId": str(record["task_type_id"]), "taskStep": int(record["step_number"]) - 1} "stageId": None if task_battle else str(record.get("stage_id")),
"stageLevel": None if task_battle else str(record.get("difficulty")),
"taskTypeId": str(record["task_type_id"]) if task_battle else None,
"taskStep": int(record["step_number"]) - 1 if task_battle else 0}
data = record["battle_data"] data = record["battle_data"]
position = data.get("battlePosition") position = data.get("battlePosition")
if not isinstance(position, dict) or {key: val for key, val in position.items() if val is not None} != { if not isinstance(position, dict) or {key: val for key, val in position.items() if val is not None} != {
key: val for key, val in expected.items() if val is not None}: key: val for key, val in expected.items() if val is not None}:
return "" return ""
ready = record.get("battle_ready_at") ready = 0 if record.get("settlement_confirmed") else record.get("battle_ready_at")
if ready is None: if ready is None:
duration = record.get("battle_clock_seconds") duration = record.get("battle_clock_seconds")
stamp = record.get("updated_at") stamp = record.get("updated_at")
@@ -500,22 +512,34 @@ class BattleOrchestrator:
return "" return ""
if time.time() < ready: if time.time() < ready:
return "已核对保存的战果;尚未到结算时间,2分钟内自动复查" return "已核对保存的战果;尚未到结算时间,2分钟内自动复查"
path = "taskService/taskCompleteStep"
payload = {"taskId": int(record["task_id"]), "taskTypeId": str(record["task_type_id"]),
"removeIds": None, "battleData": deepcopy(data)}
self.journal.update(record, "settlement_pending", path=path, settlement_dispatched=True)
try: try:
if not data["win"]:
if not task_battle or record.get("battle_kind") == "passStage":
self._record(client, record, record["stage_id"], False, cancel=cancel)
if self.observer:
self.observer("loss", intent, None)
self.journal.finish(snapshot, record, "loss", "打不过(保存的模拟结果);未提交胜利结算")
return record["message"]
response = record.get("response") if record.get("settlement_confirmed") else None
if response is None:
path = "taskService/taskCompleteStep" if task_battle else "battleService/battleEnd"
payload = {"battleData": deepcopy(data)}
if task_battle:
payload.update(taskId=int(record["task_id"]), taskTypeId=str(record["task_type_id"]), removeIds=None)
self.journal.update(record, "settlement_pending", path=path, settlement_dispatched=True)
response = self._call(client, path, payload, cancel=cancel) response = self._call(client, path, payload, cancel=cancel)
self.journal.update(record, "settlement_acknowledged", response=gameplay_response(response), 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")) settlement_confirmed=True, reward=response["stageReward"] if response.get("stageReward") is not None else response.get("reward"))
if not task_battle:
self._record(client, record, record["stage_id"], True)
if self.observer: if self.observer:
self.observer("settled", intent, response) self.observer("settled", intent, response)
else: elif task_battle:
self.journal.checkpoint(snapshot, intent, response) self.journal.checkpoint(snapshot, intent, response)
self.journal.finish(snapshot, record, "win", "已自动续交保存的战果;未重新开战或重新模拟") self.journal.finish(snapshot, record, "win", "已自动续交保存的战果;未重新开战或重新模拟")
return record["message"] return record["message"]
except CancelledBeforeDispatch: except CancelledBeforeDispatch:
self.journal.update(record, "waiting_for_battle_clock", path="battleService/battleStart", self.journal.update(record, "waiting_for_battle_clock", path="battleService/battleStart" if task_battle else "stageService/stageStart",
settlement_dispatched=False, resume_clock_ready=True) settlement_dispatched=False, resume_clock_ready=True)
return "策略已停止,保存的战果将在重新开启后续交" return "策略已停止,保存的战果将在重新开启后续交"
except Exception as error: except Exception as error:
@@ -647,7 +671,8 @@ class BattleOrchestrator:
else: else:
self.journal.checkpoint(snapshot, intent, response) self.journal.checkpoint(snapshot, intent, response)
else: else:
self._record(client, record, request["stage_id"], True, cancel=cancel) self._record(client, record, request["stage_id"], True,
cancel=None if value(intent, "kind") == "map_battle" else cancel)
if self.observer: if self.observer:
self.observer("settled", intent, response) self.observer("settled", intent, response)
label = "实验模型胜利(近似)" if mode == "experimental" else "实际胜利" label = "实验模型胜利(近似)" if mode == "experimental" else "实际胜利"
+128 -2
View File
@@ -6,6 +6,7 @@ import json
from pathlib import Path from pathlib import Path
import threading import threading
import time import time
from types import SimpleNamespace
from .model import Action, Catalog, Planner, Policy, Snapshot, seconds from .model import Action, Catalog, Planner, Policy, Snapshot, seconds
from .daily import DailyLedger, DailyPolicy, selected_entries from .daily import DailyLedger, DailyPolicy, selected_entries
from .sweeping import SweepPolicy, SweepRunner from .sweeping import SweepPolicy, SweepRunner
@@ -19,6 +20,8 @@ from .drop_statistics import reward_text
from .cultivation import CultivationSelector from .cultivation import CultivationSelector
from .battles import BattleJournal, BattleOrchestrator, CancelledBeforeDispatch, digest, gameplay_response, public_data, value from .battles import BattleJournal, BattleOrchestrator, CancelledBeforeDispatch, digest, gameplay_response, public_data, value
from .progression import ProgressionIntent, ProgressionPlanner, ProgressionPolicy from .progression import ProgressionIntent, ProgressionPlanner, ProgressionPolicy
from .battle_messages import battle_message
from .maps import stages
def account_serial(method): def account_serial(method):
@@ -94,6 +97,9 @@ class Engine:
self._commission_planner_available = False self._commission_planner_available = False
self._commission_offer_reason = "" self._commission_offer_reason = ""
self._commission_offer_checks = {} self._commission_offer_checks = {}
self._map_challenge_reasons = {}
self._map_reason_snapshot = None
self._map_reason_team = ""
self._progression_records = [] self._progression_records = []
self._progression_error = "" self._progression_error = ""
self._planner_pending = False self._planner_pending = False
@@ -200,6 +206,26 @@ class Engine:
self.battle_journal.save() self.battle_journal.save()
def _battle_observer(self, event, intent, response): def _battle_observer(self, event, intent, response):
if value(intent, "kind") == "map_battle":
stage = SimpleNamespace(stage_id=str(value(intent, "stage_id")), level=str(value(intent, "difficulty")))
key = self.sweeper.key(self.snapshot, stage)
if event == "started":
record = self.battle_journal.pending(self.snapshot)
if record is not None:
record["map_roster_signature"] = self._map_roster_signature(self.snapshot, value(intent, "team", self.sweep_policy.team))
self.sweeper.state["counts"][key] = self.sweeper.used(self.snapshot, stage) + 1
self.sweeper.save()
elif event == "cancelled_before_start":
self.sweeper.state["counts"][key] = max(0, self.sweeper.used(self.snapshot, stage) - 1)
self.sweeper.save()
elif event == "loss":
record = self.battle_journal.pending(self.snapshot) or {}
self.sweeper.state.setdefault("challenge_failures", {})[key] = record.get("map_roster_signature") or self._map_roster_signature(self.snapshot, value(intent, "team", self.sweep_policy.team))
self.sweeper.save()
elif event in ("settled", "event"):
self.sweeper.state.setdefault("challenge_failures", {}).pop(key, None)
self.sweeper.save()
return None
farming = self._is_farm(intent) farming = self._is_farm(intent)
if value(intent, "kind") != "progression_battle" and not farming: if value(intent, "kind") != "progression_battle" and not farming:
return None return None
@@ -293,6 +319,10 @@ class Engine:
record = self.battle_journal.pending(self.snapshot) record = self.battle_journal.pending(self.snapshot)
if not self.auto or self._progression_cancel.is_set() or not self.battles.resumable_task_clock(record): if not self.auto or self._progression_cancel.is_set() or not self.battles.resumable_task_clock(record):
return "" return ""
if record.get("kind") == "map_battle":
intent = {key: record.get(key) for key in ("kind", "task_id", "task_type_id", "step_number",
"stage_id", "difficulty", "battle_kind", "team", "path")}
return self.battles.resume_task_clock(self.client, self.snapshot, intent, self._map_policy(), cancel=self._progression_cancel)
pending = self.progression_planner.pending(self.snapshot) if self.progression_planner else None pending = self.progression_planner.pending(self.snapshot) if self.progression_planner else None
if not pending or not isinstance(pending.get("intent"), dict): if not pending or not isinstance(pending.get("intent"), dict):
return "" return ""
@@ -377,6 +407,7 @@ class Engine:
def _battle_request(self, snapshot, intent, policy, request): def _battle_request(self, snapshot, intent, policy, request):
self._ensure_progression() self._ensure_progression()
self._select_battle_runtime(policy.battle_mode)
if self._battle_snapshot_source is not snapshot: if self._battle_snapshot_source is not snapshot:
self._battle_snapshot_source = snapshot self._battle_snapshot_source = snapshot
self._battle_snapshot_digest = digest(snapshot.raw) self._battle_snapshot_digest = digest(snapshot.raw)
@@ -419,6 +450,8 @@ class Engine:
return value(intent, "kind") in ("sweep", "progression_sweep", "progression_farm_sweep", "progression_map_sweep") or value(intent, "battle_kind") == "sweep" 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): def _intent_policy(self, intent):
if value(intent, "kind") == "map_battle":
return self._map_policy()
if not self._is_commission(intent): if not self._is_commission(intent):
return self.progression_policy return self.progression_policy
quest = self.quest_policy quest = self.quest_policy
@@ -757,11 +790,14 @@ class Engine:
self._refresh_progression_cache() self._refresh_progression_cache()
if self._progression_pending(): if self._progression_pending():
self.pending_hatches = [] self.pending_hatches = []
pending_map = (self.battle_journal.pending(self.snapshot) or {}).get("kind") == "map_battle"
recovered = self._resume_pending_task_clock() if not self.demo else "" recovered = self._resume_pending_task_clock() if not self.demo else ""
if recovered: if recovered:
self.last_executed = True self.last_executed = True
if not self.battle_journal.pending(self.snapshot): if not self.battle_journal.pending(self.snapshot):
self.read_snapshot(sync_master=False) self.read_snapshot(sync_master=False)
if pending_map:
self.stage_cache.get(self.snapshot, refresh=True)
return self.snapshot, self.plans(), recovered return self.snapshot, self.plans(), recovered
pending = self.battle_journal.pending(self.snapshot) or {} pending = self.battle_journal.pending(self.snapshot) or {}
return self.snapshot, [], message + ";" + (pending.get("message") or "有待核对的任务 / 战斗,已暂停冲突操作") + ";后台每2分钟自动核对" return self.snapshot, [], message + ";" + (pending.get("message") or "有待核对的任务 / 战斗,已暂停冲突操作") + ";后台每2分钟自动核对"
@@ -795,6 +831,8 @@ class Engine:
if self.sweeper.statistics_error: if self.sweeper.statistics_error:
message += ";" + self.sweeper.statistics_error message += ";" + self.sweeper.statistics_error
return self.snapshot, self.plans(), message return self.snapshot, self.plans(), message
if action.kind == "map_challenge":
return self._run_map_challenge(action.payload["intent"])
if action.kind == "buy": if action.kind == "buy":
price = int(self.catalog.data["markets"][action.payload["id"]]["money"]) price = int(self.catalog.data["markets"][action.payload["id"]]["money"])
self.purchase_budget.record(self.snapshot.now, price * action.payload["num"], self.policy.daily_buy_money) self.purchase_budget.record(self.snapshot.now, price * action.payload["num"], self.policy.daily_buy_money)
@@ -850,6 +888,94 @@ class Engine:
self.battle_journal.update(record, "unknown", message="委托请求结果未确认,禁止自动重试", error_type=type(error).__name__) self.battle_journal.update(record, "unknown", message="委托请求结果未确认,禁止自动重试", error_type=type(error).__name__)
raise raise
def _map_policy(self):
return SimpleNamespace(enabled=self.sweep_policy.enabled and self.sweep_policy.allow_challenge,
team=self.sweep_policy.team, reserve_ti=self.sweep_policy.keep_stamina,
max_money=max(0, int(self.snapshot.raw["master"].get("money") or 0)) if self.snapshot else 0,
allow_items=True, item_reserves=dict(self.quest_policy.item_reserves),
stop_after_loss=0, battle_mode="experimental")
def _map_roster_signature(self, snapshot, team):
selected = next((row for row in snapshot.raw.get("teams", []) if row.get("teamName") == team
and row.get("teamType") == "battleTeam"), {})
ids = {int(mid) for mid in selected.get("monsters", []) if mid and int(mid) > 0}
transient = {"exp", "timeStart", "nicName", "roomId"}
return digest({"team": selected,
"master": {key: val for key, val in snapshot.raw["master"].items() if key == "level" or key.startswith("global")},
"monsters": sorted([{key: val for key, val in mon.items() if key not in transient}
for mon in snapshot.raw.get("monsters", []) if int(mon["id"]) in ids], key=lambda mon: int(mon["id"])),
"attributes": sorted([row for row in snapshot.raw.get("monsterAttributes", []) or [] if int(row.get("monsterId") or 0) in ids],
key=lambda row: int(row["monsterId"]))})
def map_stage_reason(self, snapshot, stage, policy, *, team_ids=None):
"""Lightweight page status; runtime inspection belongs to the account worker."""
if self._progression_pending():
return "有待核对的任务 / 战斗,后台会自动检查"
reason = self.sweeper.reason(snapshot, stage, policy, team_ids=team_ids, challenge=not stage.sweep)
if reason:
return battle_message(reason)
rule = policy.rules.get(stage.stage_id) or {}
if rule.get("enabled") and self.sweeper.used(snapshot, stage) >= max(0, int(rule.get("limit") or 0)):
return "已达本日次数上限"
if stage.sweep:
return ""
if not policy.allow_challenge:
return "未开启未满星时自动挑战"
failed = self.sweeper.state.get("challenge_failures", {}).get(self.sweeper.key(snapshot, stage))
if failed and failed == self._map_roster_signature(snapshot, policy.team):
return "打不过;调整战队或提升魔物属性后自动重试"
if self._map_reason_snapshot is snapshot and self._map_reason_team == policy.team:
return self._map_challenge_reasons.get((stage.stage_id, stage.level), "")
return ""
def _next_map_action(self):
if not self.sweep_policy.enabled or self.demo:
return None
self._map_challenge_reasons = {}
self._map_reason_snapshot, self._map_reason_team = self.snapshot, self.sweep_policy.team
for stage in sorted(stages(self.catalog, self.snapshot), key=lambda row: (row.city, row.number, row.stage_id, row.level)):
rule = self.sweep_policy.rules.get(stage.stage_id) or {}
if not rule.get("enabled") or str(rule.get("level", "3")) != stage.level:
continue
if self.map_stage_reason(self.snapshot, stage, self.sweep_policy):
continue
if stage.sweep:
return Action("sweep", f"扫荡 {stage.number} {stage.name} / 难度{stage.level}", "", {})
self._ensure_progression()
if self.progression_planner.pending(self.snapshot):
self._planner_pending = True
return None
self._select_battle_runtime("experimental")
self._battle_snapshot_digest = digest(self.snapshot.raw)
intent = {"kind": "map_battle", "description": f"挑战 {stage.number} {stage.name} / 难度{stage.level}",
"path": "stageService/stageStart", "task_id": 0, "task_type_id": "", "step_number": 0,
"stage_id": stage.stage_id, "difficulty": int(stage.level), "battle_kind": "ordinary_stage",
"position": f"city{stage.city}_wild_stage{stage.stage_id}_level{stage.level}",
"team": self.sweep_policy.team, "battle_mode": "experimental"}
supported, reason = self._battle_capability(intent)
self._map_challenge_reasons[(stage.stage_id, stage.level)] = battle_message(reason)
if supported:
return Action("map_challenge", intent["description"], "", {"intent": intent})
return None
def _run_map_challenge(self, intent):
stage = next((row for row in stages(self.catalog, self.snapshot) if row.stage_id == str(value(intent, "stage_id"))
and row.level == str(value(intent, "difficulty"))), None)
if stage is None or not self.sweep_policy.enabled or not self.sweep_policy.allow_challenge:
return self.snapshot, self.plans(), "自动挑战已关闭或关卡状态已改变"
reason = self.map_stage_reason(self.snapshot, stage, self.sweep_policy)
if reason:
return self.snapshot, self.plans(), reason
self._ensure_progression()
self._select_battle_runtime("experimental")
message = self.battles.run(self.client, self.snapshot, intent, self._map_policy(),
cancel=self._progression_cancel, ranch=self.policy)
if not self._progression_cancel.is_set():
self.read_snapshot(sync_master=False)
if not self._progression_pending():
self.stage_cache.get(self.snapshot, refresh=True)
return self.snapshot, self.plans(), battle_message(message)
def plans(self): def plans(self):
if self.snapshot is None or self._progression_pending(): if self.snapshot is None or self._progression_pending():
self.pending_hatches = [] self.pending_hatches = []
@@ -868,8 +994,8 @@ class Engine:
self.pending_hatches = self.hatch_planner.hatch_actions(self.snapshot, policy) self.pending_hatches = self.hatch_planner.hatch_actions(self.snapshot, policy)
left = self.purchase_budget.remaining(self.snapshot.now, policy.daily_buy_money) left = self.purchase_budget.remaining(self.snapshot.now, policy.daily_buy_money)
daily = [row.action for row in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger)] if self.daily_policy.enabled else [] daily = [row.action for row in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger)] if self.daily_policy.enabled else []
sweep = self.sweeper.next(self.snapshot, self.sweep_policy) if self.sweep_policy.enabled and not self.demo else None map_action = self._next_map_action()
sweep_actions = [Action(kind="sweep", path="", payload={}, description=f"扫荡 {sweep.number} {sweep.name} / 难度{sweep.level}")] if sweep else [] sweep_actions = [map_action] if map_action else []
gifts = self.gift_planner.plan(self.snapshot, policy, self.quest_policy) gifts = self.gift_planner.plan(self.snapshot, policy, self.quest_policy)
ranch = self.planner.plan(self.snapshot, policy, left) ranch = self.planner.plan(self.snapshot, policy, left)
self.planner.notes.extend(self.gift_planner.notes) self.planner.notes.extend(self.gift_planner.notes)
+8 -2
View File
@@ -1478,9 +1478,14 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
self.login_status.setText("操作失败,调试窗口中保留了请求和响应") self.login_status.setText("操作失败,调试窗口中保留了请求和响应")
self.engine.auto = False self.engine.auto = False
self.engine.heartbeat_enabled = False self.engine.heartbeat_enabled = False
self.monitoring = False pending = self.engine.battle_journal.pending(self.engine.snapshot) if self.engine.snapshot is not None else None
recovering_map = not self.engine.demo and bool(pending and pending.get("kind") == "map_battle")
self.monitoring = recovering_map
if recovering_map:
self.engine.last_pending_check = time.monotonic()
self.next_poll = self.engine.last_pending_check + 120
self.stop_workflow() self.stop_workflow()
self.report("已停止:" + message) self.report(("策略已暂停;后台每2分钟核对挑战记录:" if recovering_map else "已停止:") + message)
self.statusBar().showMessage(message) self.statusBar().showMessage(message)
def read_policy(self): def read_policy(self):
@@ -2115,6 +2120,7 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
sweep = SweepPolicy(**value.get("sweep_policy", {})) sweep = SweepPolicy(**value.get("sweep_policy", {}))
self.map_rules = copy.deepcopy(sweep.rules) self.map_rules = copy.deepcopy(sweep.rules)
self.map_enabled.setChecked(sweep.enabled) self.map_enabled.setChecked(sweep.enabled)
self.map_allow_challenge.setChecked(sweep.allow_challenge)
self.map_keep_ti.setValue(sweep.keep_stamina) self.map_keep_ti.setValue(sweep.keep_stamina)
self.map_team.setCurrentIndex(max(0, self.map_team.findData(sweep.team))) self.map_team.setCurrentIndex(max(0, self.map_team.findData(sweep.team)))
self.load_progression_policy(progression) self.load_progression_policy(progression)
+9 -2
View File
@@ -20,6 +20,7 @@ class SweepPolicy:
rules: dict = field(default_factory=dict) rules: dict = field(default_factory=dict)
keep_stamina: int = 0 keep_stamina: int = 0
team: str = "teamA" team: str = "teamA"
allow_challenge: bool = True
class SweepRunner: class SweepRunner:
@@ -123,10 +124,16 @@ class SweepRunner:
monsters = snapshot.monsters monsters = snapshot.monsters
return [mid for mid in ids if mid in monsters] return [mid for mid in ids if mid in monsters]
def reason(self, snapshot, stage, policy, *, team_ids=None): def reason(self, snapshot, stage, policy, *, team_ids=None, challenge=False):
if self.state.get("pending"): if self.state.get("pending"):
return "有未完成的扫荡,请先在游戏内检查" return "有未完成的扫荡,请先在游戏内检查"
if not stage.sweep: if challenge:
config = self.catalog.data.get("stage_info", {}).get(stage.stage_id, {})
if not stage.unlocked or not stage.open:
return "关卡尚未解锁或当前未开放"
if config.get("special") or config.get("posmode"):
return "特殊关卡当前不支持自动挑战"
elif not stage.sweep:
return stage.reason return stage.reason
if not (self.team_ids(snapshot, policy) if team_ids is None else team_ids): if not (self.team_ids(snapshot, policy) if team_ids is None else team_ids):
return "所选战队无有效魔物" return "所选战队无有效魔物"
+99
View File
@@ -2,6 +2,7 @@ import copy
import json import json
import os import os
import unittest import unittest
from unittest.mock import patch
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
@@ -258,6 +259,104 @@ class ActivityGuiTests(unittest.TestCase):
from PySide6.QtWidgets import QApplication from PySide6.QtWidgets import QApplication
cls.app = QApplication.instance() or QApplication([]) cls.app = QApplication.instance() or QApplication([])
def wait(self, predicate):
from PySide6.QtTest import QTest
for _ in range(700):
self.app.processEvents()
QTest.qWait(2)
if predicate():
return
self.fail("Qt worker or autosave did not finish")
def test_challenge_checkbox_autosave_import_restore_and_legacy_default(self):
from ranch_assistant.gui import Window
from ranch_assistant.policy_io import portable_config
with workspace_temp() as folder:
window = Window(state_root=folder)
window.timer.stop()
try:
self.wait(lambda: not window.busy and window.engine.snapshot is not None)
self.assertTrue(window.map_allow_challenge.isChecked())
self.assertEqual(window.map_allow_challenge.text(), "未满星时自动挑战")
self.assertEqual(window.tabs.tabText(window.tabs.indexOf(window.map_page)), "自动扫荡")
window.map_enabled.setChecked(True)
window.map_keep_ti.setValue(17)
window.map_team.setCurrentIndex(window.map_team.findData("teamB"))
window.map_rules = {"0102": {"enabled": True, "level": "2", "limit": 12}}
window.map_allow_challenge.click()
self.assertTrue(window.auto_save_timer.isActive())
self.wait(lambda: not window.auto_save_timer.isActive())
saved = json.loads((folder / "settings.json").read_text(encoding="utf-8"))["sweep_policy"]
self.assertFalse(saved["allow_challenge"])
self.assertFalse(window.engine.sweep_policy.allow_challenge)
self.assertEqual((saved["keep_stamina"], saved["team"], saved["rules"]["0102"]["limit"]), (17, "teamB", 12))
exported = portable_config(window.config_value(), window.engine.snapshot)
self.assertFalse(exported["sweep_policy"]["allow_challenge"])
path = folder / "import.json"
for allowed in (True, False):
with self.subTest(imported_challenge=allowed):
exported["sweep_policy"]["allow_challenge"] = allowed
path.write_text(json.dumps(exported), encoding="utf-8")
with patch("ranch_assistant.gui.W.QFileDialog.getOpenFileName", return_value=(str(path), "")):
window.import_policies()
self.assertEqual(window.map_allow_challenge.isChecked(), allowed)
self.assertEqual(window.read_sweep_policy().allow_challenge, allowed)
self.assertEqual(window.engine.sweep_policy.allow_challenge, allowed)
self.assertFalse(window.strategy_toggle.isChecked())
self.assertEqual(window.map_rules["0102"], {"enabled": True, "level": "2", "limit": 12})
finally:
window.close()
restored = Window(state_root=folder)
restored.timer.stop()
try:
self.wait(lambda: not restored.busy and restored.engine.snapshot is not None)
self.assertFalse(restored.map_allow_challenge.isChecked())
self.assertFalse(restored.read_sweep_policy().allow_challenge)
legacy = restored.config_value()
del legacy["sweep_policy"]["allow_challenge"]
restored.load_config(legacy)
self.assertTrue(restored.map_allow_challenge.isChecked())
self.assertTrue(restored.read_sweep_policy().allow_challenge)
self.assertFalse(restored.auto_save_timer.isActive())
finally:
restored.close()
def test_map_stop_cancels_only_pending_map_battles(self):
from ranch_assistant.gui import Window
with workspace_temp() as folder:
window = Window(state_root=folder)
window.timer.stop()
try:
self.wait(lambda: not window.busy and window.engine.snapshot is not None)
window.busy = True
for kind in (None, "progression_battle", "map_battle"):
for control, field in ((window.map_allow_challenge, "allow_challenge"), (window.map_enabled, "enabled")):
window.map_enabled.setChecked(True)
window.map_allow_challenge.setChecked(True)
window.engine.sweep_policy = window.read_sweep_policy()
window.update_policy()
pending = {"kind": kind} if kind else None
with self.subTest(pending=kind, stopped=field), \
patch.object(window.engine.battle_journal, "pending", return_value=pending), \
patch.object(window.engine, "cancel_progression", wraps=window.engine.cancel_progression) as cancel:
window.engine.auto = True
control.setChecked(False)
self.assertFalse(getattr(window.engine.sweep_policy, field))
self.assertFalse(getattr(window.pending_policy["sweep_policy"], field))
if kind == "map_battle":
self.assertFalse(window.engine.auto)
cancel.assert_called_once_with()
else:
self.assertTrue(window.engine.auto)
cancel.assert_not_called()
self.assertTrue(window.auto_save_timer.isActive())
with patch.object(window.engine, "cancel_progression") as cancel:
window.map_keep_ti.setValue(10)
cancel.assert_not_called()
finally:
window.busy = False
window.close()
def test_tree_rules_daily_page_and_scroll_layout(self): def test_tree_rules_daily_page_and_scroll_layout(self):
from PySide6 import QtCore as C, QtWidgets as W from PySide6 import QtCore as C, QtWidgets as W
from PySide6.QtTest import QTest from PySide6.QtTest import QTest
+81 -1
View File
@@ -5,7 +5,7 @@ import unittest
from unittest.mock import patch from unittest.mock import patch
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6 import QtWidgets as W from PySide6 import QtCore as C, QtWidgets as W
from PySide6.QtTest import QTest from PySide6.QtTest import QTest
from ranch_assistant.engine import Engine from ranch_assistant.engine import Engine
@@ -60,6 +60,86 @@ class MapCacheGuiTests(unittest.TestCase):
return return
self.fail("Qt worker did not finish") self.fail("Qt worker did not finish")
def test_map_request_error_keeps_read_only_background_reconciliation(self):
with workspace_temp() as folder:
window = Window(folder)
window.timer.stop()
try:
self.wait(lambda: not window.busy and window.engine.snapshot is not None)
catalog, snapshot = scenario()
client = FakeClient(snapshot)
client.session = Session("http://127.0.0.1/", "synthetic-test-token")
client.persist_session = lambda: None
client.close = lambda: None
window.engine = Engine(catalog, client, folder / "purchase.json")
window.engine.snapshot = snapshot
with patch.object(window.engine.battle_journal, "pending", return_value={"kind": "map_battle"}):
window.error("挑战结算回包尚未确认")
self.assertTrue(window.monitoring)
self.assertFalse(window.engine.auto)
self.assertFalse(window.strategy_toggle.isChecked())
with patch.object(window.engine, "pending_recovery_due", return_value=True), patch.object(window, "refresh") as refresh:
window.schedule()
refresh.assert_called_once_with(automated=True)
self.assertFalse(client.calls)
finally:
window.close()
def test_unlocked_uncleared_difficulty_and_cached_challenge_status(self):
with workspace_temp() as folder:
window = Window(folder)
window.timer.stop()
try:
self.wait(lambda: not window.busy and window.engine.snapshot is not None)
catalog, snapshot = scenario()
snapshot.raw["history"]["unlockStage"]["0102"] = ["1", "2"]
client = FakeClient(snapshot)
window.catalog = catalog
window.engine = Engine(catalog, client, folder / "purchase.json")
window.engine.snapshot = snapshot
window.map_rules = {"0102": {"enabled": False, "level": "1", "limit": 3}}
original = window.engine.stage_cache.get(snapshot)
statuses = {"bd00": "特殊关卡暂不支持自动挑战"}
def reason(current, stage, policy, *, team_ids=None):
self.assertIs(current, snapshot)
self.assertTrue(policy.allow_challenge)
self.assertEqual(team_ids, [900])
return statuses.get(stage.stage_id, "")
with patch.object(window.engine, "map_stage_reason", side_effect=reason) as cached_reason, \
patch.object(window.engine.sweeper, "reason", side_effect=AssertionError("UI used sweep-only reason")), \
patch.object(window.engine.battles, "inspect", side_effect=AssertionError("UI inspected runtime")), \
patch.object(window.engine.battles, "run", side_effect=AssertionError("UI ran a battle")), \
patch("ranch_assistant.stage_cache.stages", side_effect=AssertionError("UI rebuilt cached maps")):
window.tabs.setCurrentWidget(window.map_page)
self.wait(lambda: not window.map_render_timer.running)
self.assertEqual(window._map_items["0101"].text(5), "可扫荡")
item = window._map_items["0102"]
difficulty = window.maps_tree.itemWidget(item, 3)
self.assertTrue(difficulty.model().item(difficulty.findData("2")).isEnabled())
self.assertFalse(difficulty.model().item(difficulty.findData("3")).isEnabled())
self.assertNotIn("已通关", difficulty.itemText(difficulty.findData("2")))
item.setCheckState(0, C.Qt.CheckState.Checked)
difficulty.setCurrentIndex(difficulty.findData("2"))
self.app.processEvents()
self.wait(lambda: not window.map_render_timer.running)
self.assertEqual(window.map_rules["0102"], {"enabled": True, "level": "2", "limit": 3})
self.assertEqual(item.text(5), "将模拟挑战")
self.assertTrue(any(call.args[1].stage_id == "0102" and call.args[1].level == "2"
and call.args[2].rules["0102"]["enabled"] for call in cached_reason.call_args_list))
for status in ("打不过;调整战队或提升魔物属性后自动重试", "暂不支持的战斗机制:召唤"):
with self.subTest(status=status):
statuses["0102"] = status
window.render_maps()
self.wait(lambda: not window.map_render_timer.running)
self.assertEqual(item.text(5), status)
self.assertEqual(item.toolTip(5), status)
self.assertEqual(window._map_items["bd00"].text(5), statuses["bd00"])
self.assertIs(window.engine.stage_cache.rows, original)
self.assertEqual(client.calls, [])
finally:
window.engine.client = None
window.close()
def test_collapsed_maps_remain_cached_on_page_switch_and_poll_manual_refresh_updates(self): def test_collapsed_maps_remain_cached_on_page_switch_and_poll_manual_refresh_updates(self):
with workspace_temp() as folder: with workspace_temp() as folder:
window = Window(folder) window = Window(folder)
@@ -0,0 +1,208 @@
"""Offline map challenge routing; all server responses and combat are fakes."""
from copy import deepcopy
import unittest
from unittest.mock import Mock, patch
from ranch_assistant.engine import Engine
from ranch_assistant.game_data import ProgressionData
from ranch_assistant.maps import stages
from ranch_assistant.model import Policy, Snapshot
from ranch_assistant.sweeping import SweepPolicy
from ranch_assistant.tests.test_activities import scenario
from ranch_assistant.tests.test_battle_orchestration import ExperimentalRuntime
from ranch_assistant.tests.test_core import workspace_temp
class MapChallengeTests(unittest.TestCase):
def setUp(self):
self.folder = self.enterContext(workspace_temp())
self.catalog, snapshot = scenario()
self.raw = deepcopy(snapshot.raw)
self.raw["currentTasks"] = []
self.raw["history"]["passStage"]["0102"] = []
self.raw["master"].update(ti=1000, timeTi=0)
self.raw["teams"].append({"teamName": "teamB", "teamType": "battleTeam", "monsters": [900]})
stage_info = deepcopy(self.catalog.data["stage_info"])
for row in stage_info.values():
for level in row["level"].values():
level["battle"] = {"fixture": True}
self.data = ProgressionData({"task_info": {}, "stage_info": stage_info,
"game_setting": self.catalog.data["game_setting"]})
self.runtime = ExperimentalRuntime()
self.client = Mock()
self.client.snapshot.side_effect = lambda: Snapshot(deepcopy(self.raw))
self.client.call.side_effect = self.respond
self.engine = self.make_engine()
def make_engine(self):
engine = Engine(self.catalog, self.client, self.folder / "purchase.json",
game_data=self.data, experimental_runtime=self.runtime)
engine.policy = Policy(enabled=False, keep_money=0)
engine.sweep_policy = SweepPolicy(True, {"0102": {"enabled": True, "level": "1", "limit": 3}}, team="teamB")
engine.master_sync.settle = Mock()
engine.auto = True
return engine
def respond(self, path, payload):
if path.endswith("stageStart"):
return {"resCode": 0, "triggerEvent": False}
if path.endswith("recordBattleResult") and payload["result"]:
passed = self.raw["history"]["passStage"].setdefault(payload["stageId"], [])
if "1" not in passed:
passed.append("1")
return {"resCode": 0, "reward": {"money": 25}}
def stage(self):
return next(s for s in stages(self.catalog, self.engine.snapshot) if s.stage_id == "0102" and s.level == "1")
def paths(self):
return [call.args[0] for call in self.client.call.call_args_list]
def test_uncleared_map_uses_simulation_and_ordinary_settlement_without_mainline(self):
snapshot, _, message = self.engine.poll()
self.assertFalse(self.engine.progression_policy.enabled)
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
self.assertEqual(self.runtime.run.call_count, 1)
request = self.runtime.run.call_args.args[0]
self.assertEqual(request["context"], "ordinary_stage")
self.assertEqual(request["team"], "teamB")
self.assertIsNone(request["battle_position"]["taskTypeId"])
self.assertIn("胜利", message)
self.assertEqual(self.engine.sweeper.used(snapshot, self.stage()), 1)
self.assertTrue(next(s for s in self.engine.stage_cache.rows if s.stage_id == "0102" and s.level == "1").passed)
def test_three_cleared_difficulties_use_sweep_without_runtime_execution(self):
self.raw["history"]["passStage"]["0102"] = ["1", "2", "3"]
self.engine.poll()
self.runtime.run.assert_not_called()
data = self.client.call.call_args_list[1].args[1]["battleData"]
self.assertEqual(data["totalDamage"], 0) # Existing official sweep payload.
def test_loss_stops_same_team_retries_and_persists_without_blocking_mainline(self):
self.runtime.win = False
_, _, message = self.engine.poll()
self.assertIn("打不过", message)
self.assertNotIn("battleService/battleEnd", self.paths())
self.assertEqual(self.engine.battle_journal.role(self.engine.snapshot)["losses"], 0)
self.engine.poll()
self.assertEqual(self.runtime.run.call_count, 1)
self.assertIn("打不过", self.engine.map_stage_reason(self.engine.snapshot, self.stage(), self.engine.sweep_policy))
self.engine = self.make_engine()
self.engine.poll()
self.assertEqual(self.runtime.run.call_count, 1)
self.raw["monsters"][-1]["level"] += 1
self.engine.poll()
self.assertEqual(self.runtime.run.call_count, 2)
def test_unsupported_scenario_never_starts_or_uses_daily_count(self):
self.runtime.supported = False
self.engine.poll()
self.client.call.assert_not_called()
self.runtime.run.assert_not_called()
self.assertEqual(self.engine.sweeper.used(self.engine.snapshot, self.stage()), 0)
self.assertTrue(self.engine.map_stage_reason(self.engine.snapshot, self.stage(), self.engine.sweep_policy))
def test_unsupported_map_does_not_block_another_selected_map(self):
self.raw["history"]["passStage"]["0101"] = []
self.engine.sweep_policy.rules["0101"] = {"enabled": True, "level": "1", "limit": 1}
self.runtime.inspect.side_effect = lambda request: self.runtime._inspect(request) | {
"supported": request["stage_id"] != "0101"}
self.engine.poll()
started = next(call.args[1] for call in self.client.call.call_args_list if call.args[0].endswith("stageStart"))
self.assertEqual(started["stageTypeId"], "0102")
self.assertEqual(self.runtime.run.call_count, 1)
def test_stopped_closed_locked_low_stamina_and_daily_limit_never_start(self):
for blocked in ("stopped", "disabled", "locked", "stamina", "limit"):
with self.subTest(blocked=blocked):
raw = deepcopy(self.raw)
self.engine = self.make_engine()
if blocked == "stopped": self.engine.auto = False
if blocked == "disabled": self.engine.sweep_policy.allow_challenge = False
if blocked == "locked": self.raw["history"]["unlockStage"]["0102"] = []
if blocked == "stamina": self.engine.sweep_policy.keep_stamina = 1000
if blocked == "limit": self.engine.sweep_policy.rules["0102"]["limit"] = 0
self.client.call.reset_mock()
self.engine.poll()
self.client.call.assert_not_called()
self.raw = raw
def test_current_task_interception_does_not_become_ordinary_map_battle(self):
self.data.tasks["100"] = {"type": 1, "steps": [{"position": "city1_wild_stage0102_level1", "statusType": "passStage"}]}
self.raw["currentTasks"] = [{"id": 81, "typeId": "100", "curStep": 1}]
self.engine.poll()
self.client.call.assert_not_called()
self.assertIn("任务", self.engine.map_stage_reason(self.engine.snapshot, self.stage(), self.engine.sweep_policy))
def test_daily_limit_counts_real_attempts(self):
self.engine.sweep_policy.rules["0102"]["limit"] = 1
self.engine.poll()
self.engine.poll()
self.assertEqual(self.runtime.run.call_count, 1)
self.assertEqual(self.engine.sweeper.used(self.engine.snapshot, self.stage()), 1)
def test_reward_event_does_not_run_model_or_resettle(self):
self.client.call.side_effect = lambda path, payload: {"resCode": 0, "triggerEvent": True,
"stageEvent": {"resCode": 0, "result": {"money": 25}}}
self.engine.poll()
self.assertEqual(self.paths(), ["stageService/stageStart"])
self.runtime.run.assert_not_called()
self.assertIsNone(self.engine.battle_journal.pending(self.engine.snapshot))
def test_saved_clock_resumes_without_new_start_simulation_or_count(self):
original = self.runtime._run
self.runtime.run.side_effect = lambda request, cancel_event: original(request, cancel_event=cancel_event) | {
"requires_realtime_wait": True, "model_elapsed_ms": 10000}
self.engine.battles.clock = lambda: 0
cancel = self.engine._progression_cancel
cancel.wait = Mock(side_effect=lambda timeout: cancel.set() or True)
self.engine.poll()
self.assertEqual(self.paths(), ["stageService/stageStart"])
record = self.engine.battle_journal.pending(self.engine.snapshot)
record["battle_ready_at"] = 1
self.engine.battle_journal.save()
self.engine.poll()
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
self.assertEqual(self.runtime.run.call_count, 1)
self.assertEqual(self.engine.sweeper.used(self.engine.snapshot, self.stage()), 1)
def test_confirmed_settlement_restart_only_finishes_record(self):
with patch.object(self.engine.battles, "_record", side_effect=SystemExit("synthetic process crash")):
with self.assertRaises(SystemExit):
self.engine.poll()
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd"])
self.engine = self.make_engine()
self.engine.poll()
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd", "battleService/recordBattleResult"])
self.assertEqual(self.runtime.run.call_count, 1)
def test_free_entry_is_not_blocked_by_gold_purchase_reserve(self):
self.engine.policy.keep_money = 10**9
self.engine.poll()
self.assertIn("stageService/stageStart", self.paths())
def test_cancel_before_dispatch_refunds_daily_count(self):
original = self.engine.battles.observer
def cancel_before_send(event, intent, response):
result = original(event, intent, response)
if event == "started":
self.engine._progression_cancel.set()
return result
self.engine.battles.observer = cancel_before_send
self.engine.poll()
self.client.call.assert_not_called()
self.assertEqual(self.engine.sweeper.used(self.engine.snapshot, self.stage()), 0)
self.assertIsNone(self.engine.battle_journal.pending(self.engine.snapshot))
def test_uncertain_settlement_never_repeats_entry_or_settlement(self):
original = self.respond
def lost_reply(path, payload):
if path.endswith("battleEnd"):
raise TimeoutError("synthetic lost settlement reply")
return original(path, payload)
self.client.call.side_effect = lost_reply
with self.assertRaises(TimeoutError):
self.engine.poll()
self.engine.poll()
self.assertEqual(self.paths(), ["stageService/stageStart", "battleService/battleEnd"])
self.assertEqual(self.engine.sweeper.used(self.engine.snapshot, self.stage()), 1)