Add hatch retention, automatic breakthroughs and exploration

This commit is contained in:
AttilaNet
2026-11-09 11:27:29 +08:00
parent 26be820ff2
commit 9f819d828a
32 changed files with 6207 additions and 83 deletions
+4 -3
View File
@@ -23,9 +23,10 @@
| 玩家信息 | 显示等级、经验与下一级门槛、金币、氪金、体力;经验达到门槛及体力恢复到期时,在后台请求服务器结算并更新显示。 | | 玩家信息 | 显示等级、经验与下一级门槛、金币、氪金、体力;经验达到门槛及体力恢复到期时,在后台请求服务器结算并更新显示。 |
| 培育室 | 显示已开启、未开启、VIP坑位及魔物阶段、剩余时间和成熟资质;孵化与成长到期自动同步。普通坑位可在确认费用后扩建。 | | 培育室 | 显示已开启、未开启、VIP坑位及魔物阶段、剩余时间和成熟资质;孵化与成长到期自动同步。普通坑位可在确认费用后扩建。 |
| 分类背包 | 魔物蛋、可使用物品、消耗品、材料、其他、装备分别展示;支持搜索和排序。每种蛋可配置孵化开关、优先级、孵出后去向、补货下限/目标及市场;物品可配置赠礼开关和保留数量。 | | 分类背包 | 魔物蛋、可使用物品、消耗品、材料、其他、装备分别展示;支持搜索和排序。每种蛋可配置孵化开关、优先级、孵出后去向、补货下限/目标及市场;物品可配置赠礼开关和保留数量。 |
| 牧场与魔物管理 | 默认平铺全部魔物,可切换为按牧场折叠分组;显示容量、空位、等级与突破上限、资质、参考属性、好感上限及喜欢的物品。支持详情查看、多选锁定/解锁、派遣、指定喂养,以及确认费用后新建牧场。 | | 牧场与魔物管理 | 默认平铺全部魔物,可切换为按牧场折叠分组;显示容量、空位、普通等级上限、同种突破、突破经验、潜能阶段、资质、参考属性、好感上限及喜欢的物品。支持详情查看、多选锁定/解锁、派遣、指定喂养,以及确认费用后新建牧场。 |
| 自动孵蛋与补货 | 按手动规则完成金币市场买蛋/抽蛋、孵化、成长同步、成熟收取、派遣或喂养;默认只十连,可单独开启“允许单抽”,遵守金币保留和每日购蛋额度。空坑按优先级独立随机1~2秒装填,不受整体刷新间隔影响。 | | 自动孵蛋与补货 | 按手动规则完成金币市场买蛋/抽蛋、孵化、成长同步、成熟收取、派遣或喂养;默认只十连,可单独开启“允许单抽”,遵守金币保留和每日购蛋额度。空坑按优先级独立随机1~2秒装填,不受整体刷新间隔影响。 |
| 资质保留与经验喂养 | 支持星级、综合资质、四项全S(4S)保护,另可保留资质严格高于牧场同种培养代表的新魔物。经验喂养按目标优先级批量提交素材,遵守当前突破上限与停止等级,保护锁定、在队和委托所需魔物。 | | 资质保留与经验喂养 | “背包 → 魔物蛋”的“牧场保留”默认1,是最低保留数量,0表示关闭数量保护;同种数量跨牧场及孵化批次统一保底。锁定、星级/资质保护仍可让实际保留数超过该值;资质提升依次按S项数、A项数、B项数、四项成长各自归一化后的平均值,与牧场已保留的同种最高资质比较,严格更高才额外保留,同分不额外保留,不自动解锁或强删旧魔物。经验喂养遵守普通等级上限;同种突破最高4级,每只同种素材增加1点突破经验,与潜能阶段分开计算。 |
| 自动突破与探险 | 牧场勾选突破目标并设置优先级,即授权先补满四项潜能、再提升潜能阶段,消耗对应元素材料并遵守物品/委托保留量,不购买材料、不消耗金币或氪金。自动探险默认关闭,每队配置地区、保留体力和队员,完成后先领奖再出发,不花钱开队或召回;未知请求持久化,新快照确认前不重发,停止策略后继续只读刷新。 |
| 自动赠礼与好感培养 | 在背包选择物品、牧场选择目标后自动赠礼;跳过冷却目标,连续处理其他可送目标,在本地倒计时并到期核对状态。支持喜欢物品筛选、库存保留及当前好感上限。可在本地自动为每种魔物选择唯一培养代表,依次按等级、好感、成长资质比较,完全相同时随机选定并记住。 | | 自动赠礼与好感培养 | 在背包选择物品、牧场选择目标后自动赠礼;跳过冷却目标,连续处理其他可送目标,在本地倒计时并到期核对状态。支持喜欢物品筛选、库存保留及当前好感上限。可在本地自动为每种魔物选择唯一培养代表,依次按等级、好感、成长资质比较,完全相同时随机选定并记住。 |
| 每日事务 | 查看并领取每日签到礼包、七日签到、累计奖励、已有VIP日奖和邮件附件;支持手动领取及按勾选项目自动领取。 | | 每日事务 | 查看并领取每日签到礼包、七日签到、累计奖励、已有VIP日奖和邮件附件;支持手动领取及按勾选项目自动领取。 |
| 自动主线 | 展示主线、支线、委托的状态、位置、NPC、需求、对话和阻塞原因;推进已支持的接取、线性对话、交付、领奖与任务补链。材料、蛋或击杀不足时,按已知来源规划普通地图收集;开图受前置、资源和战斗能力限制。 | | 自动主线 | 展示主线、支线、委托的状态、位置、NPC、需求、对话和阻塞原因;推进已支持的接取、线性对话、交付、领奖与任务补链。材料、蛋或击杀不足时,按已知来源规划普通地图收集;开图受前置、资源和战斗能力限制。 |
@@ -34,7 +35,7 @@
| 自动扫荡与挑战 | 按地区折叠显示关卡、难度、通关星级及可能掉落;账号地图本地缓存,手动刷新或挑战结束后同步进度。逐关勾选、选择已解锁难度和本日次数上限,配置保留体力与战队;满足扫荡条件时扫荡,未满星时可自动模拟挑战,战败显示“打不过”,支持探索奖励事件。 | | 自动扫荡与挑战 | 按地区折叠显示关卡、难度、通关星级及可能掉落;账号地图本地缓存,手动刷新或挑战结束后同步进度。逐关勾选、选择已解锁难度和本日次数上限,配置保留体力与战队;满足扫荡条件时扫荡,未满星时可自动模拟挑战,战败显示“打不过”,支持探索奖励事件。 |
| 掉落数据分析 | 按账号、关卡与难度在本地保存扫荡记录,分别统计普通扫荡、奖励事件或合计;展示样本数、出现次数、总数量、实测掉落率、平均数量和95%区间。支持掉落率/每点体力获得数量的条形图,不额外请求游戏服务器。 | | 掉落数据分析 | 按账号、关卡与难度在本地保存扫荡记录,分别统计普通扫荡、奖励事件或合计;展示样本数、出现次数、总数量、实测掉落率、平均数量和95%区间。支持掉落率/每点体力获得数量的条形图,不额外请求游戏服务器。 |
| 收益资料与执行计划 | 内置749种魔物的培育时间、派遣金币、强化经验及每小时收益,支持名称/星级筛选和CSV/XLSX覆盖;执行计划显示下一步操作与等待原因。 | | 收益资料与执行计划 | 内置749种魔物的培育时间、派遣金币、强化经验及每小时收益,支持名称/星级筛选和CSV/XLSX覆盖;执行计划显示下一步操作与等待原因。 |
| 统一策略配置 | 规则修改后自动保存并应用;通过原生菜单保存、导入或导出当前账号的孵蛋、牧场、喂养、赠礼、委托、每日事务、扫荡、主线推进、战斗模式、刷新间隔及自定义收益资料。跨账号按魔物种类匹配培养目标,导出文件不包含账号凭据或服务器进度。 | | 统一策略配置 | 规则修改后自动保存并应用;通过原生菜单保存、导入或导出当前账号的孵蛋、牧场、喂养、突破、赠礼、委托、每日事务、探险、扫荡、主线推进、战斗模式、刷新间隔及自定义收益资料。跨账号按魔物种类匹配培养/突破目标,探险按队序重新绑定并匹配队员,隐藏页不丢规则;不复制原账号实例ID,不包含凭据或服务器进度。 |
| 界面与调试 | 原生Qt菜单、可调整和隐藏的日志区、各页右键刷新;数字与勾选项可排序,数字框获得焦点后才响应滚轮,下拉框按内容扩宽。独立调试窗口查看请求、响应、耗时与错误,支持复制、导出和本地脱敏日志。 | | 界面与调试 | 原生Qt菜单、可调整和隐藏的日志区、各页右键刷新;数字与勾选项可排序,数字框获得焦点后才响应滚轮,下拉框按内容扩宽。独立调试窗口查看请求、响应、耗时与错误,支持复制、导出和本地脱敏日志。 |
| 后台处理与离线演示 | 各账号后台线程独立处理网络与资料,单账号请求串行;只渲染当前查看页面,大列表分批更新并复用控件。支持随机30秒、60秒、2分钟或5分钟上限的刷新间隔,以及无需连接服务器的离线演示。 | | 后台处理与离线演示 | 各账号后台线程独立处理网络与资料,单账号请求串行;只渲染当前查看页面,大列表分批更新并复用控件。支持随机30秒、60秒、2分钟或5分钟上限的刷新间隔,以及无需连接服务器的离线演示。 |
+7 -4
View File
@@ -35,15 +35,18 @@
- 多账号:同一程序内多个独立账号页签,登录后各自自动刷新状态,策略分别开启或关闭;切换页签不停止其他账号。 - 多账号:同一程序内多个独立账号页签,登录后各自自动刷新状态,策略分别开启或关闭;切换页签不停止其他账号。
- 会话保存:成功读取角色后自动加密保存 Token、账号/区服/角色和请求编号,重启后可恢复。 - 会话保存:成功读取角色后自动加密保存 Token、账号/区服/角色和请求编号,重启后可恢复。
- 自动孵蛋:按手动规则执行,使用顶部统一的“开启 / 停止”开关;默认关闭单抽,只十连,遵守金币保留和每日购蛋额度。 - 自动孵蛋:按手动规则执行,使用顶部统一的“开启 / 停止”开关;默认关闭单抽,只十连,遵守金币保留和每日购蛋额度。
可选随机30秒、60秒、2分钟或5分钟,每轮刷新完成后从0到所选上限重新取间隔;喂养遵守当前突破上限,满级后转到下一喂养目标。 可选随机30秒、60秒、2分钟或5分钟,每轮刷新完成后从0到所选上限重新取间隔;喂养遵守普通等级上限,满级后转到下一喂养目标。
空坑装填单独计时:有可用蛋时随机等待1~2秒装填一个坑位,确认成功后继续下一坑,不受整体刷新间隔影响。 空坑装填单独计时:有可用蛋时随机等待1~2秒装填一个坑位,确认成功后继续下一坑,不受整体刷新间隔影响。
每次装填前重新读取坑位和库存;无可用蛋、坑位已满或关闭策略时暂停。此快速计时不会执行购蛋、派遣或其他操作。 每次装填前重新读取坑位和库存;无可用蛋、坑位已满或关闭策略时暂停。此快速计时不会执行购蛋、派遣或其他操作。
子页分为“孵蛋策略”“牧场策略”“喂养策略”,内容超出高度时滚动显示,修改后自动保存并应用。 子页分为“孵蛋策略”“牧场策略”“喂养策略”,内容超出高度时滚动显示,修改后自动保存并应用。
“牧场策略”新增独立开关“保留资质高于牧场同种培养代表的新魔物”,与S/A/B/C、4S及星级保护分别生效。 “牧场策略”新增独立开关“保留资质高于牧场同种培养代表的新魔物”,与S/A/B/C、4S及星级保护分别生效。
同种培养代表优先选等级最高者,再依次比较好感、综合成长资质;新魔物的四项成长按各自范围归一化后取平均,严格更高才算提升。 新魔物与牧场已保留的同种最高资质比较,依次按S项数、A项数、B项数、四项成长各自归一化后的平均值排序,严格更高才额外保留。
同分不算提升;牧场尚无同种时保留首只,代表资质未同步完整时暂留。已有锁定、队伍及保留种类保护继续生效。 同分不额外保留;已有锁定、队伍及保留种类保护继续生效。
- 统一策略配置:通过主窗口菜单“策略配置”,保存、导入或导出当前账号的全部孵蛋、牧场、喂养、赠礼、委托、每日事务、扫荡、主线推进、战斗模式及监控间隔设置,包含自定义收益资料。 - 统一策略配置:通过主窗口菜单“策略配置”,保存、导入或导出当前账号的全部孵蛋、牧场、喂养、赠礼、委托、每日事务、扫荡、主线推进、战斗模式及监控间隔设置,包含自定义收益资料。
跨账号按魔物种类匹配喂养和赠礼目标;牧场实例编号不跨账号复制,默认使用有空位的牧场。兼容旧版培养策略文件。 跨账号按魔物种类匹配喂养、赠礼和突破目标;探险队伍按队序重新绑定,手动队员按种类匹配且不复用原账号实例ID。探险总开关导入后关闭,顶部策略执行开关保持关闭,其余功能按原导入保留勾选。隐藏页不会裁剪规则,兼容旧版培养策略文件。
- 牧场保留与自动突破:“背包 → 魔物蛋”中每种蛋的“牧场保留”默认1,是最低保留数量,0关闭数量保护;同种数量跨牧场及孵化批次统一保底。锁定、星级/资质保护仍可超过数量,“更好资质额外保留”会额外保留,不自动解锁旧只或强行派遣。普通等级上限、同种突破(最高4级、每只同种素材+1突破经验)与潜能阶段是三种独立进度。
勾选“自动突破目标”即授权先补满四项潜能、再提升潜能阶段,消耗对应元素材料并沿用物品/委托保留量,不购买材料、不花金币或氪金。未勾选目标时不规划或输出突破提示。
- 自动探险:独立页签,默认关闭,每队配置开关、地区、三只手动队员或自动选人及保留体力;先领奖再出发,不花钱开队或召回。未解锁只显示原因,不阻断牧场等其他自动化;未确认的请求保留在角色本地状态中,新快照确认前禁止重发,停止后的刷新只读不写。
导入保留功能勾选和规则,策略开关保持关闭,核对后手动开启;文件不包含账号、密码、Token、会话或本机路径。 导入保留功能勾选和规则,策略开关保持关闭,核对后手动开启;文件不包含账号、密码、Token、会话或本机路径。
- 自动赠礼:独立页签,在背包勾选可用物品,在牧场勾选目标并设置优先级,再到“自动赠礼”启用。 - 自动赠礼:独立页签,在背包勾选可用物品,在牧场勾选目标并设置优先级,再到“自动赠礼”启用。
每次消耗一件物品,默认只使用目标喜欢的物品;遵守当前羁绊好感上限、赠礼间隔、物品保留数量及委托保留。 每次消耗一件物品,默认只使用目标喜欢的物品;遵守当前羁绊好感上限、赠礼间隔、物品保留数量及委托保留。
+272
View File
@@ -0,0 +1,272 @@
"""Plan one original-client potential operation from a fresh snapshot.
This module never calls a Client or updates snapshot state. The runner must read
the snapshot again after executing either returned Action. ``potentialLevel``
is the material-based PotentialPanel stage; feeding's ``tpLevel/tpExp`` is a
separate progression and deliberately does not affect readiness here.
"""
from __future__ import annotations
from dataclasses import dataclass
from .model import Action
PATH = "monsterService/monsterPotentialLevelUpgrade"
POTENTIAL_PATH = "monsterService/monsterPotentialUpgrade"
STATS = ("atk", "def", "hp", "dex")
LABELS = {"atk": "攻击", "def": "防御", "hp": "生命", "dex": "敏捷"}
def integer(value):
"""Accept integer-valued server numbers, not lossy bool/NaN conversions."""
if isinstance(value, bool) or value is None:
return None
if isinstance(value, str):
try:
return int(value.strip())
except (ValueError, OverflowError):
return None
try:
result = int(value)
except (TypeError, ValueError, OverflowError):
return None
try:
return result if result == value else None
except (TypeError, ValueError):
return None
def field(row, name, default=None):
if isinstance(row, dict):
return row.get(name, default)
return getattr(row, name, default)
@dataclass(frozen=True)
class Material:
type_id: int
required: int
available: int
item_ids: tuple[int, ...]
@dataclass(frozen=True)
class Candidate:
monster: dict
next_level: int
materials: tuple[Material, ...]
reason: str
@property
def ready(self):
return bool(self.materials) and not self.reason
class BreakthroughPlanner:
"""Plan PotentialPanel writes; each call returns at most one operation."""
def __init__(self, catalog):
self.catalog = catalog
self.notes = []
@staticmethod
def target_ids(policy, targets=None):
"""Explicit targets replace feeding, including an explicitly empty map."""
if targets is None:
targets = field(policy, "feed_targets")
if targets:
pass
else:
legacy = integer(field(policy, "feed_target", 0))
return [legacy] if legacy is not None and legacy > 0 else []
if not isinstance(targets, dict):
return []
pairs = []
for mid, priority in targets.items():
mid, priority = integer(mid), integer(priority)
if mid is not None and mid > 0 and priority is not None:
pairs.append((priority, mid))
return [mid for _, mid in sorted(pairs)]
@staticmethod
def reserves(policy, type_id):
"""Combine the target-item switch with ranch and quest reservations."""
key = str(type_id)
quest = field(policy, "quest_policy", {})
gift_rule = field(policy, "gift_items", {}).get(key, {})
values = [field(policy, "reserved_eggs", {}).get(key, 0),
field(policy, "item_reserves", {}).get(key, 0),
field(quest, "item_reserves", {}).get(key, 0),
field(gift_rule, "reserve", 0)]
parsed = [integer(value) for value in values]
if any(value is None or value < 0 for value in parsed):
return None
return max(parsed, default=0)
def stacks(self, snapshot, policy):
groups, seen = {}, set()
for item in snapshot.raw["items"]:
item_id, type_id, count = (integer(item.get(key)) for key in ("id", "typeId", "num"))
if item_id is None or type_id is None or count is None or item_id <= 0 or count <= 0:
continue
if item_id in seen:
raise ValueError("背包材料实例重复,暂不操作")
seen.add(item_id)
groups.setdefault(type_id, []).append((item_id, count, item))
usable = {}
for type_id, entries in groups.items():
reserve = self.reserves(policy, type_id)
if reserve is None:
raise ValueError("突破道具保留数量配置无效")
entries = [entry for entry in entries if not entry[2].get("lock") and not entry[2].get("feedLock")]
total = sum(count for _, count, _ in entries)
usable[type_id] = {"entries": entries, "available": max(0, total - reserve), "total": total}
return usable
def select_stack(self, usable, type_id, amount, reserved=None):
"""Select one sufficient stack; do not aggregate stock for itemIds."""
stock = usable.get(type_id, {"entries": [], "available": 0})
if stock["available"] < amount:
return None
entries = stock["entries"] if reserved is None else [
entry for entry in stock["entries"] if entry[0] not in reserved]
eligible = [entry for entry in entries if entry[1] >= amount]
if not eligible:
return None
item_id, count, _ = min(eligible, key=lambda entry: (entry[1], entry[0]))
return item_id, count
def caps(self, mon):
info = self.catalog.data.get("potential_info", {})
row = self.catalog.monster(mon.get("typeId"))
level = integer(mon.get("potentialLevel"))
if level is None or level < 1 or not row:
return None, None, "突破等级或魔物资料尚未同步"
maximum = integer(info.get("maxPotentialLevel"))
if maximum is not None and level >= maximum:
return None, None, "已达到最高突破等级"
caps = (info.get("potential") or {}).get(str(row.get("job")), {}).get(str(row.get("star")))
if not caps:
return None, None, "当前突破配置缺失"
result = {}
for stat in STATS:
base, increment = integer(caps.get(stat)), integer(caps.get(stat + "TpAdd"))
current = integer(mon.get("p" + stat.capitalize()))
if base is None or increment is None or current is None:
return None, None, "潜能数据尚未同步"
cap = base + (level - 1) * increment
if cap < 0 or current < 0:
return None, None, "潜能数据异常"
result[stat] = (current, cap)
return level, result, ""
def potential_action(self, mon, caps, usable):
"""One original addPotential call consumes exactly one type-ID item."""
row = self.catalog.monster(mon.get("typeId"))
type_id = integer((self.catalog.data.get("potential_info", {}).get("potentialElementItem") or {}).get(str(row.get("element"))))
if type_id is None:
return None, "当前补潜能材料配置缺失"
selected = self.select_stack(usable, type_id, 1)
incomplete = [stat for stat in STATS if caps[stat][0] < caps[stat][1]]
if selected is None:
total = usable.get(type_id, {}).get("available", 0)
return None, f"补潜能材料不足或受保留数量限制:{self.catalog.item_name(type_id)} {total}/1"
stat = min(incomplete, key=lambda key: (caps[key][1] - caps[key][0], STATS.index(key)))
item_id, count = selected
current, cap = caps[stat]
description = (f"补潜能 {self.catalog.monster_label(mon)} {LABELS[stat]} {current}/{cap}"
f"(消耗 {self.catalog.item_name(type_id)}×1;成功后重新读取,四项满再突破)")
return Action("potential", description, POTENTIAL_PATH,
{"traceInfo": {"itemTypeId": item_id, "itemNum": count},
"monId": integer(mon["id"]), "itemId": item_id, "monsterAttr": stat}), ""
def evaluate(self, mon, items, policy=None, snapshot=None):
"""Compatibility helper for stage evaluation with the same stock rules."""
if snapshot is None:
snapshot = type("ItemsSnapshot", (), {"raw": {"items": items}})()
policy = policy if policy is not None else type("ItemPolicy", (), {
"gift_items": {}})()
level, caps, reason = self.caps(mon)
if level is None:
return Candidate(mon, 0, (), reason)
incomplete = [f"{LABELS[stat]} {current}/{cap}" for stat, (current, cap) in caps.items() if current < cap]
if incomplete:
return Candidate(mon, level + 1, (), "潜能未满:" + ",".join(incomplete))
info = self.catalog.data.get("potential_info", {})
row = self.catalog.monster(mon.get("typeId"))
need = (info.get("potentialLevelItem") or {}).get(str(row.get("star")), {}).get(str(level))
elements = (info.get("elementItem") or {}).get(str(row.get("element")))
if not need or not elements:
return Candidate(mon, level + 1, (), "当前突破配置缺失")
try:
usable = self.stacks(snapshot, policy)
except ValueError as error:
return Candidate(mon, level + 1, (), str(error))
requirements = {}
for level_key in sorted(need, key=lambda key: integer(key[2:]) or 999):
type_id, amount = integer(elements.get(level_key)), integer(need[level_key])
if type_id is None or amount is None or amount <= 0:
return Candidate(mon, level + 1, (), "当前突破材料配置异常")
requirements[type_id] = requirements.get(type_id, 0) + amount
materials, missing, selected_ids = [], [], set()
for type_id, amount in requirements.items():
selected = self.select_stack(usable, type_id, amount)
available = usable.get(type_id, {}).get("available", 0)
materials.append(Material(type_id, amount, available, (selected[0],) if selected else ()))
if selected is None:
missing.append(f"{self.catalog.item_name(type_id)} 可用单堆不足 {available}/{amount}")
else:
selected_ids.add(selected[0])
return Candidate(mon, level + 1, tuple(materials), "材料不足:" + ",".join(missing) if missing else "")
def plan(self, snapshot, policy, *, targets=None, enabled=True):
self.notes = []
if not enabled or field(policy, "enabled", True) is not True:
return None
ids = self.target_ids(policy, targets)
if not ids:
self.notes.append("未选择自动突破目标")
return None
for mid in ids:
mon = snapshot.monsters.get(mid)
if not mon:
self.notes.append(f"#{mid} 已不在角色数据中")
continue
label = self.catalog.monster_label(mon)
if mon.get("process") != 3:
self.notes.append(f"{label} 不在牧场")
continue
if mon.get("inExploreTeam") or mon.get("inBuild"):
self.notes.append(f"{label} 正在探险或建筑,暂停自动突破")
continue
level, caps, reason = self.caps(mon)
if level is None:
self.notes.append(f"{label}:{reason}")
continue
try:
usable = self.stacks(snapshot, policy)
except ValueError as error:
self.notes.append(f"{label}:{error}")
continue
if any(current < cap for current, cap in caps.values()):
action, reason = self.potential_action(mon, caps, usable)
if action:
self.notes.append(f"{label} 先补满四项潜能,再提升至 {level + 1} 阶段;每轮仅操作一次")
return action
self.notes.append(f"{label}:{reason}")
continue
candidate = self.evaluate(mon, snapshot.raw["items"], policy, snapshot)
if not candidate.ready:
self.notes.append(f"{label}:{candidate.reason}")
continue
item_ids = [item_id for material in candidate.materials for item_id in material.item_ids]
cost = "、".join(f"{self.catalog.item_name(m.type_id)}×{m.required}" for m in candidate.materials)
self.notes.append(f"{label} 可提升至 {candidate.next_level} 阶段")
return Action("breakthrough", f"突破 {label} → {candidate.next_level} 阶段({cost};不消耗tp经验)",
PATH, {"monId": mid, "itemIds": item_ids})
return None
def plan_breakthrough(catalog, snapshot, policy, *, targets=None, enabled=True):
return BreakthroughPlanner(catalog).plan(snapshot, policy, targets=targets, enabled=enabled)
+17
View File
@@ -19,6 +19,23 @@ def growth_score(catalog, mon):
return round(sum(values) / 4, 9) if values is not None else None return round(sum(values) / 4, 9) if values is not None else None
def quality_rank(catalog, mon):
"""Compare letter grades before using raw growth to break exact-grade ties."""
qualities = catalog.quality(mon)
if any(value is None for value in qualities):
return None
# A and B grades are compared per attribute. A raw average must never
# make AASA outrank SSAS (or turn an S-grade advantage into a B-grade one).
return (sum(value == 4 for value in qualities), sum(value == 3 for value in qualities),
sum(value == 2 for value in qualities), growth_score(catalog, mon))
def quality_summary(catalog, mon):
qualities = catalog.quality(mon)
names = {1: "C", 2: "B", 3: "A", 4: "S"}
return "".join(names.get(value, "?") for value in qualities)
class CultivationSelector: class CultivationSelector:
def __init__(self, catalog, path=None): def __init__(self, catalog, path=None):
self.catalog = catalog self.catalog = catalog
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
+16 -10
View File
@@ -12,7 +12,7 @@ class EggTable(W.QTableWidget):
def __init__(self, catalog): def __init__(self, catalog):
headers = ["魔物蛋", "星", "数量", "孵化", "优先级", "孵出后", "低于补货", "补至", "补货市场", headers = ["魔物蛋", "星", "数量", "孵化", "优先级", "孵出后", "低于补货", "补至", "补货市场",
"培育时间", "派遣金币", "基础经验", "金币/小时", "经验/小时", "物品ID"] "培育时间", "派遣金币", "基础经验", "金币/小时", "经验/小时", "物品ID", "牧场保留"]
super().__init__(0, len(headers)) super().__init__(0, len(headers))
self.catalog, self.rules, self.snapshot = catalog, {}, None self.catalog, self.rules, self.snapshot = catalog, {}, None
self.default_market = "sc_city1" self.default_market = "sc_city1"
@@ -21,7 +21,7 @@ class EggTable(W.QTableWidget):
self.setEditTriggers(W.QAbstractItemView.EditTrigger.NoEditTriggers) self.setEditTriggers(W.QAbstractItemView.EditTrigger.NoEditTriggers)
self.setSelectionBehavior(W.QAbstractItemView.SelectionBehavior.SelectRows) self.setSelectionBehavior(W.QAbstractItemView.SelectionBehavior.SelectRows)
self.horizontalHeader().setSectionResizeMode(W.QHeaderView.ResizeMode.Interactive) self.horizontalHeader().setSectionResizeMode(W.QHeaderView.ResizeMode.Interactive)
for column, width in enumerate((130, 45, 65, 65, 90, 135, 95, 95, 220, 95, 90, 90, 100, 100, 160)): for column, width in enumerate((130, 45, 65, 65, 90, 135, 95, 95, 220, 95, 90, 90, 100, 100, 160, 90)):
self.setColumnWidth(column, width) self.setColumnWidth(column, width)
self.verticalHeader().setDefaultSectionSize(24) self.verticalHeader().setDefaultSectionSize(24)
@@ -60,6 +60,7 @@ class EggTable(W.QTableWidget):
money, exp = data.get("sell_money", 0), data.get("sell_exp", 0) money, exp = data.get("sell_money", 0), data.get("sell_exp", 0)
values = [data.get("name", key), data.get("star", "?"), group["count"], "", "", "", "", "", "", values = [data.get("name", key), data.get("star", "?"), group["count"], "", "", "", "", "", "",
duration(total), money, exp, round(money * 3600 / total, 2), round(exp * 3600 / total, 2), ", ".join(group["ids"])] duration(total), money, exp, round(money * 3600 / total, 2), round(exp * 3600 / total, 2), ", ".join(group["ids"])]
values.append("")
for j, value in enumerate(values): for j, value in enumerate(values):
item = self.item(i, j) item = self.item(i, j)
if item is None: if item is None:
@@ -74,20 +75,21 @@ class EggTable(W.QTableWidget):
item.setToolTip(f"魔物编号 {key}") item.setToolTip(f"魔物编号 {key}")
existing = self.cellWidget(i, 3) existing = self.cellWidget(i, 3)
if existing and existing.property("egg_type_id") == key: if existing and existing.property("egg_type_id") == key:
controls = [self.cellWidget(i, col) for col in range(3, 9)] controls = [self.cellWidget(i, col) for col in range(3, 9)] + [self.cellWidget(i, 15)]
blockers = [C.QSignalBlocker(control) for control in controls] blockers = [C.QSignalBlocker(control) for control in controls]
controls[0].setChecked(rule["enabled"]) controls[0].setChecked(rule["enabled"])
for control, field in ((controls[1], "priority"), (controls[3], "refill_below"), (controls[4], "refill_target")): for control, field in ((controls[1], "priority"), (controls[3], "refill_below"), (controls[4], "refill_target"),
(controls[6], "keep_count")):
if not control.hasFocus(): if not control.hasFocus():
control.setValue(rule[field]) control.setValue(rule[field])
controls[2].setCurrentIndex(max(0, controls[2].findData(rule["action"]))) controls[2].setCurrentIndex(max(0, controls[2].findData(rule["action"])))
controls[5].setCurrentIndex(max(0, controls[5].findData(rule["market_id"]))) controls[5].setCurrentIndex(max(0, controls[5].findData(rule["market_id"])))
bind_controls(self, i, dict(zip(range(3, 9), controls))) bind_controls(self, i, dict(zip(list(range(3, 9)) + [15], controls)))
return return
enabled = CenteredCheckBox() enabled = CenteredCheckBox()
enabled.setProperty("egg_type_id", key) enabled.setProperty("egg_type_id", key)
enabled.setChecked(rule["enabled"]) enabled.setChecked(rule["enabled"])
priority, below, target = IntegerInput(), IntegerInput(), IntegerInput() priority, below, target, keep_count = IntegerInput(), IntegerInput(), IntegerInput(), IntegerInput()
for control, low, high, value in ((priority, 1, 999, rule["priority"]), (below, 0, 1000, rule["refill_below"]), for control, low, high, value in ((priority, 1, 999, rule["priority"]), (below, 0, 1000, rule["refill_below"]),
(target, max(1, rule["refill_below"]), 1000, rule["refill_target"])): (target, max(1, rule["refill_below"]), 1000, rule["refill_target"])):
control.setRange(low, high) control.setRange(low, high)
@@ -95,6 +97,9 @@ class EggTable(W.QTableWidget):
priority.setToolTip("数字越小,孵化优先级越高") priority.setToolTip("数字越小,孵化优先级越高")
below.setToolTip("可用蛋少于此数量时补货;0表示不自动补货") below.setToolTip("可用蛋少于此数量时补货;0表示不自动补货")
target.setToolTip("补货希望达到的可用蛋数量;市场随机出蛋,实际结果由服务器决定") target.setToolTip("补货希望达到的可用蛋数量;市场随机出蛋,实际结果由服务器决定")
keep_count.setRange(0, 1000)
keep_count.setValue(rule["keep_count"])
keep_count.setToolTip("所有已启用规则均按此数量跨牧场保留;0表示不保留名额,硬保护仍有效")
action, market = ComboBox(), ComboBox() action, market = ComboBox(), ComboBox()
for name, value in (("派遣", "sell"), ("喂养", "feed"), ("保留", "keep")): for name, value in (("派遣", "sell"), ("喂养", "feed"), ("保留", "keep")):
action.addItem(name, value) action.addItem(name, value)
@@ -108,8 +113,8 @@ class EggTable(W.QTableWidget):
self.setColumnWidth(5, max(self.columnWidth(5), action.minimumSizeHint().width())) self.setColumnWidth(5, max(self.columnWidth(5), action.minimumSizeHint().width()))
self.setColumnWidth(8, max(self.columnWidth(8), market.minimumSizeHint().width())) self.setColumnWidth(8, max(self.columnWidth(8), market.minimumSizeHint().width()))
controls = {"enabled": enabled, "priority": priority, "action": action, "refill_below": below, controls = {"enabled": enabled, "priority": priority, "action": action, "refill_below": below,
"refill_target": target, "market_id": market} "refill_target": target, "market_id": market, "keep_count": keep_count}
for column, control in zip(range(3, 9), controls.values()): for column, control in zip(list(range(3, 9)) + [15], controls.values()):
self.setCellWidget(i, column, control) self.setCellWidget(i, column, control)
def commit(*args, key=key, controls=controls): def commit(*args, key=key, controls=controls):
if self.updating: if self.updating:
@@ -118,14 +123,15 @@ class EggTable(W.QTableWidget):
value = {"enabled": controls["enabled"].isChecked(), "priority": controls["priority"].value(), value = {"enabled": controls["enabled"].isChecked(), "priority": controls["priority"].value(),
"action": controls["action"].currentData(), "refill_below": controls["refill_below"].value(), "action": controls["action"].currentData(), "refill_below": controls["refill_below"].value(),
"refill_target": controls["refill_target"].value(), "market_id": controls["market_id"].currentData()} "refill_target": controls["refill_target"].value(), "market_id": controls["market_id"].currentData()}
value["keep_count"] = controls["keep_count"].value()
self.rules[key] = asdict(EggRule(**value)) self.rules[key] = asdict(EggRule(**value))
self.rules_changed.emit(copy.deepcopy(self.rules), key) self.rules_changed.emit(copy.deepcopy(self.rules), key)
enabled.toggled.connect(commit) enabled.toggled.connect(commit)
for control in (priority, below, target): for control in (priority, below, target, keep_count):
control.valueChanged.connect(commit) control.valueChanged.connect(commit)
action.currentIndexChanged.connect(commit) action.currentIndexChanged.connect(commit)
market.currentIndexChanged.connect(commit) market.currentIndexChanged.connect(commit)
bind_controls(self, i, dict(zip(range(3, 9), controls.values()))) bind_controls(self, i, dict(zip(list(range(3, 9)) + [15], controls.values())))
def finish(): def finish():
self.setSortingEnabled(True) self.setSortingEnabled(True)
self.updating = False self.updating = False
+239 -4
View File
@@ -1,11 +1,13 @@
from __future__ import annotations from __future__ import annotations
from copy import copy, deepcopy from copy import copy, deepcopy
from dataclasses import replace from dataclasses import asdict, replace
from functools import wraps from functools import wraps
import json import json
import os
from pathlib import Path from pathlib import Path
import threading import threading
import time import time
import uuid
from types import SimpleNamespace 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
@@ -22,6 +24,8 @@ from .battles import BattleJournal, BattleOrchestrator, CancelledBeforeDispatch,
from .progression import ProgressionIntent, ProgressionPlanner, ProgressionPolicy from .progression import ProgressionIntent, ProgressionPlanner, ProgressionPolicy
from .battle_messages import battle_message from .battle_messages import battle_message
from .maps import stages from .maps import stages
from .exploration import ExplorePlanner, ExplorePolicy
from .breakthrough import BreakthroughPlanner
def account_serial(method): def account_serial(method):
@@ -78,6 +82,17 @@ class Engine:
self.daily_ledger = DailyLedger(folder / "daily_claims.json" if folder else None) self.daily_ledger = DailyLedger(folder / "daily_claims.json" if folder else None)
self.sweep_policy = SweepPolicy() self.sweep_policy = SweepPolicy()
self.sweeper = SweepRunner(catalog, folder / "sweep_runs.json" if folder else None) self.sweeper = SweepRunner(catalog, folder / "sweep_runs.json" if folder else None)
self.explore_planner = ExplorePlanner(catalog)
self.explore_policy = ExplorePolicy()
self.breakthrough_planner = BreakthroughPlanner(catalog)
self.automation_state_path = folder / "automation_state.json" if folder else None
self._explore_pending_last_check = 0
self._explore_pending_confirmed = False
self._breakthrough_pending = None
self._breakthrough_pending_last_check = 0
self._breakthrough_pending_confirmed = False
self._automation_load_error = ""
self._load_automation_state()
self.progression_policy = ProgressionPolicy() self.progression_policy = ProgressionPolicy()
self.progression_view_active = False self.progression_view_active = False
self.progression_planner = None self.progression_planner = None
@@ -111,6 +126,193 @@ class Engine:
self._battle_runtimes = {"original": battle_runtime, "experimental": experimental_runtime} self._battle_runtimes = {"original": battle_runtime, "experimental": experimental_runtime}
self._selected_battle_mode = "original" self._selected_battle_mode = "original"
def _load_automation_state(self):
if not self.automation_state_path:
return
if not self.automation_state_path.exists():
self._automation_state = {"version": 1, "exploration": self.explore_planner.export_state(), "breakthrough": None}
self._save_automation_state()
return
try:
state = json.loads(self.automation_state_path.read_text(encoding="utf-8"))
if not isinstance(state, dict) or state.get("version") != 1 or set(state) != {"version", "exploration", "breakthrough"}:
raise ValueError("自动操作策略状态版本或结构无效")
if not isinstance(state["exploration"], dict):
raise ValueError("探险持久化状态无效")
self.explore_planner.restore_state(state["exploration"])
self._automation_state = deepcopy(state)
pending = state.get("breakthrough")
if pending is not None:
required = {"kind", "monster_id", "type_id", "attribute", "before", "item_type_ids", "path", "payload", "uncertain", "message", "role_id"}
if (not isinstance(pending, dict) or set(pending) != required or pending["kind"] not in ("potential", "breakthrough")
or type(pending["monster_id"]) is not int or pending["monster_id"] <= 0
or not isinstance(pending["role_id"], str) or not pending["role_id"]
or not isinstance(pending["payload"], dict) or not isinstance(pending["item_type_ids"], list)):
raise ValueError("突破待核对状态无效,保留文件并禁止重发")
if pending["kind"] == "potential":
if pending["attribute"] not in ("atk", "def", "hp", "dex") or type(pending["before"]) not in (int, float):
raise ValueError("补潜能待核对状态无效")
elif type(pending["before"]) is not int:
raise ValueError("潜能阶段待核对状态无效")
pending = deepcopy(pending)
pending.update(uncertain=True, message="上次进程突破请求结果未知,需由快照核对,禁止重放")
self._breakthrough_pending = pending
except (OSError, ValueError, TypeError, KeyError, AttributeError) as error:
# A failed restore stays fail-closed in memory; do not overwrite the evidence.
self._breakthrough_pending = {"kind": "invalid", "role_id": "", "message": "自动操作策略状态无法读取,禁止重发", "uncertain": True}
self._explore_pending_confirmed = False
self._automation_load_error = str(error)
def _save_automation_state(self):
if not self.automation_state_path:
return
if self._automation_load_error:
self.auto = False
raise ValueError("自动操作策略状态无法读取;保留原文件,禁止覆盖或重发")
value = {"version": 1, "exploration": self.explore_planner.export_state(), "breakthrough": self._breakthrough_pending}
if self._automation_state == value:
return
self.automation_state_path.parent.mkdir(parents=True, exist_ok=True)
temporary = self.automation_state_path.with_name(self.automation_state_path.name + "." + uuid.uuid4().hex + ".tmp")
try:
with temporary.open("w", encoding="utf-8") as stream:
json.dump(value, stream, ensure_ascii=False, indent=2, allow_nan=False)
stream.flush()
os.fsync(stream.fileno())
temporary.replace(self.automation_state_path)
self._automation_state = deepcopy(value)
except OSError:
self.auto = False
raise
finally:
temporary.unlink(missing_ok=True)
@staticmethod
def _automation_pending_message(planner, snapshot):
pending = planner.pending(snapshot)
return pending.get("message") if pending else ""
def _reconcile_exploration(self):
if self._automation_load_error:
return
pending = self.explore_planner.pending(self.snapshot)
if not pending:
return
if pending.get("uncertain"):
self.explore_planner.reconcile(self.snapshot)
else:
# A transport reply is not proof of server state; use the same fresh
# team fingerprint validation as an unknown-result recovery.
pending["uncertain"] = True
self.explore_planner.reconcile(self.snapshot)
self._save_automation_state()
def _discard_unsent_automation(self, *, explore=False, before=None):
"""Rollback is valid only before the host has invoked Client.call."""
if explore:
if before is not None:
self.explore_planner.restore_state(before)
else:
self._breakthrough_pending = None
self._save_automation_state()
def _reconcile_breakthrough(self):
pending = self._breakthrough_pending
if not pending:
return
if pending.get("kind") == "invalid":
return
if str(self.snapshot.raw.get("master", {}).get("id")) != pending.get("role_id"):
return
mon = self.snapshot.monsters.get(int(pending.get("monster_id", 0)))
if not mon or str(mon.get("typeId")) != str(pending.get("type_id")):
return
if pending["kind"] == "potential":
current, previous = mon.get("p" + pending["attribute"].capitalize()), pending.get("before")
if current is None or previous is None:
return
try:
confirmed = float(current) > float(previous)
except (TypeError, ValueError, OverflowError):
return
else:
try:
confirmed = int(mon.get("potentialLevel") or 0) > int(pending.get("before"))
except (TypeError, ValueError, OverflowError):
return
if confirmed:
self._breakthrough_pending = None
self._save_automation_state()
def _execute_explore(self, action):
before = self.explore_planner.export_state()
try:
self.explore_planner.mark_started(self.snapshot, action)
try:
self._save_automation_state()
except Exception:
# No wire call occurred: only this pre-dispatch failure may roll back.
self.explore_planner.restore_state(before)
self.auto = False
raise
if not self.auto or self._progression_cancel.is_set():
self._discard_unsent_automation(explore=True, before=before)
return self.snapshot, self.plans(), "探险请求尚未发送,已取消"
try:
response = self.client.call(action.path, deepcopy(action.payload))
self.explore_planner.acknowledge(self.snapshot, action, response)
self._save_automation_state()
except Exception as error:
self.explore_planner.mark_uncertain(self.snapshot, action, "探险请求结果未知:" + str(error))
self._save_automation_state()
self.auto = False
raise
self._explore_pending_last_check = time.monotonic()
self._explore_pending_confirmed = False
self.read_snapshot(sync_master=False)
return self.snapshot, self.plans(), action.description + ";已读取新快照核对"
except Exception:
self.auto = False
raise
def _execute_breakthrough(self, action):
if self._breakthrough_pending:
return self.snapshot, [], "突破请求待核对,禁止重发"
mon = self.snapshot.monsters[int(action.payload["monId"])]
attribute = action.payload.get("monsterAttr", "")
before = mon.get("p" + attribute.capitalize()) if action.kind == "potential" else mon.get("potentialLevel")
item_ids = ([int(action.payload["traceInfo"]["itemTypeId"])] if action.kind == "potential" else
[int(item_id) for item_id in action.payload["itemIds"]])
self._breakthrough_pending = {"kind": action.kind, "monster_id": int(mon["id"]), "type_id": str(mon.get("typeId")),
"attribute": attribute, "before": before, "item_type_ids": item_ids,
"path": action.path, "payload": deepcopy(action.payload), "uncertain": False,
"role_id": str(self.snapshot.raw.get("master", {}).get("id") or ""),
"message": action.description + ":请求进行中"}
try:
self._save_automation_state() # Must persist before any material request.
except Exception:
self._breakthrough_pending = None
self.auto = False
raise
if not self.auto or self._progression_cancel.is_set():
self._discard_unsent_automation()
return self.snapshot, self.plans(), "突破请求尚未发送,已取消"
try:
response = self.client.call(action.path, deepcopy(action.payload))
if not isinstance(response, dict) or response.get("resCode", 0) not in (0, "0"):
raise ValueError("突破请求尚未确认成功")
self._breakthrough_pending["message"] = action.description + ":请求已确认,等待新快照核对"
self._save_automation_state()
except Exception as error:
self._breakthrough_pending.update(uncertain=True, message="突破请求结果未知,禁止自动重发:" + str(error))
self._save_automation_state()
self.auto = False
raise
self._breakthrough_pending_last_check = time.monotonic()
self._breakthrough_pending_confirmed = False
self.read_snapshot(sync_master=False)
return self.snapshot, self.plans(), action.description + ";已读取新快照核对"
def cancel_progression(self): def cancel_progression(self):
"""Safe on Qt's thread while a worker is running; never waits or calls APIs.""" """Safe on Qt's thread while a worker is running; never waits or calls APIs."""
with self._progression_cancel_lock: with self._progression_cancel_lock:
@@ -313,7 +515,11 @@ class Engine:
"已从持久化成功回包恢复本地任务检查点;未重发请求") "已从持久化成功回包恢复本地任务检查点;未重发请求")
def pending_recovery_due(self): def pending_recovery_due(self):
return not self.demo and bool(self._progression_pending()) and time.monotonic() - self.last_pending_check >= 120 now = time.monotonic()
automation = bool(self.snapshot and (
self.explore_planner.pending(self.snapshot) and now - self._explore_pending_last_check >= 120
or self._breakthrough_pending and now - self._breakthrough_pending_last_check >= 120))
return not self.demo and bool(automation or self._progression_pending() and now - self.last_pending_check >= 120)
def _resume_pending_task_clock(self): def _resume_pending_task_clock(self):
record = self.battle_journal.pending(self.snapshot) record = self.battle_journal.pending(self.snapshot)
@@ -678,6 +884,8 @@ class Engine:
rows.append(mon) rows.append(mon)
self.snapshot.raw["monsters"] = rows self.snapshot.raw["monsters"] = rows
self.gift_planner.apply_confirmed(self.snapshot) self.gift_planner.apply_confirmed(self.snapshot)
self._reconcile_exploration()
self._reconcile_breakthrough()
self.sweeper.recover_reward_event(self.snapshot, getattr(getattr(self.client, "trace", None), "path", None)) self.sweeper.recover_reward_event(self.snapshot, getattr(getattr(self.client, "trace", None), "path", None))
self._refresh_progression_cache() self._refresh_progression_cache()
return self.snapshot return self.snapshot
@@ -801,6 +1009,14 @@ class Engine:
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分钟自动核对"
explore_pending = self.explore_planner.pending(self.snapshot)
if explore_pending or self._breakthrough_pending:
self.pending_hatches = []
if explore_pending:
message += ";" + explore_pending.get("message", "探险请求待核对") + ";后台每2分钟自动核对"
if self._breakthrough_pending:
message += ";" + self._breakthrough_pending.get("message", "突破请求待核对") + ";后台每2分钟自动核对"
return self.snapshot, [], message
try: try:
plans = self.plans() plans = self.plans()
except (ValueError, TypeError, KeyError, AttributeError) as error: except (ValueError, TypeError, KeyError, AttributeError) as error:
@@ -812,6 +1028,19 @@ class Engine:
action = actions[0] if actions else None action = actions[0] if actions else None
if action and defer_hatch and action.kind == "hatch": if action and defer_hatch and action.kind == "hatch":
action = None action = None
if self.auto and action and action.kind.startswith("explore_"):
if action.kind == "explore_blocked" or not action.path:
blocked = next((candidate for candidate in plans if candidate.path and not candidate.kind.startswith("explore_")), None)
if blocked is None:
return self.snapshot, plans, action.description
self.planner.notes.append(action.description)
action = blocked
else:
self.last_executed = True
return self._execute_explore(action)
if self.auto and action and action.kind in ("potential", "breakthrough"):
self.last_executed = True
return self._execute_breakthrough(action)
if self.auto and action is not None: if self.auto and action is not None:
self.last_executed = True self.last_executed = True
if action.kind == "progression": if action.kind == "progression":
@@ -998,14 +1227,20 @@ class Engine:
sweep_actions = [map_action] if map_action 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)
explore = self.explore_planner.plan(self.snapshot, self.explore_policy, policy)
breakthrough_policy = SimpleNamespace(**(asdict(policy) | {"item_reserves": dict(self.quest_policy.item_reserves)}))
breakthrough = self.breakthrough_planner.plan(self.snapshot, breakthrough_policy,
targets=policy.breakthrough_targets, enabled=not self._breakthrough_pending) if policy.breakthrough_targets else None
self.planner.notes.extend(self.gift_planner.notes) self.planner.notes.extend(self.gift_planner.notes)
self.planner.notes.extend(self.breakthrough_planner.notes)
breakthroughs = [breakthrough] if breakthrough else []
progression = [Action("progression", value(intent, "description", "推进任务"), "", {"intent": intent}) 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] 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"])] 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"])] progression = [action for action in progression if not self._is_commission(action.payload["intent"])]
if quests and quests[0].kind == "quest_reset": if quests and quests[0].kind == "quest_reset":
return quests + commission[:1] + daily + progression[:1] + gifts + ranch + sweep_actions return quests + commission[:1] + daily + progression[:1] + explore + breakthroughs + gifts + ranch + sweep_actions
return commission[:1] + quests + daily + progression[:1] + gifts + ranch + sweep_actions return commission[:1] + quests + daily + progression[:1] + explore + breakthroughs + gifts + ranch + sweep_actions
@account_serial @account_serial
def claim_daily_entry(self, entry): def claim_daily_entry(self, entry):
+719
View File
@@ -0,0 +1,719 @@
"""Offline automatic exploration policy, planning and durable send guards.
Integration contract (the engine owns the snapshot, HTTP client and persistence
directory; this module never imports or calls the real API):
* ``ExplorePolicy(enabled=False, reserve_ti=0, teams={})`` has ``to_dict()``
and ``ExplorePolicy.from_dict(mapping)``. Each team rule is
``{"enabled": bool, "area": "1", "monsters": [int, int, int]}``.
An empty monster list means automatic selection; no other placeholders are
accepted. Locked, high-star and equipped monsters are valid explorers.
* ``ExplorePlanner(catalog, areas=None, *, path=None, account_key=None)``.
``path`` enables internal atomic persistence of account-keyed pending sends.
Keys hash the role identity, never an account login, password or token.
``account_key`` optionally supplies an already-stable profile namespace.
* ``plan(snapshot, policy, ranch_policy) -> list[Action]`` returns zero or one
action. ``explore_start`` uses ``exploreService/start`` and payload
``{exploreTeamId, monsters, area}``; ``explore_finish`` uses
``exploreService/finish`` and payload ``{exploreTeamId}``. Finished teams
are always rewarded before a subsequent start. ``explore_blocked`` has an
empty path and a diagnostic payload; callers MUST NOT execute it.
* ``execute(snapshot, action, call)`` is the smallest runner adapter: pass the
existing ``client.call`` callable. It persists before dispatch, confirms only
successful responses, and marks every other outcome unresolved. Its return
value is the response dictionary. Direct runners instead call
``mark_started(snapshot, action)`` BEFORE sending, then
``acknowledge(snapshot, action, response)`` after confirmed success, or
``mark_uncertain(snapshot, action, reason="...")`` after an ambiguous result.
* ``reconcile(snapshot)`` resolves an unresolved send only from an authoritative
matching team snapshot. It never invents a success or clears on an unchanged
or missing snapshot. ``pending(snapshot)`` returns a small copy.
* ``rows(snapshot, policy, ranch_policy)`` and ``member_options(snapshot,
team_id, policy, ranch_policy)`` return compact plain data for worker threads.
``export_state()`` / ``restore_state(state)`` support host-owned persistence;
use one of these mechanisms, not two independent state files.
The planner never adds a paid team and never recalls an active team.
"""
from __future__ import annotations
from copy import deepcopy
from dataclasses import asdict, dataclass, field
import hashlib
import json
import math
import os
from pathlib import Path
import re
import threading
from .model import Action, seconds
DATA_PATH = Path(__file__).with_name("data") / "exploration.json"
STATE_VERSION = 1
WIRE_KINDS = {"explore_start", "explore_finish"}
PATHS = {"explore_start": "exploreService/start", "explore_finish": "exploreService/finish"}
def load_exploration_areas(path=DATA_PATH):
document = json.loads(Path(path).read_text(encoding="utf-8"))
if document.get("schema") != 1 or not isinstance(document.get("areas"), list):
raise ValueError("探险地区数据格式错误")
result = {}
for row in document["areas"]:
if not isinstance(row, dict) or row.get("team") != "normal":
continue
try:
key = str(_positive_id(row["id"], "地区编号"))
levels = row["level"]
if not isinstance(levels, list) or len(levels) != 3:
raise ValueError
levels = [_nonnegative_int(value, "地区等级") for value in levels]
cost_ti = _nonnegative_int(row.get("costTi", 0), "地区体力")
cost_time = _nonnegative_int(row.get("costTime", 0), "地区时长")
except (KeyError, TypeError, ValueError) as error:
raise ValueError("探险地区数据格式错误") from error
if key in result or not row.get("passStage"):
raise ValueError("探险地区数据格式错误")
result[key] = dict(row, id=key, level=levels, costTi=cost_ti, costTime=cost_time)
if not result:
raise ValueError("探险地区数据为空")
return result
def _integer(value, default=0):
if isinstance(value, bool):
return default
try:
number = float(value)
return int(number) if math.isfinite(number) and number.is_integer() else default
except (TypeError, ValueError, OverflowError):
return default
def _nonnegative_int(value, label):
if type(value) is not int or not 0 <= value <= 1_000_000_000:
raise ValueError(label + "必须为非负整数")
return value
def _positive_id(value, label="魔物编号"):
if isinstance(value, bool):
raise ValueError(label + "无效")
text = str(value)
if not text.isdigit() or int(text) <= 0 or int(text) > 9_223_372_036_854_775_807:
raise ValueError(label + "无效")
return int(text)
def _flag(mapping, key, level=None):
"""Match HistoryVo/StageCenter's explicit stage-level dictionary."""
if level is not None:
if not isinstance(mapping, dict):
return False
value = mapping.get(str(key), mapping.get(key))
if not isinstance(value, dict):
# Legacy flat snapshots used {stage: true}; nested is authoritative
# whenever the stage has a level map.
return value is True
return value.get(str(level), value.get(level)) is True
if isinstance(mapping, dict):
value = mapping.get(str(key), mapping.get(key))
return value is True or value == 1 and not isinstance(value, bool)
if isinstance(mapping, list):
if mapping and all(value is None or isinstance(value, bool) for value in mapping):
return str(key).isdigit() and 0 <= int(key) < len(mapping) and mapping[int(key)] is True
return str(key) in {str(value) for value in mapping if not isinstance(value, bool)}
return False
def _team_monsters(value):
# ExploreCenter.makeTeamByData uses ArrayUtil.split(data.monsters, ",").
if isinstance(value, str):
value = value.split(",")
if not isinstance(value, (list, tuple)):
return []
result = []
for item in value:
mid = _integer(item)
if mid > 0 and mid not in result:
result.append(mid)
return result
def _target_ids(*mappings):
result = set()
for mapping in mappings:
if isinstance(mapping, dict):
for key in mapping:
mid = _integer(key)
if mid > 0:
result.add(mid)
return result
@dataclass
class ExploreTeamRule:
enabled: bool = False
area: str = ""
monsters: list[int] = field(default_factory=list)
def __post_init__(self):
if type(self.enabled) is not bool:
raise ValueError("探险队伍开关必须为布尔值")
if not isinstance(self.area, str) or self.area and (not self.area.isdigit() or int(self.area) <= 0):
raise ValueError("探险地区编号无效")
self.area = str(int(self.area)) if self.area else ""
if not isinstance(self.monsters, list) or len(self.monsters) not in (0, 3):
raise ValueError("探险队员须为空或恰好三只")
self.monsters = [_positive_id(mid) for mid in self.monsters]
if len(set(self.monsters)) != len(self.monsters):
raise ValueError("探险队员不可重复")
@dataclass
class ExplorePolicy:
enabled: bool = False
teams: dict[str, ExploreTeamRule] = field(default_factory=dict)
reserve_ti: int = 0
def __post_init__(self):
if type(self.enabled) is not bool:
raise ValueError("自动探险开关必须为布尔值")
_nonnegative_int(self.reserve_ti, "探险保留体力")
if not isinstance(self.teams, dict):
raise ValueError("探险队伍配置必须为对象")
rules = {}
for key, value in self.teams.items():
team_id = _positive_id(key, "探险队伍编号")
if isinstance(value, ExploreTeamRule):
value = asdict(value)
if not isinstance(value, dict) or set(value) - {"enabled", "area", "monsters"}:
raise ValueError("探险队伍配置格式错误")
rules[str(team_id)] = ExploreTeamRule(**value)
self.teams = rules
def to_dict(self):
return {"enabled": self.enabled, "reserve_ti": self.reserve_ti,
"teams": {key: asdict(rule) for key, rule in self.teams.items()}}
@classmethod
def from_dict(cls, value):
if not isinstance(value, dict) or set(value) - {"enabled", "teams", "reserve_ti"}:
raise ValueError("自动探险策略格式错误")
return cls(**value)
class ExplorePlanner:
"""Pure snapshot planning plus a serialized, durable unresolved-send guard."""
def __init__(self, catalog, areas=None, *, path=None, account_key=None):
self.catalog = catalog
self.areas = load_exploration_areas() if areas is None else {
str(key): dict(value, id=str(key)) for key, value in areas.items()}
self._namespace = str(account_key) if account_key is not None else ""
self._path = Path(path) if path is not None else None
self._lock = threading.RLock()
self._accounts = {}
self._issued = {}
self._persistence_error = None
self._load_state()
@staticmethod
def role_key(snapshot, namespace=""):
raw = snapshot.raw if hasattr(snapshot, "raw") else snapshot
master = raw.get("master") if isinstance(raw, dict) else None
master = master if isinstance(master, dict) else {}
role = master.get("id", master.get("userId"))
if role is None or not str(role).strip():
raise ValueError("角色快照缺少稳定的角色编号,已暂停探险")
# These values are role routing data, not login/account credentials.
identity = [str(namespace), str(role), str(raw.get("serverId", "")),
str(raw.get("areaId", "")), str(master.get("serverId", ""))]
return hashlib.sha256(json.dumps(identity, ensure_ascii=True, separators=(",", ":")).encode()).hexdigest()
def _scope(self, snapshot):
return self.role_key(snapshot, self._namespace)
def _account(self, snapshot):
scope = self._scope(snapshot)
account = self._accounts.setdefault(scope, {"pending": None})
return scope, account
def _load_state(self):
if self._path is None or not self._path.exists():
return
try:
self.restore_state(json.loads(self._path.read_text(encoding="utf-8")))
except (OSError, ValueError, TypeError, json.JSONDecodeError) as error:
self._accounts = {}
self._persistence_error = "探险请求状态无法读取,已暂停:" + str(error)
def _save_state(self):
if self._path is None:
return
self._path.parent.mkdir(parents=True, exist_ok=True)
temporary = self._path.with_name(self._path.name + ".tmp")
data = json.dumps(self.export_state(), ensure_ascii=True, sort_keys=True,
indent=2, allow_nan=False) + "\n"
try:
with temporary.open("w", encoding="utf-8") as stream:
stream.write(data)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, self._path)
except OSError as error:
try:
temporary.unlink(missing_ok=True)
except OSError:
pass
raise OSError("探险请求状态未能落盘,已暂停发送") from error
@staticmethod
def _validate_state(state):
if not isinstance(state, dict) or state.get("version") != STATE_VERSION or set(state) != {"version", "accounts"}:
raise ValueError("探险状态版本无效")
if not isinstance(state["accounts"], dict):
raise ValueError("探险账号状态无效")
encoded = json.dumps(state, allow_nan=False)
state = json.loads(encoded)
for key, account in state["accounts"].items():
if not re.fullmatch(r"[0-9a-f]{64}", key) or not isinstance(account, dict) or set(account) != {"pending"}:
raise ValueError("探险账号状态无效")
pending = account["pending"]
if pending is None:
continue
required = {"kind", "team_id", "path", "payload", "description", "message", "uncertain", "confirmed", "started_at", "snapshot", "expected"}
if not isinstance(pending, dict) or set(pending) != required:
raise ValueError("探险待核对状态无效")
if pending["kind"] not in WIRE_KINDS or pending["path"] != PATHS[pending["kind"]]:
raise ValueError("探险待核对动作无效")
if not isinstance(pending["payload"], dict) or _integer(pending["team_id"]) <= 0:
raise ValueError("探险待核对队伍无效")
if type(pending["uncertain"]) is not bool or type(pending["confirmed"]) is not bool:
raise ValueError("探险待核对阶段无效")
if pending["uncertain"] and pending["confirmed"] or not isinstance(pending["snapshot"], dict) or not isinstance(pending["expected"], dict):
raise ValueError("探险待核对快照无效")
return state["accounts"]
def restore_state(self, state):
restored = self._validate_state(state)
with self._lock:
self._accounts = restored
self._issued.clear()
for account in self._accounts.values():
if account["pending"] and not account["pending"]["confirmed"]:
# Restored sends are always unknown, even if the old writer
# had not yet marked its network outcome uncertain.
account["pending"]["uncertain"] = True
account["pending"]["message"] = "上次进程请求结果未知,需由快照核对,禁止重放"
def export_state(self):
with self._lock:
return deepcopy({"version": STATE_VERSION, "accounts": self._accounts})
def pending(self, snapshot):
with self._lock:
_, account = self._account(snapshot)
return deepcopy(account["pending"])
@staticmethod
def _fingerprint(team):
return {"id": _integer(team.get("id"), -1), "status": _integer(team.get("status"), -1),
"area": str(team.get("area") or ""), "endTime": str(team.get("endTime") or ""),
"monsters": _team_monsters(team.get("monsters"))}
@classmethod
def _fingerprint_action(cls, action):
payload = action.payload
team_id = _positive_id(payload.get("exploreTeamId"), "探险队伍编号")
if action.kind == "explore_start":
if set(payload) != {"exploreTeamId", "monsters", "area"}:
raise ValueError("探险出发字段无效")
monsters = [_positive_id(mid) for mid in payload.get("monsters", [])]
if len(monsters) != 3 or len(set(monsters)) != 3:
raise ValueError("探险出发必须选择三只不同魔物")
area = payload.get("area")
if not isinstance(area, str) or not area.isdigit() or int(area) <= 0:
raise ValueError("探险出发地区无效")
return {"id": team_id, "status": 1, "area": str(int(area)), "monsters": monsters}
if action.kind == "explore_finish":
if set(payload) != {"exploreTeamId"}:
raise ValueError("探险领奖字段无效")
return {"id": team_id, "status": 0}
raise ValueError("该操作不是探险请求")
@staticmethod
def _team(snapshot, team_id):
teams = snapshot.raw.get("exploreTeams") or []
if not isinstance(teams, list):
raise ValueError("探险队快照格式无效")
matches = [team for team in teams if isinstance(team, dict) and _integer(team.get("id"), -1) == team_id]
if len(matches) > 1:
raise ValueError("探险队快照存在重复编号")
return matches[0] if matches else None
def _validate_intent(self, snapshot, action):
if not isinstance(action, Action) or action.kind not in WIRE_KINDS:
raise ValueError("该操作不是探险请求")
if action.path != PATHS[action.kind] or not isinstance(action.payload, dict):
raise ValueError("探险请求路径或字段无效")
expected = self._fingerprint_action(action)
scope, account = self._account(snapshot)
issued = self._issued.get(scope)
if issued != action or account["pending"] is not None:
raise ValueError("探险动作已过期或已有请求待核对")
team = self._team(snapshot, expected["id"])
if team is None:
raise ValueError("探险队已不在角色快照中")
if action.kind == "explore_start":
if _integer(team.get("status")) != 0:
raise ValueError("探险队当前不可出发")
area = self.areas.get(expected["area"])
if area is None or not self.area_unlocked(snapshot, area):
raise ValueError("探险地区已失效或未解锁")
if _integer((snapshot.raw.get("master") or {}).get("ti")) < _integer(area.get("costTi")):
raise ValueError("当前体力不足以出发")
elif _integer(team.get("status")) != 1 or self.remaining(snapshot, team) is None or self.remaining(snapshot, team) > 0:
raise ValueError("探险奖励当前不可领取")
return scope, account
def mark_started(self, snapshot, action):
with self._lock:
if self._persistence_error:
raise OSError(self._persistence_error)
scope, account = self._validate_intent(snapshot, action)
account["pending"] = {"kind": action.kind, "team_id": _integer(action.payload["exploreTeamId"]),
"path": action.path, "payload": deepcopy(action.payload), "description": action.description,
"message": action.description + ":请求进行中", "uncertain": False, "confirmed": False, "started_at": snapshot.now,
"snapshot": self._fingerprint(self._team(snapshot, _integer(action.payload["exploreTeamId"]))),
"expected": self._expected_snapshot(action, None)}
try:
self._save_state() # Durably block replay before the wire call.
except Exception:
account["pending"] = None
raise
return deepcopy(account["pending"])
def acknowledge(self, snapshot, action, response=None, *, _from_snapshot=False):
with self._lock:
scope, account = self._account(snapshot)
pending = account["pending"]
if pending is None:
return False
if not _from_snapshot:
if not isinstance(response, dict) or response.get("resCode", 0) not in (0, "0"):
raise ValueError("探险请求尚未确认成功")
if pending["kind"] != action.kind or pending["path"] != action.path or pending["payload"] != action.payload:
raise ValueError("探险回包与待核对动作不匹配")
self._verify_response(pending, response)
pending.update(confirmed=True, uncertain=False,
message=action.description + ":成功已确认,等待角色快照同步,禁止重放",
expected=self._expected_snapshot(action, response))
self._issued.pop(scope, None)
self._save_state()
return True
def _expected_snapshot(self, action, response):
expected = self._fingerprint_action(action)
team = response.get("exploreTeam") if isinstance(response, dict) else None
if action.kind == "explore_start" and isinstance(team, dict):
expected["endTime"] = str(team.get("endTime") or "")
else:
expected["endTime"] = ""
return expected
@staticmethod
def _verify_response(pending, response):
if pending["kind"] == "explore_start":
team = response.get("exploreTeam")
if not isinstance(team, dict):
# Success is definite; the next snapshot must still supply the
# authoritative timer/membership rather than a local guess.
return
if _integer(team.get("id")) != pending["team_id"] or _integer(team.get("status")) != 1:
raise ValueError("探险出发回包的队伍状态不匹配")
elif "rewardResult" not in response and "monExp" not in response:
return
def mark_uncertain(self, snapshot, action, reason="请求结果未知,需重新同步"):
with self._lock:
scope, account = self._account(snapshot)
pending = account["pending"]
if not pending or pending["kind"] != action.kind or pending["payload"] != action.payload:
raise ValueError("没有对应的探险请求")
pending.update(uncertain=True, message=str(reason) + ";禁止自动重放")
self._save_state()
return deepcopy(pending)
def reconcile(self, snapshot):
"""Confirm a changed authoritative team; unchanged/missing stays blocked."""
with self._lock:
scope, account = self._account(snapshot)
pending = account["pending"]
if not pending:
return False
team = self._team(snapshot, pending["team_id"])
if team is None:
return False
current = self._fingerprint(team)
if pending["kind"] == "explore_start":
expected = pending["expected"]
end_time = seconds(team.get("endTime"))
confirmed = (current["status"] == expected["status"] and current["area"] == expected["area"]
and current["monsters"] == expected["monsters"]
and math.isfinite(end_time) and end_time > pending["started_at"])
else:
# A pending start has a distinguishable active timer. A finish
# must additionally have changed the previously active snapshot,
# so another role/session's stale idle row cannot acknowledge it.
confirmed = current["status"] == 0 and current != pending["snapshot"]
if not confirmed:
return False
account["pending"] = None
self._issued.pop(scope, None)
self._save_state()
return True
def execute(self, snapshot, action, call):
"""Run one host-supplied callable; no real API is referenced here."""
self.mark_started(snapshot, action)
try:
response = call(action.path, deepcopy(action.payload))
self.acknowledge(snapshot, action, response)
return response
except Exception as error:
try:
self.mark_uncertain(snapshot, action, "探险请求结果未知:" + str(error))
except (OSError, ValueError):
pass
raise
def area_unlocked(self, snapshot, area):
# ExploreAreaVo.unlock -> StageCenter.isStagePass(passStage, 1).
return _flag((snapshot.raw.get("history") or {}).get("passStage"), area.get("passStage"), 1)
def open(self, snapshot):
# HistoryVo.exploreOpen uses passTask["1001008"].
return _flag((snapshot.raw.get("history") or {}).get("passTask"), "1001008")
def team_rule(self, policy, team_id):
return policy.teams.get(str(int(team_id))) or ExploreTeamRule()
@staticmethod
def remaining(snapshot, team):
if team.get("endTime") is None:
return None
try:
end_time = seconds(team["endTime"])
if not math.isfinite(end_time) or end_time <= 0:
return None
remaining = end_time - snapshot.now
except (TypeError, ValueError, OverflowError):
return None
return max(0, remaining) if math.isfinite(remaining) else None
def _occupied(self, snapshot, excluded_team=None):
result = set()
for team in snapshot.raw.get("exploreTeams") or []:
if isinstance(team, dict) and _integer(team.get("id")) != excluded_team and _integer(team.get("status")) == 1:
result.add(str(team.get("area") or ""))
return result
def _automatic_targets(self, ranch_policy):
# Exploration does not consume monsters. These exclusions prevent
# interference with other automation, not original-client eligibility.
targets = _target_ids(getattr(ranch_policy, "feed_targets", {}),
getattr(ranch_policy, "gift_targets", {}), getattr(ranch_policy, "breakthrough_targets", {}))
legacy = _integer(getattr(ranch_policy, "feed_target", 0))
if legacy > 0:
targets.add(legacy)
return targets
def monster_exclusion(self, snapshot, mon, ranch_policy, *, automatic):
if mon.get("process") != 3:
return "尚未成熟"
if mon.get("inExploreTeam"):
return "正在其他探险队"
if not automatic:
return ""
mid = _integer(mon.get("id"))
if mid in snapshot.team_ids:
return "已占用:战斗队"
if mid in _target_ids(getattr(ranch_policy, "feed_targets", {})) or mid == _integer(getattr(ranch_policy, "feed_target", 0)):
return "已占用:喂养目标"
if mid in _target_ids(getattr(ranch_policy, "gift_targets", {})):
return "已占用:赠礼目标"
if mid in _target_ids(getattr(ranch_policy, "breakthrough_targets", {})):
return "已占用:突破目标"
return ""
def _selection(self, snapshot, area, rule, ranch_policy, *, excluded=()):
excluded = set(excluded)
monsters = {mid: mon for mon in snapshot.raw.get("monsters") or []
if isinstance(mon, dict) and (mid := _integer(mon.get("id"))) > 0}
unavailable = {mid for team in snapshot.raw.get("exploreTeams") or [] if isinstance(team, dict)
and _integer(team.get("status")) == 1 for mid in _team_monsters(team.get("monsters"))}
if rule.monsters:
reasons = []
leader = monsters.get(rule.monsters[0])
for position, mid in enumerate(rule.monsters):
mon = monsters.get(mid)
if mon is None:
reasons.append(f"#{mid} 不存在")
continue
reason = self.monster_exclusion(snapshot, mon, ranch_policy, automatic=False)
if mid in excluded or mid in unavailable:
reason = "正在其他探险队"
level = _integer(mon.get("level"))
minimum = _integer((area.get("level") or [0, 0, 0])[position])
if level < minimum:
reason = f"等级不足 Lv.{level}/{minimum}"
if position and leader is not None and level > _integer(leader.get("level")):
reason = "队员等级不可高于队长"
if reason:
reasons.append(f"#{mid}:{reason}")
return list(rule.monsters) if not reasons else None, ";".join(reasons)
automatic_targets = self._automatic_targets(ranch_policy)
candidates = []
for mid, mon in monsters.items():
if mid in excluded or mid in unavailable or mid in automatic_targets:
continue
if self.monster_exclusion(snapshot, mon, ranch_policy, automatic=True):
continue
candidates.append((mid, _integer(mon.get("level"))))
candidates.sort(key=lambda row: (-row[1], row[0]))
levels = area.get("level") or []
if len(levels) != 3:
return None, "地区队员等级配置缺失"
leader = next((row for row in candidates if row[1] >= _integer(levels[0])), None)
if leader is None:
return None, "没有符合队长等级且未被其他自动化占用的魔物;可手动指定"
selected = [leader]
for position in (1, 2):
member = next((row for row in candidates if row not in selected
and _integer(levels[position]) <= row[1] <= leader[1]), None)
if member is None:
return None, "可自动选队员不足三只;可手动选择战斗或培养目标"
selected.append(member)
return [row[0] for row in selected], ""
def select_monsters(self, snapshot, area, ranch_policy, rule=None):
return self._selection(snapshot, area, rule or ExploreTeamRule(), ranch_policy)[0]
def _blocked(self, pending):
return Action("explore_blocked", pending.get("message", "探险请求待核对,禁止重放"), "",
{"team_id": pending.get("team_id"), "pending": True})
def plan(self, snapshot, policy, ranch_policy):
with self._lock:
scope, account = self._account(snapshot)
if self._persistence_error:
return [Action("explore_blocked", self._persistence_error, "", {"pending": True})]
if account["pending"]:
return [self._blocked(account["pending"])]
self._issued.pop(scope, None)
if not policy.enabled:
return []
if not self.open(snapshot):
return [Action("explore_blocked", "探险功能尚未解锁", "", {})]
teams = [team for team in snapshot.raw.get("exploreTeams") or [] if isinstance(team, dict)]
for team in teams:
team_id = _integer(team.get("id"), -1)
if (team_id > 0 and self.team_rule(policy, team_id).enabled
and _integer(team.get("status")) == 1 and self.remaining(snapshot, team) == 0):
return [self._issue(scope, Action("explore_finish", f"领取探险队 {team_id} 的奖励",
"exploreService/finish", {"exploreTeamId": team_id}))]
stamina = _integer((snapshot.raw.get("master") or {}).get("ti"))
occupied = self._occupied(snapshot)
for team in teams:
team_id = _integer(team.get("id"), -1)
rule = self.team_rule(policy, team_id)
if team_id <= 0 or not rule.enabled or _integer(team.get("status")) != 0:
continue
area = self.areas.get(rule.area)
if area is None or not self.area_unlocked(snapshot, area) or rule.area in occupied:
continue
cost = _integer(area.get("costTi"))
if cost <= 0 or stamina < cost + policy.reserve_ti:
continue
monsters, _ = self._selection(snapshot, area, rule, ranch_policy)
if monsters is None:
continue
return [self._issue(scope, Action("explore_start", f"探险队 {team_id} → {area.get('name') or rule.area}",
"exploreService/start", {"exploreTeamId": team_id, "monsters": monsters, "area": rule.area}))]
return []
def _issue(self, scope, action):
self._issued[scope] = deepcopy(action)
return action
def _diagnosis(self, snapshot, team, policy, ranch_policy):
team_id = _integer(team.get("id"), -1)
rule = self.team_rule(policy, team_id)
area = self.areas.get(rule.area)
remaining = self.remaining(snapshot, team)
status = _integer(team.get("status"))
members = _team_monsters(team.get("monsters"))
selected, reason = (None, "")
if status == 1:
state = "可领取" if remaining == 0 else "探索中" if remaining is not None else "状态待同步"
else:
state = "空闲"
if not self.open(snapshot):
state, reason = "未解锁", "完成指定主线后解锁探险"
elif not rule.enabled:
state, reason = "未启用", "勾选此队伍后参与自动探险"
elif status != 0:
pass
elif area is None:
state, reason = "待配置", "请选择普通探险地区"
elif not self.area_unlocked(snapshot, area):
state, reason = "地区未解锁", f"需通关 {area.get('passStage') or '指定关卡'} 难度1"
elif rule.area in self._occupied(snapshot):
state, reason = "地区占用", "同一地区已有队伍探索"
elif _integer((snapshot.raw.get("master") or {}).get("ti")) < _integer(area.get("costTi")) + policy.reserve_ti:
state, reason = "体力不足", f"需要 {area.get('costTi')},另保留 {policy.reserve_ti}"
else:
selected, reason = self._selection(snapshot, area, rule, ranch_policy)
state = "可出发" if selected is not None else "队员不足"
_, account = self._account(snapshot)
if account["pending"]:
state = "待核对"
reason = account["pending"]["message"]
monsters = members if status == 1 else selected or rule.monsters
return {"team_id": team_id, "enabled": rule.enabled, "area": rule.area,
"area_name": (area or {}).get("name", ""), "state": state, "reason": reason,
"remaining": remaining if status == 1 else None, "monster_ids": monsters,
"cost_ti": _integer((area or {}).get("costTi")), "cost_time": _integer((area or {}).get("costTime")),
"manual": bool(rule.monsters), "can_auto": self._selection(snapshot, area, ExploreTeamRule(), ranch_policy)[0] is not None if area else False}
def rows(self, snapshot, policy, ranch_policy):
with self._lock:
return [self._diagnosis(snapshot, team, policy, ranch_policy)
for team in snapshot.raw.get("exploreTeams") or [] if isinstance(team, dict)]
def member_options(self, snapshot, team_id, policy, ranch_policy):
"""Small worker DTOs: automatic exclusion is advisory for manual picks."""
rule = self.team_rule(policy, team_id)
area = self.areas.get(rule.area)
if area is None:
return []
occupied = {mid for team in snapshot.raw.get("exploreTeams") or [] if isinstance(team, dict)
and _integer(team.get("id")) != _integer(team_id) and _integer(team.get("status")) == 1
for mid in _team_monsters(team.get("monsters"))}
result = []
for mon in snapshot.raw.get("monsters") or []:
if not isinstance(mon, dict):
continue
mid = _integer(mon.get("id"))
if mid <= 0:
continue
reason = self.monster_exclusion(snapshot, mon, ranch_policy, automatic=True)
if mid in occupied:
reason = "正在其他探险队"
result.append({"id": mid, "level": _integer(mon.get("level")),
"label": self.catalog.monster_label(mon), "automatic": not reason, "reason": reason})
result.sort(key=lambda row: (-row["level"], row["id"]))
return result
+411
View File
@@ -0,0 +1,411 @@
"""Independent Qt exploration page; heavy snapshot work belongs in workers."""
from __future__ import annotations
from dataclasses import replace
import copy
from PySide6 import QtCore as C, QtWidgets as W
from .exploration import ExplorePolicy, ExploreTeamRule
from .model import duration
from .native_widgets import ComboBox, IntegerInput, RowBatch
from .table_widgets import CenteredCheckBox, set_value, table_item
def prepare_exploration_rows(engine):
"""Worker boundary: return only small plain-data DTOs, no Qt objects."""
if engine.snapshot is None:
return []
planner = engine.explore_planner
snapshot = engine.snapshot
policy = engine.explore_policy
ranch = engine.policy
rows = planner.rows(snapshot, policy, ranch)
prepared = []
for row in rows:
labels = []
for mid in row["monster_ids"]:
mon = snapshot.monsters.get(mid)
labels.append((planner.catalog.monster_label(mon) + f" Lv.{mon.get('level', 0)}") if mon else f"#{mid}")
prepared.append(dict(row, monster_labels=labels,
remaining_text=duration(row["remaining"]) if row["remaining"] is not None else "—",
cost_text=f"{row['cost_ti']} / {duration(row['cost_time'])}"))
return prepared
def prepare_exploration_members(engine, team_id):
"""Worker candidate DTOs include protected monsters with exclusion reasons."""
if engine.snapshot is None:
return []
return engine.explore_planner.member_options(engine.snapshot, int(team_id),
engine.explore_policy, engine.policy)
class ExplorationTable(W.QTableWidget):
"""Own each cell once and mutate it in place during every later render."""
cell_changed = C.Signal(str, str, object)
def __init__(self, parent=None):
super().__init__(0, 7, parent)
self.setHorizontalHeaderLabels(["启用", "队伍", "地区", "状态 / 剩余", "队员", "体力 / 时长", "说明"])
self.setSelectionBehavior(W.QAbstractItemView.SelectionBehavior.SelectRows)
self.setEditTriggers(W.QAbstractItemView.EditTrigger.NoEditTriggers)
self.horizontalHeader().setStretchLastSection(True)
self.verticalHeader().setDefaultSectionSize(34)
self.verticalHeader().setMinimumSectionSize(30)
self.row_batch = RowBatch(self)
self._cells = {}
self._controls = {}
self._generation = 0
self._rendering = False
@staticmethod
def _cell_widget(control):
cell = W.QWidget()
layout = W.QHBoxLayout(cell)
layout.setContentsMargins(2, 0, 2, 0)
layout.setSpacing(4)
layout.addWidget(control)
return cell
def _make_row(self, key, area_options):
enabled = CenteredCheckBox()
enabled.setToolTip("启用此探险队;完成领奖后再出发")
enabled.setFixedWidth(26)
auto = W.QPushButton("自动选三只")
auto.setToolTip("只选择未被战斗队、喂养、赠礼或突破目标占用的魔物")
area = ComboBox()
area.addItem("请选择地区", "")
for area_id, name in area_options:
area.addItem(f"{name}({area_id})", area_id)
members = []
for position in range(3):
combo = ComboBox()
combo.setMinimumContentsLength(3)
combo.setToolTip(["队长", "队员(等级不可高于队长)", "队员(等级不可高于队长)"][position])
members.append(combo)
member_cell = W.QWidget()
line = W.QHBoxLayout(member_cell)
line.setContentsMargins(2, 0, 2, 0)
line.setSpacing(3)
for combo in members:
line.addWidget(combo, 1)
line.addWidget(auto)
cells = {}
for column in range(self.columnCount()):
item = table_item("", column)
item.setFlags(item.flags() & ~C.Qt.ItemFlag.ItemIsEditable)
cells[column] = item
enabled.toggled.connect(lambda checked, key=key: self.cell_changed.emit(key, "enabled", checked))
area.currentIndexChanged.connect(lambda index, key=key: self.cell_changed.emit(key, "area", area.itemData(index) or ""))
for position, combo in enumerate(members):
combo.currentIndexChanged.connect(lambda index, key=key, position=position, combo=combo:
self.cell_changed.emit(key, "monster", (position, combo.itemData(index))))
auto.clicked.connect(lambda checked=False, key=key: self.cell_changed.emit(key, "auto", None))
return {"enabled": enabled, "area": area, "members": members, "auto": auto,
"enabled_cell": self._cell_widget(enabled), "area_cell": self._cell_widget(area),
"member_cell": member_cell, "cells": cells}
def set_rows(self, rows, policies, area_options, member_options):
self._generation += 1
generation = self._generation
self.row_batch.stop()
self._rendering = True
self.setSortingEnabled(False)
active = {str(row["team_id"]) for row in rows}
for key in set(self._controls) - active:
control = self._controls.pop(key)
for column in range(self.columnCount()):
item = self._cells[key][column]
index = self.indexFromItem(item)
if index.isValid():
self.removeCellWidget(index.row(), column)
self._cells.pop(key, None)
self.setRowCount(len(rows))
ordered = []
for index, row in enumerate(rows):
key = str(row["team_id"])
control = self._controls.get(key)
if control is None:
control = self._controls[key] = self._make_row(key, area_options)
self._cells[key] = control["cells"]
for column, item in self._cells[key].items():
# setItem is used only when this stable item is not in a table.
if item.tableWidget() is None:
self.setItem(index, column, item)
self.setCellWidget(index, 0, control["enabled_cell"])
self.setCellWidget(index, 2, control["area_cell"])
self.setCellWidget(index, 4, control["member_cell"])
ordered.append((index, row, control, policies[key], member_options.get(key, [])))
def apply(entry):
index, row, control, policy, options = entry
if generation != self._generation:
return
self._rendering = True
control["enabled"].setChecked(policy.enabled)
control["area"].setCurrentIndex(control["area"].findData(policy.area))
self._set_members(control, policy, options)
control["enabled"].setEnabled(row["state"] not in ("探索中", "可领取", "待核对"))
control["area"].setEnabled(row["state"] not in ("探索中", "可领取", "待核对"))
for combo in control["members"]:
combo.setEnabled(control["area"].isEnabled())
control["auto"].setEnabled(control["area"].isEnabled() and bool(options))
texts = {1: str(row["team_id"]),
3: row["state"] + " / " + row["remaining_text"],
5: row["cost_text"], 6: row["reason"] or ("手动指定;允许锁定 / 装备" if row["manual"] else "自动选空闲魔物")}
for column, value in texts.items():
item = self._cells[str(row["team_id"])][column]
set_value(item, column, value)
item.setToolTip(value)
self._cells[str(row["team_id"])][1].setData(C.Qt.ItemDataRole.UserRole, str(row["team_id"]))
def finish():
self._rendering = False
self.resizeColumnsToContents()
self.setColumnWidth(2, min(240, max(160, self.columnWidth(2))))
self.setColumnWidth(4, 440)
self.row_batch.start(ordered, apply, finish)
def _set_members(self, control, policy, options):
by_id = {str(option["id"]): option for option in options}
for position, combo in enumerate(control["members"]):
selected = policy.monsters[position] if policy.monsters else None
combo.clear()
combo.addItem("自动", None)
# Manual lists include locked/equipped and other automation targets.
for option in options:
reason = ";" + option["reason"] if option["reason"] else ""
combo.addItem(f"{option['label']} Lv.{option['level']}{reason}", option["id"])
if selected is not None and str(selected) not in by_id:
combo.addItem(f"#{selected}(当前快照不存在)", selected)
combo.setCurrentIndex(combo.findData(selected))
class ExplorationPages:
"""Mixin: engine.explore_planner/explore_policy/policy + tabs/submit."""
def exploration_tab(self):
self.exploration_page = W.QWidget()
layout = W.QVBoxLayout(self.exploration_page)
tools = W.QHBoxLayout()
self.explore_enabled = W.QCheckBox("启用自动探险")
self.explore_reserve_ti = IntegerInput()
self.explore_reserve_ti.setRange(0, 1_000_000_000)
self.explore_refresh_button = W.QPushButton("刷新探险状态")
tools.addWidget(self.explore_enabled)
tools.addWidget(W.QLabel("保留体力"))
tools.addWidget(self.explore_reserve_ti)
tools.addWidget(self.explore_refresh_button)
tools.addStretch()
layout.addLayout(tools)
self.exploration_summary = W.QLabel("领奖后再出发;不自动花钱开队或召回。手动队员允许锁定、装备和其他培养目标。")
self.exploration_summary.setWordWrap(True)
layout.addWidget(self.exploration_summary)
self.exploration_table = ExplorationTable(self.exploration_page)
layout.addWidget(self.exploration_table, 1)
self.exploration_detail = W.QLabel("留空任一槽位即恢复自动选人;手动选择需三只不同魔物,队员等级不高于队长。")
self.exploration_detail.setWordWrap(True)
layout.addWidget(self.exploration_detail)
self.tabs.addTab(self.exploration_page, "自动探险")
self._exploration_policy = ExplorePolicy.from_dict(getattr(self.engine, "explore_policy", ExplorePolicy()).to_dict())
self._exploration_rows = []
self._exploration_member_options = {}
self._exploration_rendering = False
self._exploration_generation = 0
self._exploration_member_queue = []
self._exploration_member_busy = False
self._exploration_drafts = {}
self._exploration_engine_identity = None
self._exploration_role_key = None
self.explore_enabled.toggled.connect(self.exploration_settings_changed)
self.explore_reserve_ti.valueChanged.connect(self.exploration_settings_changed)
self.explore_refresh_button.clicked.connect(self.refresh_exploration)
self.exploration_table.cell_changed.connect(self._exploration_cell_changed)
self._exploration_complete_member_request()
def read_explore_policy(self):
# Read the retained full configuration, never the currently visible rows.
return ExplorePolicy.from_dict(self._exploration_policy.to_dict())
def exploration_settings_changed(self, *args):
if self.closed or self.loading_config or self._exploration_rendering:
return
self._exploration_policy = replace(self._exploration_policy,
enabled=self.explore_enabled.isChecked(), reserve_ti=self.explore_reserve_ti.value())
self._save_exploration_policy()
def _save_exploration_policy(self):
# Host update_policy() serializes configuration with account jobs.
self.settings_changed()
def _exploration_cell_changed(self, key, field, value):
if self._exploration_rendering or self.exploration_table._rendering:
return
if field == "auto":
# QPushButton.clicked carries a bool, but auto is not a field on
# ExploreTeamRule; always reset the saved trio explicitly.
self._exploration_drafts.pop(key, None)
self._exploration_policy.teams[key] = replace(self._exploration_policy.teams.get(key, ExploreTeamRule()), monsters=[])
self._save_exploration_policy()
self.exploration_detail.setText("已恢复自动选人;排除原因显示在各槽位下拉列表中。")
self._set_team_members(key)
return
rule = self._exploration_policy.teams.get(key, ExploreTeamRule())
if field == "enabled":
rule = replace(rule, enabled=bool(value))
self._exploration_policy.teams[key] = rule
self._save_exploration_policy()
elif field == "area":
rule = replace(rule, area=str(value))
self._exploration_drafts.pop(key, None)
self._exploration_policy.teams[key] = rule
self._save_exploration_policy()
elif field == "monster":
position, mid = value
if not 0 <= position < 3:
return
members = self._exploration_drafts.get(key)
if members is None:
members = list(rule.monsters) if rule.monsters else [None, None, None]
members[position] = mid
self._exploration_drafts[key] = members
if all(mid is not None for mid in members):
self._exploration_policy.teams[key] = replace(rule, monsters=[int(mid) for mid in members])
self._exploration_drafts.pop(key, None)
self._save_exploration_policy()
else:
self.exploration_detail.setText("正在选择手动队员;三格选齐后保存,刷新不会清除草稿。")
return
elif field == "auto":
rule = replace(rule, monsters=[])
self._exploration_drafts.pop(key, None)
self._exploration_policy.teams[key] = rule
self._save_exploration_policy()
self._exploration_detail.setText("已恢复自动选人;排除原因显示在各槽位下拉列表中。")
if field in ("area", "auto"):
self.refresh_exploration()
def exploration_item_changed(self, item):
# Compatibility with the old mixin; the native page uses widgets.
self.exploration_settings_changed()
def refresh_exploration(self):
if self.closed:
return
if self.busy:
self.pending_refresh = self.exploration_page
return
generation = self._exploration_generation + 1
self._exploration_generation = generation
self.explore_refresh_button.setEnabled(False)
self.submit("exploration_view", lambda: prepare_exploration_rows(self.engine))
def _exploration_complete_member_request(self):
"""Drain the host's one-shot member job before scheduling the next."""
self._exploration_member_busy = False
if getattr(self, "_exploration_member_timer", None) is None:
self._exploration_member_timer = C.QTimer(self.exploration_page)
self._exploration_member_timer.setSingleShot(True)
self._exploration_member_timer.setInterval(0)
self._exploration_member_timer.timeout.connect(self._request_next_exploration_members)
self._exploration_member_timer.start()
def reset_exploration_account(self):
"""Host calls on login/switch; no candidates or drafts cross roles."""
self._exploration_generation += 1
self._exploration_member_options.clear()
self._exploration_drafts.clear()
self._exploration_member_queue.clear()
self._exploration_rows = []
self._exploration_member_busy = False
self._exploration_role_key = None
self._exploration_engine_identity = id(self.engine)
if hasattr(self, "exploration_table"):
self.exploration_table.set_rows([], {}, [], {})
def render_exploration(self, rows=None):
if not hasattr(self, "exploration_table"):
return
if rows is None:
# Explicit synchronous use in unit tests is worker-free. Host code
# must call refresh_exploration()/accept result for live snapshots.
rows = prepare_exploration_rows(self.engine)
identity = id(self.engine)
role_key = None
if self.engine.snapshot is not None:
role_key = self.engine.explore_planner.role_key(self.engine.snapshot)
if self._exploration_engine_identity not in (None, identity) or self._exploration_role_key not in (None, role_key):
self.reset_exploration_account()
self._exploration_engine_identity = identity
self._exploration_role_key = role_key
self._exploration_rows = list(rows)
self._exploration_rendering = True
try:
self.explore_enabled.setChecked(self._exploration_policy.enabled)
self.explore_reserve_ti.setValue(self._exploration_policy.reserve_ti)
keys = [str(row["team_id"]) for row in rows]
policies = copy.deepcopy(self._exploration_policy.teams)
for key in keys:
policies.setdefault(key, ExploreTeamRule())
if key in self._exploration_drafts:
# UI-only partial drafts are deliberately not a valid
# ExploreTeamRule and never enter engine configuration.
policies[key].monsters = list(self._exploration_drafts[key])
areas = [(key, row.get("name") or key) for key, row in self.engine.explore_planner.areas.items()]
self.exploration_table.set_rows(rows, policies, areas, self._exploration_member_options)
self.exploration_summary.setText(f"已有 {len(rows)} 支探险队;配置 {len(self._exploration_policy.teams)} 支;启用 {sum(rule.enabled for rule in self._exploration_policy.teams.values())} 支")
self._exploration_member_queue = [key for key in keys if key not in self._exploration_member_options]
finally:
self._exploration_rendering = False
self._request_next_exploration_members()
def _set_team_members(self, key):
control = self.exploration_table._controls.get(str(key))
if control is None:
return
self._exploration_rendering = True
self.exploration_table._rendering = True
try:
self.exploration_table._set_members(control, self._exploration_policy.teams[str(key)],
self._exploration_member_options.get(str(key), []))
finally:
self.exploration_table._rendering = False
self._exploration_rendering = False
def _request_next_exploration_members(self):
if self.closed or self._exploration_member_busy or not self._exploration_member_queue:
return
key = self._exploration_member_queue.pop(0)
if self.busy:
self._exploration_member_queue.insert(0, key)
return
self._exploration_member_busy = True
generation = self._exploration_generation
self.submit("exploration_members:" + key,
lambda key=key: (generation, key, prepare_exploration_members(self.engine, key)))
def accept_exploration_members(self, generation, key, options):
if generation == self._exploration_generation:
self._exploration_member_options[key] = options
self.render_exploration(self._exploration_rows)
self._exploration_complete_member_request()
def apply_explore_policy(self, policy):
"""Apply/import the entire policy before rendering, including hidden teams."""
if isinstance(policy, dict):
policy = ExplorePolicy.from_dict(policy)
self._exploration_policy = ExplorePolicy.from_dict(policy.to_dict())
self._exploration_rendering = True
try:
self.explore_enabled.setChecked(policy.enabled)
self.explore_reserve_ti.setValue(policy.reserve_ti)
finally:
self._exploration_rendering = False
def accept_exploration_view(self, rows):
self.explore_refresh_button.setEnabled(True)
self.render_exploration(rows)
self._exploration_complete_member_request()
+76 -10
View File
@@ -20,6 +20,7 @@ from .quests import QuestPolicy
from .daily import DailyPolicy from .daily import DailyPolicy
from .sweeping import SweepPolicy from .sweeping import SweepPolicy
from .progression import ProgressionPolicy from .progression import ProgressionPolicy
from .exploration import ExplorePolicy
from .activity_gui import ActivityPages from .activity_gui import ActivityPages
from .progression_gui import ProgressionPages, prepare_progression_views from .progression_gui import ProgressionPages, prepare_progression_views
from .battle_messages import battle_message from .battle_messages import battle_message
@@ -35,6 +36,7 @@ from .table_widgets import table_item
from .stage_cache import StageCache from .stage_cache import StageCache
from .drop_statistics import SweepStatistics from .drop_statistics import SweepStatistics
from .statistics_gui import StatisticsPage from .statistics_gui import StatisticsPage
from .exploration_gui import ExplorationPages, prepare_exploration_rows, prepare_exploration_members
APP_VERSION = "1.2.0.dev1" APP_VERSION = "1.2.0.dev1"
GAME_VERSION = "1.9.68" GAME_VERSION = "1.9.68"
@@ -112,7 +114,7 @@ def fill_table(widget, rows, sorting=True):
widget.setSortingEnabled(sorting) widget.setSortingEnabled(sorting)
class Window(ProgressionPages, ActivityPages, W.QMainWindow): class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
network_event = C.Signal(object) network_event = C.Signal(object)
profile_changed = C.Signal(str) profile_changed = C.Signal(str)
@@ -154,8 +156,11 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
self.pending_policy = None self.pending_policy = None
self.logout_phase = None self.logout_phase = None
self.pending_monster_view = False self.pending_monster_view = False
self.pending_exploration_view = False
self.monster_data_pending = False self.monster_data_pending = False
self.pending_schedule = False self.pending_schedule = False
self.next_explore = float("inf")
self.next_breakthrough = float("inf")
self.monster_view_visible = False self.monster_view_visible = False
self.presentation_active = True self.presentation_active = True
self.engine.presentation_active = True self.engine.presentation_active = True
@@ -174,6 +179,7 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
self.egg_rules = {} self.egg_rules = {}
self.feed_targets = {} self.feed_targets = {}
self.gift_targets = {} self.gift_targets = {}
self.breakthrough_targets = {}
self.gift_items = {} self.gift_items = {}
central = W.QWidget() central = W.QWidget()
layout = W.QVBoxLayout(central) layout = W.QVBoxLayout(central)
@@ -290,7 +296,7 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
monster_tools.addWidget(button) monster_tools.addWidget(button)
monster_tools.addStretch() monster_tools.addStretch()
monster_layout.addLayout(monster_tools) monster_layout.addLayout(monster_tools)
detail_note = W.QLabel("勾选“喂养目标”并设置优先级(数字小的先喂);当前突破上限满级后转下一个目标。参考属性含等级、潜能、好感和升星,不含装备、羁绊或全局加成。") detail_note = W.QLabel("喂养与赠礼分别设置目标及优先级(数字小的先执行)。同种突破最高4级,每只同种素材增加1点突破经验;普通经验等级与潜能阶段分别计算。勾选“自动突破目标”即授权先补满四项潜能、再提升潜能阶段,消耗对应元素材料并遵守物品/委托保留量;不购买材料,不消耗金币或氪金。参考属性不含装备、羁绊或全局加成。")
detail_note.setWordWrap(True) detail_note.setWordWrap(True)
monster_layout.addWidget(detail_note) monster_layout.addWidget(detail_note)
self.ranch_view = self.monsters self.ranch_view = self.monsters
@@ -299,6 +305,7 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
self.monsters.monster_activated.connect(self.show_monster_detail) self.monsters.monster_activated.connect(self.show_monster_detail)
self.monsters.feed_changed.connect(self.monster_feed_changed) self.monsters.feed_changed.connect(self.monster_feed_changed)
self.monsters.gift_changed.connect(self.monster_gift_changed) self.monsters.gift_changed.connect(self.monster_gift_changed)
self.monsters.breakthrough_changed.connect(self.monster_breakthrough_changed)
self.room_page = self.monster_page self.room_page = self.monster_page
self.tabs.addTab(self.room_page, "牧场") self.tabs.addTab(self.room_page, "牧场")
self.policy_page = self.policy_tab(embedded=True) self.policy_page = self.policy_tab(embedded=True)
@@ -309,6 +316,7 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
self.yield_tab() self.yield_tab()
self.quests_tab() self.quests_tab()
self.maps_tab() self.maps_tab()
self.exploration_tab()
self.analysis_page = StatisticsPage(self.catalog) self.analysis_page = StatisticsPage(self.catalog)
self.analysis_page.refresh_requested.connect(self.refresh_analysis) self.analysis_page.refresh_requested.connect(self.refresh_analysis)
self.tabs.addTab(self.analysis_page, "数据分析") self.tabs.addTab(self.analysis_page, "数据分析")
@@ -317,7 +325,7 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
self.tabs.addTab(self.plans, "执行计划") self.tabs.addTab(self.plans, "执行计划")
order = [self.tabs.widget(0), self.slot_page, self.inventory_tabs, self.room_page, order = [self.tabs.widget(0), self.slot_page, self.inventory_tabs, self.room_page,
self.daily_page, self.automation_page, self.progression_page, self.battle_records_page, self.gift_page, self.daily_page, self.automation_page, self.progression_page, self.battle_records_page, self.gift_page,
self.quests_table.parentWidget(), self.map_page, self.analysis_page, self.quests_table.parentWidget(), self.exploration_page, self.map_page, self.analysis_page,
self.plans, self.yields.parentWidget()] self.plans, self.yields.parentWidget()]
for page in order: for page in order:
self.tabs.addTab(page, self.tabs.tabText(self.tabs.indexOf(page))) self.tabs.addTab(page, self.tabs.tabText(self.tabs.indexOf(page)))
@@ -442,7 +450,7 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
self.protect_quality.setToolTip("4S要求攻、防、生命、敏捷分别为S;锁定、队伍、保留星级等保护仍单独生效。") self.protect_quality.setToolTip("4S要求攻、防、生命、敏捷分别为S;锁定、队伍、保留星级等保护仍单独生效。")
self.protect_quality.setCurrentIndex(1) self.protect_quality.setCurrentIndex(1)
self.keep_better_quality = W.QCheckBox("保留资质高于牧场同种培养代表的新魔物") self.keep_better_quality = W.QCheckBox("保留资质高于牧场同种培养代表的新魔物")
self.keep_better_quality.setToolTip("独立于S/A/B/C及4S条件:按四项成长范围归一化后的平均值比较,严格更高才算提升;牧场没有同种魔物时保留首只。") self.keep_better_quality.setToolTip("独立于S/A/B/C及4S条件:新魔物与牧场已保留的同种最高资质比较,依次按S项数、A项数、B项数、四项成长各自归一化后的平均值排序,严格更高才额外保留,同分不额外保留。")
self.room = combo([("自动选择有空位的牧场", 0)]) self.room = combo([("自动选择有空位的牧场", 0)])
self.coin_exp = spin(0, 10000, 5, True) self.coin_exp = spin(0, 10000, 5, True)
self.reserved_types = W.QLineEdit() self.reserved_types = W.QLineEdit()
@@ -632,6 +640,7 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
policy = self.read_policy() policy = self.read_policy()
progression = self.read_progression_policy() progression = self.read_progression_policy()
other = (self.quest_enabled.isChecked() or self.daily_enabled.isChecked() or self.map_enabled.isChecked() other = (self.quest_enabled.isChecked() or self.daily_enabled.isChecked() or self.map_enabled.isChecked()
or self.explore_enabled.isChecked() or bool(policy.breakthrough_targets)
or policy.gift_enabled or progression.enabled) or policy.gift_enabled or progression.enabled)
if not (policy.enabled and any((policy.buy, policy.fill, policy.dispatch, policy.collect, policy.feed))) and not other: if not (policy.enabled and any((policy.buy, policy.fill, policy.dispatch, policy.collect, policy.feed))) and not other:
self.report("请先勾选至少一项功能,并启用对应策略") self.report("请先勾选至少一项功能,并启用对应策略")
@@ -665,6 +674,7 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
self.cancel_progression() self.cancel_progression()
self.pending_execute = False self.pending_execute = False
self.next_gift = float("inf") self.next_gift = float("inf")
self.next_explore = self.next_breakthrough = float("inf")
self.update_gift_clock() self.update_gift_clock()
self.arm_hatching() self.arm_hatching()
self.update_workflow_status() self.update_workflow_status()
@@ -709,6 +719,7 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
enabled = [label for checked, label in ((self.ranch_enabled.isChecked(), "牧场 / 孵蛋"), enabled = [label for checked, label in ((self.ranch_enabled.isChecked(), "牧场 / 孵蛋"),
(self.gift_enabled.isChecked(), "赠礼"), (self.quest_enabled.isChecked(), "委托"), (self.gift_enabled.isChecked(), "赠礼"), (self.quest_enabled.isChecked(), "委托"),
(self.map_enabled.isChecked(), "扫荡"), (self.daily_enabled.isChecked(), "每日事务"), (self.map_enabled.isChecked(), "扫荡"), (self.daily_enabled.isChecked(), "每日事务"),
(self.explore_enabled.isChecked(), "探险"), (bool(self.breakthrough_targets), "突破"),
(self.progression_enabled.isChecked(), "主线推进")) if checked] (self.progression_enabled.isChecked(), "主线推进")) if checked]
self.workflow_status.setText(self.workflow_status.text() + ";已选功能:" + ("、".join(enabled) or "无")) self.workflow_status.setText(self.workflow_status.text() + ";已选功能:" + ("、".join(enabled) or "无"))
self.update_progression_status() self.update_progression_status()
@@ -800,6 +811,13 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
self.settings_changed() self.settings_changed()
self.update_gift_status() self.update_gift_status()
def monster_breakthrough_changed(self, mid, enabled, priority):
if enabled:
self.breakthrough_targets[str(mid)] = priority
else:
self.breakthrough_targets.pop(str(mid), None)
self.settings_changed()
def add_egg_rule(self): def add_egg_rule(self):
choices = {f"{row.get('name', key)} [{key}]": key for key, row in self.catalog.monsters.items() choices = {f"{row.get('name', key)} [{key}]": key for key, row in self.catalog.monsters.items()
if not row.get("npc") and self.catalog.total_time(key) > 0} if not row.get("npc") and self.catalog.total_time(key) > 0}
@@ -1240,9 +1258,12 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
policies = {key: cls(**value[key]) for key, cls in (("policy", Policy), ("quest_policy", QuestPolicy), policies = {key: cls(**value[key]) for key, cls in (("policy", Policy), ("quest_policy", QuestPolicy),
("daily_policy", DailyPolicy), ("sweep_policy", SweepPolicy))} ("daily_policy", DailyPolicy), ("sweep_policy", SweepPolicy))}
policies["progression_policy"] = checked_progression_policy(value.get("progression_policy", {})) policies["progression_policy"] = checked_progression_policy(value.get("progression_policy", {}))
policies["explore_policy"] = ExplorePolicy.from_dict(value.get("explore_policy", {}))
if self.busy: if self.busy:
self.pending_policy = policies self.pending_policy = policies
return False return False
explore = policies.pop("explore_policy")
self.apply_explore_policy(explore)
for key, policy in policies.items(): for key, policy in policies.items():
setattr(self.engine, key, policy) setattr(self.engine, key, policy)
return True return True
@@ -1259,7 +1280,7 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
def background(): def background():
started = time.perf_counter() started = time.perf_counter()
value = function() value = function()
if kind in ("poll", "hatch", "monster_lock", "manual_monsters", "expansion", "growth_sync", "master_sync", "map_refresh", "daily_claim", "connected", "policy_preview", "progression_refresh", "progression_run"): if kind in ("poll", "hatch", "automation", "monster_lock", "manual_monsters", "expansion", "growth_sync", "master_sync", "map_refresh", "daily_claim", "connected", "policy_preview", "progression_refresh", "progression_run"):
snapshot = value[1] if kind == "connected" else value[0] snapshot = value[1] if kind == "connected" else value[0]
managed = set() if kind == "connected" else set(engine.planner.managed) managed = set() if kind == "connected" else set(engine.planner.managed)
preparing = time.perf_counter() preparing = time.perf_counter()
@@ -1279,6 +1300,8 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
if kind != "connected" and (progression_visible or records_visible or explicit_progression): if kind != "connected" and (progression_visible or records_visible or explicit_progression):
views.progression = prepare_progression_views(engine, views.progression = prepare_progression_views(engine,
tasks=progression_visible or explicit_progression, records=records_visible or explicit_progression) tasks=progression_visible or explicit_progression, records=records_visible or explicit_progression)
if kind != "connected" and self.presentation_active and not self.closed and self.tabs.currentWidget() is self.exploration_page:
views.exploration = prepare_exploration_rows(engine)
return Presented(value, views, (time.perf_counter() - preparing) * 1000, (time.perf_counter() - started) * 1000) return Presented(value, views, (time.perf_counter() - preparing) * 1000, (time.perf_counter() - started) * 1000)
return value return value
job = Job(kind, background) job = Job(kind, background)
@@ -1305,6 +1328,8 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
self.pending_monster_view = False self.pending_monster_view = False
if self.pending_policy is not None and not self.closed: if self.pending_policy is not None and not self.closed:
policies, self.pending_policy = self.pending_policy, None policies, self.pending_policy = self.pending_policy, None
explore = policies.pop("explore_policy", self.engine.explore_policy)
self.apply_explore_policy(explore)
progression_changed = asdict(getattr(self.engine, "progression_policy", ProgressionPolicy())) != asdict(policies["progression_policy"]) progression_changed = asdict(getattr(self.engine, "progression_policy", ProgressionPolicy())) != asdict(policies["progression_policy"])
for key, policy in policies.items(): for key, policy in policies.items():
setattr(self.engine, key, policy) setattr(self.engine, key, policy)
@@ -1317,6 +1342,11 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
self.schedule() self.schedule()
if self.busy: if self.busy:
return return
if self.pending_exploration_view and not self.closed and self.presentation_active and self.tabs.currentWidget() is self.exploration_page:
self.pending_exploration_view = False
self.refresh_exploration()
if self.busy:
return
if self.close_after_job: if self.close_after_job:
C.QTimer.singleShot(0, self.close) C.QTimer.singleShot(0, self.close)
elif self.pending_refresh is not None: elif self.pending_refresh is not None:
@@ -1353,13 +1383,15 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
note="worker总耗时包含网络;大列表在后续短批次更新") note="worker总耗时包含网络;大列表在后续短批次更新")
def apply_result(self, kind, value): def apply_result(self, kind, value):
if kind in ("poll", "hatch", "monster_lock", "manual_monsters", "expansion", "growth_sync", "master_sync", "map_refresh", "daily_claim", "policy_preview", "progression_refresh", "progression_run"): if kind in ("poll", "hatch", "automation", "monster_lock", "manual_monsters", "expansion", "growth_sync", "master_sync", "map_refresh", "daily_claim", "policy_preview", "progression_refresh", "progression_run"):
snapshot, plans, message = value snapshot, plans, message = value
if kind != "policy_preview" and not self.engine.demo and not self.closed and self.logout_phase is None: if kind != "policy_preview" and not self.engine.demo and not self.closed and self.logout_phase is None:
self.monitoring = True self.monitoring = True
self.engine.heartbeat_enabled = True self.engine.heartbeat_enabled = True
self.render(snapshot, plans) self.render(snapshot, plans)
self.report(message) self.report(message)
if kind in ("poll", "automation") and self.engine.pending_recovery_due():
self.next_poll = min(self.next_poll, time.monotonic() + 120)
self.reload_saved_sessions() self.reload_saved_sessions()
if kind == "poll": if kind == "poll":
self.next_poll = time.monotonic() + self.poll_delay() self.next_poll = time.monotonic() + self.poll_delay()
@@ -1367,6 +1399,11 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
self.stop_workflow() self.stop_workflow()
self.arm_hatching() self.arm_hatching()
self.arm_gifting() self.arm_gifting()
self.arm_extended_automation()
elif kind == "exploration_view":
self.accept_exploration_view(value)
elif kind.startswith("exploration_members:"):
self.accept_exploration_members(*value)
elif kind == "heartbeat": elif kind == "heartbeat":
self.report(value) self.report(value)
elif kind == "analysis": elif kind == "analysis":
@@ -1508,6 +1545,7 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
gift_enabled=self.gift_enabled.isChecked(), gift_targets=copy.deepcopy(self.gift_targets), gift_enabled=self.gift_enabled.isChecked(), gift_targets=copy.deepcopy(self.gift_targets),
gift_items=copy.deepcopy(self.gift_items), gift_liked_only=self.gift_liked_only.isChecked(), gift_items=copy.deepcopy(self.gift_items), gift_liked_only=self.gift_liked_only.isChecked(),
gift_auto_representative=self.gift_auto_representative.isChecked(), keep_better_quality=self.keep_better_quality.isChecked(), gift_auto_representative=self.gift_auto_representative.isChecked(), keep_better_quality=self.keep_better_quality.isChecked(),
breakthrough_targets=copy.deepcopy(self.breakthrough_targets),
keep_money=self.keep_money.value(), daily_buy_money=self.daily_buy_money.value()) keep_money=self.keep_money.value(), daily_buy_money=self.daily_buy_money.value())
def read_quest_policy(self): def read_quest_policy(self):
@@ -1538,6 +1576,20 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
self.report("策略输入尚未完整,已关闭策略;本次继续刷新角色数据:" + str(error)) self.report("策略输入尚未完整,已关闭策略;本次继续刷新角色数据:" + str(error))
self.submit("poll", self.engine.poll) self.submit("poll", self.engine.poll)
def run_extended_automation(self):
if self.busy or not self.engine.auto or not self.engine.snapshot:
return
self.submit("automation", self.engine.poll)
def arm_extended_automation(self):
active = self.monitoring and self.strategy_toggle.isChecked() and not self.closed and self.engine.snapshot is not None
plans = self.latest_render[1] if self.latest_render else []
explore = active and self.explore_enabled.isChecked() and any(
action.kind in ("explore_start", "explore_finish") and action.path for action in plans)
breakthrough = active and any(action.kind in ("potential", "breakthrough") for action in plans)
self.next_explore = time.monotonic() + 1 if explore else float("inf")
self.next_breakthrough = time.monotonic() + 1 if breakthrough else float("inf")
def poll_delay(self): def poll_delay(self):
return random.uniform(0, self.interval.currentData()) return random.uniform(0, self.interval.currentData())
@@ -1607,6 +1659,8 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
self.refresh(automated=True) self.refresh(automated=True)
elif self.monitoring and self.strategy_toggle.isChecked() and now >= self.next_gift: elif self.monitoring and self.strategy_toggle.isChecked() and now >= self.next_gift:
self.refresh(automated=True) self.refresh(automated=True)
elif self.monitoring and self.strategy_toggle.isChecked() and now >= min(self.next_explore, self.next_breakthrough):
self.run_extended_automation()
def render(self, snapshot, plans): def render(self, snapshot, plans):
self.latest_render = (snapshot, plans) self.latest_render = (snapshot, plans)
@@ -1697,6 +1751,8 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
widget.row_batch.stop() widget.row_batch.stop()
if page is not self.analysis_page: if page is not self.analysis_page:
self.analysis_page.row_batch.stop() self.analysis_page.row_batch.stop()
if page is not self.exploration_page:
self.exploration_table.row_batch.stop()
for name, target in (("map_render_timer", self.map_page), ("monster_render_timer", self.monster_page)): for name, target in (("map_render_timer", self.map_page), ("monster_render_timer", self.monster_page)):
timer = getattr(self, name, None) timer = getattr(self, name, None)
if timer and page is not target: if timer and page is not target:
@@ -1722,6 +1778,11 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
self.render_quests(snapshot) self.render_quests(snapshot)
elif page is self.map_page: elif page is self.map_page:
self.render_maps() self.render_maps()
elif page is self.exploration_page:
if self.prepared_views and self.prepared_views.snapshot is snapshot and self.prepared_views.exploration is not None:
self.accept_exploration_view(self.prepared_views.exploration)
elif not self.busy:
self.refresh_exploration()
elif page is self.analysis_page: elif page is self.analysis_page:
views = self.prepared_views views = self.prepared_views
owner = str(snapshot.raw["master"]["id"]) owner = str(snapshot.raw["master"]["id"])
@@ -1751,7 +1812,7 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
if self.monster_data_pending: if self.monster_data_pending:
self.monster_render_timer.stop() self.monster_render_timer.stop()
self.monster_data_pending = False self.monster_data_pending = False
self.monsters.set_data(snapshot, views.monsters, self.feed_targets, self.gift_targets) self.monsters.set_data(snapshot, views.monsters, self.feed_targets, self.gift_targets, self.breakthrough_targets)
else: else:
self.request_monster_views(snapshot) self.request_monster_views(snapshot)
@@ -1971,6 +2032,7 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
return {"policy": asdict(self.read_policy()), "quest_policy": asdict(self.read_quest_policy()), return {"policy": asdict(self.read_policy()), "quest_policy": asdict(self.read_quest_policy()),
"daily_policy": asdict(self.read_daily_policy()), "sweep_policy": asdict(self.read_sweep_policy()), "daily_policy": asdict(self.read_daily_policy()), "sweep_policy": asdict(self.read_sweep_policy()),
"progression_policy": asdict(self.read_progression_policy()), "progression_policy": asdict(self.read_progression_policy()),
"explore_policy": self.read_explore_policy().to_dict(),
"overrides": copy.deepcopy(self.catalog.overrides), "overrides": copy.deepcopy(self.catalog.overrides),
"log_visible": self.show_log.isChecked(), "log_sizes": self.log_splitter.sizes() if self.show_log.isChecked() else self.log_sizes, "log_visible": self.show_log.isChecked(), "log_sizes": self.log_splitter.sizes() if self.show_log.isChecked() else self.log_sizes,
"yield_stars": [star for star, check in self.yield_stars.items() if check.isChecked()], "yield_stars": [star for star, check in self.yield_stars.items() if check.isChecked()],
@@ -1984,6 +2046,7 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
"coin_exp", "reserved_types", "reserve_eggs", "fill", "egg_order", "min_gold", "min_exp", "buy_eggs", "coin_exp", "reserved_types", "reserve_eggs", "fill", "egg_order", "min_gold", "min_exp", "buy_eggs",
"buy_ten", "allow_single_draw", "dispatch", "collect", "feed", "market", "egg_stock", "buy_batch", "keep_money", "daily_buy_money", "buy_ten", "allow_single_draw", "dispatch", "collect", "feed", "market", "egg_stock", "buy_batch", "keep_money", "daily_buy_money",
"hatch_max_star", "gift_enabled", "gift_liked_only", "quest_enabled", "quest_accept", "quest_city", "quest_items", "hatch_max_star", "gift_enabled", "gift_liked_only", "quest_enabled", "quest_accept", "quest_city", "quest_items",
"explore_enabled", "explore_reserve_ti",
"quest_monsters", "quest_money", "quest_battles", "quest_reserves", "keep_better_quality", "gift_auto_representative") "quest_monsters", "quest_money", "quest_battles", "quest_reserves", "keep_better_quality", "gift_auto_representative")
for name in names: for name in names:
widget = getattr(self, name) widget = getattr(self, name)
@@ -2015,7 +2078,7 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
changed = any(asdict(getattr(self.engine, key)) != value[key] changed = any(asdict(getattr(self.engine, key)) != value[key]
for key in ("policy", "quest_policy", "daily_policy", "sweep_policy")) for key in ("policy", "quest_policy", "daily_policy", "sweep_policy"))
progression_changed = asdict(getattr(self.engine, "progression_policy", ProgressionPolicy())) != value["progression_policy"] progression_changed = asdict(getattr(self.engine, "progression_policy", ProgressionPolicy())) != value["progression_policy"]
changed = changed or progression_changed changed = changed or progression_changed or self.engine.explore_policy.to_dict() != value["explore_policy"]
local_selection_changed = any(getattr(self.engine.policy, key) != value["policy"][key] local_selection_changed = any(getattr(self.engine.policy, key) != value["policy"][key]
for key in ("gift_auto_representative", "keep_better_quality")) for key in ("gift_auto_representative", "keep_better_quality"))
self.update_policy(value) self.update_policy(value)
@@ -2087,8 +2150,8 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
self.load_config(self.config_value() | config) self.load_config(self.config_value() | config)
self.persist_settings() self.persist_settings()
policy = self.read_policy() policy = self.read_policy()
matched = len(policy.feed_targets) + len(policy.gift_targets) matched = len(policy.feed_targets) + len(policy.gift_targets) + len(policy.breakthrough_targets)
self.report(f"已导入并保存策略;已匹配 {matched} 个当前账号的喂养/赠礼目标;顶部策略开关保持关闭") self.report(f"已导入并保存策略;已匹配 {matched} 个当前账号的喂养/赠礼/突破目标;探险队伍按队序重绑定;顶部策略开关保持关闭")
except (OSError, ValueError, TypeError, KeyError) as error: except (OSError, ValueError, TypeError, KeyError) as error:
self.report("策略导入失败:" + str(error)) self.report("策略导入失败:" + str(error))
@@ -2103,6 +2166,8 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
if value is None: if value is None:
value = json.loads(path.read_text(encoding="utf-8")) value = json.loads(path.read_text(encoding="utf-8"))
progression = checked_progression_policy(value.get("progression_policy", {})) progression = checked_progression_policy(value.get("progression_policy", {}))
explore = ExplorePolicy.from_dict(value.get("explore_policy", self.read_explore_policy().to_dict()))
self.apply_explore_policy(explore)
sizes = value.get("log_sizes", [420, 140]) sizes = value.get("log_sizes", [420, 140])
if isinstance(sizes, list) and len(sizes) == 2 and all(isinstance(v, int) and v >= 0 for v in sizes) and sum(sizes) > 0: if isinstance(sizes, list) and len(sizes) == 2 and all(isinstance(v, int) and v >= 0 for v in sizes) and sum(sizes) > 0:
self.log_sizes = sizes self.log_sizes = sizes
@@ -2129,6 +2194,7 @@ class Window(ProgressionPages, ActivityPages, W.QMainWindow):
if not self.feed_targets and policy.feed_target: if not self.feed_targets and policy.feed_target:
self.feed_targets[str(policy.feed_target)] = 1 self.feed_targets[str(policy.feed_target)] = 1
self.gift_targets = copy.deepcopy(policy.gift_targets) self.gift_targets = copy.deepcopy(policy.gift_targets)
self.breakthrough_targets = copy.deepcopy(policy.breakthrough_targets)
self.gift_items = copy.deepcopy(policy.gift_items) self.gift_items = copy.deepcopy(policy.gift_items)
self.gift_enabled.setChecked(policy.gift_enabled) self.gift_enabled.setChecked(policy.gift_enabled)
self.gift_liked_only.setChecked(policy.gift_liked_only) self.gift_liked_only.setChecked(policy.gift_liked_only)
+274 -18
View File
@@ -5,7 +5,7 @@ import json
import math import math
from pathlib import Path from pathlib import Path
import time import time
from .cultivation import CultivationSelector, growth_score from .cultivation import CultivationSelector, growth_score, quality_rank, quality_summary
WIKI = "https://wiki.biligame.com/myrzx/魔物收益表" WIKI = "https://wiki.biligame.com/myrzx/魔物收益表"
@@ -258,12 +258,25 @@ class EggRule:
refill_below: int = 1 refill_below: int = 1
refill_target: int = 10 refill_target: int = 10
market_id: str = "" market_id: str = ""
keep_count: int = 1
def __post_init__(self): def __post_init__(self):
if self.action not in ("sell", "feed", "keep") or not 1 <= self.priority <= 999: if self.action not in ("sell", "feed", "keep") or not 1 <= self.priority <= 999:
raise ValueError("魔物蛋规则的优先级或孵化后去向无效") raise ValueError("魔物蛋规则的优先级或孵化后去向无效")
if not 0 <= self.refill_below <= 1000 or not max(1, self.refill_below) <= self.refill_target <= 1000: if not 0 <= self.refill_below <= 1000 or not max(1, self.refill_below) <= self.refill_target <= 1000:
raise ValueError("补货目标不能低于补货下限,0下限表示不自动补货") raise ValueError("补货目标不能低于补货下限,0下限表示不自动补货")
value = self.keep_count
if isinstance(value, bool) or not isinstance(value, (int, str)):
raise ValueError("牧场保留数量须为0至1000的整数")
try:
count = int(value)
except (TypeError, ValueError) as error:
raise ValueError("牧场保留数量须为0至1000的整数") from error
if isinstance(value, str) and value != str(count):
raise ValueError("牧场保留数量须为0至1000的整数")
self.keep_count = count
if not 0 <= count <= 1000:
raise ValueError("牧场保留数量须为0至1000")
@dataclass @dataclass
@@ -303,14 +316,39 @@ class Policy:
gift_liked_only: bool = True gift_liked_only: bool = True
gift_auto_representative: bool = False gift_auto_representative: bool = False
keep_better_quality: bool = False keep_better_quality: bool = False
breakthrough_targets: dict[str, int] = field(default_factory=dict)
def __post_init__(self): def __post_init__(self):
self.egg_rules = {str(int(key)): asdict(EggRule(**rule)) for key, rule in self.egg_rules.items()} self.egg_rules = {str(int(key)): asdict(EggRule(**rule)) for key, rule in self.egg_rules.items()}
self.feed_targets = {str(int(key)): int(priority) for key, priority in self.feed_targets.items() if int(key) > 0 and 1 <= int(priority) <= 999} self.feed_targets = {str(int(key)): int(priority) for key, priority in self.feed_targets.items() if int(key) > 0 and 1 <= int(priority) <= 999}
self.gift_targets = {str(int(key)): int(priority) for key, priority in self.gift_targets.items() if int(key) > 0 and 1 <= int(priority) <= 999} self.gift_targets = {str(int(key)): int(priority) for key, priority in self.gift_targets.items() if int(key) > 0 and 1 <= int(priority) <= 999}
self.breakthrough_targets = self._validated_targets(self.breakthrough_targets, "自动突破")
self.gift_items = {str(int(key)): {"enabled": bool(rule.get("enabled")), "reserve": max(0, int(rule.get("reserve", 0)))} self.gift_items = {str(int(key)): {"enabled": bool(rule.get("enabled")), "reserve": max(0, int(rule.get("reserve", 0)))}
for key, rule in self.gift_items.items()} for key, rule in self.gift_items.items()}
@staticmethod
def _validated_targets(targets, label):
if not isinstance(targets, dict):
raise ValueError(f"{label}目标须为“魔物ID: 优先级”字典")
result = {}
for key, priority in targets.items():
if isinstance(key, bool) or isinstance(priority, bool):
raise ValueError(f"{label}目标ID须为正整数,优先级须为1至999")
try:
monster_id, rank = int(key), int(priority)
except (TypeError, ValueError) as error:
raise ValueError(f"{label}目标ID须为正整数,优先级须为1至999") from error
if isinstance(key, float) and not key.is_integer() or isinstance(priority, float) and not priority.is_integer():
raise ValueError(f"{label}目标ID须为正整数,优先级须为1至999")
if isinstance(key, str) and key.strip() != str(monster_id) or isinstance(priority, str) and priority.strip() != str(rank):
raise ValueError(f"{label}目标ID须为正整数,优先级须为1至999")
if monster_id <= 0 or not 1 <= rank <= 999:
raise ValueError(f"{label}目标ID须为正整数,优先级须为1至999")
if str(monster_id) in result:
raise ValueError(f"{label}目标ID重复:{monster_id}")
result[str(monster_id)] = rank
return result
@dataclass @dataclass
class Action: class Action:
@@ -328,10 +366,29 @@ class Planner:
self.notes = [] self.notes = []
self.restocking = set() self.restocking = set()
self.statuses = {} self.statuses = {}
self.retained = set()
self.retention_reasons = {}
self.representatives = {}
self.preparing_retention = False
self.retention_signature = None
self.tp_feed_targets = set()
self.food_protection = {}
def protected(self, mon, snapshot, policy): def protected(self, mon, snapshot, policy):
self.ensure_retention(snapshot, policy)
return bool(self.protection_reason(mon, snapshot, policy)) return bool(self.protection_reason(mon, snapshot, policy))
def ensure_retention(self, snapshot, policy):
if not policy.manual_eggs:
return
signature = (repr(snapshot.raw.get("monsters")), repr(snapshot.raw.get("teams")),
repr((policy.manual_eggs, policy.egg_rules, policy.keep_better_quality,
policy.gift_auto_representative, policy.protect_star, policy.protect_quality,
policy.feed_target, policy.feed_targets, policy.breakthrough_targets, policy.reserved_types)))
if signature != self.retention_signature:
self.prepare_retention(snapshot, policy)
self.retention_signature = signature
def protection_reason(self, mon, snapshot, policy): def protection_reason(self, mon, snapshot, policy):
row = self.catalog.monster(mon.get("typeId")) row = self.catalog.monster(mon.get("typeId"))
qualities = self.catalog.quality(mon) qualities = self.catalog.quality(mon)
@@ -340,30 +397,124 @@ class Planner:
(mon.get("inExploreTeam"), "正在探索"), (mon.get("inBuild"), "正在建筑中"), (mon.get("inExploreTeam"), "正在探索"), (mon.get("inBuild"), "正在建筑中"),
(any(mon.get(f"equip{i}", 0) for i in range(1, 6)), "携带装备"), (any(mon.get(f"equip{i}", 0) for i in range(1, 6)), "携带装备"),
(int(mon["id"]) == policy.feed_target or str(mon["id"]) in policy.feed_targets, "已选为喂养目标"), (int(mon["id"]) == policy.feed_target or str(mon["id"]) in policy.feed_targets, "已选为喂养目标"),
(str(mon["id"]) in policy.breakthrough_targets, "已选为自动突破目标"),
(str(mon.get("typeId")) in {str(t) for t in policy.reserved_types}, "保留种类或委托保留"), (str(mon.get("typeId")) in {str(t) for t in policy.reserved_types}, "保留种类或委托保留"),
(row.get("star", 0) >= policy.protect_star, f"{row.get('star', '?')}星达到保留星级{policy.protect_star}"), (row.get("star", 0) >= policy.protect_star, f"{row.get('star', '?')}星达到保留星级{policy.protect_star}"),
(any(q is None for q in qualities), "资质尚未确定 / 未同步")): (any(q is None for q in qualities), "资质尚未确定 / 未同步")):
if condition: if condition:
return reason return reason
if int(mon["id"]) in self.retained:
return self.retention_reasons[int(mon["id"])]
quality = math.ceil(sum(qualities) / 4) quality = math.ceil(sum(qualities) / 4)
if policy.keep_better_quality or policy.gift_auto_representative: if (policy.keep_better_quality or policy.gift_auto_representative) and not policy.manual_eggs:
representative = self.cultivation.select(snapshot).get(str(mon.get("typeId"))) representative = (self.representatives if policy.manual_eggs else self.cultivation.select(snapshot)).get(str(mon.get("typeId")))
if representative and int(representative["id"]) == int(mon["id"]): if policy.gift_auto_representative and representative and int(representative["id"]) == int(mon["id"]):
return "同种魔物的唯一培养代表(等级、好感、资质优先)" return "同种魔物的唯一培养代表(等级、好感、资质优先)"
if policy.keep_better_quality: if policy.keep_better_quality and not self.preparing_retention:
if representative is None: if representative is None:
return "牧场尚无同种魔物,保留首次获得的魔物" return "牧场尚无同种魔物,保留首次获得的魔物"
baseline, candidate = growth_score(self.catalog, representative), growth_score(self.catalog, mon) baseline, candidate = quality_rank(self.catalog, representative), quality_rank(self.catalog, mon)
if baseline is None: if baseline is None:
return "同种培养代表的资质尚未同步,暂时保留" return "同种培养代表的资质尚未同步,暂时保留"
if candidate is not None and candidate > baseline + 1e-8: if candidate is not None and candidate > baseline:
return f"综合成长资质高于同种培养代表 #{representative['id']}({candidate:.1%} > {baseline:.1%})" return (f"资质优于同种培养代表 #{representative['id']}"
f"({quality_summary(self.catalog, mon)} / S项{candidate[0]} > "
f"{quality_summary(self.catalog, representative)} / S项{baseline[0]})")
if policy.protect_quality == 6: if policy.protect_quality == 6:
return "攻/防/生命/敏捷四项资质全S(4S)" if all(q == 4 for q in qualities) else "" return "攻/防/生命/敏捷四项资质全S(4S)" if all(q == 4 for q in qualities) else ""
if quality >= policy.protect_quality: if quality >= policy.protect_quality:
return f"综合资质{'CBAS'[quality - 1]}达到保留资质{'CBAS'[policy.protect_quality - 1]}" return f"综合资质{'CBAS'[quality - 1]}达到保留资质{'CBAS'[policy.protect_quality - 1]}"
return "" return ""
def prepare_retention(self, snapshot, policy):
"""Allocate each species quota once for all ranches and this hatch batch."""
self.retained, self.retention_reasons, self.representatives = set(), {}, {}
self.retention_signature = None
if not policy.manual_eggs:
return
self.preparing_retention = True
try:
for mon in snapshot.raw["monsters"]:
if mon.get("process") == 3:
reason = self.protection_reason(mon, snapshot, policy)
if reason:
self.retained.add(int(mon["id"]))
self.retention_reasons[int(mon["id"])] = reason
finally:
self.preparing_retention = False
self.representatives = self.cultivation.select(snapshot)
groups = {}
for mon in snapshot.raw["monsters"]:
if mon.get("process") in (2, 3) and int(mon.get("mode") or 0) == 2:
groups.setdefault(str(mon.get("typeId")), []).append(mon)
for key, rule in policy.egg_rules.items():
if not rule.get("enabled"):
continue
members = groups.get(key, [])
representative = self.representatives.get(key)
if representative is None and members:
representative = min(members, key=lambda row: (quality_rank(self.catalog, row) is None,
tuple(-value for value in (quality_rank(self.catalog, row) or ())), int(row["id"])))
quota = int(rule.get("keep_count", 1))
occupied = sum(row.get("process") == 3 and int(row["id"]) in self.retained for row in members)
if quota > 0 and representative is not None and representative.get("process") == 3 and occupied < quota:
mid = int(representative["id"])
already_retained = mid in self.retained
self.retained.add(mid)
self.retention_reasons[mid] = f"同种稳定培养代表,牧场保留数量 1 / {quota}"
occupied += int(representative.get("process") == 3 and not already_retained)
ranch = [row for row in members if row.get("process") == 3 and int(row["id"]) not in self.retained]
ranch.sort(key=lambda row: (quality_rank(self.catalog, row) is None,
tuple(-value for value in (quality_rank(self.catalog, row) or ())), int(row["id"])))
used = occupied
quality_baseline = [quality_rank(self.catalog, row) for row in members
if row.get("process") == 3 and int(row["id"]) in self.retained]
quality_baseline = [value for value in quality_baseline if value is not None]
for row in ranch:
if used >= quota:
break
used += 1
self.retained.add(int(row["id"]))
self.retention_reasons[int(row["id"])] = f"同种牧场保留数量 {used} / {quota}"
rank = quality_rank(self.catalog, row)
if rank is not None:
quality_baseline.append(rank)
incubator = [row for row in members if row.get("process") == 2 and int(row["id"]) not in self.retained]
incubator.sort(key=lambda row: (quality_rank(self.catalog, row) is None,
tuple(-value for value in (quality_rank(self.catalog, row) or ())), int(row["id"])))
for row in incubator:
if used >= quota:
break
used += 1
self.retained.add(int(row["id"]))
self.retention_reasons[int(row["id"])] = f"同种牧场及培育室保留数量 {used} / {quota}"
rank = quality_rank(self.catalog, row)
if rank is not None:
quality_baseline.append(rank)
# Compare with the best retained ranch quality, not repeatedly
# with an inferior locked monster. Select at most one improvement
# per snapshot, including the newly collected batch as one group.
if policy.keep_better_quality and quality_baseline:
baseline = max(quality_baseline)
candidates = [(quality_rank(self.catalog, row), row) for row in members
if int(row["id"]) not in self.retained]
candidates = [(rank, row) for rank, row in candidates if rank is not None and rank > baseline]
if candidates:
rank, row = min(candidates, key=lambda pair: (-pair[0][0], -pair[0][1], -pair[0][2], -pair[0][3], int(pair[1]["id"])))
self.retained.add(int(row["id"]))
self.retention_reasons[int(row["id"])] = (
f"额外保留更优资质 {quality_summary(self.catalog, row)} / S项{rank[0]},"
f"牧场已保留最高资质 S项{baseline[0]}")
# If the only mature monster is still incubating, it becomes the
# representative upon collection rather than being disposed first.
if quota > 0 and not any(int(row["id"]) in self.retained for row in members) and members:
row = members[0]
self.retained.add(int(row["id"]))
self.retention_reasons[int(row["id"])] = f"同种本批培养代表,牧场保留数量 1 / {quota}"
def disposition(self, mon, snapshot, policy): def disposition(self, mon, snapshot, policy):
if self.protected(mon, snapshot, policy): if self.protected(mon, snapshot, policy):
return "keep" return "keep"
@@ -403,6 +554,85 @@ class Planner:
target, reason = self.feeding_target(snapshot, policy) target, reason = self.feeding_target(snapshot, policy)
return target is not None, reason return target is not None, reason
def tp_thresholds(self, target):
"""Cumulative TP thresholds, indexed by species star rating (AS3 GameMath.tpExp)."""
table = self.catalog.data.get("game_setting", {}).get("tpExp")
star = self.catalog.monster(target.get("typeId")).get("star")
if isinstance(table, dict):
table = table.get(str(star), table.get(star))
if isinstance(table, list) and table and not isinstance(table[0], (list, dict)) and star is not None:
table = table[int(star)] if int(star) < len(table) else None
if isinstance(table, dict):
table = [value for _, value in sorted(table.items(), key=lambda pair: int(pair[0]))]
if not isinstance(table, list) or len(table) < 5:
return None
try:
return [int(value) for value in table[:5]]
except (TypeError, ValueError):
return None
def tp_feeding_remaining(self, target):
# GameMath.maxTpLevel is hardcoded to 4; potentialLevel is unrelated.
if target.get("tpLevel") is None or target.get("tpExp") is None:
return None
level = max(0, int(target.get("tpLevel")))
if level >= 4:
return 0
thresholds = self.tp_thresholds(target)
if thresholds is None:
return None
return max(0, thresholds[4] - int(target.get("tpExp")))
def same_species_feeding_target(self, mon, snapshot, policy, exclude=()):
"""Prefer an unfinished same-species TP target; never consume a representative."""
if mon.get("process") != 3:
return None, "素材尚未收取到牧场"
excluded = {int(mid) for mid in exclude} | {int(mon["id"])}
candidates = [row for row in snapshot.raw["monsters"] if row.get("process") == 3
and str(row.get("typeId")) == str(mon.get("typeId"))
and int(row["id"]) != int(mon["id"])
and not self.food_protection.get(int(row["id"]))
and (quality_rank(self.catalog, mon) is None or quality_rank(self.catalog, row) is not None
and quality_rank(self.catalog, row) >= quality_rank(self.catalog, mon))
and (int(row["id"]) in self.managed or self.protected(row, snapshot, policy))]
candidates.sort(key=lambda row: (int(policy.feed_targets.get(str(row["id"]), 9999)),
int(policy.breakthrough_targets.get(str(row["id"]), 9999)), -int(row.get("level") or 1), int(row["id"])))
unknown = False
for target in candidates:
remaining = self.tp_feeding_remaining(target)
if remaining is None:
unknown = True
continue
# TP food works even at the ordinary experience cap. Do not use
# potentialLevel here: it controls the separate material breakthrough.
if remaining > 0:
self.tp_feed_targets.add(int(target["id"]))
return target, f"优先同种突破喂养 #{target['id']}(tpLevel {int(target.get('tpLevel') or 0)} / 4)"
cap = self.catalog.max_level(target)
if remaining == 0 and cap is not None and int(target.get("level") or 1) < cap and self.catalog.feed_remaining(target, cap) != 0:
self.tp_feed_targets.add(int(target["id"]))
return target, f"同种突破已满,继续普通经验喂养 #{target['id']}"
if unknown:
return None, "缺少game_setting.tpExp累计门槛,暂停同种突破喂养"
ordinary = [target for target in candidates if self.tp_feeding_remaining(target) == 0
and self.catalog.max_level(target) is not None and int(target.get("level") or 1) < self.catalog.max_level(target)
and self.catalog.feed_remaining(target, self.catalog.max_level(target)) != 0]
if ordinary:
target = ordinary[0]
self.tp_feed_targets.add(int(target["id"]))
return target, f"同种突破已满,继续普通经验喂养 #{target['id']}"
return None, "同种魔物均已完成突破,不继续消耗同种素材"
def is_same_species_tp_feed(self, target, food):
return self.tp_food_value(target, food) > 0 and (self.tp_feeding_remaining(target) or 0) > 0
def tp_food_value(self, target, food):
settings = self.catalog.data.get("game_setting", {})
target_star = int(self.catalog.monster(target.get("typeId")).get("star") or 0)
return int(str(food.get("typeId")) == str(target.get("typeId"))
or str(food.get("typeId")) == str(settings.get("specialFood"))
or target_star < 5 and str(food.get("typeId")) == str(settings.get("specialFood14")))
def available_eggs(self, snapshot, policy): def available_eggs(self, snapshot, policy):
reserves = dict(policy.reserved_eggs) reserves = dict(policy.reserved_eggs)
result = [] result = []
@@ -491,7 +721,10 @@ class Planner:
def plan(self, snapshot, policy, daily_left=None): def plan(self, snapshot, policy, daily_left=None):
self.notes = [] self.notes = []
self.statuses = {} self.statuses = {}
self.tp_feed_targets = set()
self.food_protection = {}
self.managed.update(int(s["monsterId"]) for s in snapshot.raw["stacks"] if int(s.get("monsterId") or 0) > 0) self.managed.update(int(s["monsterId"]) for s in snapshot.raw["stacks"] if int(s.get("monsterId") or 0) > 0)
self.ensure_retention(snapshot, policy)
if not policy.enabled: if not policy.enabled:
self.notes.append("牧场策略未启用") self.notes.append("牧场策略未启用")
return [] return []
@@ -542,7 +775,12 @@ class Planner:
else: else:
self.notes.append(f"{name} 等待收取:牧场没有空位") self.notes.append(f"{name} 等待收取:牧场没有空位")
elif disposition == "feed" and mon.get("process") == 3: elif disposition == "feed" and mon.get("process") == 3:
target, reason = self.feeding_target(snapshot, policy) target, reason = (None, "")
if not policy.feed_target and not policy.feed_targets:
self.food_protection[mid] = self.protection_reason(mon, snapshot, policy)
target, reason = self.same_species_feeding_target(mon, snapshot, policy, exclude=self.retained)
if target is None:
target, reason = self.feeding_target(snapshot, policy)
if target: if target:
actions.append(Action("feed", f"{name} #{mid} → 喂养 #{target['id']}", "monsterService/monsterIntensify", {"targetId": int(target["id"]), "foods": [mid]})) actions.append(Action("feed", f"{name} #{mid} → 喂养 #{target['id']}", "monsterService/monsterIntensify", {"targetId": int(target["id"]), "foods": [mid]}))
else: else:
@@ -551,6 +789,10 @@ class Planner:
self.notes.append(f"{name} 已保留:{reason}") self.notes.append(f"{name} 已保留:{reason}")
if actions: if actions:
return self.batch_actions(actions, snapshot, policy) return self.batch_actions(actions, snapshot, policy)
# Feeding can be unavailable while another mature monster still needs
# collection. Returning the hatch now would hide that pending batch.
if policy.collect and any(a.kind == "collect" for a in actions):
return []
return self.hatch_actions(snapshot, policy) or self.purchase(snapshot, policy, daily_left) return self.hatch_actions(snapshot, policy) or self.purchase(snapshot, policy, daily_left)
def hatch_actions(self, snapshot, policy): def hatch_actions(self, snapshot, policy):
@@ -586,6 +828,7 @@ class Planner:
def batch_actions(self, actions, snapshot, policy): def batch_actions(self, actions, snapshot, policy):
monsters = snapshot.monsters monsters = snapshot.monsters
collects = [a for a in actions if a.kind == "collect"] collects = [a for a in actions if a.kind == "collect"]
merged_collect = None
if collects: if collects:
rooms = {} rooms = {}
for action in collects: for action in collects:
@@ -594,28 +837,41 @@ class Planner:
ids = [mid for mids in rooms.values() for mid in mids] ids = [mid for mids in rooms.values() for mid in mids]
description = "批量收取 " + "、".join(self.catalog.monster_label(monsters[mid]) for mid in ids) description = "批量收取 " + "、".join(self.catalog.monster_label(monsters[mid]) for mid in ids)
merged = Action("collect", description, "stackService/stackTransferMonster", {"datas": [{"monsterId": mids, "roomId": room} for room, mids in rooms.items()]}) merged = Action("collect", description, "stackService/stackTransferMonster", {"datas": [{"monsterId": mids, "roomId": room} for room, mids in rooms.items()]})
return [merged] + [a for a in actions if a.kind != "collect"] merged_collect = merged
actions = [a for a in actions if a.kind != "collect"]
if merged_collect is not None:
# Refresh after collection before disposing of old ranch monsters.
return [merged_collect]
feeds = [a for a in actions if a.kind == "feed"] feeds = [a for a in actions if a.kind == "feed"]
if not feeds: if not feeds:
return actions return ([merged_collect] if merged_collect else []) + actions
target_id = feeds[0].payload["targetId"] target_id = feeds[0].payload["targetId"]
target = monsters[target_id] target = monsters[target_id]
feeds = [action for action in feeds if action.payload["targetId"] == target_id
and all(mid != target_id and mid in self.managed and not self.protected(monsters[mid], snapshot, policy)
for mid in action.payload["foods"])]
if not feeds:
return ([merged_collect] if merged_collect else [])
stop_level = self.catalog.max_level(target) stop_level = self.catalog.max_level(target)
need = self.catalog.feed_remaining(target, stop_level) need = self.catalog.feed_remaining(target, stop_level)
ids, experience = [], 0 same_species = target_id in self.tp_feed_targets and all(self.is_same_species_tp_feed(target, monsters[mid])
for action in feeds if action.payload["targetId"] == target_id for mid in action.payload["foods"])
tp_need = self.tp_feeding_remaining(target) if same_species else 0
ids, experience, tp_experience = [], 0, 0
for action in feeds: for action in feeds:
if action.payload["targetId"] != target_id:
continue
for mid in action.payload["foods"]: for mid in action.payload["foods"]:
if mid in ids: if mid in ids or mid == target_id:
continue continue
ids.append(mid) ids.append(mid)
experience += self.catalog.feed_exp(monsters[mid]) experience += self.catalog.feed_exp(monsters[mid])
if need is None or experience >= need: tp_experience += self.tp_food_value(target, monsters[mid])
if same_species and tp_need is not None and tp_experience >= tp_need or not same_species and need is not None and experience >= need:
break break
if need is None or experience >= need: if same_species and tp_need is not None and tp_experience >= tp_need or not same_species and need is not None and experience >= need:
break break
label = self.catalog.monster_label(target) label = self.catalog.monster_label(target)
foods = "、".join(self.catalog.monster_label(monsters[mid]) for mid in ids) foods = "、".join(self.catalog.monster_label(monsters[mid]) for mid in ids)
if not ids:
return ([merged_collect] if merged_collect else []) + [a for a in actions if a not in feeds]
merged = Action("feed", f"喂养 {label} ← {len(ids)} 只素材:{foods}(经验 {experience})", "monsterService/monsterIntensify", {"targetId": target_id, "foods": ids}) merged = Action("feed", f"喂养 {label} ← {len(ids)} 只素材:{foods}(经验 {experience})", "monsterService/monsterIntensify", {"targetId": target_id, "foods": ids})
return [merged] + [a for a in actions if a.kind != "feed"] return ([merged_collect] if merged_collect else []) + [merged] + [a for a in actions if a not in feeds]
+60 -4
View File
@@ -7,6 +7,7 @@ from .daily import DailyPolicy
from .quests import QuestPolicy from .quests import QuestPolicy
from .sweeping import SweepPolicy from .sweeping import SweepPolicy
from .progression import ProgressionPolicy from .progression import ProgressionPolicy
from .exploration import ExplorePolicy
FORMAT = "ranch-helper-policies" FORMAT = "ranch-helper-policies"
VERSION = 1 VERSION = 1
@@ -28,6 +29,8 @@ def checked_policy(cls, data):
raise ValueError("策略字段类型错误:" + key) raise ValueError("策略字段类型错误:" + key)
try: try:
return cls(**data) return cls(**data)
except (AttributeError, TypeError, KeyError) as error: except (AttributeError, TypeError, KeyError) as error:
raise ValueError("策略字段格式错误") from error raise ValueError("策略字段格式错误") from error
@@ -58,7 +61,7 @@ def portable_policy(policy, snapshot=None):
value["feed_targets"] = {str(value["feed_target"]): 1} value["feed_targets"] = {str(value["feed_target"]): 1}
value["feed_target"] = value["room_id"] = 0 value["feed_target"] = value["room_id"] = 0
targets = {} targets = {}
for kind, field in (("feed", "feed_targets"), ("gift", "gift_targets")): for kind, field in (("feed", "feed_targets"), ("gift", "gift_targets"), ("breakthrough", "breakthrough_targets")):
targets[kind] = [] targets[kind] = []
for key, priority in sorted(value.pop(field).items(), key=lambda pair: pair[1]): for key, priority in sorted(value.pop(field).items(), key=lambda pair: pair[1]):
mon = snapshot.monsters.get(int(key)) if snapshot else None mon = snapshot.monsters.get(int(key)) if snapshot else None
@@ -73,8 +76,8 @@ def import_policy(value, snapshot=None):
policy = checked_policy(Policy, value["policy"]) policy = checked_policy(Policy, value["policy"])
policy.feed_target = policy.room_id = 0 policy.feed_target = policy.room_id = 0
if snapshot: if snapshot:
used = {"feed": set(), "gift": set()} used = {"feed": set(), "gift": set(), "breakthrough": set()}
for kind, field in (("feed", "feed_targets"), ("gift", "gift_targets")): for kind, field in (("feed", "feed_targets"), ("gift", "gift_targets"), ("breakthrough", "breakthrough_targets")):
result = {} result = {}
targets = value.get("targetSpecies", {}) targets = value.get("targetSpecies", {})
if not isinstance(targets, dict) or not isinstance(targets.get(kind, []), list): if not isinstance(targets, dict) or not isinstance(targets.get(kind, []), list):
@@ -90,7 +93,7 @@ def import_policy(value, snapshot=None):
break break
setattr(policy, field, result) setattr(policy, field, result)
else: else:
policy.feed_targets, policy.gift_targets = {}, {} policy.feed_targets, policy.gift_targets, policy.breakthrough_targets = {}, {}, {}
return policy return policy
@@ -109,9 +112,60 @@ def portable_config(config, snapshot=None):
value["interval"] = config.get("interval", 30) value["interval"] = config.get("interval", 30)
value["overrides"] = copy.deepcopy(config.get("overrides", {})) value["overrides"] = copy.deepcopy(config.get("overrides", {}))
value["yield_stars"] = list(config.get("yield_stars", [1, 2, 3, 4, 5])) value["yield_stars"] = list(config.get("yield_stars", [1, 2, 3, 4, 5]))
value["explore_policy"] = portable_explore_policy(ExplorePolicy.from_dict(config.get("explore_policy", {})), snapshot)
return value return value
def portable_explore_policy(policy, snapshot=None):
"""Team and monster IDs are account-local; preserve positions, not identities."""
value = policy.to_dict()
teams = [team for team in (snapshot.raw.get("exploreTeams", []) if snapshot else [])
if isinstance(team, dict) and str(team.get("id")) in value["teams"]]
teams.sort(key=lambda team: int(team["id"]))
if snapshot is None:
teams = list(value["teams"])
result = []
for position, team in enumerate(teams):
key = str(team.get("id")) if isinstance(team, dict) else str(team)
rule = value["teams"][key]
species = []
if snapshot:
for mid in rule["monsters"]:
mon = snapshot.monsters.get(int(mid))
species.append(str(mon.get("typeId")) if mon and mon.get("process") == 3 else "")
result.append({"position": position, "enabled": rule["enabled"], "area": rule["area"], "memberSpecies": species})
return {"enabled": False, "reserve_ti": value["reserve_ti"], "teams": result}
def import_explore_policy(value, snapshot=None):
if not isinstance(value, dict) or set(value) - {"enabled", "reserve_ti", "teams"} or not isinstance(value.get("teams"), list):
raise ValueError("自动探险策略格式错误")
teams = [team for team in (snapshot.raw.get("exploreTeams", []) if snapshot else []) if isinstance(team, dict)]
teams.sort(key=lambda team: int(team["id"]))
used = set()
result = {}
for index, rule in enumerate(value["teams"]):
if (not isinstance(rule, dict) or set(rule) != {"position", "enabled", "area", "memberSpecies"}
or type(rule["position"]) is not int or rule["position"] != index):
raise ValueError("自动探险队伍顺序配置无效")
if index >= len(teams):
continue
members = []
if rule["memberSpecies"]:
if len(rule["memberSpecies"]) != 3:
raise ValueError("自动探险手动队员须恰好三只")
for type_id in rule["memberSpecies"]:
match = next((mon for mon in sorted(snapshot.raw["monsters"], key=lambda row: int(row["id"]))
if mon.get("process") == 3 and str(mon.get("typeId")) == str(type_id) and int(mon["id"]) not in used), None)
if match is None:
raise ValueError("当前账号无法完整匹配探险手动队员;请重新选择")
used.add(int(match["id"]))
members.append(int(match["id"]))
result[str(int(teams[index]["id"]))] = {"enabled": rule["enabled"], "area": rule["area"], "monsters": members}
# Never copy the exported enable switch or any source-account instance IDs.
return ExplorePolicy(enabled=False, reserve_ti=value.get("reserve_ti", 0), teams=result).to_dict()
def import_config(value, snapshot=None): def import_config(value, snapshot=None):
if not isinstance(value, dict) or value.get("format") != FORMAT: if not isinstance(value, dict) or value.get("format") != FORMAT:
raise ValueError("不是受支持的辅助策略文件") raise ValueError("不是受支持的辅助策略文件")
@@ -120,6 +174,8 @@ def import_config(value, snapshot=None):
if value.get("schema") != CONFIG_VERSION: if value.get("schema") != CONFIG_VERSION:
raise ValueError("不支持此策略文件版本") raise ValueError("不支持此策略文件版本")
config = {"policy": asdict(import_policy(value | {"schema": VERSION}, snapshot))} config = {"policy": asdict(import_policy(value | {"schema": VERSION}, snapshot))}
if "explore_policy" in value:
config["explore_policy"] = import_explore_policy(value["explore_policy"], snapshot)
for key, cls in (("quest_policy", QuestPolicy), ("daily_policy", DailyPolicy), ("sweep_policy", SweepPolicy)): for key, cls in (("quest_policy", QuestPolicy), ("daily_policy", DailyPolicy), ("sweep_policy", SweepPolicy)):
if not isinstance(value.get(key), dict): if not isinstance(value.get(key), dict):
raise ValueError("策略文件缺少 " + key) raise ValueError("策略文件缺少 " + key)
+15 -2
View File
@@ -4,12 +4,23 @@ from .maps import stages
def monster_rows(catalog, snapshot, managed, room_id=0): def monster_rows(catalog, snapshot, managed, room_id=0):
planner = None
def tp_values(mon):
nonlocal planner
if planner is None:
# Snapshot formatting shares the pure TP calculation with policy planning.
from .model import Planner
planner = Planner(catalog)
thresholds = planner.tp_thresholds(mon)
return thresholds[4] if thresholds is not None else None
return [[m["id"], m.get("nicName") or catalog.monster(m["typeId"]).get("name", "未知"), catalog.monster(m["typeId"]).get("star", "?"), return [[m["id"], m.get("nicName") or catalog.monster(m["typeId"]).get("name", "未知"), catalog.monster(m["typeId"]).get("star", "?"),
f"{m.get('level', 1)} / {catalog.max_level(m) or '?'}", catalog.quality_text(m), f"{m.get('level', 1)} / {catalog.max_level(m) or '?'}", catalog.quality_text(m),
"培育室 · " + snapshot.phase_text(m, catalog) if m.get("process") == 2 else f"牧场 {m.get('roomId', 0)}", "培育室 · " + snapshot.phase_text(m, catalog) if m.get("process") == 2 else f"牧场 {m.get('roomId', 0)}",
"系统锁定" if m.get("sysLock") else "是" if m.get("lock") else "否", "系统锁定" if m.get("sysLock") else "是" if m.get("lock") else "否",
"本次培育" if int(m["id"]) in managed else "已有:不自动处理", "", "", m.get("potentialLevel", "?"), "本次培育" if int(m["id"]) in managed else "已有:不自动处理", "", "", m.get("potentialLevel", "?"),
*catalog.reference_stats(m), f"{m.get('feel', 0)} / {catalog.max_feel(m)}", catalog.likes_text(m["typeId"]), "", ""] for m in snapshot.raw["monsters"] *catalog.reference_stats(m), f"{m.get('feel', 0)} / {catalog.max_feel(m)}", catalog.likes_text(m["typeId"]), "", "",
"", "", f"{m.get('tpLevel', 0)} / 4", f"{m.get('tpExp', 0)} / {tp_values(m) or '?'}"] for m in snapshot.raw["monsters"]
if not room_id or m.get("process") == 3 and int(m.get("roomId") or 0) == room_id] if not room_id or m.get("process") == 3 and int(m.get("roomId") or 0) == room_id]
@@ -29,6 +40,7 @@ class Views:
statistics_store: object = None statistics_store: object = None
drop_statistics: dict = None drop_statistics: dict = None
progression: object = None progression: object = None
exploration: object = None
@dataclass @dataclass
@@ -43,6 +55,7 @@ def prepare_views(catalog, snapshot, managed, stage_cache=None, statistics=None,
"""Omitted monster rows stay dirty; the default preserves the full view API.""" """Omitted monster rows stay dirty; the default preserves the full view API."""
source = repr(snapshot.raw["monsters"]) if include_monsters else None source = repr(snapshot.raw["monsters"]) if include_monsters else None
monsters = monster_rows(catalog, snapshot, managed) if include_monsters else None monsters = monster_rows(catalog, snapshot, managed) if include_monsters else None
return Views(snapshot, source, set(managed), monsters, views = Views(snapshot, source, set(managed), monsters,
str(snapshot.raw["master"]["id"]), stage_cache.get(snapshot) if stage_cache else stages(catalog, snapshot), stage_cache, str(snapshot.raw["master"]["id"]), stage_cache.get(snapshot) if stage_cache else stages(catalog, snapshot), stage_cache,
statistics, statistics.snapshot(snapshot.raw["master"]["id"]) if statistics else None) statistics, statistics.snapshot(snapshot.raw["master"]["id"]) if statistics else None)
return views
+15 -6
View File
@@ -11,16 +11,21 @@ from .table_widgets import CenteredCheckBox, TreeItem, bind_controls, set_value
class RanchView(W.QTreeWidget): class RanchView(W.QTreeWidget):
feed_changed = C.Signal(str, bool, int) feed_changed = C.Signal(str, bool, int)
gift_changed = C.Signal(str, bool, int) gift_changed = C.Signal(str, bool, int)
breakthrough_changed = C.Signal(str, bool, int)
monster_activated = C.Signal(int) monster_activated = C.Signal(int)
def __init__(self, catalog): def __init__(self, catalog):
super().__init__() super().__init__()
self.catalog = catalog self.catalog = catalog
self.setHeaderLabels(["牧场 / 魔物ID", "名称", "星", "等级 / 当前上限", "资质 攻/防/血/敏", "位置", "锁定", "管理范围", self.setHeaderLabels(["牧场 / 魔物ID", "名称", "星", "等级 / 当前上限", "资质 攻/防/血/敏", "位置", "锁定", "管理范围",
"喂养目标", "喂养优先级", "突破等级", "参考攻击", "参考防御", "参考生命", "参考敏捷", "好感 / 当前上限", "喜欢的物品", "赠礼", "赠礼优先级"]) "喂养目标", "喂养优先级", "潜能阶段", "参考攻击", "参考防御", "参考生命", "参考敏捷", "好感 / 当前上限", "喜欢的物品", "赠礼", "赠礼优先级"])
self.header().setSectionResizeMode(W.QHeaderView.ResizeMode.Interactive) self.header().setSectionResizeMode(W.QHeaderView.ResizeMode.Interactive)
for column, width in enumerate((260, 140, 45, 120, 150, 140, 80, 130, 90, 110, 85, 90, 90, 90, 90, 90, 220, 65, 110)): for column, width in enumerate((260, 140, 45, 120, 150, 140, 80, 130, 90, 110, 85, 90, 90, 90, 90, 90, 220, 65, 110)):
self.setColumnWidth(column, width) self.setColumnWidth(column, width)
for label, width in (("自动突破目标", 110), ("突破优先级", 100), ("同种突破", 100), ("突破经验", 120)):
column = self.columnCount()
self.headerItem().setText(column, label)
self.setColumnWidth(column, width)
self.setSelectionMode(W.QAbstractItemView.SelectionMode.ExtendedSelection) self.setSelectionMode(W.QAbstractItemView.SelectionMode.ExtendedSelection)
self.setSelectionBehavior(W.QAbstractItemView.SelectionBehavior.SelectRows) self.setSelectionBehavior(W.QAbstractItemView.SelectionBehavior.SelectRows)
self.setEditTriggers(W.QAbstractItemView.EditTrigger.NoEditTriggers) self.setEditTriggers(W.QAbstractItemView.EditTrigger.NoEditTriggers)
@@ -50,11 +55,12 @@ class RanchView(W.QTreeWidget):
return "incubator" return "incubator"
return f"room:{int(mon.get('roomId') or 0)}" return f"room:{int(mon.get('roomId') or 0)}"
def set_data(self, snapshot, rows, feed_targets, gift_targets): def set_data(self, snapshot, rows, feed_targets, gift_targets, breakthrough_targets=None):
breakthrough_targets = breakthrough_targets or {}
monsters = snapshot.raw["monsters"] monsters = snapshot.raw["monsters"]
entries = [(mon, values) for mon, values in zip(monsters, rows) entries = [(mon, values) for mon, values in zip(monsters, rows)
if not self.room_id or mon.get("process") == 3 and int(mon.get("roomId") or 0) == self.room_id] if not self.room_id or mon.get("process") == 3 and int(mon.get("roomId") or 0) == self.room_id]
signature = (entries, snapshot.raw["rooms"], feed_targets, gift_targets, self.grouped, self.room_id) signature = (entries, snapshot.raw["rooms"], feed_targets, gift_targets, breakthrough_targets, self.grouped, self.room_id)
if self.render_signature == signature: if self.render_signature == signature:
return return
self.row_batch.stop() self.row_batch.stop()
@@ -112,7 +118,8 @@ class RanchView(W.QTreeWidget):
item = TreeItem(parent if parent is not None else self) item = TreeItem(parent if parent is not None else self)
item.setData(0, C.Qt.ItemDataRole.UserRole, mid) item.setData(0, C.Qt.ItemDataRole.UserRole, mid)
self.monster_items[mid] = item self.monster_items[mid] = item
for check_column, priority_column, signal in ((8, 9, self.feed_changed), (17, 18, self.gift_changed)): for check_column, priority_column, signal in ((8, 9, self.feed_changed), (17, 18, self.gift_changed),
(19, 20, self.breakthrough_changed)):
check, priority = CenteredCheckBox(), IntegerInput() check, priority = CenteredCheckBox(), IntegerInput()
priority.setRange(1, 999) priority.setRange(1, 999)
def changed(*args, check=check, priority=priority, signal=signal, mid=mid): def changed(*args, check=check, priority=priority, signal=signal, mid=mid):
@@ -123,11 +130,13 @@ class RanchView(W.QTreeWidget):
self.setItemWidget(item, priority_column, priority) self.setItemWidget(item, priority_column, priority)
item.setSizeHint(0, C.QSize(100, 26)) item.setSizeHint(0, C.QSize(100, 26))
item.setSelected(mid in selected) item.setSelected(mid in selected)
self.itemWidget(item, 19).setToolTip("勾选即授权消耗对应材料补满潜能并提升潜能阶段;不消耗金币或氪金")
for column, value in enumerate(values): for column, value in enumerate(values):
if item.data(column, C.Qt.ItemDataRole.DisplayRole) != value: if item.data(column, C.Qt.ItemDataRole.DisplayRole) != value:
set_value(item, column, value) set_value(item, column, value)
item.setToolTip(16, str(values[16])) item.setToolTip(16, str(values[16]))
for check_column, priority_column, targets in ((8, 9, feed_targets), (17, 18, gift_targets)): for check_column, priority_column, targets in ((8, 9, feed_targets), (17, 18, gift_targets),
(19, 20, breakthrough_targets)):
check, priority = self.itemWidget(item, check_column), self.itemWidget(item, priority_column) check, priority = self.itemWidget(item, check_column), self.itemWidget(item, priority_column)
blockers = [C.QSignalBlocker(check), C.QSignalBlocker(priority)] blockers = [C.QSignalBlocker(check), C.QSignalBlocker(priority)]
check.setChecked(str(mid) in targets) check.setChecked(str(mid) in targets)
@@ -135,7 +144,7 @@ class RanchView(W.QTreeWidget):
priority.setEnabled(mon.get("process") == 3) priority.setEnabled(mon.get("process") == 3)
if not priority.hasFocus(): if not priority.hasFocus():
priority.setValue(targets.get(str(mid), 100)) priority.setValue(targets.get(str(mid), 100))
bind_controls(self, item, {column: self.itemWidget(item, column) for column in (8, 9, 17, 18)}) bind_controls(self, item, {column: self.itemWidget(item, column) for column in (8, 9, 17, 18, 19, 20)})
def finish(): def finish():
self.render_signature = copy.deepcopy(signature) self.render_signature = copy.deepcopy(signature)
+5 -3
View File
@@ -161,6 +161,8 @@ class AutomationTests(unittest.TestCase):
self.assertFalse(any(a.kind == "feed" for a in self.planner.plan(snapshot, policy))) self.assertFalse(any(a.kind == "feed" for a in self.planner.plan(snapshot, policy)))
self.assertIn("上限 20", self.planner.feed_status(snapshot, policy)[1]) self.assertIn("上限 20", self.planner.feed_status(snapshot, policy)[1])
target["level"] = 19 target["level"] = 19
snapshot.raw["monsters"][1].update(process=3, roomId=1)
snapshot.raw["monsters"][2].update(process=3, roomId=1)
self.assertTrue(any(a.kind == "feed" for a in self.planner.plan(snapshot, policy))) self.assertTrue(any(a.kind == "feed" for a in self.planner.plan(snapshot, policy)))
policy.target_level = 19 policy.target_level = 19
self.assertTrue(any(a.kind == "feed" for a in self.planner.plan(snapshot, policy))) self.assertTrue(any(a.kind == "feed" for a in self.planner.plan(snapshot, policy)))
@@ -297,7 +299,7 @@ class AutomationTests(unittest.TestCase):
client = Client(Session(f"http://127.0.0.1:{server.server_port}/", "synthetic-test-token")) client = Client(Session(f"http://127.0.0.1:{server.server_port}/", "synthetic-test-token"))
try: try:
engine = Engine(catalog, client, budget_path) engine = Engine(catalog, client, budget_path)
engine.policy = replace(self.policy, manual_eggs=True, egg_rules={"1001010": asdict(EggRule(enabled=True, priority=1, refill_target=12, market_id="sc_city1"))}) engine.policy = replace(self.policy, manual_eggs=True, egg_rules={"1001010": asdict(EggRule(enabled=True, priority=1, refill_target=12, market_id="sc_city1", keep_count=0))})
engine.policy.egg_stock = 12 engine.policy.egg_stock = 12
engine.policy.buy_batch = 5 engine.policy.buy_batch = 5
engine.policy.daily_buy_money = 1000 engine.policy.daily_buy_money = 1000
@@ -376,7 +378,7 @@ class AutomationGuiTests(unittest.TestCase):
self.assertIn("自动孵蛋", [window.tabs.tabText(i) for i in range(window.tabs.count())]) self.assertIn("自动孵蛋", [window.tabs.tabText(i) for i in range(window.tabs.count())])
window.gold_preset() window.gold_preset()
self.wait(window) self.wait(window)
window.egg_rules = {str(m["typeId"]): {"enabled": True, "action": "sell"} for m in window.engine.snapshot.raw["monsters"][:2]} window.egg_rules = {str(m["typeId"]): {"enabled": True, "action": "sell", "keep_count": 0} for m in window.engine.snapshot.raw["monsters"][:2]}
window.fill.setChecked(False) window.fill.setChecked(False)
window.buy_eggs.setChecked(False) window.buy_eggs.setChecked(False)
before = len(window.engine.snapshot.raw["monsters"]) before = len(window.engine.snapshot.raw["monsters"])
@@ -428,7 +430,7 @@ class AutomationGuiTests(unittest.TestCase):
try: try:
self.wait(window) self.wait(window)
window.strategy.setCurrentIndex(window.strategy.findData("gold")) window.strategy.setCurrentIndex(window.strategy.findData("gold"))
window.egg_rules = {str(m["typeId"]): {"enabled": True, "action": "sell"} for m in window.engine.snapshot.raw["monsters"][:2]} window.egg_rules = {str(m["typeId"]): {"enabled": True, "action": "sell", "keep_count": 0} for m in window.engine.snapshot.raw["monsters"][:2]}
window.fill.setChecked(False) window.fill.setChecked(False)
before = len(window.engine.snapshot.raw["monsters"]) before = len(window.engine.snapshot.raw["monsters"])
window.refresh() window.refresh()
+231
View File
@@ -0,0 +1,231 @@
import copy
import json
import subprocess
import sys
from pathlib import Path
import unittest
from unittest.mock import patch
from ranch_assistant.breakthrough import (
BreakthroughPlanner, PATH, POTENTIAL_PATH, plan_breakthrough,
)
from ranch_assistant.model import Catalog, Policy, Snapshot
from ranch_assistant.tests.test_core import workspace_temp
ROOT = Path(__file__).resolve().parents[2]
def snapshot_with(**monster):
mon = {"id": 900, "typeId": 1001010, "process": 3, "mode": 2,
"potentialLevel": 1, "level": 1, "pAtk": 4, "pDef": 8,
"pHp": 105, "pDex": 1}
mon.update(monster)
return Snapshot({"master": {"id": 1}, "monsters": [mon], "items": [
{"id": 600, "typeId": 30058, "num": 100}], "stacks": [],
"rooms": [{"id": 1, "typeId": 1000}], "teams": []})
class BreakthroughTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.catalog = Catalog()
def setUp(self):
self.snapshot = snapshot_with()
self.policy = Policy(feed_targets={"900": 1})
self.planner = BreakthroughPlanner(self.catalog)
def test_original_first_breakthrough_payload_and_chinese_description(self):
action = self.planner.plan(self.snapshot, self.policy)
self.assertEqual(action.path, PATH)
self.assertEqual(action.payload, {"monId": 900, "itemIds": [600]})
self.assertEqual(action.kind, "breakthrough")
self.assertIn("突破", action.description)
self.assertIn("2 阶段", action.description)
self.assertNotIn("monsterPotential", action.description)
def test_incomplete_potential_first_consumes_one_item_on_original_path(self):
self.snapshot.monsters[900]["pAtk"] = 2
action = self.planner.plan(self.snapshot, self.policy)
self.assertEqual(action.kind, "potential")
self.assertEqual(action.path, POTENTIAL_PATH)
self.assertEqual(action.payload, {"monId": 900, "itemId": 600, "monsterAttr": "atk",
"traceInfo": {"itemTypeId": 600, "itemNum": 100}})
self.assertIn("消耗", action.description)
self.assertIn("重新读取", action.description)
def test_potential_trace_info_uses_selected_stack_instance_id(self):
self.snapshot.monsters[900]["pAtk"] = 2
self.assertEqual(self.snapshot.raw["items"], [{"id": 600, "typeId": 30058, "num": 100}])
action = self.planner.plan(self.snapshot, self.policy)
self.assertEqual(action.payload["itemId"], 600)
self.assertEqual(action.payload["traceInfo"], {"itemTypeId": 600, "itemNum": 100})
def test_potential_reserve_allows_partial_consumption_of_one_stack(self):
self.snapshot.monsters[900]["pAtk"] = 2
self.policy.gift_items = {"30058": {"enabled": False, "reserve": 10}}
action = self.planner.plan(self.snapshot, self.policy)
self.assertEqual(action.payload["itemId"], 600)
self.policy.gift_items["30058"]["reserve"] = 100
self.assertIsNone(self.planner.plan(self.snapshot, self.policy))
def test_potential_proceeds_even_at_ordinary_level_cap(self):
self.snapshot.monsters[900].update(pAtk=3, level=10)
action = self.planner.plan(self.snapshot, self.policy)
self.assertEqual(action.kind, "potential")
def test_ordinary_level_below_cap_does_not_block_full_potential(self):
self.assertEqual(self.snapshot.monsters[900]["level"], 1)
self.assertIsNotNone(self.planner.plan(self.snapshot, self.policy))
def test_stage_reserve_uses_total_stock_and_one_sufficient_stack(self):
self.policy.gift_items = {"30058": {"enabled": False, "reserve": 96}}
action = self.planner.plan(self.snapshot, self.policy)
self.assertEqual(action.payload["itemIds"], [600])
self.policy.gift_items["30058"]["reserve"] = 97
self.assertIsNone(self.planner.plan(self.snapshot, self.policy))
self.assertIn("单堆", " ".join(self.planner.notes))
def test_missing_or_insufficient_material_never_returns_action(self):
self.snapshot.raw["items"][0]["num"] = 3
self.assertIsNone(self.planner.plan(self.snapshot, self.policy))
self.assertIn("3/4", self.planner.notes[0])
self.snapshot.raw["items"] = []
self.assertIsNone(self.planner.plan(self.snapshot, self.policy))
def test_multiple_stacks_choose_a_sufficient_id_not_aggregate_ids(self):
self.snapshot.raw["items"] = [
{"id": 600, "typeId": 30058, "num": 1},
{"id": 601, "typeId": 30058, "num": 2},
{"id": 602, "typeId": 30058, "num": 8},
]
action = self.planner.plan(self.snapshot, self.policy)
self.assertEqual(action.payload["itemIds"], [602])
def test_locked_stock_is_not_counted_toward_reserves_or_requests(self):
self.snapshot.raw["items"] = [{"id": 600, "typeId": 30058, "num": 100, "lock": 1}]
self.assertIsNone(self.planner.plan(self.snapshot, self.policy))
self.snapshot.raw["items"][0].pop("lock")
self.assertIsNotNone(self.planner.plan(self.snapshot, self.policy))
def test_priority_skips_blocked_candidate_and_uses_next(self):
other = copy.deepcopy(self.snapshot.monsters[900])
other.update(id=901, pAtk=3)
self.snapshot.raw["monsters"].append(other)
self.assertEqual(self.planner.plan(self.snapshot, self.policy, targets={"901": 2, "900": 1}).payload["monId"], 900)
def test_independent_targets_replace_feed_targets_and_empty_is_empty(self):
other = copy.deepcopy(self.snapshot.monsters[900])
other["id"] = 901
self.snapshot.raw["monsters"].append(other)
action = self.planner.plan(self.snapshot, self.policy, targets={"901": 1})
self.assertEqual(action.payload["monId"], 901)
self.assertIsNone(self.planner.plan(self.snapshot, self.policy, targets={}))
def test_exploration_build_non_ranch_disabled_and_maximum_do_not_plan(self):
for flags in ({"process": 1}, {"process": 2}, {"inExploreTeam": True}, {"inBuild": True}):
self.snapshot.monsters[900].update(flags)
self.assertIsNone(self.planner.plan(self.snapshot, self.policy))
self.snapshot.monsters[900].update(process=3, inExploreTeam=False, inBuild=False)
self.snapshot.monsters[900]["potentialLevel"] = 7
self.assertIsNone(self.planner.plan(self.snapshot, self.policy))
self.assertIsNone(self.planner.plan(self.snapshot, self.policy, enabled=False))
self.policy.enabled = False
self.assertIsNone(self.planner.plan(self.snapshot, self.policy))
def test_tp_level_and_exp_do_not_gate_material_breakthrough(self):
self.snapshot.monsters[900].update(tpLevel=4, tpExp=33, potentialLevel=1)
self.assertEqual(self.planner.plan(self.snapshot, self.policy).kind, "breakthrough")
self.snapshot.monsters[900].update(tpLevel=0, tpExp=0, pAtk=0)
self.assertEqual(self.planner.plan(self.snapshot, self.policy).kind, "potential")
def test_invalid_and_incomplete_snapshots_are_safe(self):
for field in ("potentialLevel", "pAtk", "pDef", "pHp", "pDex"):
snapshot = snapshot_with()
snapshot.monsters[900][field] = None
self.assertIsNone(BreakthroughPlanner(self.catalog).plan(snapshot, self.policy))
snapshot = snapshot_with()
snapshot.monsters[900]["typeId"] = 999999999
self.assertIsNone(BreakthroughPlanner(self.catalog).plan(snapshot, self.policy))
def test_duplicate_item_instances_block_instead_of_double_spending(self):
self.snapshot.raw["items"] = [
{"id": 600, "typeId": 30058, "num": 2},
{"id": 600, "typeId": 30058, "num": 2},
]
self.assertIsNone(self.planner.plan(self.snapshot, self.policy))
self.assertIn("实例重复", self.planner.notes[0])
def test_second_stage_matches_original_element_table(self):
self.snapshot.monsters[900].update(potentialLevel=2, pAtk=16, pDef=28, pHp=345, pDex=4)
self.snapshot.raw["items"] = [{"id": 600, "typeId": 30058, "num": 4},
{"id": 601, "typeId": 30041, "num": 1}]
action = self.planner.plan(self.snapshot, self.policy)
self.assertEqual(action.payload, {"monId": 900, "itemIds": [600, 601]})
def test_same_type_requirements_are_combined_and_instance_sent_once(self):
info = copy.deepcopy(self.catalog.data["potential_info"])
info["elementItem"]["4"]["lv2"] = 30058
catalog = copy.copy(self.catalog)
catalog.data = copy.deepcopy(self.catalog.data) | {"potential_info": info}
self.snapshot.monsters[900].update(potentialLevel=2, pAtk=16, pDef=28, pHp=345, pDex=4)
self.snapshot.raw["items"] = [{"id": 600, "typeId": 30058, "num": 5}]
action = BreakthroughPlanner(catalog).plan(self.snapshot, self.policy)
self.assertEqual(action.payload, {"monId": 900, "itemIds": [600]})
self.snapshot.raw["items"][0]["num"] = 4
self.assertIsNone(BreakthroughPlanner(catalog).plan(self.snapshot, self.policy))
def test_chain_replans_fresh_snapshot_without_mutating_state(self):
self.snapshot.monsters[900]["pAtk"] = 0
original = copy.deepcopy(self.snapshot.raw)
first = self.planner.plan(self.snapshot, self.policy, targets={"900": 1})
self.assertEqual(first.kind, "potential")
self.assertEqual(self.snapshot.raw, original)
# Simulate a subsequent server read, not client-side success inference.
fresh = snapshot_with(pAtk=2)
second = self.planner.plan(fresh, self.policy, targets={"900": 1})
self.assertEqual(second.kind, "potential")
final = self.planner.plan(snapshot_with(), self.policy, targets={"900": 1})
self.assertEqual(final.kind, "breakthrough")
self.assertEqual(original["monsters"][0]["pAtk"], 0)
def test_functional_integration_is_pure_and_makes_no_client_call(self):
with patch("ranch_assistant.api.Client.call") as call:
action = plan_breakthrough(self.catalog, self.snapshot, self.policy)
self.assertEqual(action.payload["monId"], 900)
call.assert_not_called()
class CatalogBuildTests(unittest.TestCase):
def test_local_build_is_valid_and_preserves_unrelated_top_level_data(self):
if not list(ROOT.glob("*_1.9.68.apk")):
self.skipTest("Local source APK is not present")
before = json.loads(subprocess.check_output(
["git", "show", "HEAD:ranch_assistant/data/catalog.json"], cwd=ROOT).decode("utf-8"))
with workspace_temp() as directory:
destination = directory / "catalog.json"
destination.write_text(json.dumps(before, ensure_ascii=False), encoding="utf-8")
source_apk = next(ROOT.glob("*_1.9.68.apk"))
live_catalog = ROOT / "ranch_assistant" / "data" / "catalog.json"
live_bytes = live_catalog.read_bytes()
result = subprocess.run([sys.executable, str(ROOT / "tools" / "extract_ranch_catalog.py"),
"--apk", str(source_apk), "--output", str(destination)],
cwd=ROOT, capture_output=True, text=True, timeout=60)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(live_catalog.read_bytes(), live_bytes)
after = json.loads(destination.read_text(encoding="utf-8"))
changed = {"monster_info", "potential_info", "game_setting", "client_constants"}
self.assertEqual({key: value for key, value in after.items() if key not in changed},
{key: value for key, value in before.items() if key not in changed})
self.assertTrue(all({"job", "element"} <= set(row)
for row in after["monster_info"].values() if isinstance(row, dict)))
self.assertEqual(after["client_constants"], {"maxTpLevel": 4})
self.assertTrue(after["game_setting"]["tpExp"])
self.assertIn("specialFood", after["game_setting"])
self.assertIn("specialFood14", after["game_setting"])
self.assertNotIn("maxTpLevel", after["game_setting"])
if __name__ == "__main__":
unittest.main()
+4
View File
@@ -70,6 +70,10 @@ class CoreTests(unittest.TestCase):
mon = snapshot.raw["monsters"][0] mon = snapshot.raw["monsters"][0]
mon.update(process=3, roomId=1) mon.update(process=3, roomId=1)
snapshot.raw["stacks"][0]["monsterId"] = 0 snapshot.raw["stacks"][0]["monsterId"] = 0
snapshot.raw["monsters"][1].update(process=3, roomId=1)
cap = self.catalog.max_level(snapshot.monsters[900])
snapshot.monsters[900].update(level=cap - 1,
exp=int(self.catalog.data["monster_level"][str(cap)]) - 1)
plans = planner.plan(snapshot, policy) plans = planner.plan(snapshot, policy)
feeding = next(a for a in plans if a.kind == "feed") feeding = next(a for a in plans if a.kind == "feed")
self.assertEqual(feeding.payload, {"targetId": 900, "foods": [mon["id"]]}) self.assertEqual(feeding.payload, {"targetId": 900, "foods": [mon["id"]]})
+13 -4
View File
@@ -9,23 +9,32 @@ os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6 import QtWidgets as W from PySide6 import QtWidgets as W
from PySide6.QtTest import QTest from PySide6.QtTest import QTest
from ranch_assistant.cultivation import CultivationSelector, growth_score from ranch_assistant.cultivation import CultivationSelector, growth_score, quality_rank
from ranch_assistant.engine import Engine, demo_snapshot from ranch_assistant.engine import Engine, demo_snapshot
from ranch_assistant.gifts import GiftPlanner from ranch_assistant.gifts import GiftPlanner
from ranch_assistant.gui import Window from ranch_assistant.gui import Window
from ranch_assistant.model import Catalog, Planner, Policy, Snapshot from ranch_assistant.model import Catalog, EggRule, Planner, Policy, Snapshot
from ranch_assistant.policy_io import import_config, portable_config from ranch_assistant.policy_io import import_config, portable_config
from ranch_assistant.tests.test_core import workspace_temp from ranch_assistant.tests.test_core import workspace_temp
from ranch_assistant.tests.test_accounts import fake_client, role_snapshot from ranch_assistant.tests.test_accounts import fake_client, role_snapshot
from ranch_assistant.api import Session from ranch_assistant.api import Session
def monster(catalog, mid, *, level=10, feel=0, scale=.3, species=1001010, process=3): def monster(catalog, mid, *, level=10, feel=0, scale=.3, species=1001010, process=3, **values):
row = catalog.monster(species) row = catalog.monster(species)
return {"id": mid, "typeId": species, "process": process, "mode": 2, "level": level, return {"id": mid, "typeId": species, "process": process, "mode": 2, "level": level,
"feel": feel, "entangleLevel": 0, "giftTime": 0, "roomId": 1, "lock": 0, "feel": feel, "entangleLevel": 0, "giftTime": 0, "roomId": 1, "lock": 0,
**{"g" + stat.capitalize(): row[stat + "_grow_min"] + scale * (row[stat + "_grow_max"] - row[stat + "_grow_min"]) **{"g" + stat.capitalize(): row[stat + "_grow_min"] + scale * (row[stat + "_grow_max"] - row[stat + "_grow_min"])
for stat in ("atk", "def", "hp", "dex")}} for stat in ("atk", "def", "hp", "dex")}, **values}
def graded_monster(catalog, mid, grades, **values):
mon = monster(catalog, mid, **values)
row = catalog.monster(mon["typeId"])
for stat, grade in zip(("atk", "def", "hp", "dex"), grades):
low, high = row[stat + "_grow_min"], row[stat + "_grow_max"]
mon["g" + stat.capitalize()] = low + (high - low) * {"C": .1, "B": .375, "A": .625, "S": .9}[grade]
return mon
class CultivationTests(unittest.TestCase): class CultivationTests(unittest.TestCase):
+243
View File
@@ -0,0 +1,243 @@
"""Offline exploration policy, pending-send, snapshot and data tests."""
from copy import deepcopy
from dataclasses import asdict
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import Mock, patch
from ranch_assistant.exploration import ExplorePlanner, ExplorePolicy, ExploreTeamRule, load_exploration_areas
from ranch_assistant.model import Catalog, Policy, Snapshot
from ranch_assistant.tests.test_core import workspace_temp
NOW = 1_700_000_000
AREAS = {
"1": {"id": "1", "name": "测试矿洞", "passStage": "0101", "costTi": 20,
"costTime": 3600, "level": [5, 1, 1], "team": "normal"},
"2": {"id": "2", "name": "测试森林", "passStage": "0102", "costTi": 30,
"costTime": 7200, "level": [10, 2, 2], "team": "normal"},
}
def monster(mid, level, **changes):
return {"id": mid, "typeId": "1001010", "level": level, "process": 3,
"mode": 2, "lock": False, **changes}
def make_snapshot(**changes):
value = {"master": {"id": 11, "ti": 100}, "serverId": 7, "areaId": 1,
"items": [], "stacks": [], "rooms": [], "teams": [],
"monsters": [monster(mid, level) for mid, level in ((1, 20), (2, 15), (3, 10), (4, 8), (5, 7), (6, 6), (7, 5))],
"history": {"passTask": {"1001008": True},
"passStage": {"0101": {"1": True}, "0102": {"1": True}}},
"exploreTeams": [{"id": 1, "status": 0, "area": "", "monsters": ""}], **changes}
snapshot = Snapshot(value, received_at=NOW)
return patch("time.time", return_value=NOW), snapshot
def policy(**team):
values = {"enabled": True, "area": "1", "monsters": []} | team
return ExplorePolicy(True, {"1": ExploreTeamRule(**values)})
class ExplorationTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.catalog = Catalog()
def setUp(self):
self.clock, self.snapshot = make_snapshot()
self.clock.start()
self.addCleanup(self.clock.stop)
self.ranch = Policy(protect_star=6, protect_quality=5, keep_better_quality=False)
self.planner = ExplorePlanner(self.catalog, areas=AREAS)
def action(self, snapshot=None, planner=None, explore_policy=None):
return (planner or self.planner).plan(snapshot or self.snapshot, explore_policy or policy(), self.ranch)[0]
def start_confirmed(self, team, end=NOW + 3600):
team.update(status=1, area="1", monsters="1,2,3", endTime=end * 1000)
def test_static_data_and_source_extractor(self):
areas = load_exploration_areas()
self.assertEqual(len(areas), 22)
self.assertEqual(areas["1"]["name"], "废弃矿洞")
self.assertEqual(areas["1"]["level"], [4, 1, 1])
self.assertEqual(areas["1"]["passStage"], "0109")
self.assertTrue(all(row["team"] == "normal" and len(row["level"]) == 3 for row in areas.values()))
def test_policy_roundtrip_and_strict_validation(self):
configured = policy(monsters=[1, 2, 3])
self.assertEqual(ExplorePolicy.from_dict(json.loads(json.dumps(configured.to_dict()))), configured)
for value in ({"enabled": 1}, {"reserve_ti": -1}, {"reserve_ti": True},
{"teams": {"0": {"enabled": True, "area": "1", "monsters": []}}},
{"teams": {"1": {"enabled": True, "area": "bad", "monsters": []}}},
{"teams": {"1": {"enabled": True, "area": "1", "monsters": [1]}}},
{"teams": {"1": {"enabled": True, "area": "1", "monsters": [1, 1, 2]}}},
{"teams": {"1": {"enabled": True, "area": "1", "unknown": 1}}}):
with self.subTest(value=value), self.assertRaises(ValueError):
ExplorePolicy(**(asdict(ExplorePolicy()) | value))
def test_original_monster_eligibility_does_not_protect_lock_star_or_equipment(self):
selected = policy(monsters=[1, 2, 3])
for mid in (1, 2, 3):
self.snapshot.raw["monsters"][mid - 1].update(lock=True, sysLock=True, equip1=7)
action = self.action(explore_policy=selected)
self.assertEqual(action.payload["monsters"], [1, 2, 3])
self.assertEqual(self.planner.rows(self.snapshot, selected, self.ranch)[0]["state"], "可出发")
options = self.planner.member_options(self.snapshot, 1, selected, self.ranch)
self.assertTrue(all(option["automatic"] for option in options))
def test_automatic_excludes_battle_feed_gift_and_breakthrough_targets(self):
self.snapshot.raw["teams"] = [{"teamType": "battleTeam", "teamName": "teamA", "monsters": [1]}]
self.ranch.feed_targets = {"2": 1}
self.ranch.gift_targets = {"3": 1}
self.ranch.breakthrough_targets = {"4": 1}
action = self.action()
self.assertEqual(action.payload["monsters"], [5, 6, 7])
def test_manual_remains_available_when_automatic_targets_exhausted(self):
self.snapshot.raw["teams"] = [{"teamType": "battleTeam", "monsters": [1]}]
self.ranch.feed_targets = {str(mid): 1 for mid in (2, 3, 4, 5, 6, 7)}
self.assertEqual(self.planner.plan(self.snapshot, policy(), self.ranch), [])
row = self.planner.rows(self.snapshot, policy(), self.ranch)[0]
self.assertIn("手动", row["reason"])
manual = policy(monsters=[1, 2, 3])
self.assertEqual(self.action(explore_policy=manual).payload["monsters"], [1, 2, 3])
options = self.planner.member_options(self.snapshot, 1, manual, self.ranch)
self.assertEqual(len(options), 7)
self.assertTrue(all(not option["automatic"] for option in options))
def test_manual_missing_leader_and_other_team_members_do_not_raise(self):
for ids in ([99, 2, 3], [1, 2, 2]):
if len(set(ids)) == 3:
selected = policy(monsters=ids)
self.assertEqual(self.planner.plan(self.snapshot, selected, self.ranch), [])
row = self.planner.rows(self.snapshot, selected, self.ranch)[0]
self.assertIn("不存在", row["reason"])
self.snapshot.raw["exploreTeams"].append({"id": 2, "status": 1, "area": "2", "monsters": "2", "endTime": (NOW + 30) * 1000})
selected = policy(monsters=[1, 2, 3])
self.assertIn("其他探险队", self.planner.rows(self.snapshot, selected, self.ranch)[0]["reason"])
def test_raw_string_members_unlock_stamina_and_finish_priority(self):
self.assertFalse(self.planner.area_unlocked(self.snapshot, AREAS["1"] | {"passStage": "0103"}))
self.snapshot.raw["history"]["passStage"]["0101"] = {"2": True}
self.assertFalse(self.planner.area_unlocked(self.snapshot, AREAS["1"]))
self.snapshot.raw["history"]["passStage"]["0101"]["1"] = True
self.snapshot.raw["master"]["ti"] = 19
self.assertEqual(self.planner.plan(self.snapshot, policy(), self.ranch), [])
self.snapshot.raw["master"]["ti"] = 100
self.snapshot.raw["exploreTeams"].append({"id": 2, "status": 1, "area": "1", "endTime": (NOW + 60) * 1000})
self.assertEqual(self.planner.plan(self.snapshot, policy(), self.ranch), [])
self.snapshot.raw["exploreTeams"].pop()
self.snapshot.raw["exploreTeams"][0].update(status=1, area="1", monsters="1,2,3", endTime=(NOW - 1) * 1000)
self.assertEqual(self.action().kind, "explore_finish")
self.assertEqual(self.planner.rows(self.snapshot, policy(), self.ranch)[0]["monster_ids"], [1, 2, 3])
def test_active_zero_or_missing_deadline_is_unknown_and_never_finished(self):
for value in (None, 0, "", "not-a-time"):
with self.subTest(value=value):
self.snapshot.raw["exploreTeams"][0].update(status=1, endTime=value, monsters="1,2,3")
self.assertEqual(self.planner.plan(self.snapshot, policy(), self.ranch), [])
self.assertEqual(self.planner.rows(self.snapshot, policy(), self.ranch)[0]["state"], "状态待同步")
def test_success_with_stale_snapshot_never_repeats_start_even_after_restart(self):
with workspace_temp() as folder:
path = folder / "exploration-state.json"
planner = ExplorePlanner(self.catalog, areas=AREAS, path=path)
action = self.action(planner=planner)
response = planner.execute(self.snapshot, action, Mock(return_value={"resCode": 0}))
self.assertEqual(response, {"resCode": 0})
for _ in range(3):
self.assertEqual(self.action(planner=planner).kind, "explore_blocked")
self.assertFalse(planner.reconcile(self.snapshot))
restored = ExplorePlanner(self.catalog, areas=AREAS, path=path)
self.assertEqual(self.action(planner=restored).kind, "explore_blocked")
self.assertTrue(restored.pending(self.snapshot)["confirmed"])
self.start_confirmed(self.snapshot.raw["exploreTeams"][0])
self.assertTrue(restored.reconcile(self.snapshot))
self.assertIsNone(restored.pending(self.snapshot))
def test_success_with_stale_snapshot_never_repeats_finish_even_after_restart(self):
self.snapshot.raw["exploreTeams"][0].update(status=1, area="1", monsters="1,2,3", endTime=(NOW - 1) * 1000)
with workspace_temp() as folder:
path = folder / "state.json"
planner = ExplorePlanner(self.catalog, areas=AREAS, path=path)
action = self.action(planner=planner)
planner.execute(self.snapshot, action, Mock(return_value={"resCode": 0}))
for _ in range(3):
self.assertEqual(self.action(planner=planner).kind, "explore_blocked")
self.assertFalse(planner.reconcile(self.snapshot))
restored = ExplorePlanner(self.catalog, areas=AREAS, path=path)
self.assertEqual(self.action(planner=restored).kind, "explore_blocked")
self.snapshot.raw["exploreTeams"][0].update(status=0, monsters="", endTime=0)
self.assertTrue(restored.reconcile(self.snapshot))
self.assertEqual(self.action(planner=restored).kind, "explore_start")
def test_unknown_write_requires_authoritative_matching_snapshot(self):
with workspace_temp() as folder:
planner = ExplorePlanner(self.catalog, areas=AREAS, path=folder / "state.json")
action = self.action(planner=planner)
planner.mark_started(self.snapshot, action)
planner.mark_uncertain(self.snapshot, action)
restored = ExplorePlanner(self.catalog, areas=AREAS, path=folder / "state.json")
self.assertEqual(self.action(planner=restored).kind, "explore_blocked")
self.start_confirmed(self.snapshot.raw["exploreTeams"][0])
self.assertTrue(restored.reconcile(self.snapshot))
self.assertFalse(restored.reconcile(self.snapshot))
def test_unknown_action_cannot_be_forged_or_confirmed(self):
from ranch_assistant.model import Action
action = self.action()
forged = Action("explore_start", "forged", "exploreService/start", deepcopy(action.payload))
with self.assertRaises(ValueError):
self.planner.mark_started(self.snapshot, forged)
self.planner.mark_started(self.snapshot, action)
with self.assertRaises(ValueError):
self.planner.mark_started(self.snapshot, action)
self.assertTrue(self.planner.pending(self.snapshot))
self.planner._accounts.clear()
with self.assertRaises(ValueError):
self.planner.mark_started(self.snapshot, forged)
def test_pending_persistence_hashed_role_and_has_no_credentials(self):
with workspace_temp() as folder:
path = folder / "state.json"
planner = ExplorePlanner(self.catalog, areas=AREAS, path=path, account_key="profile-only")
action = self.action(planner=planner)
planner.mark_started(self.snapshot, action)
text = path.read_text(encoding="utf-8")
state = json.loads(text)
key = next(iter(state["accounts"]))
self.assertRegex(key, r"^[0-9a-f]{64}$")
self.assertNotIn("11", key)
for secret in ("password", "token", "sdkToken", "account_name", "session_token"):
self.assertNotIn(secret, text)
other_clock, other = make_snapshot(master={"id": 12, "ti": 100})
with other_clock:
self.assertIsNone(planner.pending(other))
self.assertEqual(planner.plan(other, policy(), self.ranch)[0].kind, "explore_start")
def test_corrupt_state_blocks_instead_of_replaying(self):
with workspace_temp() as folder:
path = folder / "state.json"
path.write_text("{broken", encoding="utf-8")
planner = ExplorePlanner(self.catalog, areas=AREAS, path=path)
self.assertEqual(self.action(planner=planner).kind, "explore_blocked")
def test_worker_rows_are_compact_plain_data(self):
from ranch_assistant.exploration_gui import prepare_exploration_rows, prepare_exploration_members
from types import SimpleNamespace
engine = SimpleNamespace(snapshot=self.snapshot, explore_planner=self.planner, explore_policy=policy(), policy=self.ranch)
rows = prepare_exploration_rows(engine)
self.assertEqual(rows[0]["monster_labels"], ["#1 绿色史莱姆 Lv.20", "#2 绿色史莱姆 Lv.15", "#3 绿色史莱姆 Lv.10"])
self.assertEqual(rows[0]["remaining_text"], "—")
json.dumps(rows)
options = prepare_exploration_members(engine, 1)
self.assertLess(len(json.dumps(options)), 4000)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,157 @@
"""Repeated native Qt rendering, manual drafts and account isolation."""
import os
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from dataclasses import replace
import copy
import time
import unittest
from unittest.mock import patch
from PySide6 import QtCore as C, QtWidgets as W
from PySide6.QtTest import QTest
from ranch_assistant import gui
from ranch_assistant.exploration import ExplorePlanner
from ranch_assistant.tests.test_core import workspace_temp
from ranch_assistant.tests.test_exploration import AREAS, make_snapshot, policy
class ExplorationGuiTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = W.QApplication.instance() or W.QApplication([])
def wait(self, window, predicate=lambda: True, timeout=8):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
self.app.processEvents()
QTest.qWait(5)
if (not window.busy and not window.exploration_table.row_batch.running
and not window._exploration_member_busy and predicate()):
return
self.fail("Offline exploration Qt job did not finish")
def setUp(self):
self.folder = self.enterContext(workspace_temp())
self.qt_messages = []
self.qt_handler = C.qInstallMessageHandler(lambda kind, context, message: self.qt_messages.append(message))
self.window = gui.Window(self.folder)
self.window.timer.stop()
self.window.auto_save_timer.stop()
self.clock, self.snapshot = make_snapshot()
self.clock.start()
self.addCleanup(self.clock.stop)
self.window.engine.snapshot = self.snapshot
self.window.engine.explore_planner = ExplorePlanner(self.window.catalog, areas=AREAS)
self.window.engine.explore_policy = policy()
self.window.apply_explore_policy(policy())
self.window.presentation_active = True
self.window.pending_exploration_view = False
self.window.tabs.setCurrentWidget(self.window.exploration_page)
def tearDown(self):
self.window.pool.clear()
self.window.pool.waitForDone(3000)
self.window.close()
self.app.processEvents()
C.qInstallMessageHandler(self.qt_handler)
self.assertFalse([message for message in self.qt_messages if "Traceback" in message or "QTableWidgetItem" in message], self.qt_messages)
def controls(self):
return self.window.exploration_table._controls["1"]
def test_real_window_three_selections_and_busy_policy_queue(self):
window = self.window
window.refresh_exploration()
self.wait(window, lambda: bool(window._exploration_member_options))
control = self.controls()
window.busy = True
before = window.engine.explore_policy.to_dict()
saved = []
with patch.object(window, "settings_changed", side_effect=lambda: saved.append(window.read_explore_policy().to_dict())):
control["members"][0].setCurrentIndex(control["members"][0].findData(1))
self.assertEqual(window.read_explore_policy().teams["1"].monsters, [])
self.assertEqual(window.engine.explore_policy.to_dict(), before)
for _ in range(5):
self.app.processEvents()
QTest.qWait(2)
self.assertEqual(window._exploration_drafts["1"], [1, None, None])
control["members"][1].setCurrentIndex(control["members"][1].findData(2))
self.assertEqual(window._exploration_drafts["1"][:2], [1, 2])
self.assertEqual(window.read_explore_policy().teams["1"].monsters, [])
control["members"][2].setCurrentIndex(control["members"][2].findData(3))
self.assertEqual(window.read_explore_policy().teams["1"].monsters, [1, 2, 3])
self.assertNotIn("1", window._exploration_drafts)
# The module signals only; host update_policy owns engine writes.
self.assertEqual(window.engine.explore_policy.to_dict(), before)
self.assertEqual(saved[-1]["teams"]["1"]["monsters"], [1, 2, 3])
control["auto"].click()
self.assertEqual(window.read_explore_policy().teams["1"].monsters, [])
window.busy = False
def test_real_window_update_policy_waits_for_job(self):
window = self.window
window.refresh_exploration()
self.wait(window, lambda: bool(window._exploration_member_options))
configured = policy(monsters=[1, 2, 3])
window.apply_explore_policy(configured)
window.busy = True
window.pending_policy = None
self.assertFalse(window.update_policy())
self.assertEqual(window.pending_policy["explore_policy"].teams["1"].monsters, [1, 2, 3])
self.assertEqual(window.engine.explore_policy.to_dict(), policy().to_dict())
window.busy = False
def test_repeated_render_keeps_owned_items_and_drafts_and_captures_no_qt_warning(self):
window = self.window
window.refresh_exploration()
self.wait(window, lambda: bool(window._exploration_member_options))
rows = copy.deepcopy(window._exploration_rows)
identities = [window.exploration_table.item(0, column) for column in range(7)]
control = self.controls()
control["members"][0].setCurrentIndex(control["members"][0].findData(1))
warnings = []
handler = C.qInstallMessageHandler(lambda kind, context, message: warnings.append(message))
try:
with patch.object(gui, "prepare_exploration_rows", wraps=gui.prepare_exploration_rows) as worker:
for _ in range(12):
# Prevent member refetch jobs so this test repeatedly renders
# a stable already-prepared small DTO in the GUI thread.
window._exploration_member_options["1"] = [{"id": 1, "level": 20, "label": "one", "automatic": True, "reason": ""}]
window.render_exploration(copy.deepcopy(rows))
while window.exploration_table.row_batch.running:
self.app.processEvents()
QTest.qWait(2)
worker.assert_not_called()
finally:
C.qInstallMessageHandler(handler)
self.assertEqual([window.exploration_table.item(0, column) for column in range(7)], identities)
self.assertEqual(window._exploration_drafts["1"], [1, None, None])
self.assertEqual(window.read_explore_policy().teams["1"].monsters, [])
self.assertFalse(warnings)
def test_account_switch_drops_drafts_and_cached_candidates(self):
window = self.window
window.refresh_exploration()
self.wait(window, lambda: bool(window._exploration_member_options))
control = self.controls()
control["members"][0].setCurrentIndex(control["members"][0].findData(1))
other_clock, other = make_snapshot(master={"id": 12, "ti": 100})
with other_clock:
window.engine.snapshot = other
window.render_exploration([])
self.assertFalse(window._exploration_drafts)
self.assertFalse(window._exploration_member_options)
self.assertEqual(window.exploration_table.rowCount(), 0)
def test_hidden_team_rules_survive_render_and_worker_returns_plain_rows(self):
configured = policy(monsters=[1, 2, 3])
configured.teams["99"] = replace(configured.teams["1"], area="2", monsters=[4, 5, 6])
self.window.apply_explore_policy(configured)
self.window.render_exploration([])
self.assertEqual(self.window.read_explore_policy(), configured)
if __name__ == "__main__":
unittest.main()
+2 -2
View File
@@ -71,7 +71,7 @@ class GrowthTests(unittest.TestCase):
def engine(self, client): def engine(self, client):
engine = Engine(self.catalog, client) engine = Engine(self.catalog, client)
engine.policy = Policy(manual_eggs=True, fill=False, buy=False, collect=False, protect_star=4, protect_quality=3, engine.policy = Policy(manual_eggs=True, fill=False, buy=False, collect=False, protect_star=4, protect_quality=3,
egg_rules={"1001010": asdict(EggRule(enabled=True, action="sell"))}) egg_rules={"1001010": asdict(EggRule(enabled=True, action="sell", keep_count=0))})
engine.auto = True engine.auto = True
return engine return engine
@@ -194,7 +194,7 @@ class GrowthGuiTests(unittest.TestCase):
client = GrowthClient(window.catalog, age=610, grade="S") client = GrowthClient(window.catalog, age=610, grade="S")
client.session = Session("http://127.0.0.1/", "synthetic-test-token") client.session = Session("http://127.0.0.1/", "synthetic-test-token")
window.engine = Engine(window.catalog, client) window.engine = Engine(window.catalog, client)
window.egg_rules = {"1001010": asdict(EggRule(enabled=True, action="sell"))} window.egg_rules = {"1001010": asdict(EggRule(enabled=True, action="sell", keep_count=0))}
window.engine.policy = window.read_policy() window.engine.policy = window.read_policy()
window.engine.snapshot = client.snapshot() window.engine.snapshot = client.snapshot()
window.render(window.engine.snapshot, window.engine.plans()) window.render(window.engine.snapshot, window.engine.plans())
+1 -1
View File
@@ -45,7 +45,7 @@ class GuiTests(unittest.TestCase):
self.assertNotIn(removed, buttons) self.assertNotIn(removed, buttons)
self.assertNotIn("自动执行已启用策略", {check.text() for check in window.findChildren(QCheckBox)}) self.assertNotIn("自动执行已启用策略", {check.text() for check in window.findChildren(QCheckBox)})
window.strategy.setCurrentIndex(window.strategy.findData("gold")) window.strategy.setCurrentIndex(window.strategy.findData("gold"))
window.egg_rules = {str(m["typeId"]): {"enabled": True, "action": "sell"} for m in window.engine.snapshot.raw["monsters"][:2]} window.egg_rules = {str(m["typeId"]): {"enabled": True, "action": "sell", "keep_count": 0} for m in window.engine.snapshot.raw["monsters"][:2]}
window.protect_star.setValue(6) window.protect_star.setValue(6)
window.protect_quality.setCurrentIndex(window.protect_quality.findData(5)) window.protect_quality.setCurrentIndex(window.protect_quality.findData(5))
window.fill.setChecked(False) window.fill.setChecked(False)
+1 -1
View File
@@ -53,7 +53,7 @@ class HatchClient:
def policy_for(client): def policy_for(client):
return Policy(manual_eggs=True, protect_star=6, protect_quality=5, buy=True, return Policy(manual_eggs=True, protect_star=6, protect_quality=5, buy=True,
egg_rules={str(client.template["typeId"]): asdict(EggRule(enabled=True, action="sell"))}) egg_rules={str(client.template["typeId"]): asdict(EggRule(enabled=True, action="sell", keep_count=0))})
class HatchTimingTests(unittest.TestCase): class HatchTimingTests(unittest.TestCase):
+40 -1
View File
@@ -1,4 +1,5 @@
from dataclasses import asdict from dataclasses import asdict
import copy
import json import json
import os import os
import unittest import unittest
@@ -21,7 +22,7 @@ from ranch_assistant.tests.test_core import workspace_temp
class UnifiedPolicyTests(unittest.TestCase): class UnifiedPolicyTests(unittest.TestCase):
def config(self): def config(self):
return {"policy": asdict(Policy(buy=True, gift_enabled=True, feed_target=900, room_id=999999, return {"policy": asdict(Policy(buy=True, gift_enabled=True, feed_target=900, room_id=999999,
gift_targets={"900": 2}, gift_items={"30001": {"enabled": True, "reserve": 5}})), gift_targets={"900": 2}, breakthrough_targets={"900": 3}, gift_items={"30001": {"enabled": True, "reserve": 5}})),
"quest_policy": asdict(QuestPolicy(enabled=True, max_money=100, item_reserves={"30001": 6})), "quest_policy": asdict(QuestPolicy(enabled=True, max_money=100, item_reserves={"30001": 6})),
"daily_policy": asdict(DailyPolicy(enabled=True, selected=["mail"])), "daily_policy": asdict(DailyPolicy(enabled=True, selected=["mail"])),
"sweep_policy": asdict(SweepPolicy(enabled=True, rules={"0101": {"enabled": True, "level": 3, "limit": 5}}, keep_stamina=22)), "sweep_policy": asdict(SweepPolicy(enabled=True, rules={"0101": {"enabled": True, "level": 3, "limit": 5}}, keep_stamina=22)),
@@ -38,6 +39,7 @@ class UnifiedPolicyTests(unittest.TestCase):
config = import_config(exported, snapshot) config = import_config(exported, snapshot)
self.assertEqual(config["policy"]["feed_targets"], {"999": 1}) self.assertEqual(config["policy"]["feed_targets"], {"999": 1})
self.assertEqual(config["policy"]["gift_targets"], {"999": 2}) self.assertEqual(config["policy"]["gift_targets"], {"999": 2})
self.assertEqual(config["policy"]["breakthrough_targets"], {"999": 3})
self.assertEqual(config["policy"]["feed_target"], 0) self.assertEqual(config["policy"]["feed_target"], 0)
self.assertEqual(config["policy"]["room_id"], 0) self.assertEqual(config["policy"]["room_id"], 0)
self.assertTrue(config["policy"]["gift_enabled"]) self.assertTrue(config["policy"]["gift_enabled"])
@@ -50,6 +52,31 @@ class UnifiedPolicyTests(unittest.TestCase):
self.assertEqual(config["policy"]["protect_quality"], 6) self.assertEqual(config["policy"]["protect_quality"], 6)
self.assertFalse(config["policy"]["enabled"]) self.assertFalse(config["policy"]["enabled"])
def test_explore_round_trip_rebinds_team_order_and_species_without_instance_ids(self):
snapshot = demo_snapshot(Catalog())
snapshot.raw["exploreTeams"] = [{"id": 800, "status": 0}, {"id": 700, "status": 0}]
snapshot.monsters[900].update(id=900, typeId=1001010)
snapshot.monsters[101].update(id=101, typeId=1001010, process=3)
snapshot.monsters[102].update(id=102, typeId=1001010, process=3)
config = self.config() | {"explore_policy": {"enabled": True, "reserve_ti": 21,
"teams": {"800": {"enabled": True, "area": "1", "monsters": [900, 101, 102]}}}}
exported = portable_config(config, snapshot)
text = json.dumps(exported)
self.assertNotIn('"800"', text)
self.assertNotIn('"900"', text)
snapshot.raw["exploreTeams"] = [{"id": 90, "status": 0}, {"id": 80, "status": 0}]
for mon in snapshot.raw["monsters"]:
mon["process"] = 2
for index, mid in enumerate((901, 902, 903), 1):
mon = copy.deepcopy(snapshot.monsters[900])
mon.update(id=mid, process=3)
snapshot.raw["monsters"].append(mon)
snapshot.monsters[mid] = mon
imported = import_config(exported, snapshot)
self.assertEqual(imported["explore_policy"]["teams"]["80"]["monsters"], [901, 902, 903])
self.assertFalse(imported["explore_policy"]["enabled"])
self.assertNotIn("800", imported["explore_policy"]["teams"])
def test_invalid_bundle_rejected_before_applying(self): def test_invalid_bundle_rejected_before_applying(self):
exported = portable_config(self.config()) exported = portable_config(self.config())
for value in (exported | {"schema": 100}, exported | {"interval": 0}, for value in (exported | {"schema": 100}, exported | {"interval": 0},
@@ -98,11 +125,23 @@ class StrategyGuiTests(unittest.TestCase):
self.assertEqual(window.engine.sweep_policy.keep_stamina, 22) self.assertEqual(window.engine.sweep_policy.keep_stamina, 22)
self.assertEqual(window.engine.daily_policy.selected, ["mail"]) self.assertEqual(window.engine.daily_policy.selected, ["mail"])
self.assertEqual(window.interval.currentData(), 120) self.assertEqual(window.interval.currentData(), 120)
self.assertLess(window.tabs.indexOf(window.map_page), window.tabs.indexOf(window.analysis_page))
self.assertEqual(window.tabs.indexOf(window.analysis_page) - window.tabs.indexOf(window.map_page), 1)
window.quest_money.setValue(42) window.quest_money.setValue(42)
window.gift_liked_only.setChecked(False) window.gift_liked_only.setChecked(False)
QTest.qWait(400) QTest.qWait(400)
self.assertEqual(window.engine.quest_policy.max_money, 42) self.assertEqual(window.engine.quest_policy.max_money, 42)
self.assertFalse(window.engine.policy.gift_liked_only) self.assertFalse(window.engine.policy.gift_liked_only)
window.monster_breakthrough_changed("900", True, 6)
window._exploration_policy = window.read_explore_policy()
window._exploration_policy.enabled = True
window._exploration_policy.reserve_ti = 9
window._save_exploration_policy()
QTest.qWait(400)
saved = json.loads((folder / "settings.json").read_text(encoding="utf-8"))
self.assertEqual(saved["policy"]["breakthrough_targets"], {"900": 6})
self.assertTrue(saved["explore_policy"]["enabled"])
self.assertEqual(saved["explore_policy"]["reserve_ti"], 9)
with patch("ranch_assistant.gui.W.QFileDialog.getSaveFileName", return_value=(str(path), "")): with patch("ranch_assistant.gui.W.QFileDialog.getSaveFileName", return_value=(str(path), "")):
window.export_policies() window.export_policies()
exported = json.loads(path.read_text(encoding="utf-8")) exported = json.loads(path.read_text(encoding="utf-8"))
@@ -0,0 +1,197 @@
import copy
import json
import unittest
from ranch_assistant.breakthrough import POTENTIAL_PATH
from ranch_assistant.engine import Engine
from ranch_assistant.exploration import ExplorePolicy
from ranch_assistant.model import Catalog, Policy, Snapshot
from ranch_assistant.tests.test_core import workspace_temp
def raw(catalog):
value = {"master": {"id": 1, "ti": 100, "money": 0, "ke": 0},
"monsters": [{"id": mid, "typeId": 1001010, "process": 3, "mode": 2, "level": 10,
"potentialLevel": 1, "pAtk": 2, "pDef": 8, "pHp": 105, "pDex": 1} for mid in (900, 901, 902)],
"items": [{"id": 600, "typeId": 30058, "num": 100}], "stacks": [], "rooms": [], "teams": [],
"currentTasks": [], "history": {"passTask": {"1001008": True}, "passStage": {"0109": {"1": True}}},
"activityHistory": {}, "monsterAttributes": [],
"exploreTeams": [{"id": 77, "status": 0, "monsters": [], "area": "", "endTime": 0}]}
return value
class FakeClient:
def __init__(self, value):
self.value, self.calls = value, []
self.response = {"resCode": 0}
def snapshot(self):
return Snapshot(copy.deepcopy(self.value))
def call(self, path, payload):
self.calls.append((path, payload))
if isinstance(self.response, Exception):
raise self.response
return copy.deepcopy(self.response)
class RanchAutomationIntegrationTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.catalog = Catalog()
def engine(self, folder, value=None):
client = FakeClient(value or raw(self.catalog))
engine = Engine(self.catalog, client, folder / "budget.json")
engine.master_sync.settle = lambda *args: None
engine.settle_pending_growth = lambda *args, **kwargs: False
return engine, client
def test_breakthrough_targets_execute_and_require_new_snapshot_before_repeat(self):
with workspace_temp() as folder:
engine, client = self.engine(folder)
engine.policy = Policy(breakthrough_targets={"900": 1})
engine.auto = True
engine.poll()
self.assertEqual([path for path, _ in client.calls], [POTENTIAL_PATH])
self.assertEqual(client.calls[0][1]["itemId"], 600)
self.assertIsNotNone(engine._breakthrough_pending)
# An acknowledged response with an unchanged snapshot cannot repeat.
engine.poll()
self.assertEqual(len(client.calls), 1)
client.value["monsters"][0]["pAtk"] += 1
client.value["monsters"][0]["pDef"] -= 1
engine.auto = True
engine.poll()
self.assertEqual(len(client.calls), 2)
restored, _ = self.engine(folder, client.value)
self.assertEqual(restored._breakthrough_pending["role_id"], "1")
self.assertTrue(restored._breakthrough_pending["uncertain"])
def test_stop_during_snapshot_and_pending_block_every_new_write(self):
with workspace_temp() as folder:
engine, client = self.engine(folder)
engine.policy = Policy(breakthrough_targets={"900": 1})
engine.auto = True
read = client.snapshot
def stopped():
engine.auto = False
return read()
client.snapshot = stopped
engine.poll()
self.assertEqual(client.calls, [])
engine, client = self.engine(folder)
engine._breakthrough_pending = {"kind": "invalid", "role_id": "1", "uncertain": True, "message": "待核对"}
engine.policy = Policy(enabled=True, dispatch=True, egg_rules={"1001010": {"enabled": True, "action": "sell"}})
engine.auto = True
_, plans, _ = engine.poll()
self.assertEqual((client.calls, plans), ([], []))
def test_pre_dispatch_persistence_failure_never_sends(self):
with workspace_temp() as folder:
engine, client = self.engine(folder)
engine.policy = Policy(breakthrough_targets={"900": 1})
engine.auto = True
engine.automation_state_path = folder / "missing" / "state.json"
original = engine._save_automation_state
def fail():
original()
raise OSError("synthetic disk failure")
engine._save_automation_state = fail
with self.assertRaises(OSError):
engine.poll()
self.assertEqual(client.calls, [])
self.assertFalse(engine.auto)
def test_locked_exploration_is_diagnostic_and_does_not_block_ranch(self):
with workspace_temp() as folder:
engine, client = self.engine(folder)
client.value["history"]["passTask"] = {}
client.value["monsters"].append({"id": 101, "typeId": 1001010, "process": 3, "mode": 2, "level": 1})
for stat in ("atk", "def", "hp", "dex"):
client.value["monsters"][-1]["g" + stat.capitalize()] = self.catalog.monster(1001010)[stat + "_grow_min"]
engine.policy = Policy(enabled=True, dispatch=True, fill=False, collect=False,
egg_rules={"1001010": {"enabled": True, "action": "sell", "keep_count": 0}})
engine.planner.managed.add(101)
engine.explore_policy = ExplorePolicy(True)
engine.auto = True
_, plans, _ = engine.poll()
self.assertEqual([path for path, _ in client.calls], ["monsterService/monsterSell"])
self.assertTrue(any(action.kind == "explore_blocked" and "探险功能尚未解锁" in action.description for action in plans))
self.assertFalse(any(action.kind == "explore_start" for action in plans))
def test_unknown_result_survives_restart_and_owner_mismatch_cannot_confirm(self):
with workspace_temp() as folder:
engine, client = self.engine(folder)
engine.policy = Policy(breakthrough_targets={"900": 1})
engine.auto = True
client.response = TimeoutError("synthetic lost reply")
with self.assertRaises(TimeoutError):
engine.poll()
other = copy.deepcopy(client.value)
other["master"]["id"] = 2
other["monsters"][0]["pAtk"] += 1
restored, other_client = self.engine(folder, other)
restored.policy = Policy(breakthrough_targets={"900": 1})
restored.auto = True
restored.poll()
self.assertEqual(other_client.calls, [])
self.assertEqual(restored._breakthrough_pending["role_id"], "1")
def test_stop_after_durable_prepare_before_dispatch_rolls_back_without_write(self):
with workspace_temp() as folder:
for explore in (False, True):
engine, client = self.engine(folder)
if explore:
engine.explore_policy = ExplorePolicy(True, {"77": {"enabled": True, "area": "1", "monsters": []}})
area = engine.explore_planner.areas["1"]
client.value["history"]["passStage"] = {area["passStage"]: {"1": True}}
client.value["monsters"][0]["level"] = 60
else:
engine.policy = Policy(breakthrough_targets={"900": 1})
engine.auto = True
save = engine._save_automation_state
def stop_after_save():
save()
engine.cancel_progression()
engine._save_automation_state = stop_after_save
engine.poll()
self.assertEqual(client.calls, [])
self.assertIsNone(engine._breakthrough_pending)
self.assertIsNone(engine.explore_planner.pending(engine.snapshot))
def test_corrupt_state_preserves_barrier_and_file(self):
with workspace_temp() as folder:
path = folder / "automation_state.json"
path.write_text('{"version":0,"breakthrough":{}}', encoding="utf-8")
engine, client = self.engine(folder)
engine.policy = Policy(breakthrough_targets={"900": 1})
engine.auto = True
engine.poll()
self.assertEqual(client.calls, [])
self.assertEqual(path.read_text(encoding="utf-8"), '{"version":0,"breakthrough":{}}')
def test_explore_executes_then_reconciles_and_pending_is_not_rolled_back(self):
with workspace_temp() as folder:
engine, client = self.engine(folder)
engine.explore_policy = ExplorePolicy(True, {"77": {"enabled": True, "area": "1", "monsters": []}}, 0)
engine.auto = True
area = next(row for row in engine.explore_planner.areas.values() if row["id"] == "1")
client.value["history"]["passStage"] = {area["passStage"]: {"1": True}}
client.value["monsters"][0]["level"] = 60
engine.poll()
self.assertEqual([call[0] for call in client.calls], ["exploreService/start"])
self.assertIsNotNone(engine.explore_planner.pending(engine.snapshot))
engine.poll()
self.assertEqual(len(client.calls), 1)
action = engine.explore_planner.pending(engine.snapshot)
team = client.value["exploreTeams"][0]
team.update(status=1, area="1", monsters=action["payload"]["monsters"], endTime=9999999999999)
engine.poll()
self.assertIsNone(engine.explore_planner.pending(engine.snapshot))
self.assertEqual(json.loads((folder / "automation_state.json").read_text(encoding="utf-8"))["version"], 1)
if __name__ == "__main__":
unittest.main()
+16 -2
View File
@@ -37,8 +37,8 @@ class RanchTreeTests(unittest.TestCase):
snapshot.raw["monsters"].append(snapshot.monsters[900] | {"id": 901, "roomId": 2}) snapshot.raw["monsters"].append(snapshot.monsters[900] | {"id": 901, "roomId": 2})
return catalog, snapshot return catalog, snapshot
def render(self, tree, snapshot, feeds=None, gifts=None): def render(self, tree, snapshot, feeds=None, gifts=None, breakthroughs=None):
tree.set_data(snapshot, monster_rows(tree.catalog, snapshot, set()), feeds or {}, gifts or {}) tree.set_data(snapshot, monster_rows(tree.catalog, snapshot, set()), feeds or {}, gifts or {}, breakthroughs or {})
self.drain(tree) self.drain(tree)
def test_ranch_headers_children_and_refresh_preserve_controls_and_collapse(self): def test_ranch_headers_children_and_refresh_preserve_controls_and_collapse(self):
@@ -69,6 +69,16 @@ class RanchTreeTests(unittest.TestCase):
self.assertFalse(tree.group_items["room:1"].isExpanded()) self.assertFalse(tree.group_items["room:1"].isExpanded())
self.assertEqual(tree.selected_monster_ids(), [900]) self.assertEqual(tree.selected_monster_ids(), [900])
self.assertTrue(item.text(15).startswith("30 /")) self.assertTrue(item.text(15).startswith("30 /"))
self.assertEqual(tree.columnCount(), 23)
self.assertEqual(tree.headerItem().text(17), "赠礼")
self.assertEqual(tree.headerItem().text(18), "赠礼优先级")
self.assertEqual(tree.headerItem().text(10), "潜能阶段")
self.assertEqual(tree.headerItem().text(21), "同种突破")
self.assertEqual(tree.headerItem().text(22), "突破经验")
self.assertEqual(item.text(21), "0 / 4")
self.render(tree, updated, {"900": 2}, {"900": 3}, {"900": 7})
self.assertTrue(tree.itemWidget(item, 19).isChecked())
self.assertEqual(tree.itemWidget(item, 20).value(), 7)
finally: finally:
tree.row_batch.stop() tree.row_batch.stop()
tree.close() tree.close()
@@ -133,6 +143,10 @@ class RanchTreeTests(unittest.TestCase):
tree.itemWidget(item, 18).setValue(5) tree.itemWidget(item, 18).setValue(5)
self.assertEqual(window.read_policy().feed_targets, {"900": 4}) self.assertEqual(window.read_policy().feed_targets, {"900": 4})
self.assertEqual(window.read_policy().gift_targets, {"900": 5}) self.assertEqual(window.read_policy().gift_targets, {"900": 5})
tree.itemWidget(item, 19).setChecked(True)
tree.itemWidget(item, 20).setValue(6)
self.assertEqual(window.read_policy().breakthrough_targets, {"900": 6})
self.assertTrue(window.read_policy().gift_enabled)
tree.setCurrentItem(item) tree.setCurrentItem(item)
with patch("PySide6.QtWidgets.QMenu.popup"): with patch("PySide6.QtWidgets.QMenu.popup"):
window.page_menu(tree.viewport(), C.QPoint(-1, -1), window.monster_page) window.page_menu(tree.viewport(), C.QPoint(-1, -1), window.monster_page)
+221
View File
@@ -0,0 +1,221 @@
import unittest
from dataclasses import asdict
from unittest.mock import patch
from ranch_assistant.cultivation import quality_rank
from ranch_assistant.model import Catalog, EggRule, Planner, Policy, Snapshot
def graded_monster(catalog, mid, grades, *, level=10, species=1001010, process=3, **values):
row = catalog.monster(species)
mon = {"id": mid, "typeId": species, "process": process, "mode": 2, "level": level,
"feel": 0, "entangleLevel": 0, "giftTime": 0, "roomId": 1, "lock": 0, **values}
for stat, grade in zip(("atk", "def", "hp", "dex"), grades):
low, high = row[stat + "_grow_min"], row[stat + "_grow_max"]
mon["g" + stat.capitalize()] = low + (high - low) * {"C": .1, "B": .375, "A": .625, "S": .9}[grade]
return mon
class RanchRetentionTests(unittest.TestCase):
def setUp(self):
self.catalog = Catalog()
room_type = next(iter(self.catalog.data["room_info"]))
self.catalog.data["room_info"][room_type]["maxNum"] = 10
self.snapshot = Snapshot({"master": {"id": 1}, "monsters": [], "teams": [], "stacks": [],
"items": [], "rooms": [{"id": 1, "typeId": int(room_type)}], "history": {}, "activityHistory": {}})
self.planner = Planner(self.catalog)
def policy(self, action="sell", count=1, **values):
values.setdefault("protect_star", 6)
return Policy(manual_eggs=True, fill=False, protect_quality=6, keep_better_quality=True,
egg_rules={"1001010": asdict(EggRule(enabled=True, action=action, keep_count=count))}, **values)
def plan(self, rows, policy=None, managed=None):
self.snapshot.raw["monsters"] = rows
self.planner.managed.update(managed if managed is not None else [row["id"] for row in rows])
self.planner.cultivation.choices["1001010"] = 1
self.planner.cultivation.signature = None
return self.planner.plan(self.snapshot, policy or self.policy())
def test_quality_uses_s_then_a_then_b_before_normalized_growth(self):
aasa, ssas = graded_monster(self.catalog, 1, "AASA", level=50), graded_monster(self.catalog, 2, "SSAS")
self.assertLess(quality_rank(self.catalog, aasa), quality_rank(self.catalog, ssas))
self.assertGreater(quality_rank(self.catalog, graded_monster(self.catalog, 3, "AAAC")),
quality_rank(self.catalog, graded_monster(self.catalog, 4, "BBAA")))
self.assertFalse(any(a.kind == "sell" for a in self.plan([aasa, ssas])))
reason = self.planner.protection_reason(ssas, self.snapshot, self.policy())
self.assertIn("SSAS", reason)
self.assertIn("S项3", reason)
def test_quota_zero_one_two_apply_to_every_enabled_action(self):
for action in ("sell", "feed", "keep"):
for quota, disposed in ((0, 3), (1, 2), (2, 1)):
with self.subTest(action=action, quota=quota):
rows = [graded_monster(self.catalog, mid, "CCCC", tpLevel=4) for mid in (1, 2, 3)]
if action == "feed":
target = graded_monster(self.catalog, 99, "SSSS", species=1002010,
level=1, exp=0, potentialLevel=2, tpLevel=4, tpExp=33)
rows.append(target)
elif action == "keep":
disposed = 0
policy = self.policy(action=action, count=quota,
feed_targets={"99": 1} if action == "feed" else {})
actions = self.plan(rows, policy)
sold = [mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]]
fed = [mid for a in actions if a.kind == "feed" for mid in a.payload["foods"] if mid != 99]
self.assertEqual(len(sold + fed), disposed)
for target in (a.payload["targetId"] for a in actions if a.kind == "feed"):
self.assertNotIn(target, fed)
def test_same_batch_and_locked_ranch_monsters_share_one_quota(self):
rows = [graded_monster(self.catalog, mid, "CCCC", roomId=mid) for mid in (1, 2)]
rows += [graded_monster(self.catalog, mid, "CCCC", process=2, roomId=None) for mid in (3, 4)]
for row in rows[:2]:
row["lock"] = 1
actions = self.plan(rows, self.policy(count=2))
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [3, 4])
def test_incubator_batch_fills_quota_and_keeps_same_ids_after_collection(self):
for quota in (2, 3):
with self.subTest(quota=quota):
self.setUp()
rows = [graded_monster(self.catalog, mid, "CCCC", process=2, roomId=None) for mid in (1, 2, 3)]
self.snapshot.raw["stacks"] = [{"id": mid, "position": mid - 1, "monsterId": mid} for mid in (1, 2, 3)]
actions = self.plan(rows, self.policy(count=quota))
collected = {mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]}
self.assertEqual(collected, set(range(1, quota + 1)))
self.assertEqual(self.planner.retained, collected)
for row in rows:
row.update(process=3, roomId=1)
actions = self.plan(rows, self.policy(count=quota))
self.assertEqual(self.planner.retained, collected)
sold = {mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]}
self.assertEqual(sold, set(range(1, 4)) - collected)
actions = self.plan(rows, self.policy(count=quota))
self.assertEqual(self.planner.retained, collected)
self.assertTrue(all(mid not in collected for a in actions for mid in a.payload.get("foods", [])))
def test_ranch_and_incubator_share_quota_before_and_after_collection(self):
ranch = graded_monster(self.catalog, 1, "CCCC")
rows = [ranch] + [graded_monster(self.catalog, mid, "CCCC", process=2, roomId=None) for mid in (2, 3, 4)]
self.snapshot.raw["stacks"] = [{"id": mid, "position": mid - 1, "monsterId": mid} for mid in (2, 3, 4)]
actions = self.plan(rows, self.policy(count=2))
collected = {mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]}
self.assertEqual(collected, {2})
self.assertEqual(self.planner.retained, {1, 2})
for row in rows[1:]:
row.update(process=3, roomId=1)
actions = self.plan(rows, self.policy(count=2))
self.assertEqual(self.planner.retained, {1, 2})
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [3, 4])
def test_initial_incubator_quota_prefers_best_quality_last_in_raw(self):
rows = [graded_monster(self.catalog, mid, "CCCC", process=2, roomId=None) for mid in (1, 2)]
rows.append(graded_monster(self.catalog, 3, "SSAS", process=2, roomId=None))
self.snapshot.raw["stacks"] = [{"id": mid, "position": mid - 1, "monsterId": mid} for mid in (1, 2, 3)]
actions = self.plan(rows, self.policy(count=2))
collected = {mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]}
self.assertEqual(collected, {1, 3})
self.assertEqual(self.planner.retained, {1, 3})
def test_incubator_quota_quality_prevents_equal_quality_extra_retention(self):
rows = [graded_monster(self.catalog, 1, "AASA")]
rows += [graded_monster(self.catalog, mid, "SSAS", process=2, roomId=None) for mid in (2, 3)]
self.snapshot.raw["stacks"] = [{"id": mid, "position": mid - 1, "monsterId": mid} for mid in (2, 3)]
actions = self.plan(rows, self.policy(count=2))
self.assertEqual(self.planner.retained, {1, 2})
collected = [mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]]
self.assertEqual(collected, [2])
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [])
def test_zero_quota_still_protects_better_incubator_above_locked_ranch(self):
locked = graded_monster(self.catalog, 1, "AASA", lock=1)
better = graded_monster(self.catalog, 2, "SSAS", process=2, roomId=None)
self.snapshot.raw["stacks"] = [{"id": 2, "position": 0, "monsterId": 2}]
actions = self.plan([locked, better], self.policy(count=0))
self.assertEqual(self.planner.retained, {1, 2})
self.assertEqual([mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]], [2])
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [])
def test_three_collection_rounds_keep_only_best_ssas_above_locked_aasa(self):
locked = graded_monster(self.catalog, 1, "AASA", level=50, lock=1)
first = graded_monster(self.catalog, 2, "SSAS", process=2, roomId=None)
self.snapshot.raw["stacks"] = [{"id": 1, "position": 0, "monsterId": 2}]
policy = self.policy()
self.assertEqual(self.plan([locked, first], policy)[0].kind, "collect")
first.update(process=3, roomId=1)
self.assertFalse(any(a.kind == "sell" for a in self.plan([locked, first], policy)))
second = graded_monster(self.catalog, 3, "SSAS", process=2, roomId=None)
self.snapshot.raw["stacks"][0]["monsterId"] = 3
self.assertEqual([a.payload["monsterIds"] for a in self.plan([locked, first, second], policy)
if a.kind == "sell"], [[3]])
second.update(process=3, roomId=1)
actions = self.plan([locked, first, second], policy)
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [3])
self.assertTrue(all(2 not in a.payload.get("monsterIds", []) and 2 not in a.payload.get("foods", []) for a in actions))
def test_same_species_tp_batch_ignores_potential_cap_and_never_swaps_representative(self):
target = graded_monster(self.catalog, 1, "SCCC", level=10, tpLevel=2, tpExp=5, potentialLevel=1)
rows = [target, graded_monster(self.catalog, 2, "CCCC"), graded_monster(self.catalog, 3, "CCCC")]
self.assertEqual(self.plan(rows, self.policy(action="feed"))[0].payload, {"targetId": 1, "foods": [2, 3]})
target.update(tpLevel=4, tpExp=self.catalog.data["game_setting"]["tpExp"]["1"]["4"])
self.assertFalse(any(a.kind == "feed" and 1 in a.payload["foods"] for a in self.plan(rows, self.policy(action="feed"))))
def test_normal_cap_still_allows_tp_food_until_cumulative_exp_is_full(self):
target = graded_monster(self.catalog, 1, "SCCC", level=10, tpLevel=2, tpExp=6,
potentialLevel=1, exp=self.catalog.data["monster_level"]["10"])
food = graded_monster(self.catalog, 2, "CCCC")
self.assertEqual(self.plan([target, food], self.policy(action="feed"))[0].payload["foods"], [2])
target["tpExp"] = self.catalog.data["game_setting"]["tpExp"]["1"]["4"] - 1
self.assertEqual(self.plan([target, food], self.policy(action="feed"))[0].payload["foods"], [2])
target["tpExp"] = self.catalog.data["game_setting"]["tpExp"]["1"]["4"]
self.assertFalse(any(a.kind == "feed" for a in self.plan([target, food], self.policy(action="feed"))))
def test_unmanaged_protected_and_other_feed_targets_are_not_materials(self):
target = graded_monster(self.catalog, 1, "SSSS", tpLevel=0, tpExp=0)
other = graded_monster(self.catalog, 2, "SSSA", tpLevel=0, tpExp=0)
food = graded_monster(self.catalog, 3, "SSSB")
action = self.plan([target, other, food], self.policy(action="feed", count=0), managed=[3])[0]
self.assertEqual(action.payload, {"targetId": 1, "foods": [3]})
self.planner.managed.discard(2)
other["lock"] = 1
action = self.plan([target, other, food], self.policy(action="feed", count=0))[0]
self.assertEqual(action.payload["foods"], [3])
def test_direct_protected_and_disposition_prepare_quota_before_first_call(self):
rows = [graded_monster(self.catalog, 1, "CCCC"), graded_monster(self.catalog, 2, "CCCC")]
self.snapshot.raw["monsters"] = rows
policy = self.policy()
self.planner.cultivation.choices["1001010"] = 1
self.planner.cultivation.signature = None
self.planner.managed.update((1, 2))
with patch.object(self.planner, "prepare_retention", wraps=self.planner.prepare_retention) as prepare:
protected = [self.planner.protected(row, self.snapshot, policy) for row in rows]
self.assertEqual(protected.count(True), 1)
self.assertEqual(self.planner.disposition(rows[0], self.snapshot, policy), "keep" if protected[0] else "sell")
self.assertEqual(self.planner.disposition(rows[1], self.snapshot, policy), "keep" if protected[1] else "sell")
self.assertEqual(prepare.call_count, 1)
def test_missing_tp_fields_pause_special_feed_but_not_legacy_experience(self):
target = graded_monster(self.catalog, 1, "SCCC", level=10,
potentialLevel=1, exp=self.catalog.data["monster_level"]["10"])
food = graded_monster(self.catalog, 2, "CCCC")
self.assertFalse(any(a.kind == "feed" for a in self.plan([target, food], self.policy(action="feed"))))
target.update(tpLevel=0, tpExp=0, level=1, exp=0)
policy = Policy(strategy="experience", feed_target=1, fill=False, protect_star=6, protect_quality=6)
self.assertEqual(self.plan([target, food], policy)[0].payload, {"targetId": 1, "foods": [2]})
def test_special_food_tp_count_matches_client_rules(self):
target = graded_monster(self.catalog, 1, "SSSS", tpLevel=0, tpExp=0)
settings = self.catalog.data["game_setting"]
special = graded_monster(self.catalog, 2, "CCCC", species=int(settings["specialFood"]))
special14 = graded_monster(self.catalog, 3, "CCCC", species=int(settings["specialFood14"]))
self.assertEqual((self.planner.tp_food_value(target, special), self.planner.tp_food_value(target, special14)), (1, 1))
five_star = next(int(key) for key, row in self.catalog.monsters.items()
if int(row.get("star") or 0) == 5 and all(row.get(stat + "_grow_min") is not None for stat in ("atk", "def", "hp", "dex")))
target = graded_monster(self.catalog, 1, "SSSS", species=five_star, tpLevel=0, tpExp=0)
self.assertEqual((self.planner.tp_food_value(target, special), self.planner.tp_food_value(target, special14)), (1, 0))
if __name__ == "__main__":
unittest.main()
@@ -48,6 +48,13 @@ class RuleEditingTests(unittest.TestCase):
self.assertEqual([table.cellWidget(i, 5).currentText() for i in range(3)], ["保留", "喂养", "派遣"]) self.assertEqual([table.cellWidget(i, 5).currentText() for i in range(3)], ["保留", "喂养", "派遣"])
table.sortItems(3, C.Qt.SortOrder.DescendingOrder) table.sortItems(3, C.Qt.SortOrder.DescendingOrder)
self.assertEqual([table.cellWidget(i, 3).isChecked() for i in range(3)], [True, True, False]) self.assertEqual([table.cellWidget(i, 3).isChecked() for i in range(3)], [True, True, False])
table.sortItems(15, C.Qt.SortOrder.AscendingOrder)
key = table.item(0, 0).data(C.Qt.ItemDataRole.UserRole)
table.cellWidget(0, 15).setValue(2)
self.assertEqual(table.rules[key]["keep_count"], 2)
self.assertTrue(table.cellWidget(0, 15).alignment() & C.Qt.AlignmentFlag.AlignHCenter)
self.assertEqual(table.horizontalHeaderItem(14).text(), "物品ID")
self.assertEqual(table.horizontalHeaderItem(15).text(), "牧场保留")
key = table.item(0, 0).data(C.Qt.ItemDataRole.UserRole) key = table.item(0, 0).data(C.Qt.ItemDataRole.UserRole)
table.cellWidget(0, 3).setChecked(False) table.cellWidget(0, 3).setChecked(False)
self.assertFalse(table.rules[key]["enabled"]) self.assertFalse(table.rules[key]["enabled"])
+14 -1
View File
@@ -44,7 +44,7 @@ class ManualRuleTests(unittest.TestCase):
secondary = dict(primary, id=901, level=9, potentialLevel=1) secondary = dict(primary, id=901, level=9, potentialLevel=1)
self.snapshot.raw["monsters"].append(secondary) self.snapshot.raw["monsters"].append(secondary)
policy = Policy(manual_eggs=True, strategy="gold", fill=False, protect_star=6, protect_quality=5, policy = Policy(manual_eggs=True, strategy="gold", fill=False, protect_star=6, protect_quality=5,
egg_rules={str(food["typeId"]): self.rule(action="feed")}, feed_targets={"900": 1, "901": 2}) egg_rules={str(food["typeId"]): self.rule(action="feed", keep_count=0)}, feed_targets={"900": 1, "901": 2})
action = self.planner.plan(self.snapshot, policy)[0] action = self.planner.plan(self.snapshot, policy)[0]
self.assertEqual(action.kind, "feed") self.assertEqual(action.kind, "feed")
self.assertEqual(action.payload["targetId"], 901) self.assertEqual(action.payload["targetId"], 901)
@@ -83,6 +83,19 @@ class ManualRuleTests(unittest.TestCase):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
Policy(egg_rules={"1001010": {"refill_below": 5, "refill_target": 2}}) Policy(egg_rules={"1001010": {"refill_below": 5, "refill_target": 2}})
def test_quota_and_breakthrough_targets_validate_instead_of_silently_dropping_bad_values(self):
self.assertEqual(EggRule().keep_count, 1)
self.assertEqual(EggRule(keep_count="2").keep_count, 2)
for value in (True, 1.0, 1.5, "1.0", " 1", "+1", -1, 1001, None):
with self.subTest(keep_count=value), self.assertRaises(ValueError):
EggRule(keep_count=value)
self.assertEqual(Policy(breakthrough_targets={"900": 2}).breakthrough_targets, {"900": 2})
self.assertTrue(self.planner.protected(self.snapshot.monsters[900], self.snapshot,
Policy(protect_star=6, protect_quality=6, breakthrough_targets={"900": 2})))
for targets in ([], {"0": 1}, {"900": 0}, {"900": 1000}, {"900": True}, {"900": 1.5}, {"x": 1}):
with self.subTest(targets=targets), self.assertRaises(ValueError):
Policy(breakthrough_targets=targets)
class ManagementTests(unittest.TestCase): class ManagementTests(unittest.TestCase):
def setUp(self): def setUp(self):
+56
View File
@@ -0,0 +1,56 @@
"""Extract the original normal-team exploration areas for offline planning."""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import sys
import zipfile
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
from tools.research_battle_v12 import recover_table
from ranch_assistant.game_data import ORIGINAL_APK_SHA256
def repair(value):
if isinstance(value, dict):
return {str(key): repair(item) for key, item in value.items()}
if isinstance(value, list):
return [repair(item) for item in value]
if isinstance(value, str):
try:
return value.encode("latin1").decode("gbk")
except (UnicodeEncodeError, UnicodeDecodeError):
pass
return value
def build(apk, output):
import hashlib
with Path(apk).open("rb") as stream:
if hashlib.file_digest(stream, "sha256").hexdigest() != ORIGINAL_APK_SHA256:
raise ValueError("Only the verified original 1.9.68 APK is accepted")
with zipfile.ZipFile(apk) as archive:
original, metadata = recover_table(archive, "explore_info")
source = original.get("datas", original)["areas"]
fields = ("id", "name", "passStage", "costTi", "costTime", "level", "team", "monExpMin", "monExpMax", "dlevel", "reward")
areas = [{key: repair(row.get(key)) for key in fields} for row in source.values() if row.get("team") == "normal"]
document = {"schema": 1, "source_apk_sha256": ORIGINAL_APK_SHA256,
"source_table_sha256": metadata.get("sha256"), "areas": areas}
Path(output).write_text(json.dumps(document, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
return document
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--apk", type=Path)
parser.add_argument("--output", type=Path, default=ROOT / "ranch_assistant/data/exploration.json")
arguments = parser.parse_args()
if arguments.apk is None:
candidates = list(ROOT.glob("*_1.9.68.apk"))
if len(candidates) != 1:
parser.error("Pass --apk with the original 1.9.68 APK")
arguments.apk = candidates[0]
result = build(arguments.apk, arguments.output)
print(json.dumps({"areas": len(result["areas"]), "output": str(arguments.output)}, ensure_ascii=True))
+26 -6
View File
@@ -1,6 +1,7 @@
"""Recover factual game tables from the user-supplied APK; no network access.""" """Recover factual game tables from the user-supplied APK; no network access."""
import hashlib import hashlib
import json import json
import os
from pathlib import Path from pathlib import Path
import sys import sys
import zipfile import zipfile
@@ -8,6 +9,7 @@ import zlib
root = Path(__file__).resolve().parent.parent root = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(root)) sys.path.insert(0, str(root))
os.environ["PYTHONUTF8"] = "1"
from ranch_assistant.amf import Reader from ranch_assistant.amf import Reader
@@ -24,7 +26,13 @@ def repair_names(value):
return value return value
return value return value
apk = next(p for p in root.glob("*.apk") if p.name.endswith("_1.9.68.apk")) import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--apk", type=Path, help="Read-only local 1.9.68 APK")
parser.add_argument("--output", type=Path, help="catalog.json output path")
options = parser.parse_args()
apk = options.apk or next(p for p in root.glob("*.apk") if p.name.endswith("_1.9.68.apk"))
tables = {} tables = {}
with zipfile.ZipFile(apk) as archive: with zipfile.ZipFile(apk) as archive:
tables["tjchannel"] = json.loads(archive.read("assets/tjchannel.json")) if "assets/tjchannel.json" in archive.namelist() else {"tjchannel": "unknow"} tables["tjchannel"] = json.loads(archive.read("assets/tjchannel.json")) if "assets/tjchannel.json" in archive.namelist() else {"tjchannel": "unknow"}
@@ -40,6 +48,7 @@ with zipfile.ZipFile(apk) as archive:
tables["stack_meta"] = {"total": int(value["total"])} tables["stack_meta"] = {"total": int(value["total"])}
print(name, len(tables[name])) print(name, len(tables[name]))
fields = {"type", "name", "star", "time_1", "time_2", "sell_money", "sell_exp", "hideLib", "npc", "atk", "def", "hp", "dex", "like"} fields = {"type", "name", "star", "time_1", "time_2", "sell_money", "sell_exp", "hideLib", "npc", "atk", "def", "hp", "dex", "like"}
fields |= {"job", "element"}
fields |= {p + "_grow_" + bound for p in ("atk", "def", "hp", "dex") for bound in ("min", "max")} fields |= {p + "_grow_" + bound for p in ("atk", "def", "hp", "dex") for bound in ("min", "max")}
tables["monster_info"] = {str(k): {f: v for f, v in row.items() if f in fields} for k, row in tables["monster_info"].items()} tables["monster_info"] = {str(k): {f: v for f, v in row.items() if f in fields} for k, row in tables["monster_info"].items()}
tables = repair_names(tables) tables = repair_names(tables)
@@ -53,7 +62,8 @@ tables["entangle_info"] = {"haoganMax": tables["entangle_info"]["haoganMax"]}
tables["markets"] = {row["id"]: {k: row.get(k) for k in ("id", "money", "ke", "max", "eggs", "freegift")} | tables["markets"] = {row["id"]: {k: row.get(k) for k in ("id", "money", "ke", "max", "eggs", "freegift")} |
{"city": int(row["id"][7:]), "name": tables["game_setting"]["cityInfo"][row["id"][7:]]["name"]} {"city": int(row["id"][7:]), "name": tables["game_setting"]["cityInfo"][row["id"][7:]]["name"]}
for row in tables.pop("gacha_machine") if row["id"].startswith("sc_city")} for row in tables.pop("gacha_machine") if row["id"].startswith("sc_city")}
tables["potential_info"] = {k: tables["potential_info"][k] for k in ("potentialLevelMaxAdd", "maxPotentialLevel")} tables["potential_info"] = {k: tables["potential_info"][k] for k in
("potentialLevelMaxAdd", "maxPotentialLevel", "potential", "potentialAdd", "potentialLevelItem", "elementItem", "potentialElementItem")}
tables["stage_info"] = {r["id"]: {f: r.get(f) for f in ("id", "name", "city", "closed", "cost", "tagname", "special", "posmode")} | tables["stage_info"] = {r["id"]: {f: r.get(f) for f in ("id", "name", "city", "closed", "cost", "tagname", "special", "posmode")} |
{"level": {k: {f: v for f, v in level.items() if f in ("cost", "levelLock", "reward", "monExp")} for k, level in r.get("level", {}).items()}} {"level": {k: {f: v for f, v in level.items() if f in ("cost", "levelLock", "reward", "monExp")} for k, level in r.get("level", {}).items()}}
for r in tables["stage_info"]} for r in tables["stage_info"]}
@@ -61,15 +71,25 @@ tables["activity_info"] = {k: v for k, v in tables["activity_info"].items() if k
# Only positions are needed to avoid starting a sweep through an active story task. # Only positions are needed to avoid starting a sweep through an active story task.
tables["stage_task_positions"] = {str(k): [s.get("position", "") for s in r.get("steps", [])] for k, r in tables["task_info"].items() tables["stage_task_positions"] = {str(k): [s.get("position", "") for s in r.get("steps", [])] for k, r in tables["task_info"].items()
if any(str(s.get("position", "")).startswith("city") for s in r.get("steps", []))} if any(str(s.get("position", "")).startswith("city") for s in r.get("steps", []))}
tables["game_setting"] = {k: v for k, v in tables["game_setting"].items() if k in ("monExpScale", "xyz", "xyz1", "cityInfo", "upStarAdd", "maxLike", "vipReward", "monGiftTime", "monGiftMax", "masterMaxLevel", "tiCD", "tiFirst", "tiLevelAdd", "tiTotalMax") or k.startswith("loopTask") or k.endswith("_xyz")} tables["game_setting"] = {k: v for k, v in tables["game_setting"].items() if k in ("monExpScale", "xyz", "xyz1", "cityInfo", "upStarAdd", "maxLike", "vipReward", "monGiftTime", "monGiftMax", "masterMaxLevel", "tiCD", "tiFirst", "tiLevelAdd", "tiTotalMax", "tpExp", "specialFood", "specialFood14") or k.startswith("loopTask") or k.endswith("_xyz")}
# This is a GameMath constant, not a server-supplied game_setting field.
tables["client_constants"] = {"maxTpLevel": 4}
task_fields = {"type", "typeId", "name", "des", "city", "closed", "condition", "startStep", "reward"} task_fields = {"type", "typeId", "name", "des", "city", "closed", "condition", "startStep", "reward"}
step_fields = {"statusType", "statusValue", "condition", "des", "position", "npc", "afterStory", "auto"} step_fields = {"statusType", "statusValue", "condition", "des", "position", "npc", "afterStory", "auto"}
tables["task_info"] = {str(k): {f: v for f, v in row.items() if f in task_fields} | tables["task_info"] = {str(k): {f: v for f, v in row.items() if f in task_fields} |
{"steps": [{f: v for f, v in step.items() if f in step_fields} for step in row.get("steps", [])]} {"steps": [{f: v for f, v in step.items() if f in step_fields} for step in row.get("steps", [])]}
for k, row in tables["task_info"].items() if int(row.get("type", 0)) == 4} for k, row in tables["task_info"].items() if int(row.get("type", 0)) == 4}
output = root / "ranch_assistant" / "data" catalog_path = options.output or root / "ranch_assistant" / "data" / "catalog.json"
output.mkdir(exist_ok=True) catalog_path.parent.mkdir(parents=True, exist_ok=True)
(output / "catalog.json").write_text(json.dumps(tables, ensure_ascii=False, separators=(",", ":")), encoding="utf-8") text = json.dumps(tables, ensure_ascii=False, separators=(",", ":"))
if catalog_path.exists():
# Keep unrelated and locally maintained catalog data out of this table update.
previous = json.loads(catalog_path.read_text(encoding="utf-8"))
for key in ("monster_info", "potential_info", "game_setting"):
previous[key] = tables[key]
previous["client_constants"] = tables["client_constants"]
text = json.dumps(previous, ensure_ascii=False, separators=(",", ":"))
catalog_path.write_text(text, encoding="utf-8")
for table in ("monster_info", "stage_info"): for table in ("monster_info", "stage_info"):
values = tables[table].items() if isinstance(tables[table], dict) else enumerate(tables[table]) values = tables[table].items() if isinstance(tables[table], dict) else enumerate(tables[table])
for key, row in values: for key, row in values: