Revert ranch retention, breakthroughs and exploration
This commit is contained in:
@@ -22,8 +22,8 @@
|
||||
| 状态刷新与策略开关 | 登录后自动刷新角色、培育室、背包及牧场状态;每个账号只有一个“开启 / 停止”开关,菜单支持批量控制。关闭策略后仍同步状态和到期成长;手动刷新不触发消耗类自动操作。 |
|
||||
| 玩家信息 | 显示等级、经验与下一级门槛、金币、氪金、体力;经验达到门槛及体力恢复到期时,在后台请求服务器结算并更新显示。 |
|
||||
| 培育室 | 显示已开启、未开启、VIP坑位及魔物阶段、剩余时间和成熟资质;孵化与成长到期自动同步。普通坑位可在确认费用后扩建。 |
|
||||
| 分类背包 | 魔物蛋、可使用物品、消耗品、材料、其他、装备分别展示;支持搜索和排序。每种蛋可配置孵化开关、优先级、孵出后去向、牧场保留数量(默认1只)、补货下限/目标及市场;物品可配置赠礼开关和保留数量。 |
|
||||
| 牧场与魔物管理 | 默认平铺全部魔物,可切换为按牧场折叠分组;显示容量、空位、等级与突破上限、资质、参考属性、好感上限及喜欢的物品。支持详情查看、多选锁定/解锁、派遣、指定喂养,以及确认费用后新建牧场。可逐只勾选自动突破并设置优先级,仅处理四项潜能满且材料充足的目标。 |
|
||||
| 分类背包 | 魔物蛋、可使用物品、消耗品、材料、其他、装备分别展示;支持搜索和排序。每种蛋可配置孵化开关、优先级、孵出后去向、补货下限/目标及市场;物品可配置赠礼开关和保留数量。 |
|
||||
| 牧场与魔物管理 | 默认平铺全部魔物,可切换为按牧场折叠分组;显示容量、空位、等级与突破上限、资质、参考属性、好感上限及喜欢的物品。支持详情查看、多选锁定/解锁、派遣、指定喂养,以及确认费用后新建牧场。 |
|
||||
| 自动孵蛋与补货 | 按手动规则完成金币市场买蛋/抽蛋、孵化、成长同步、成熟收取、派遣或喂养;默认只十连,可单独开启“允许单抽”,遵守金币保留和每日购蛋额度。空坑按优先级独立随机1~2秒装填,不受整体刷新间隔影响。 |
|
||||
| 资质保留与经验喂养 | 支持星级、综合资质、四项全S(4S)保护,另可保留资质严格高于牧场同种培养代表的新魔物。经验喂养按目标优先级批量提交素材,遵守当前突破上限与停止等级,保护锁定、在队和委托所需魔物。 |
|
||||
| 自动赠礼与好感培养 | 在背包选择物品、牧场选择目标后自动赠礼;跳过冷却目标,连续处理其他可送目标,在本地倒计时并到期核对状态。支持喜欢物品筛选、库存保留及当前好感上限。可在本地自动为每种魔物选择唯一培养代表,依次按等级、好感、成长资质比较,完全相同时随机选定并记住。 |
|
||||
@@ -33,7 +33,6 @@
|
||||
| 战斗模式与记录 | “自动主线 → 推进策略”显式选择原版运行时(默认)或实验模拟(近似);按普通地图、任务专属战斗、任务通关战斗分别编排。记录胜负、模式、地图奖励事件和待核对原因,支持停止与中断恢复;局部能力不代表全部关卡可用。 |
|
||||
| 自动扫荡与挑战 | 按地区折叠显示关卡、难度、通关星级及可能掉落;账号地图本地缓存,手动刷新或挑战结束后同步进度。逐关勾选、选择已解锁难度和本日次数上限,配置保留体力与战队;满足扫荡条件时扫荡,未满星时可自动模拟挑战,战败显示“打不过”,支持探索奖励事件。 |
|
||||
| 掉落数据分析 | 按账号、关卡与难度在本地保存扫荡记录,分别统计普通扫荡、奖励事件或合计;展示样本数、出现次数、总数量、实测掉落率、平均数量和95%区间。支持掉落率/每点体力获得数量的条形图,不额外请求游戏服务器。 |
|
||||
| 自动探险 | 每支已有探险队可独立启用并选择已解锁的普通地区;完成后自动领取奖励再派出,遵守保留体力、队长/队员等级和牧场保护规则;不自动召回或花钱新增队伍。 |
|
||||
| 收益资料与执行计划 | 内置749种魔物的培育时间、派遣金币、强化经验及每小时收益,支持名称/星级筛选和CSV/XLSX覆盖;执行计划显示下一步操作与等待原因。 |
|
||||
| 统一策略配置 | 规则修改后自动保存并应用;通过原生菜单保存、导入或导出当前账号的孵蛋、牧场、喂养、赠礼、委托、每日事务、扫荡、主线推进、战斗模式、刷新间隔及自定义收益资料。跨账号按魔物种类匹配培养目标,导出文件不包含账号凭据或服务器进度。 |
|
||||
| 界面与调试 | 原生Qt菜单、可调整和隐藏的日志区、各页右键刷新;数字与勾选项可排序,数字框获得焦点后才响应滚轮,下拉框按内容扩宽。独立调试窗口查看请求、响应、耗时与错误,支持复制、导出和本地脱敏日志。 |
|
||||
|
||||
@@ -25,14 +25,11 @@
|
||||
“退出登录”保留登录记录;“退出登录并清除登录记录”经确认后只清除当前账号页签的凭据和会话。
|
||||
- 培育室:已开启、未开启和VIP坑位分别显示;支持金币/氪金开普通坑位,先显示费用再确认。
|
||||
- 背包:按“魔物蛋、可使用、消耗品、材料、其他、装备”分别显示子标签。魔物蛋逐种勾选孵化、设置优先级、选择孵出后派遣/喂养/保留,设置补货下限、目标和市场。
|
||||
“牧场保留”按种类设置通常保留数量,默认1只;与更高资质保护配合时,更好的新魔物可额外保留,较差的同种魔物优先喂给牧场中经验未满的同类。
|
||||
数量归零后保留规则;可添加当前无库存的蛋。未勾选的蛋不会自动孵化或触发补货。
|
||||
各物品分类支持名称筛选,显示数量、品质和售价;可为物品设置赠礼开关及至少保留数量。只刷新当前打开的分类表格。
|
||||
- 牧场:默认显示全部魔物,可手动切换为按牧场分组;按钮或右键可新建金币/氪金牧场,提交前确认费用。
|
||||
“按牧场分组”使用可折叠树形:牧场标题显示数量、容量和空位,下方直接列出所属魔物;空牧场也保留显示,培育室魔物单独分组。
|
||||
勾选喂养/赠礼目标并分别设置优先级;显示突破、当前等级上限、成长资质、参考属性、当前好感上限和喜欢的物品。
|
||||
自动突破使用独立的勾选和优先级:只有四项潜能达到当前阶段上限且材料齐全才请求突破,不会仅因等级满就操作。
|
||||
- 自动探险:在对应页签为每支已有探险队启用并选择地区;先领取完成奖励再派出,遵守保留体力、队员等级和保护规则,不自动召回或新增付费队伍。
|
||||
双击查看详情;右键可锁定、解锁、派遣、喂给指定魔物。
|
||||
- 每个页面的表格和空白处可右键“刷新本页”;刷新会同步到期的成长状态,不执行派遣、喂养等消耗类策略。
|
||||
- 多账号:同一程序内多个独立账号页签,登录后各自自动刷新状态,策略分别开启或关闭;切换页签不停止其他账号。
|
||||
@@ -74,7 +71,7 @@
|
||||
首次读取后按账号/角色保存本地地图缓存,重启、切换页面或普通监控刷新均复用缓存,仅“刷新关卡”(或本页右键刷新)更新列表。
|
||||
每关可勾选、选择已解锁难度和本日上限;满足游戏原有条件的普通关卡可接口扫荡,
|
||||
“未满星时自动挑战”默认开启,勾选已解锁普通关卡后可模拟首次挑战;符合三个难度全部通关条件后使用扫荡。打不过会暂停同一队伍的重复尝试,换队或提升属性后再试;未支持的规则显示中文原因。
|
||||
- 战斗记录:按上下文筛选普通地图、主线、任务与委托战斗、扫荡和地图奖励事件;任务/关卡显示名称、编号和难度,队伍与结果使用中文;只有模拟战斗标明“模拟近似”,普通剧情显示“剧情已推进”,未知结果保留待核对原因。
|
||||
- 战斗记录:按上下文筛选普通地图、主线、任务与委托战斗、扫荡和地图奖励事件;实验模型结果标明“实验近似”,未知结果保留待核对原因。
|
||||
- 扫荡奖励:普通扫荡读取 `battleEnd.reward`,奖励事件读取 `stageEvent.result`,日志列出本次实际获得的物品、魔物蛋、金币和经验。
|
||||
- 数据分析:紧邻“自动扫荡”的独立页签。左侧按地区选择关卡和难度,右侧显示条形图与掉落明细;关卡和可能掉落来自本地静态配置。
|
||||
可分别查看普通扫荡、奖励事件或合计,显示样本数、出现次数、获得总数量、实测掉落率、每次平均数量及95%区间。
|
||||
|
||||
@@ -1,164 +0,0 @@
|
||||
"""Human-readable battle journal presentation; stored records stay unchanged."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
|
||||
from .battle_messages import battle_message
|
||||
|
||||
|
||||
OUTCOMES = {
|
||||
"local": "剧情已推进", "win": "战斗胜利", "loss": "打不过",
|
||||
"unsupported": "暂不支持", "event": "已获得地图事件奖励",
|
||||
"sweep": "扫荡已完成", "completed": "已完成", "complete": "已完成",
|
||||
"cancelled": "已取消", "cancel": "已取消", "timeout": "已超时",
|
||||
"unknown": "结果待核对", "pending": "结果待核对", "failed": "执行失败",
|
||||
"done": "已完成", "settled": "结算已提交",
|
||||
}
|
||||
TEAMS = {f"team{letter}": f"战队{letter}" for letter in "ABCDEFGH"}
|
||||
MODES = {"original": "原版战斗运行时", "experimental": "内置模拟战斗(结果近似)"}
|
||||
RECORD_KINDS = {
|
||||
"mainline": "主线战斗", "sidequest": "支线战斗", "commission": "委托战斗",
|
||||
"battle": "普通战斗", "map_battle": "地图战斗", "sweep": "扫荡",
|
||||
"map_reward_event": "地图奖励事件", "ordinary_stage": "普通关卡战斗",
|
||||
"task_battle": "任务战斗", "task_pass_stage": "任务通关战斗",
|
||||
"progression_navigate": "剧情 · 前往地点", "progression_dialogue": "剧情 · NPC 对话",
|
||||
"progression_local_step": "剧情 · 步骤收尾", "progression_battle": "任务战斗",
|
||||
"progression_sweep": "任务扫荡", "progression_farm": "任务补缺",
|
||||
"progression_farm_sweep": "任务补缺扫荡", "progression_map_sweep": "地图扫荡",
|
||||
"unknown": "其他 / 未知",
|
||||
}
|
||||
REWARD_NAMES = {"money": "金币", "exp": "经验", "ke": "氪金", "ti": "体力"}
|
||||
|
||||
|
||||
def _identifier(value):
|
||||
text = str(value or "").strip()
|
||||
return text if text and text not in ("0", "None") else ""
|
||||
|
||||
|
||||
def _name(info, fallback):
|
||||
if isinstance(info, dict):
|
||||
return str(info.get("name") or fallback)
|
||||
return fallback
|
||||
|
||||
|
||||
def record_subject(row, data=None):
|
||||
"""Prefer task names, then stage names; always retain useful identifiers."""
|
||||
task_id = _identifier(row.get("task_type_id"))
|
||||
if not task_id and row.get("task_id"):
|
||||
task_id = _identifier(row.get("source_task_type_id"))
|
||||
stage_id = _identifier(row.get("stage_id"))
|
||||
task = stage = None
|
||||
if data is not None:
|
||||
try:
|
||||
task = data.task(task_id) if task_id else None
|
||||
if not stage_id and isinstance(task, dict):
|
||||
number = int(row.get("step_number") or 0)
|
||||
steps = task.get("steps") or []
|
||||
if 1 <= number <= len(steps):
|
||||
step = steps[number - 1]
|
||||
stage_id = _identifier((step.get("statusValue") or {}).get("stage"))
|
||||
if stage_id and not row.get("difficulty"):
|
||||
row = row | {"difficulty": (step.get("statusValue") or {}).get("level", 1)}
|
||||
stage = data.stage(stage_id) if stage_id else None
|
||||
except (AttributeError, TypeError, ValueError, KeyError, IndexError):
|
||||
task = stage = None
|
||||
given_name = _identifier(row.get("name"))
|
||||
if task_id:
|
||||
name = _name(task, given_name or "未知名称任务")
|
||||
subject = f"{name} #{task_id}"
|
||||
if stage_id:
|
||||
stage_name = _name(stage, "未知名称关卡")
|
||||
tag = str((stage or {}).get("tagname") or "").strip()
|
||||
subject += f";{stage_name}" + (f"({tag})" if tag else "") + f" #{stage_id}"
|
||||
difficulty = _identifier(row.get("difficulty"))
|
||||
if difficulty:
|
||||
subject += f",难度 {difficulty}"
|
||||
return subject
|
||||
if stage_id:
|
||||
name = _name(stage, "未知名称关卡")
|
||||
tag = str((stage or {}).get("tagname") or "").strip()
|
||||
subject = f"{name}" + (f"({tag})" if tag else "") + f" #{stage_id}"
|
||||
difficulty = _identifier(row.get("difficulty"))
|
||||
return subject + (f",难度 {difficulty}" if difficulty else "")
|
||||
if given_name:
|
||||
return given_name
|
||||
description = _identifier(row.get("description"))
|
||||
return description or "未标明任务或关卡"
|
||||
|
||||
|
||||
def record_team(value):
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
return "未标明"
|
||||
match = re.fullmatch(r"team([A-Za-z])", text)
|
||||
return "战队" + match.group(1).upper() if match else text
|
||||
|
||||
|
||||
def record_context(row, kind):
|
||||
raw = row.get("battle_kind") or row.get("kind") or row.get("context")
|
||||
return RECORD_KINDS.get(kind, RECORD_KINDS.get(raw, "其他 / 未知"))
|
||||
|
||||
|
||||
def record_outcome(row):
|
||||
raw = row.get("outcome") or row.get("status") or row.get("phase") or row.get("result")
|
||||
if isinstance(raw, dict):
|
||||
raw = raw.get("outcome") or raw.get("status")
|
||||
text = str(raw or "未确认")
|
||||
result = OUTCOMES.get(text, text if re.search(r"[\u3400-\u9fff]", text) else "结果状态未确认")
|
||||
mode = row.get("battle_mode") or row.get("execution_mode")
|
||||
# Local dialogue/story checkpoints never run the combat simulator.
|
||||
if text != "local" and mode == "experimental":
|
||||
result += "(模拟近似)"
|
||||
return result
|
||||
|
||||
|
||||
def record_detail(row, data=None):
|
||||
message = battle_message(str(row.get("blocked_reason") or row.get("block_reason")
|
||||
or row.get("message") or row.get("reason") or ""))
|
||||
return message or "无额外说明"
|
||||
|
||||
|
||||
def reward_display(reward, catalog=None):
|
||||
if reward is None:
|
||||
return "未记录"
|
||||
if not isinstance(reward, dict):
|
||||
return str(reward)
|
||||
if "drops" in reward:
|
||||
try:
|
||||
from .drop_statistics import reward_text
|
||||
return reward_text(reward)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
pass
|
||||
parts = []
|
||||
for key, label in REWARD_NAMES.items():
|
||||
value = reward.get(key)
|
||||
if isinstance(value, (int, float)) and not isinstance(value, bool) and value:
|
||||
parts.append(f"{label} {value:g}")
|
||||
entries = []
|
||||
for key, kind in (("items", "item"), ("monsters", "monster")):
|
||||
rows = reward.get(key) or []
|
||||
if not isinstance(rows, list):
|
||||
continue
|
||||
for entry in rows:
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
type_id = entry.get("typeId", entry.get("type"))
|
||||
if type_id is None:
|
||||
continue
|
||||
name = f"物品 #{type_id}" if kind == "item" else f"魔物 #{type_id}"
|
||||
if catalog is not None:
|
||||
try:
|
||||
from .drop_statistics import drop_info
|
||||
name = drop_info(catalog, type_id, kind)["name"]
|
||||
except (AttributeError, KeyError, TypeError, ValueError):
|
||||
pass
|
||||
entries.append({"name": name, "num": entry.get("num", 1)})
|
||||
# Some journal writers store the already-normalized drop form directly.
|
||||
if isinstance(reward.get("drops"), list):
|
||||
for entry in reward["drops"]:
|
||||
if isinstance(entry, dict) and entry.get("name"):
|
||||
entries.append({"name": str(entry["name"]), "num": entry.get("num", 1)})
|
||||
for entry in entries:
|
||||
parts.append(f"{entry['name']} ×{entry['num']}")
|
||||
return ";".join(parts) or "无物品或货币奖励"
|
||||
@@ -1,174 +0,0 @@
|
||||
"""Plan original ranch breakthroughs without performing network writes.
|
||||
|
||||
The selected target order comes from ``feed_targets`` by default. Callers with
|
||||
an independent breakthrough switch should invoke this planner only when that
|
||||
switch is enabled; the returned Action can then use the normal Action runner.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .model import Action
|
||||
|
||||
|
||||
PATH = "monsterService/monsterPotentialLevelUpgrade"
|
||||
STATS = ("atk", "def", "hp", "dex")
|
||||
LABELS = {"atk": "攻击", "def": "防御", "hp": "生命", "dex": "敏捷"}
|
||||
|
||||
|
||||
def integer(value):
|
||||
"""Reject missing/non-integral server values instead of issuing a write."""
|
||||
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
|
||||
|
||||
|
||||
@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:
|
||||
"""Pure snapshot planner following PotentialPanel/PotentialCenter rules."""
|
||||
|
||||
def __init__(self, catalog):
|
||||
self.catalog = catalog
|
||||
self.notes = []
|
||||
|
||||
@staticmethod
|
||||
def target_ids(policy, targets=None):
|
||||
"""Numeric priority is ascending; an explicit mapping replaces feeding."""
|
||||
if targets is None:
|
||||
targets = getattr(policy, "feed_targets", None)
|
||||
if targets:
|
||||
pairs = []
|
||||
for mid, priority in targets.items():
|
||||
mid, priority = integer(mid), integer(priority)
|
||||
if mid is not None and priority is not None and mid > 0:
|
||||
pairs.append((priority, mid))
|
||||
return [mid for _, mid in sorted(pairs)]
|
||||
legacy = integer(getattr(policy, "feed_target", 0))
|
||||
return [legacy] if legacy and legacy > 0 else []
|
||||
|
||||
def evaluate(self, mon, items):
|
||||
"""Return full requirements even when the candidate cannot proceed."""
|
||||
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:
|
||||
return Candidate(mon, 0, (), "突破等级尚未同步")
|
||||
maximum = integer(info.get("maxPotentialLevel"))
|
||||
if maximum is not None and level >= maximum:
|
||||
return Candidate(mon, level, (), "已达到最高突破等级")
|
||||
jobs = info.get("potential") or {}
|
||||
stars = jobs.get(str(row.get("job")), {})
|
||||
caps = stars.get(str(row.get("star")))
|
||||
needs = (info.get("potentialLevelItem") or {}).get(str(row.get("star")), {})
|
||||
need = needs.get(str(level))
|
||||
elements = (info.get("elementItem") or {}).get(str(row.get("element")))
|
||||
if not caps or not need or not elements:
|
||||
return Candidate(mon, level + 1, (), "当前突破配置缺失")
|
||||
incomplete = []
|
||||
for stat in STATS:
|
||||
current = integer(mon.get("p" + stat.capitalize()))
|
||||
base, increment = integer(caps.get(stat)), integer(caps.get(stat + "TpAdd"))
|
||||
if current is None or base is None or increment is None:
|
||||
return Candidate(mon, level + 1, (), "潜能数据尚未同步")
|
||||
cap = base + (level - 1) * increment
|
||||
if current < cap:
|
||||
incomplete.append(f"{LABELS[stat]} {current}/{cap}")
|
||||
if incomplete:
|
||||
return Candidate(mon, level + 1, (), "潜能未满:" + ",".join(incomplete))
|
||||
|
||||
stacks = {}
|
||||
ids = set()
|
||||
for item in items:
|
||||
item_id, type_id = integer(item.get("id")), integer(item.get("typeId"))
|
||||
count = integer(item.get("num"))
|
||||
if item_id is None or type_id is None or item_id <= 0 or count is None or count <= 0:
|
||||
continue
|
||||
if item_id in ids:
|
||||
return Candidate(mon, level + 1, (), "背包材料实例重复,暂不操作")
|
||||
ids.add(item_id)
|
||||
stacks.setdefault(type_id, []).append((item_id, count))
|
||||
|
||||
materials, missing = [], []
|
||||
# PotentialCenter sends one getByType() stack per material level and
|
||||
# leaves quantity consumption to the server; mirror that exact shape.
|
||||
for level_key in sorted(need, key=lambda key: integer(key[2:]) or 999):
|
||||
amount_value = need[level_key]
|
||||
type_id = integer(elements.get(level_key))
|
||||
amount = integer(amount_value)
|
||||
if type_id is None or amount is None or amount <= 0:
|
||||
return Candidate(mon, level + 1, (), "当前突破材料配置异常")
|
||||
available = sum(count for _, count in stacks.get(type_id, []))
|
||||
selected = [stacks[type_id][0][0]] if stacks.get(type_id) else []
|
||||
materials.append(Material(type_id, amount, available, tuple(selected)))
|
||||
if available < amount:
|
||||
name = self.catalog.item_name(type_id)
|
||||
missing.append(f"{name} {available}/{amount}")
|
||||
reason = "材料不足:" + ",".join(missing) if missing else ""
|
||||
return Candidate(mon, level + 1, tuple(materials), reason)
|
||||
|
||||
def plan(self, snapshot, policy, *, targets=None, enabled=True):
|
||||
"""Return at most one Action, avoiding duplicate material consumption."""
|
||||
self.notes = []
|
||||
if not enabled or not getattr(policy, "enabled", True):
|
||||
return None
|
||||
ids = self.target_ids(policy, targets)
|
||||
if not ids:
|
||||
self.notes.append("未选择自动突破目标")
|
||||
return None
|
||||
monsters = snapshot.monsters
|
||||
for mid in ids:
|
||||
mon = monsters.get(mid)
|
||||
if not mon:
|
||||
self.notes.append(f"#{mid} 已不在角色数据中")
|
||||
continue
|
||||
if mon.get("process") != 3:
|
||||
self.notes.append(f"{self.catalog.monster_label(mon)} 不在牧场")
|
||||
continue
|
||||
candidate = self.evaluate(mon, snapshot.raw["items"])
|
||||
label = self.catalog.monster_label(mon)
|
||||
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})",
|
||||
PATH, {"monId": mid, "itemIds": item_ids})
|
||||
return None
|
||||
|
||||
|
||||
def plan_breakthrough(catalog, snapshot, policy, *, targets=None, enabled=True):
|
||||
"""Small integration entry point for Engine or GUI orchestration."""
|
||||
return BreakthroughPlanner(catalog).plan(snapshot, policy, targets=targets, enabled=enabled)
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
@@ -12,7 +12,7 @@ class EggTable(W.QTableWidget):
|
||||
|
||||
def __init__(self, catalog):
|
||||
headers = ["魔物蛋", "星", "数量", "孵化", "优先级", "孵出后", "低于补货", "补至", "补货市场",
|
||||
"牧场保留", "培育时间", "派遣金币", "基础经验", "金币/小时", "经验/小时", "物品ID"]
|
||||
"培育时间", "派遣金币", "基础经验", "金币/小时", "经验/小时", "物品ID"]
|
||||
super().__init__(0, len(headers))
|
||||
self.catalog, self.rules, self.snapshot = catalog, {}, None
|
||||
self.default_market = "sc_city1"
|
||||
@@ -21,7 +21,7 @@ class EggTable(W.QTableWidget):
|
||||
self.setEditTriggers(W.QAbstractItemView.EditTrigger.NoEditTriggers)
|
||||
self.setSelectionBehavior(W.QAbstractItemView.SelectionBehavior.SelectRows)
|
||||
self.horizontalHeader().setSectionResizeMode(W.QHeaderView.ResizeMode.Interactive)
|
||||
for column, width in enumerate((130, 45, 65, 65, 90, 135, 95, 95, 220, 90, 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)):
|
||||
self.setColumnWidth(column, width)
|
||||
self.verticalHeader().setDefaultSectionSize(24)
|
||||
|
||||
@@ -58,7 +58,7 @@ class EggTable(W.QTableWidget):
|
||||
group = groups.get(key, {"count": 0, "ids": []})
|
||||
total = max(1, self.catalog.total_time(key))
|
||||
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"])]
|
||||
for j, value in enumerate(values):
|
||||
item = self.item(i, j)
|
||||
@@ -74,21 +74,20 @@ class EggTable(W.QTableWidget):
|
||||
item.setToolTip(f"魔物编号 {key}")
|
||||
existing = self.cellWidget(i, 3)
|
||||
if existing and existing.property("egg_type_id") == key:
|
||||
controls = [self.cellWidget(i, col) for col in range(3, 10)]
|
||||
controls = [self.cellWidget(i, col) for col in range(3, 9)]
|
||||
blockers = [C.QSignalBlocker(control) for control in controls]
|
||||
controls[0].setChecked(rule["enabled"])
|
||||
for control, field in ((controls[1], "priority"), (controls[3], "refill_below"), (controls[4], "refill_target"),
|
||||
(controls[6], "keep_count")):
|
||||
for control, field in ((controls[1], "priority"), (controls[3], "refill_below"), (controls[4], "refill_target")):
|
||||
if not control.hasFocus():
|
||||
control.setValue(rule[field])
|
||||
controls[2].setCurrentIndex(max(0, controls[2].findData(rule["action"])))
|
||||
controls[5].setCurrentIndex(max(0, controls[5].findData(rule["market_id"])))
|
||||
bind_controls(self, i, dict(zip(range(3, 10), controls)))
|
||||
bind_controls(self, i, dict(zip(range(3, 9), controls)))
|
||||
return
|
||||
enabled = CenteredCheckBox()
|
||||
enabled.setProperty("egg_type_id", key)
|
||||
enabled.setChecked(rule["enabled"])
|
||||
priority, below, target, keep_count = IntegerInput(), IntegerInput(), IntegerInput(), IntegerInput()
|
||||
priority, below, target = IntegerInput(), IntegerInput(), IntegerInput()
|
||||
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"])):
|
||||
control.setRange(low, high)
|
||||
@@ -96,9 +95,6 @@ class EggTable(W.QTableWidget):
|
||||
priority.setToolTip("数字越小,孵化优先级越高")
|
||||
below.setToolTip("可用蛋少于此数量时补货;0表示不自动补货")
|
||||
target.setToolTip("补货希望达到的可用蛋数量;市场随机出蛋,实际结果由服务器决定")
|
||||
keep_count.setRange(0, 1000)
|
||||
keep_count.setValue(rule["keep_count"])
|
||||
keep_count.setToolTip("保留或更高资质保护下,每种魔物通常保留几只;默认1只,资质提升的新魔物可额外保留")
|
||||
action, market = ComboBox(), ComboBox()
|
||||
for name, value in (("派遣", "sell"), ("喂养", "feed"), ("保留", "keep")):
|
||||
action.addItem(name, value)
|
||||
@@ -112,8 +108,8 @@ class EggTable(W.QTableWidget):
|
||||
self.setColumnWidth(5, max(self.columnWidth(5), action.minimumSizeHint().width()))
|
||||
self.setColumnWidth(8, max(self.columnWidth(8), market.minimumSizeHint().width()))
|
||||
controls = {"enabled": enabled, "priority": priority, "action": action, "refill_below": below,
|
||||
"refill_target": target, "market_id": market, "keep_count": keep_count}
|
||||
for column, control in zip(range(3, 10), controls.values()):
|
||||
"refill_target": target, "market_id": market}
|
||||
for column, control in zip(range(3, 9), controls.values()):
|
||||
self.setCellWidget(i, column, control)
|
||||
def commit(*args, key=key, controls=controls):
|
||||
if self.updating:
|
||||
@@ -121,16 +117,15 @@ class EggTable(W.QTableWidget):
|
||||
controls["refill_target"].setMinimum(max(1, controls["refill_below"].value()))
|
||||
value = {"enabled": controls["enabled"].isChecked(), "priority": controls["priority"].value(),
|
||||
"action": controls["action"].currentData(), "refill_below": controls["refill_below"].value(),
|
||||
"refill_target": controls["refill_target"].value(), "market_id": controls["market_id"].currentData(),
|
||||
"keep_count": controls["keep_count"].value()}
|
||||
"refill_target": controls["refill_target"].value(), "market_id": controls["market_id"].currentData()}
|
||||
self.rules[key] = asdict(EggRule(**value))
|
||||
self.rules_changed.emit(copy.deepcopy(self.rules), key)
|
||||
enabled.toggled.connect(commit)
|
||||
for control in (priority, below, target, keep_count):
|
||||
for control in (priority, below, target):
|
||||
control.valueChanged.connect(commit)
|
||||
action.currentIndexChanged.connect(commit)
|
||||
market.currentIndexChanged.connect(commit)
|
||||
bind_controls(self, i, dict(zip(range(3, 10), controls.values())))
|
||||
bind_controls(self, i, dict(zip(range(3, 9), controls.values())))
|
||||
def finish():
|
||||
self.setSortingEnabled(True)
|
||||
self.updating = False
|
||||
|
||||
@@ -18,8 +18,6 @@ from .master_sync import MasterSync
|
||||
from .stage_cache import StageCache
|
||||
from .drop_statistics import reward_text
|
||||
from .cultivation import CultivationSelector
|
||||
from .breakthrough import BreakthroughPlanner
|
||||
from .exploration import ExplorePlanner, ExplorePolicy
|
||||
from .battles import BattleJournal, BattleOrchestrator, CancelledBeforeDispatch, digest, gameplay_response, public_data, value
|
||||
from .progression import ProgressionIntent, ProgressionPlanner, ProgressionPolicy
|
||||
from .battle_messages import battle_message
|
||||
@@ -60,9 +58,6 @@ class Engine:
|
||||
self.hatch_planner = Planner(catalog, self.cultivation)
|
||||
self.pending_hatches = []
|
||||
self.gift_planner = GiftPlanner(catalog, self.cultivation)
|
||||
self.breakthrough_planner = BreakthroughPlanner(catalog)
|
||||
self.explore_planner = ExplorePlanner(catalog)
|
||||
self.explore_policy = ExplorePolicy()
|
||||
self.policy = Policy()
|
||||
self.quest_policy = QuestPolicy()
|
||||
self.tasks = TaskPlanner(catalog)
|
||||
@@ -844,11 +839,7 @@ class Engine:
|
||||
if self.demo:
|
||||
self.apply_demo(action)
|
||||
else:
|
||||
if action.kind.startswith("explore_"):
|
||||
self.explore_planner.mark_started(self.snapshot, action)
|
||||
response = self._execute_legacy_task(action) if action.kind.startswith("quest_") else self.client.call(action.path, action.payload)
|
||||
if action.kind.startswith("explore_"):
|
||||
self.explore_planner.acknowledge(self.snapshot, action, response)
|
||||
if action.kind == "buy":
|
||||
self.record_draw(response.get("eggs") or [])
|
||||
if action.kind == "gift":
|
||||
@@ -867,15 +858,6 @@ class Engine:
|
||||
if action.kind == "feed" and any(mid in self.snapshot.monsters for mid in action.payload["foods"]):
|
||||
self.auto = False
|
||||
raise ValueError("喂养已返回,但素材状态尚未同步;已停止,请刷新核对后再继续")
|
||||
if action.kind == "breakthrough" and self.snapshot.monsters.get(action.payload["monId"], {}).get("potentialLevel") is not None:
|
||||
# A successful write is followed by a fresh snapshot. Do
|
||||
# not repeat it merely because a legacy response is sparse.
|
||||
self.planner.notes.append("突破请求已返回,已刷新突破等级和材料")
|
||||
if action.kind == "breakthrough":
|
||||
expected = int(action.description.split("→")[-1].split("级")[0].strip()) if "→" in action.description else 0
|
||||
actual = int(self.snapshot.monsters.get(action.payload["monId"], {}).get("potentialLevel") or 0)
|
||||
if expected and actual != expected:
|
||||
raise ValueError("突破请求已返回,但突破等级尚未同步;不会自动重复提交")
|
||||
message = ("[演示] " if self.demo else "") + action.description
|
||||
if action.kind == "buy" and self.last_draw:
|
||||
message += ";" + self.last_draw
|
||||
@@ -1016,13 +998,6 @@ class Engine:
|
||||
sweep_actions = [map_action] if map_action else []
|
||||
gifts = self.gift_planner.plan(self.snapshot, policy, self.quest_policy)
|
||||
ranch = self.planner.plan(self.snapshot, policy, left)
|
||||
breakthrough = self.breakthrough_planner.plan(self.snapshot, self.policy,
|
||||
targets=self.policy.breakthrough_targets)
|
||||
if breakthrough:
|
||||
ranch = [breakthrough] + ranch
|
||||
exploration = self.explore_planner.plan(self.snapshot, self.explore_policy, self.policy)
|
||||
exploration = [] if exploration and exploration[0].kind == "explore_blocked" else exploration
|
||||
self.planner.notes.extend(self.breakthrough_planner.notes)
|
||||
self.planner.notes.extend(self.gift_planner.notes)
|
||||
progression = [Action("progression", value(intent, "description", "推进任务"), "", {"intent": intent})
|
||||
for intent in self._progression_intents if not value(intent, "block_reason") and self._intent_policy(intent).enabled]
|
||||
@@ -1030,7 +1005,7 @@ class Engine:
|
||||
progression = [action for action in progression if not self._is_commission(action.payload["intent"])]
|
||||
if quests and quests[0].kind == "quest_reset":
|
||||
return quests + commission[:1] + daily + progression[:1] + gifts + ranch + sweep_actions
|
||||
return commission[:1] + quests + daily + progression[:1] + gifts + ranch + exploration + sweep_actions
|
||||
return commission[:1] + quests + daily + progression[:1] + gifts + ranch + sweep_actions
|
||||
|
||||
@account_serial
|
||||
def claim_daily_entry(self, entry):
|
||||
@@ -1158,13 +1133,6 @@ class Engine:
|
||||
if action.kind.startswith("quest_"):
|
||||
self.apply_demo_quest(action)
|
||||
return
|
||||
if action.kind == "breakthrough":
|
||||
mon = self.snapshot.monsters.get(action.payload["monId"])
|
||||
if mon is not None:
|
||||
mon["potentialLevel"] = int(mon.get("potentialLevel") or 1) + 1
|
||||
return
|
||||
if action.kind.startswith("explore_"):
|
||||
return
|
||||
if action.kind == "buy":
|
||||
market = self.catalog.data["markets"][action.payload["id"]]
|
||||
count = action.payload["num"]
|
||||
|
||||
@@ -1,293 +0,0 @@
|
||||
"""Offline automatic-exploration policy and one-action planning.
|
||||
|
||||
The integration owns HTTP and must call ``mark_started`` before every wire
|
||||
request. Uncertain responses stay pending and are never automatically replayed.
|
||||
Only ``finish`` and ``start`` are emitted; adding/recalling teams is deliberate
|
||||
outside this module.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import asdict, dataclass, field
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
from .model import Action, Planner, seconds
|
||||
|
||||
|
||||
DATA_PATH = Path(__file__).with_name("data") / "exploration.json"
|
||||
|
||||
|
||||
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
|
||||
key = str(int(row["id"]))
|
||||
levels = row.get("level")
|
||||
if not isinstance(levels, list) or len(levels) != 3:
|
||||
continue
|
||||
result[key] = dict(row, id=key, level=[int(value) for value in levels],
|
||||
costTi=int(row.get("costTi") or 0), costTime=int(row.get("costTime") or 0))
|
||||
return result
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExploreTeamRule:
|
||||
enabled: bool = False
|
||||
area: str = ""
|
||||
|
||||
def __post_init__(self):
|
||||
if type(self.enabled) is not bool:
|
||||
raise ValueError("探险队伍开关必须为布尔值")
|
||||
self.area = str(self.area)
|
||||
if self.area and (not self.area.isdigit() or int(self.area) <= 0):
|
||||
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("自动探险开关必须为布尔值")
|
||||
if type(self.reserve_ti) is not int or not 0 <= self.reserve_ti <= 1_000_000_000:
|
||||
raise ValueError("探险保留体力必须为非负整数")
|
||||
if not isinstance(self.teams, dict):
|
||||
raise ValueError("探险队伍配置必须为对象")
|
||||
rules = {}
|
||||
for key, value in self.teams.items():
|
||||
if not str(key).isdigit() or int(key) <= 0:
|
||||
raise ValueError("探险队伍编号无效")
|
||||
if isinstance(value, ExploreTeamRule):
|
||||
value = asdict(value)
|
||||
if not isinstance(value, dict) or set(value) - {"enabled", "area"}:
|
||||
raise ValueError("探险队伍配置格式错误")
|
||||
rules[str(int(key))] = 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)
|
||||
|
||||
|
||||
def _integer(value, default=0):
|
||||
try:
|
||||
number = float(value)
|
||||
return int(number) if math.isfinite(number) and number.is_integer() else default
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
return default
|
||||
|
||||
|
||||
def _flag(mapping, key):
|
||||
if isinstance(mapping, dict):
|
||||
value = mapping.get(str(key), mapping.get(key, False))
|
||||
return value is True or value == 1
|
||||
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
|
||||
|
||||
|
||||
class ExplorePlanner:
|
||||
"""Plan at most one server action; snapshots are always read-only."""
|
||||
|
||||
def __init__(self, catalog, *, areas=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.guard = Planner(catalog)
|
||||
self._accounts = {}
|
||||
|
||||
def _scope(self, snapshot):
|
||||
master = snapshot.raw.get("master") or {}
|
||||
return f"{master.get('id', master.get('userId', ''))}:{snapshot.raw.get('serverId', '')}:{snapshot.raw.get('areaId', '')}"
|
||||
|
||||
def _account(self, snapshot):
|
||||
return self._accounts.setdefault(self._scope(snapshot), {"pending": None})
|
||||
|
||||
def area_unlocked(self, snapshot, area):
|
||||
history = snapshot.raw.get("history") or {}
|
||||
return _flag(history.get("passStage"), area.get("passStage"))
|
||||
|
||||
def open(self, snapshot):
|
||||
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()
|
||||
|
||||
def _pending_action(self, pending):
|
||||
return Action("explore_blocked", pending.get("message", "探险请求待核对,禁止重放"), "",
|
||||
{"team_id": pending.get("team_id"), "pending": True})
|
||||
|
||||
def plan(self, snapshot, policy, ranch_policy):
|
||||
if not policy.enabled:
|
||||
return []
|
||||
pending = self._account(snapshot)["pending"]
|
||||
if pending:
|
||||
return [self._pending_action(pending)]
|
||||
if not self.open(snapshot):
|
||||
return [Action("explore_blocked", "探险功能尚未解锁", "", {})]
|
||||
teams = self._teams(snapshot)
|
||||
occupied = {str(team.get("area")) for team in teams if _integer(team.get("status")) == 1}
|
||||
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:
|
||||
continue
|
||||
if _integer(team.get("status")) == 1 and self.remaining(snapshot, team) <= 0:
|
||||
return [Action("explore_finish", f"领取探险队 {team_id} 的奖励", "exploreService/finish",
|
||||
{"exploreTeamId": team_id})]
|
||||
stamina = _integer(snapshot.raw["master"].get("ti"))
|
||||
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:
|
||||
continue
|
||||
if not self.area_unlocked(snapshot, area) or str(area["id"]) in occupied:
|
||||
continue
|
||||
if area["costTi"] <= 0 or stamina < area["costTi"] + policy.reserve_ti:
|
||||
continue
|
||||
monsters = self.select_monsters(snapshot, area, ranch_policy)
|
||||
if monsters is None:
|
||||
continue
|
||||
return [Action("explore_start", f"探险队 {team_id} → {area.get('name') or rule.area}", "exploreService/start",
|
||||
{"exploreTeamId": team_id, "monsters": monsters, "area": rule.area})]
|
||||
return []
|
||||
|
||||
def _teams(self, snapshot):
|
||||
return [team for team in snapshot.raw.get("exploreTeams") or [] if isinstance(team, dict)]
|
||||
|
||||
def remaining(self, snapshot, team):
|
||||
return max(0, seconds(team.get("endTime")) - snapshot.now) if team.get("endTime") is not None else None
|
||||
|
||||
def select_monsters(self, snapshot, area, ranch_policy):
|
||||
levels = area.get("level") or []
|
||||
if len(levels) != 3:
|
||||
return None
|
||||
candidates = []
|
||||
for mon in snapshot.raw.get("monsters") or []:
|
||||
try:
|
||||
mid, level = int(mon["id"]), int(mon.get("level") or 0)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if mid <= 0 or mon.get("process") != 3 or self.guard.protected(mon, snapshot, ranch_policy):
|
||||
continue
|
||||
candidates.append((mid, level, mon))
|
||||
# The highest-level eligible leader improves member experience. Lower
|
||||
# slots cannot exceed the leader, matching ExploreCreateUI.
|
||||
candidates.sort(key=lambda row: (-row[1], row[0]))
|
||||
leader = next((row for row in candidates if row[1] >= 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 levels[position] <= row[1] <= leader[1]), None)
|
||||
if member is None:
|
||||
return None
|
||||
selected.append(member)
|
||||
return [row[0] for row in selected]
|
||||
|
||||
def rows(self, snapshot, policy, ranch_policy):
|
||||
pending = self._account(snapshot)["pending"]
|
||||
rows = []
|
||||
teams = self._teams(snapshot)
|
||||
occupied = {str(team.get("area")) for team in teams if _integer(team.get("status")) == 1}
|
||||
for team in teams:
|
||||
team_id = _integer(team.get("id"), -1)
|
||||
rule = self.team_rule(policy, team_id)
|
||||
area = self.areas.get(rule.area)
|
||||
status, reason, monsters = "空闲", "", []
|
||||
remaining = self.remaining(snapshot, team)
|
||||
if not self.open(snapshot):
|
||||
status, reason = "未解锁", "完成指定主线后解锁探险"
|
||||
elif not rule.enabled:
|
||||
status, reason = "未启用", "勾选此队伍后参与自动探险"
|
||||
elif _integer(team.get("status")) == 1:
|
||||
status = "可领取" if remaining is not None and remaining <= 0 else "探索中"
|
||||
elif pending and pending.get("team_id") == team_id:
|
||||
status, reason = "待核对", "请求结果尚未确认,不会自动重发"
|
||||
elif area is None:
|
||||
status, reason = "待配置", "请选择普通探险地区"
|
||||
elif not self.area_unlocked(snapshot, area):
|
||||
status, reason = "地区未解锁", f"需通关 {area.get('passStage') or '指定关卡'}"
|
||||
elif str(area["id"]) in occupied:
|
||||
status, reason = "地区占用", "同一地区已有队伍探索"
|
||||
elif _integer(snapshot.raw["master"].get("ti")) < area["costTi"] + policy.reserve_ti:
|
||||
status, reason = "体力不足", f"需要 {area['costTi']},另保留 {policy.reserve_ti}"
|
||||
else:
|
||||
selected = self.select_monsters(snapshot, area, ranch_policy)
|
||||
if selected is None:
|
||||
status, reason = "队员不足", "需要3只未被保护的成熟魔物;队员等级不高于队长"
|
||||
else:
|
||||
status, monsters = "可出发", selected
|
||||
members = team.get("monsters") if isinstance(team.get("monsters"), list) else []
|
||||
if not monsters:
|
||||
monsters = [_integer(mid) for mid in members if _integer(mid) > 0]
|
||||
rows.append({"team_id": team_id, "enabled": rule.enabled, "area": rule.area,
|
||||
"area_name": (area or {}).get("name", ""), "state": status, "reason": reason,
|
||||
"remaining": remaining if _integer(team.get("status")) == 1 else None,
|
||||
"monster_ids": monsters, "cost_ti": (area or {}).get("costTi", 0),
|
||||
"cost_time": (area or {}).get("costTime", 0)})
|
||||
return rows
|
||||
|
||||
def mark_started(self, snapshot, action):
|
||||
if action.kind not in ("explore_start", "explore_finish"):
|
||||
raise ValueError("该操作不是探险请求")
|
||||
account = self._account(snapshot)
|
||||
if account["pending"]:
|
||||
raise ValueError("已有探险请求待核对")
|
||||
account["pending"] = {"kind": action.kind, "team_id": _integer(action.payload.get("exploreTeamId")),
|
||||
"payload": dict(action.payload), "message": action.description + ":请求待核对,禁止重放"}
|
||||
|
||||
def acknowledge(self, snapshot, action, response=None):
|
||||
account = self._account(snapshot)
|
||||
pending = account["pending"]
|
||||
if not pending or pending["kind"] != action.kind or pending["payload"] != action.payload:
|
||||
return False
|
||||
account["pending"] = None
|
||||
return True
|
||||
|
||||
def mark_uncertain(self, snapshot, action):
|
||||
account = self._account(snapshot)
|
||||
pending = account["pending"]
|
||||
if not pending or pending["payload"] != action.payload:
|
||||
raise ValueError("没有对应的探险请求")
|
||||
pending["uncertain"] = True
|
||||
pending["message"] = action.description + ":结果未知,已禁止自动重放"
|
||||
|
||||
def export_state(self):
|
||||
return {key: {"pending": dict(value["pending"]) if value["pending"] else None}
|
||||
for key, value in self._accounts.items()}
|
||||
|
||||
def restore_state(self, value):
|
||||
if not isinstance(value, dict):
|
||||
raise ValueError("探险状态必须为对象")
|
||||
restored = {}
|
||||
for key, account in value.items():
|
||||
pending = account.get("pending") if isinstance(account, dict) else None
|
||||
if pending is not None:
|
||||
if (not isinstance(pending, dict) or pending.get("kind") not in ("explore_start", "explore_finish")
|
||||
or not isinstance(pending.get("payload"), dict)
|
||||
or not pending["payload"].get("exploreTeamId")):
|
||||
raise ValueError("探险待核对状态无效")
|
||||
pending = dict(pending, payload=dict(pending["payload"]))
|
||||
restored[str(key)] = {"pending": pending}
|
||||
self._accounts = restored
|
||||
@@ -1,134 +0,0 @@
|
||||
"""Native Qt exploration settings; planning and refresh stay off the UI thread."""
|
||||
from dataclasses import asdict
|
||||
|
||||
from PySide6 import QtCore as C, QtWidgets as W
|
||||
|
||||
from .exploration import ExplorePolicy, ExploreTeamRule
|
||||
from .model import duration
|
||||
from .native_widgets import ComboBox, IntegerInput
|
||||
|
||||
|
||||
def prepare_exploration_rows(engine):
|
||||
"""Worker boundary: return plain data and never construct Qt objects."""
|
||||
if engine.snapshot is None:
|
||||
return []
|
||||
return engine.explore_planner.rows(engine.snapshot, engine.explore_policy, engine.policy)
|
||||
|
||||
|
||||
class ExplorationPages:
|
||||
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)
|
||||
tools.addWidget(self.explore_enabled)
|
||||
tools.addWidget(W.QLabel("保留体力"))
|
||||
tools.addWidget(self.explore_reserve_ti)
|
||||
refresh = W.QPushButton("刷新探险状态")
|
||||
refresh.clicked.connect(self.refresh_exploration)
|
||||
tools.addWidget(refresh)
|
||||
tools.addStretch()
|
||||
layout.addLayout(tools)
|
||||
self.exploration_summary = W.QLabel("登录后显示已有探险队;不自动召回或花钱新增队伍")
|
||||
self.exploration_summary.setWordWrap(True)
|
||||
layout.addWidget(self.exploration_summary)
|
||||
self.exploration_table = W.QTableWidget(0, 8)
|
||||
self.exploration_table.setHorizontalHeaderLabels(["启用", "队伍", "地区", "状态", "剩余时间", "队员", "体力 / 时长", "说明"])
|
||||
self.exploration_table.setSelectionBehavior(W.QAbstractItemView.SelectionBehavior.SelectRows)
|
||||
self.exploration_table.setEditTriggers(W.QAbstractItemView.EditTrigger.NoEditTriggers)
|
||||
self.exploration_table.horizontalHeader().setStretchLastSection(True)
|
||||
self.exploration_table.verticalHeader().setDefaultSectionSize(25)
|
||||
layout.addWidget(self.exploration_table, 1)
|
||||
note = W.QLabel("每队独立勾选并选择地区;先领取已完成奖励,再自动派出。队员选择遵守牧场保护规则,队员等级不高于队长。")
|
||||
note.setWordWrap(True)
|
||||
layout.addWidget(note)
|
||||
self.tabs.addTab(self.exploration_page, "自动探险")
|
||||
self._exploration_rendering = False
|
||||
self._exploration_controls = {}
|
||||
self.explore_enabled.toggled.connect(self.exploration_settings_changed)
|
||||
self.explore_reserve_ti.valueChanged.connect(self.exploration_settings_changed)
|
||||
self.exploration_table.itemChanged.connect(self.exploration_item_changed)
|
||||
|
||||
def read_explore_policy(self):
|
||||
teams = {}
|
||||
for key, controls in self._exploration_controls.items():
|
||||
teams[key] = ExploreTeamRule(controls["enabled"].checkState() == C.Qt.CheckState.Checked,
|
||||
str(controls["area"].currentData() or ""))
|
||||
return ExplorePolicy(self.explore_enabled.isChecked(), teams, self.explore_reserve_ti.value())
|
||||
|
||||
def exploration_settings_changed(self, *args):
|
||||
if self.closed or self.loading_config or getattr(self, "_exploration_rendering", False):
|
||||
return
|
||||
policy = self.read_explore_policy()
|
||||
self.engine.explore_policy = policy
|
||||
if hasattr(self, "pending_policy") and self.pending_policy is not None:
|
||||
self.pending_policy["explore_policy"] = policy
|
||||
self.settings_changed()
|
||||
|
||||
def exploration_item_changed(self, item):
|
||||
if item.column() == 0:
|
||||
self.exploration_settings_changed()
|
||||
|
||||
def refresh_exploration(self):
|
||||
if self.closed:
|
||||
return
|
||||
if self.busy:
|
||||
self.pending_refresh = self.exploration_page
|
||||
return
|
||||
self.submit("exploration_view", lambda: prepare_exploration_rows(self.engine))
|
||||
|
||||
def render_exploration(self, rows=None):
|
||||
if not hasattr(self, "exploration_table"):
|
||||
return
|
||||
rows = prepare_exploration_rows(self.engine) if rows is None else rows
|
||||
self._exploration_rendering = True
|
||||
try:
|
||||
self.exploration_table.setRowCount(len(rows))
|
||||
active = set()
|
||||
for index, row in enumerate(rows):
|
||||
key = str(row["team_id"])
|
||||
active.add(key)
|
||||
controls = self._exploration_controls.get(key)
|
||||
if controls is None:
|
||||
enabled = W.QTableWidgetItem()
|
||||
enabled.setFlags(C.Qt.ItemFlag.ItemIsEnabled | C.Qt.ItemFlag.ItemIsUserCheckable)
|
||||
area = ComboBox()
|
||||
for area_id, config in self.engine.explore_planner.areas.items():
|
||||
area.addItem(f"{config.get('name') or area_id}({area_id})", area_id)
|
||||
area.currentIndexChanged.connect(self.exploration_settings_changed)
|
||||
controls = {"enabled": enabled, "area": area}
|
||||
self._exploration_controls[key] = controls
|
||||
enabled, area = controls["enabled"], controls["area"]
|
||||
enabled.setCheckState(C.Qt.CheckState.Checked if row["enabled"] else C.Qt.CheckState.Unchecked)
|
||||
enabled.setData(C.Qt.ItemDataRole.UserRole, key)
|
||||
self.exploration_table.setItem(index, 0, enabled)
|
||||
if area.count():
|
||||
position = area.findData(row["area"])
|
||||
area.setCurrentIndex(position if position >= 0 else -1)
|
||||
self.exploration_table.setCellWidget(index, 2, area)
|
||||
monsters = "、".join(self.catalog.monster_label(mon) for mid in row["monster_ids"]
|
||||
if (mon := self.engine.snapshot.monsters.get(mid)) is not None) or "—"
|
||||
values = [key, "", row["state"], duration(row["remaining"]) if row["remaining"] is not None else "—",
|
||||
monsters, f"{row['cost_ti']} / {duration(row['cost_time'])}", row["reason"]]
|
||||
for column, text in enumerate(values, 1):
|
||||
if column == 2:
|
||||
continue
|
||||
cell = self.exploration_table.item(index, column) or W.QTableWidgetItem()
|
||||
cell.setText(text)
|
||||
cell.setToolTip(text)
|
||||
self.exploration_table.setItem(index, column, cell)
|
||||
for key in set(self._exploration_controls) - active:
|
||||
self._exploration_controls.pop(key)
|
||||
self.exploration_summary.setText(f"已有 {len(rows)} 支探险队;启用 {sum(row['enabled'] for row in rows)} 支")
|
||||
finally:
|
||||
self._exploration_rendering = False
|
||||
|
||||
def apply_explore_policy(self, policy):
|
||||
"""Apply imported/saved plain configuration before rendering rows."""
|
||||
if isinstance(policy, dict):
|
||||
policy = ExplorePolicy.from_dict(policy)
|
||||
self.explore_enabled.setChecked(policy.enabled)
|
||||
self.explore_reserve_ti.setValue(policy.reserve_ti)
|
||||
self.engine.explore_policy = policy
|
||||
+3
-26
@@ -35,8 +35,6 @@ from .table_widgets import table_item
|
||||
from .stage_cache import StageCache
|
||||
from .drop_statistics import SweepStatistics
|
||||
from .statistics_gui import StatisticsPage
|
||||
from .exploration_gui import ExplorationPages
|
||||
from .exploration import ExplorePolicy
|
||||
|
||||
APP_VERSION = "1.2.0.dev1"
|
||||
GAME_VERSION = "1.9.68"
|
||||
@@ -114,7 +112,7 @@ def fill_table(widget, rows, sorting=True):
|
||||
widget.setSortingEnabled(sorting)
|
||||
|
||||
|
||||
class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
|
||||
class Window(ProgressionPages, ActivityPages, W.QMainWindow):
|
||||
network_event = C.Signal(object)
|
||||
profile_changed = C.Signal(str)
|
||||
|
||||
@@ -176,7 +174,6 @@ class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
|
||||
self.egg_rules = {}
|
||||
self.feed_targets = {}
|
||||
self.gift_targets = {}
|
||||
self.breakthrough_targets = {}
|
||||
self.gift_items = {}
|
||||
central = W.QWidget()
|
||||
layout = W.QVBoxLayout(central)
|
||||
@@ -295,7 +292,6 @@ class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
|
||||
monster_layout.addLayout(monster_tools)
|
||||
detail_note = W.QLabel("勾选“喂养目标”并设置优先级(数字小的先喂);当前突破上限满级后转下一个目标。参考属性含等级、潜能、好感和升星,不含装备、羁绊或全局加成。")
|
||||
detail_note.setWordWrap(True)
|
||||
detail_note.setText(detail_note.text() + "\n自动突破按突破优先级处理:四项潜能达到当前阶段上限且材料充足才执行;不满足时跳过。")
|
||||
monster_layout.addWidget(detail_note)
|
||||
self.ranch_view = self.monsters
|
||||
monster_layout.addWidget(self.ranch_view)
|
||||
@@ -303,7 +299,6 @@ class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
|
||||
self.monsters.monster_activated.connect(self.show_monster_detail)
|
||||
self.monsters.feed_changed.connect(self.monster_feed_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.tabs.addTab(self.room_page, "牧场")
|
||||
self.policy_page = self.policy_tab(embedded=True)
|
||||
@@ -314,7 +309,6 @@ class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
|
||||
self.yield_tab()
|
||||
self.quests_tab()
|
||||
self.maps_tab()
|
||||
self.exploration_tab()
|
||||
self.analysis_page = StatisticsPage(self.catalog)
|
||||
self.analysis_page.refresh_requested.connect(self.refresh_analysis)
|
||||
self.tabs.addTab(self.analysis_page, "数据分析")
|
||||
@@ -323,7 +317,7 @@ class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
|
||||
self.tabs.addTab(self.plans, "执行计划")
|
||||
order = [self.tabs.widget(0), self.slot_page, self.inventory_tabs, self.room_page,
|
||||
self.daily_page, self.automation_page, self.progression_page, self.battle_records_page, self.gift_page,
|
||||
self.quests_table.parentWidget(), self.map_page, self.exploration_page, self.analysis_page,
|
||||
self.quests_table.parentWidget(), self.map_page, self.analysis_page,
|
||||
self.plans, self.yields.parentWidget()]
|
||||
for page in order:
|
||||
self.tabs.addTab(page, self.tabs.tabText(self.tabs.indexOf(page)))
|
||||
@@ -806,14 +800,6 @@ class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
|
||||
self.settings_changed()
|
||||
self.update_gift_status()
|
||||
|
||||
def monster_breakthrough_changed(self, mid, enabled, priority):
|
||||
if enabled:
|
||||
self.breakthrough_targets[mid] = priority
|
||||
self.feed.setChecked(True)
|
||||
else:
|
||||
self.breakthrough_targets.pop(mid, None)
|
||||
self.settings_changed()
|
||||
|
||||
def add_egg_rule(self):
|
||||
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}
|
||||
@@ -1254,7 +1240,6 @@ class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
|
||||
policies = {key: cls(**value[key]) for key, cls in (("policy", Policy), ("quest_policy", QuestPolicy),
|
||||
("daily_policy", DailyPolicy), ("sweep_policy", SweepPolicy))}
|
||||
policies["progression_policy"] = checked_progression_policy(value.get("progression_policy", {}))
|
||||
policies["explore_policy"] = ExplorePolicy.from_dict(value.get("explore_policy", {}))
|
||||
if self.busy:
|
||||
self.pending_policy = policies
|
||||
return False
|
||||
@@ -1389,8 +1374,6 @@ class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
|
||||
self.prepared_views.drop_statistics = value
|
||||
self.analysis_page.set_data(self.catalog, value)
|
||||
self.report("已从本地刷新掉落统计")
|
||||
elif kind == "exploration_view":
|
||||
self.render_exploration(value)
|
||||
elif kind == "progression_view":
|
||||
self.accept_progression_views(value)
|
||||
self.render_progression()
|
||||
@@ -1525,7 +1508,6 @@ class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
|
||||
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_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())
|
||||
|
||||
def read_quest_policy(self):
|
||||
@@ -1738,8 +1720,6 @@ class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
|
||||
self.render_egg_rules()
|
||||
elif page is self.quests_table.parentWidget():
|
||||
self.render_quests(snapshot)
|
||||
elif page is self.exploration_page:
|
||||
self.refresh_exploration()
|
||||
elif page is self.map_page:
|
||||
self.render_maps()
|
||||
elif page is self.analysis_page:
|
||||
@@ -1771,7 +1751,7 @@ class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
|
||||
if self.monster_data_pending:
|
||||
self.monster_render_timer.stop()
|
||||
self.monster_data_pending = False
|
||||
self.monsters.set_data(snapshot, views.monsters, self.feed_targets, self.gift_targets, self.breakthrough_targets)
|
||||
self.monsters.set_data(snapshot, views.monsters, self.feed_targets, self.gift_targets)
|
||||
else:
|
||||
self.request_monster_views(snapshot)
|
||||
|
||||
@@ -1989,7 +1969,6 @@ class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
|
||||
|
||||
def config_value(self):
|
||||
return {"policy": asdict(self.read_policy()), "quest_policy": asdict(self.read_quest_policy()),
|
||||
"explore_policy": self.read_explore_policy().to_dict(),
|
||||
"daily_policy": asdict(self.read_daily_policy()), "sweep_policy": asdict(self.read_sweep_policy()),
|
||||
"progression_policy": asdict(self.read_progression_policy()),
|
||||
"overrides": copy.deepcopy(self.catalog.overrides),
|
||||
@@ -2150,13 +2129,11 @@ class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
|
||||
if not self.feed_targets and policy.feed_target:
|
||||
self.feed_targets[str(policy.feed_target)] = 1
|
||||
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_enabled.setChecked(policy.gift_enabled)
|
||||
self.gift_liked_only.setChecked(policy.gift_liked_only)
|
||||
self.gift_auto_representative.setChecked(policy.gift_auto_representative)
|
||||
self.keep_better_quality.setChecked(policy.keep_better_quality)
|
||||
self.apply_explore_policy(ExplorePolicy.from_dict(value.get("explore_policy", {})))
|
||||
blocker = C.QSignalBlocker(self.interval)
|
||||
self.interval.setCurrentIndex(max(0, self.interval.findData(value.get("interval", 30))))
|
||||
del blocker
|
||||
|
||||
@@ -258,15 +258,12 @@ class EggRule:
|
||||
refill_below: int = 1
|
||||
refill_target: int = 10
|
||||
market_id: str = ""
|
||||
keep_count: int = 1
|
||||
|
||||
def __post_init__(self):
|
||||
if self.action not in ("sell", "feed", "keep") or not 1 <= self.priority <= 999:
|
||||
raise ValueError("魔物蛋规则的优先级或孵化后去向无效")
|
||||
if not 0 <= self.refill_below <= 1000 or not max(1, self.refill_below) <= self.refill_target <= 1000:
|
||||
raise ValueError("补货目标不能低于补货下限,0下限表示不自动补货")
|
||||
if not 0 <= self.keep_count <= 1000:
|
||||
raise ValueError("牧场保留数量须为0至1000")
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -306,13 +303,11 @@ class Policy:
|
||||
gift_liked_only: bool = True
|
||||
gift_auto_representative: bool = False
|
||||
keep_better_quality: bool = False
|
||||
breakthrough_targets: dict[str, int] = field(default_factory=dict)
|
||||
|
||||
def __post_init__(self):
|
||||
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.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 = {str(int(key)): int(priority) for key, priority in self.breakthrough_targets.items() if int(key) > 0 and 1 <= int(priority) <= 999}
|
||||
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()}
|
||||
|
||||
@@ -353,7 +348,7 @@ class Planner:
|
||||
quality = math.ceil(sum(qualities) / 4)
|
||||
if policy.keep_better_quality or policy.gift_auto_representative:
|
||||
representative = self.cultivation.select(snapshot).get(str(mon.get("typeId")))
|
||||
if policy.gift_auto_representative and representative and int(representative["id"]) == int(mon["id"]):
|
||||
if representative and int(representative["id"]) == int(mon["id"]):
|
||||
return "同种魔物的唯一培养代表(等级、好感、资质优先)"
|
||||
if policy.keep_better_quality:
|
||||
if representative is None:
|
||||
@@ -363,15 +358,6 @@ class Planner:
|
||||
return "同种培养代表的资质尚未同步,暂时保留"
|
||||
if candidate is not None and candidate > baseline + 1e-8:
|
||||
return f"综合成长资质高于同种培养代表 #{representative['id']}({candidate:.1%} > {baseline:.1%})"
|
||||
if policy.manual_eggs:
|
||||
rule = policy.egg_rules.get(str(mon.get("typeId")), {})
|
||||
quota = int(rule.get("keep_count", 1))
|
||||
if quota > 0 and (rule.get("action") == "keep" or policy.keep_better_quality):
|
||||
ranch = [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"])]
|
||||
if len(ranch) < quota:
|
||||
return f"同种魔物保留数量 {len(ranch) + 1} / {quota}"
|
||||
if policy.protect_quality == 6:
|
||||
return "攻/防/生命/敏捷四项资质全S(4S)" if all(q == 4 for q in qualities) else ""
|
||||
if quality >= policy.protect_quality:
|
||||
@@ -417,22 +403,6 @@ class Planner:
|
||||
target, reason = self.feeding_target(snapshot, policy)
|
||||
return target is not None, reason
|
||||
|
||||
def same_species_feeding_target(self, mon, snapshot, policy):
|
||||
"""Use an inferior duplicate to raise its ranch species before others."""
|
||||
if mon.get("process") != 3 or policy.egg_rules.get(str(mon.get("typeId")), {}).get("action") != "feed":
|
||||
return None
|
||||
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"])]
|
||||
candidates.sort(key=lambda row: (int(policy.feed_targets.get(str(row["id"]), 9999)),
|
||||
-int(row.get("potentialLevel") or 0), -int(row.get("level") or 1), int(row["id"])))
|
||||
for target in candidates:
|
||||
cap = self.catalog.max_level(target)
|
||||
if int(target.get("potentialLevel") or 0) >= int(self.catalog.data.get("potential_info", {}).get("maxPotentialLevel") or 0):
|
||||
continue
|
||||
if cap is not None and int(target.get("level") or 1) < cap and self.catalog.feed_remaining(target, cap) != 0:
|
||||
return target
|
||||
return None
|
||||
|
||||
def available_eggs(self, snapshot, policy):
|
||||
reserves = dict(policy.reserved_eggs)
|
||||
result = []
|
||||
@@ -572,8 +542,7 @@ class Planner:
|
||||
else:
|
||||
self.notes.append(f"{name} 等待收取:牧场没有空位")
|
||||
elif disposition == "feed" and mon.get("process") == 3:
|
||||
target = self.same_species_feeding_target(mon, snapshot, policy)
|
||||
target, reason = (target, f"优先培养未满经验的同种魔物 #{target['id']}") if target else self.feeding_target(snapshot, policy)
|
||||
target, reason = self.feeding_target(snapshot, policy)
|
||||
if target:
|
||||
actions.append(Action("feed", f"{name} #{mid} → 喂养 #{target['id']}", "monsterService/monsterIntensify", {"targetId": int(target["id"]), "foods": [mid]}))
|
||||
else:
|
||||
@@ -616,11 +585,6 @@ class Planner:
|
||||
|
||||
def batch_actions(self, actions, snapshot, policy):
|
||||
monsters = snapshot.monsters
|
||||
feeds = [a for a in actions if a.kind == "feed"]
|
||||
if feeds:
|
||||
# Feeding changes its target's level; later targets need a fresh
|
||||
# server read rather than a stale batch computed in this pass.
|
||||
actions = [a for a in actions if a.kind != "feed"] + feeds
|
||||
collects = [a for a in actions if a.kind == "collect"]
|
||||
if collects:
|
||||
rooms = {}
|
||||
|
||||
@@ -7,7 +7,6 @@ from .daily import DailyPolicy
|
||||
from .quests import QuestPolicy
|
||||
from .sweeping import SweepPolicy
|
||||
from .progression import ProgressionPolicy
|
||||
from .exploration import ExplorePolicy
|
||||
|
||||
FORMAT = "ranch-helper-policies"
|
||||
VERSION = 1
|
||||
@@ -59,7 +58,7 @@ def portable_policy(policy, snapshot=None):
|
||||
value["feed_targets"] = {str(value["feed_target"]): 1}
|
||||
value["feed_target"] = value["room_id"] = 0
|
||||
targets = {}
|
||||
for kind, field in (("feed", "feed_targets"), ("gift", "gift_targets"), ("breakthrough", "breakthrough_targets")):
|
||||
for kind, field in (("feed", "feed_targets"), ("gift", "gift_targets")):
|
||||
targets[kind] = []
|
||||
for key, priority in sorted(value.pop(field).items(), key=lambda pair: pair[1]):
|
||||
mon = snapshot.monsters.get(int(key)) if snapshot else None
|
||||
@@ -74,8 +73,8 @@ def import_policy(value, snapshot=None):
|
||||
policy = checked_policy(Policy, value["policy"])
|
||||
policy.feed_target = policy.room_id = 0
|
||||
if snapshot:
|
||||
used = {"feed": set(), "gift": set(), "breakthrough": set()}
|
||||
for kind, field in (("feed", "feed_targets"), ("gift", "gift_targets"), ("breakthrough", "breakthrough_targets")):
|
||||
used = {"feed": set(), "gift": set()}
|
||||
for kind, field in (("feed", "feed_targets"), ("gift", "gift_targets")):
|
||||
result = {}
|
||||
targets = value.get("targetSpecies", {})
|
||||
if not isinstance(targets, dict) or not isinstance(targets.get(kind, []), list):
|
||||
@@ -91,7 +90,7 @@ def import_policy(value, snapshot=None):
|
||||
break
|
||||
setattr(policy, field, result)
|
||||
else:
|
||||
policy.feed_targets, policy.gift_targets, policy.breakthrough_targets = {}, {}, {}
|
||||
policy.feed_targets, policy.gift_targets = {}, {}
|
||||
return policy
|
||||
|
||||
|
||||
@@ -107,7 +106,6 @@ def portable_config(config, snapshot=None):
|
||||
for key, cls in (("quest_policy", QuestPolicy), ("daily_policy", DailyPolicy), ("sweep_policy", SweepPolicy)):
|
||||
value[key] = asdict(cls(**config.get(key, {})))
|
||||
value["progression_policy"] = asdict(checked_progression_policy(config.get("progression_policy", {})))
|
||||
value["explore_policy"] = ExplorePolicy.from_dict(config.get("explore_policy", {})).to_dict()
|
||||
value["interval"] = config.get("interval", 30)
|
||||
value["overrides"] = copy.deepcopy(config.get("overrides", {}))
|
||||
value["yield_stars"] = list(config.get("yield_stars", [1, 2, 3, 4, 5]))
|
||||
@@ -129,8 +127,6 @@ def import_config(value, snapshot=None):
|
||||
# An additive section preserves schema-2 compatibility with older bundles.
|
||||
if "progression_policy" in value:
|
||||
config["progression_policy"] = asdict(checked_progression_policy(value["progression_policy"]))
|
||||
if "explore_policy" in value:
|
||||
config["explore_policy"] = ExplorePolicy.from_dict(value["explore_policy"]).to_dict()
|
||||
interval = value.get("interval", 30)
|
||||
if interval not in (30, 60, 120, 300):
|
||||
raise ValueError("刷新间隔须为30、60、120或300秒")
|
||||
|
||||
@@ -8,7 +8,7 @@ def monster_rows(catalog, snapshot, managed, room_id=0):
|
||||
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)}",
|
||||
"系统锁定" 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"]
|
||||
if not room_id or m.get("process") == 3 and int(m.get("roomId") or 0) == room_id]
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ from .policy_io import checked_progression_policy
|
||||
from .progression import ProgressionPolicy
|
||||
from .table_widgets import set_value, table_item
|
||||
from .battle_messages import battle_message
|
||||
from .battle_record_display import RECORD_KINDS, record_context, record_detail, record_outcome, record_subject, record_team, reward_display
|
||||
|
||||
|
||||
CATEGORIES = {"mainline": "主线", "sidequest": "支线", "commission": "委托", "event": "活动(暂不自动)",
|
||||
@@ -19,7 +18,6 @@ CATEGORIES = {"mainline": "主线", "sidequest": "支线", "commission": "委托
|
||||
BATTLE_KINDS = {"mainline": "主线战斗", "sidequest": "支线战斗", "commission": "委托战斗",
|
||||
"battle": "普通战斗", "map_battle": "地图战斗", "sweep": "扫荡", "map_reward_event": "地图奖励事件",
|
||||
"ordinary_stage": "普通关卡战斗", "task_battle": "任务战斗", "task_pass_stage": "任务通关战斗", "unknown": "其他 / 未知"}
|
||||
BATTLE_KINDS.update({key: value for key, value in RECORD_KINDS.items() if key not in BATTLE_KINDS})
|
||||
BATTLE_ALIASES = {"task": "task_battle", "passStage": "task_pass_stage", "event": "map_reward_event",
|
||||
"reward_event": "map_reward_event", "normal": "battle"}
|
||||
BATTLE_MODES = {"original": "原版运行时(以能力检查为准)", "experimental": "实验模拟(近似,未完整验证)"}
|
||||
@@ -28,6 +26,10 @@ STATES = {"available": "可接取", "unaccepted": "未接取", "active": "进行
|
||||
"received": "进行中", "unlocked": "已解锁 / 待接取", "locked": "未解锁", "finished": "已完成",
|
||||
"ready_to_reward": "待领取任务奖励", "blocked": "受阻", "unsupported": "暂不支持", "unknown": "未知"}
|
||||
CHINA_TIME = timezone(timedelta(hours=8))
|
||||
OUTCOMES = {"win": "胜利", "loss": "打不过", "unsupported": "暂不支持", "event": "地图奖励事件",
|
||||
"completed": "已完成", "cancelled": "已取消", "timeout": "超时", "unknown": "结果待核对"}
|
||||
|
||||
|
||||
def category(value):
|
||||
return {"main": "mainline", "side": "sidequest", "sidequests": "sidequest", "commissions": "commission",
|
||||
"主线": "mainline", "支线": "sidequest", "委托": "commission"}.get(value, value) if isinstance(value, str) else "unknown"
|
||||
@@ -55,7 +57,6 @@ def prepare_progression_views(engine, *, tasks=True, records=True):
|
||||
record_reader = getattr(engine, "progression_records", None)
|
||||
task_data = task_reader() if tasks and callable(task_reader) else []
|
||||
record_data = record_reader() if records and callable(record_reader) else []
|
||||
record_data_source = getattr(engine, "game_data", None)
|
||||
for name, rows in (("progression_rows", task_data), ("progression_records", record_data)):
|
||||
if not isinstance(rows, list) or any(not isinstance(row, dict) for row in rows):
|
||||
raise TypeError(name + "() 必须返回 list[dict]")
|
||||
@@ -95,17 +96,21 @@ def prepare_progression_views(engine, *, tasks=True, records=True):
|
||||
stamp = row.get("finished_at") or row.get("started_at") or row.get("timestamp", row.get("time", row.get("at")))
|
||||
if type(stamp) in (int, float) and 0 <= stamp <= 253402271999:
|
||||
stamp = datetime.fromtimestamp(stamp, CHINA_TIME).strftime("%Y-%m-%d %H:%M:%S")
|
||||
values = [display(stamp), record_context(row, kind),
|
||||
record_subject(row, record_data_source), record_team(row.get("team")), record_outcome(row), record_detail(row)]
|
||||
outcome = row.get("outcome") or row.get("status") or row.get("phase") or row.get("result")
|
||||
if isinstance(outcome, dict):
|
||||
outcome = outcome.get("outcome") or outcome.get("status")
|
||||
outcome = display(outcome, "未确认")
|
||||
values = [display(stamp), BATTLE_KINDS.get(kind, display(raw_kind)),
|
||||
display(row.get("name") or row.get("task_type_id") or row.get("stage_id") or row.get("stage") or row.get("description")),
|
||||
display(row.get("team")), OUTCOMES.get(outcome, outcome),
|
||||
battle_message(display(row.get("blocked_reason") or row.get("block_reason") or row.get("message") or row.get("reason")))]
|
||||
mode = row.get("battle_mode") or row.get("execution_mode")
|
||||
mode = mode if isinstance(mode, str) else None
|
||||
is_combat = row.get("outcome") != "local"
|
||||
mode_text = BATTLE_MODES.get(mode, "记录未标明") if is_combat else "本地剧情处理(未运行战斗)"
|
||||
if is_combat and mode in ("experimental", "original"):
|
||||
mode_text = "内置模拟战斗(结果近似,未完整验证)" if mode == "experimental" else "原版战斗运行时"
|
||||
if mode == "experimental":
|
||||
values[4] += "(实验近似)"
|
||||
detail = "\n".join(("时间(北京时间):" + values[0], "上下文:" + values[1] + ";任务 / 地图:" + values[2],
|
||||
"战斗模式:" + mode_text, "队伍:" + values[3] + ";结果:" + values[4],
|
||||
"详情 / 阻塞原因:" + values[5], "奖励:" + reward_display(row.get("reward"), getattr(engine, "catalog", None))))
|
||||
"战斗模式:" + BATTLE_MODES.get(mode, "记录未标明"),
|
||||
"队伍:" + values[3] + ";结果:" + values[4], "详情 / 阻塞原因:" + values[5], "奖励:" + display(row.get("reward"))))
|
||||
record_rows.append({"key": str(index), "category": kind if kind in BATTLE_KINDS else "unknown", "values": values,
|
||||
"detail": detail, "search": " ".join(values).casefold()})
|
||||
message = "" if callable(task_reader) else "当前引擎尚未提供任务读取;任务只展示,不自动推进"
|
||||
|
||||
@@ -11,16 +11,15 @@ from .table_widgets import CenteredCheckBox, TreeItem, bind_controls, set_value
|
||||
class RanchView(W.QTreeWidget):
|
||||
feed_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)
|
||||
|
||||
def __init__(self, catalog):
|
||||
super().__init__()
|
||||
self.catalog = catalog
|
||||
self.setHeaderLabels(["牧场 / 魔物ID", "名称", "星", "等级 / 当前上限", "资质 攻/防/血/敏", "位置", "锁定", "管理范围",
|
||||
"喂养目标", "喂养优先级", "自动突破", "突破优先级", "突破等级", "参考攻击", "参考防御", "参考生命", "参考敏捷", "好感 / 当前上限", "喜欢的物品", "赠礼", "赠礼优先级"])
|
||||
"喂养目标", "喂养优先级", "突破等级", "参考攻击", "参考防御", "参考生命", "参考敏捷", "好感 / 当前上限", "喜欢的物品", "赠礼", "赠礼优先级"])
|
||||
self.header().setSectionResizeMode(W.QHeaderView.ResizeMode.Interactive)
|
||||
for column, width in enumerate((260, 140, 45, 120, 150, 140, 80, 130, 90, 110, 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.setSelectionMode(W.QAbstractItemView.SelectionMode.ExtendedSelection)
|
||||
self.setSelectionBehavior(W.QAbstractItemView.SelectionBehavior.SelectRows)
|
||||
@@ -51,12 +50,11 @@ class RanchView(W.QTreeWidget):
|
||||
return "incubator"
|
||||
return f"room:{int(mon.get('roomId') or 0)}"
|
||||
|
||||
def set_data(self, snapshot, rows, feed_targets, gift_targets, breakthrough_targets=None):
|
||||
breakthrough_targets = breakthrough_targets or {}
|
||||
def set_data(self, snapshot, rows, feed_targets, gift_targets):
|
||||
monsters = snapshot.raw["monsters"]
|
||||
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]
|
||||
signature = (entries, snapshot.raw["rooms"], feed_targets, gift_targets, breakthrough_targets, self.grouped, self.room_id)
|
||||
signature = (entries, snapshot.raw["rooms"], feed_targets, gift_targets, self.grouped, self.room_id)
|
||||
if self.render_signature == signature:
|
||||
return
|
||||
self.row_batch.stop()
|
||||
@@ -114,7 +112,7 @@ class RanchView(W.QTreeWidget):
|
||||
item = TreeItem(parent if parent is not None else self)
|
||||
item.setData(0, C.Qt.ItemDataRole.UserRole, mid)
|
||||
self.monster_items[mid] = item
|
||||
for check_column, priority_column, signal in ((8, 9, self.feed_changed), (10, 11, self.breakthrough_changed), (19, 20, self.gift_changed)):
|
||||
for check_column, priority_column, signal in ((8, 9, self.feed_changed), (17, 18, self.gift_changed)):
|
||||
check, priority = CenteredCheckBox(), IntegerInput()
|
||||
priority.setRange(1, 999)
|
||||
def changed(*args, check=check, priority=priority, signal=signal, mid=mid):
|
||||
@@ -128,8 +126,8 @@ class RanchView(W.QTreeWidget):
|
||||
for column, value in enumerate(values):
|
||||
if item.data(column, C.Qt.ItemDataRole.DisplayRole) != value:
|
||||
set_value(item, column, value)
|
||||
item.setToolTip(18, str(values[18]))
|
||||
for check_column, priority_column, targets in ((8, 9, feed_targets), (10, 11, breakthrough_targets), (19, 20, gift_targets)):
|
||||
item.setToolTip(16, str(values[16]))
|
||||
for check_column, priority_column, targets in ((8, 9, feed_targets), (17, 18, gift_targets)):
|
||||
check, priority = self.itemWidget(item, check_column), self.itemWidget(item, priority_column)
|
||||
blockers = [C.QSignalBlocker(check), C.QSignalBlocker(priority)]
|
||||
check.setChecked(str(mid) in targets)
|
||||
@@ -137,7 +135,7 @@ class RanchView(W.QTreeWidget):
|
||||
priority.setEnabled(mon.get("process") == 3)
|
||||
if not priority.hasFocus():
|
||||
priority.setValue(targets.get(str(mid), 100))
|
||||
bind_controls(self, item, {column: self.itemWidget(item, column) for column in (8, 9, 10, 11, 19, 20)})
|
||||
bind_controls(self, item, {column: self.itemWidget(item, column) for column in (8, 9, 17, 18)})
|
||||
|
||||
def finish():
|
||||
self.render_signature = copy.deepcopy(signature)
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
from copy import deepcopy
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
|
||||
from ranch_assistant.game_data import load_progression_data
|
||||
from ranch_assistant.progression_gui import prepare_progression_views
|
||||
|
||||
|
||||
def views(records, data=None):
|
||||
engine = SimpleNamespace(snapshot=None, game_data=data, catalog=None,
|
||||
progression_rows=lambda: [], progression_records=lambda: records)
|
||||
return prepare_progression_views(engine).records
|
||||
|
||||
|
||||
class BattleRecordDisplayTests(unittest.TestCase):
|
||||
def test_local_story_uses_real_task_name_without_fake_combat_annotation(self):
|
||||
records = [
|
||||
{"kind": "progression_local_step", "battle_kind": "passStage", "task_type_id": "1002003",
|
||||
"step_number": 1, "team": "teamA", "outcome": "local", "battle_mode": "experimental",
|
||||
"message": "已保存普通剧情的本地检查点"},
|
||||
{"kind": "progression_dialogue", "task_type_id": "2001006", "step_number": 2,
|
||||
"team": "teamA", "outcome": "local", "battle_mode": "experimental"},
|
||||
]
|
||||
original = deepcopy(records)
|
||||
rows = views(records, load_progression_data())
|
||||
self.assertEqual(rows[0]["values"][2], "为了友情1 #1002003;莉安湖水猫小径(2-3) #0203,难度 1")
|
||||
self.assertEqual(rows[0]["values"][3], "战队A")
|
||||
self.assertEqual(rows[0]["values"][4], "剧情已推进")
|
||||
self.assertEqual(rows[0]["values"][5], "已保存普通剧情的本地检查点")
|
||||
self.assertEqual(rows[1]["values"][2], "逃跑的雷素 #2001006")
|
||||
self.assertEqual(rows[1]["values"][1], "剧情 · NPC 对话")
|
||||
for row in rows:
|
||||
self.assertNotIn("近似", row["values"][4])
|
||||
self.assertIn("本地剧情处理(未运行战斗)", row["detail"])
|
||||
self.assertEqual(records, original)
|
||||
|
||||
def test_simulation_sweep_event_and_fallbacks_are_distinct(self):
|
||||
data = SimpleNamespace(task=lambda key: None, stage=lambda key:
|
||||
{"name": "测试关卡", "tagname": "9-20"} if key == "0920" else None)
|
||||
rows = views([
|
||||
{"battle_kind": "ordinary_stage", "stage_id": "0920", "difficulty": 2,
|
||||
"outcome": "win", "battle_mode": "experimental", "team": "teamB"},
|
||||
{"battle_kind": "sweep", "stage_id": "missing", "difficulty": 3,
|
||||
"outcome": "sweep", "battle_mode": "experimental"},
|
||||
{"battle_kind": "map_reward_event", "stage_id": "0920", "outcome": "event"},
|
||||
{"battle_kind": "ordinary_stage", "stage_id": "0920", "outcome": "local"},
|
||||
], data)
|
||||
self.assertEqual(rows[0]["values"][2:5], ["测试关卡(9-20) #0920,难度 2", "战队B", "战斗胜利(模拟近似)"])
|
||||
self.assertEqual(rows[1]["values"][2], "未知名称关卡 #missing,难度 3")
|
||||
self.assertEqual(rows[1]["values"][4], "扫荡已完成(模拟近似)")
|
||||
self.assertEqual(rows[2]["values"][4], "已获得地图事件奖励")
|
||||
self.assertEqual(rows[3]["values"][4], "剧情已推进")
|
||||
self.assertNotIn("battle_mode", rows[0]["detail"])
|
||||
|
||||
def test_unknown_internal_context_does_not_leak_into_cells(self):
|
||||
row = views([{"kind": "future_internal_operation", "outcome": "done"}])[0]
|
||||
self.assertEqual(row["values"][1], "其他 / 未知")
|
||||
self.assertEqual(row["values"][4], "已完成")
|
||||
self.assertEqual(row["category"], "unknown")
|
||||
|
||||
def test_task_fallback_and_rewards_do_not_expose_raw_json(self):
|
||||
data = SimpleNamespace(task=lambda key: None, stage=lambda key: None)
|
||||
rows = views([{"battle_kind": "task", "task_type_id": "999", "outcome": "completed",
|
||||
"reward": {"money": 12, "exp": 3, "ke": 0, "items": [{"typeId": 30001, "num": 2}]}}], data)
|
||||
self.assertEqual(rows[0]["values"][2], "未知名称任务 #999")
|
||||
self.assertEqual(rows[0]["values"][4], "已完成")
|
||||
self.assertIn("奖励:金币 12;经验 3;物品 #30001 ×2", rows[0]["detail"])
|
||||
self.assertNotIn('{"money"', rows[0]["detail"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,118 +0,0 @@
|
||||
import copy
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from ranch_assistant.breakthrough import BreakthroughPlanner, PATH, plan_breakthrough
|
||||
from ranch_assistant.model import Catalog, Policy, Snapshot
|
||||
|
||||
|
||||
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": 4}], "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_blocks_even_at_ordinary_level_cap(self):
|
||||
self.snapshot.monsters[900].update(pAtk=3, level=10)
|
||||
self.assertIsNone(self.planner.plan(self.snapshot, self.policy))
|
||||
self.assertIn("攻击 3/4", self.planner.notes[0])
|
||||
|
||||
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_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_use_first_stack_id_and_total_stock(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"], [600])
|
||||
|
||||
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.policy.feed_targets = {"901": 2, "900": 1}
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy).payload["monId"], 900)
|
||||
|
||||
def test_independent_targets_replace_feed_targets(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)
|
||||
|
||||
def test_non_ranch_disabled_and_maximum_level_do_not_plan(self):
|
||||
for process in (1, 2):
|
||||
self.snapshot.monsters[900]["process"] = process
|
||||
self.assertIsNone(self.planner.plan(self.snapshot, self.policy))
|
||||
self.snapshot.monsters[900].update(process=3, potentialLevel=7)
|
||||
self.assertIsNone(self.planner.plan(self.snapshot, self.policy))
|
||||
self.assertIsNone(self.planner.plan(self.snapshot, self.policy, enabled=False))
|
||||
|
||||
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):
|
||||
# 1-star job 5, level 1->2; level 2 requires lv1 x4 + lv2 x1.
|
||||
self.snapshot.monsters[900].update(potentialLevel=2, pAtk=16, pDef=30, 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_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()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -13,7 +13,7 @@ from ranch_assistant.cultivation import CultivationSelector, growth_score
|
||||
from ranch_assistant.engine import Engine, demo_snapshot
|
||||
from ranch_assistant.gifts import GiftPlanner
|
||||
from ranch_assistant.gui import Window
|
||||
from ranch_assistant.model import Catalog, EggRule, Planner, Policy, Snapshot
|
||||
from ranch_assistant.model import Catalog, Planner, Policy, Snapshot
|
||||
from ranch_assistant.policy_io import import_config, portable_config
|
||||
from ranch_assistant.tests.test_core import workspace_temp
|
||||
from ranch_assistant.tests.test_accounts import fake_client, role_snapshot
|
||||
@@ -138,52 +138,6 @@ class CultivationTests(unittest.TestCase):
|
||||
mon["gHp"] = self.catalog.monster(1001010)["hp_grow_max"]
|
||||
self.assertAlmostEqual(growth_score(self.catalog, mon), .625, places=3)
|
||||
|
||||
def test_per_species_keep_quota_does_not_discard_better_replacement(self):
|
||||
representative = monster(self.catalog, 1, level=50, scale=.3)
|
||||
representative["lock"] = 1
|
||||
better = monster(self.catalog, 2, scale=.8, process=2)
|
||||
self.snapshot.raw["monsters"] = [representative, better]
|
||||
rule = asdict(EggRule(enabled=True, action="feed", keep_count=1))
|
||||
policy = Policy(manual_eggs=True, protect_star=6, protect_quality=5,
|
||||
keep_better_quality=True, egg_rules={"1001010": rule})
|
||||
planner = Planner(self.catalog)
|
||||
self.assertIn("高于", planner.protection_reason(better, self.snapshot, policy))
|
||||
self.snapshot.raw["monsters"].append(monster(self.catalog, 3, scale=.2, process=2))
|
||||
self.assertEqual(planner.disposition(self.snapshot.monsters[3], self.snapshot, policy), "feed")
|
||||
|
||||
def test_keep_quota_defaults_to_one_and_can_keep_two(self):
|
||||
hatched = monster(self.catalog, 1, process=2)
|
||||
self.snapshot.raw["monsters"] = [hatched]
|
||||
planner = Planner(self.catalog)
|
||||
policy = Policy(manual_eggs=True, protect_star=6, protect_quality=5,
|
||||
egg_rules={"1001010": asdict(EggRule(enabled=True, action="keep"))})
|
||||
self.assertIn("1 / 1", planner.protection_reason(hatched, self.snapshot, policy))
|
||||
policy.egg_rules["1001010"]["keep_count"] = 2
|
||||
self.snapshot.raw["monsters"].append(monster(self.catalog, 2, process=3))
|
||||
self.assertIn("2 / 2", planner.protection_reason(hatched, self.snapshot, policy))
|
||||
self.snapshot.raw["monsters"].append(monster(self.catalog, 3, process=3))
|
||||
self.assertEqual(planner.disposition(hatched, self.snapshot, policy), "keep")
|
||||
self.assertNotIn("保留数量", planner.protection_reason(hatched, self.snapshot, policy))
|
||||
|
||||
def test_inferior_duplicate_feeds_same_species_until_current_cap(self):
|
||||
target = monster(self.catalog, 10, level=9, scale=.8)
|
||||
target["potentialLevel"] = 1
|
||||
food = monster(self.catalog, 11, level=1, scale=.2)
|
||||
other = monster(self.catalog, 12, level=1, species=1002010)
|
||||
other["potentialLevel"] = 1
|
||||
self.snapshot.raw["monsters"] = [target, food, other]
|
||||
rule = asdict(EggRule(enabled=True, action="feed", keep_count=1))
|
||||
policy = Policy(manual_eggs=True, protect_star=6, protect_quality=5,
|
||||
egg_rules={"1001010": rule, "1002010": asdict(EggRule(enabled=True, action="feed"))},
|
||||
feed_targets={"12": 1})
|
||||
planner = Planner(self.catalog)
|
||||
planner.managed.update((11, 12))
|
||||
feeds = [action for action in planner.plan(self.snapshot, policy) if action.kind == "feed"]
|
||||
self.assertEqual(feeds[0].payload["targetId"], 10)
|
||||
target.update(level=10, potentialLevel=1, exp=self.catalog.data["monster_level"]["10"])
|
||||
target["level"] = 10
|
||||
self.assertIsNone(planner.same_species_feeding_target(food, self.snapshot, policy))
|
||||
|
||||
|
||||
class CultivationGuiTests(unittest.TestCase):
|
||||
@classmethod
|
||||
|
||||
@@ -224,7 +224,7 @@ class AnalysisGuiTests(unittest.TestCase):
|
||||
try:
|
||||
self.wait(lambda: not window.busy and window.engine.snapshot is not None)
|
||||
labels = [window.tabs.tabText(i) for i in range(window.tabs.count())]
|
||||
self.assertEqual(labels[labels.index("自动探险") + 1], "数据分析")
|
||||
self.assertEqual(labels[labels.index("自动扫荡") + 1], "数据分析")
|
||||
window.tabs.setCurrentWidget(window.analysis_page)
|
||||
self.wait(lambda: not window.analysis_page.row_batch.running)
|
||||
with patch.object(window.engine, "poll", side_effect=AssertionError("Analysis must not refresh game state")):
|
||||
|
||||
@@ -1,203 +0,0 @@
|
||||
"""Offline exploration policy, wire intent, state and native GUI tests."""
|
||||
import os
|
||||
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
|
||||
|
||||
from copy import deepcopy
|
||||
from dataclasses import asdict
|
||||
import json
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from ranch_assistant.exploration import ExplorePlanner, ExplorePolicy, ExploreTeamRule, load_exploration_areas
|
||||
from ranch_assistant.model import Catalog, Policy, Snapshot
|
||||
|
||||
|
||||
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):
|
||||
table = Catalog().monster("1001010")
|
||||
growth = {name: (table[name + "_grow_min"] + table[name + "_grow_max"]) / 2
|
||||
for name in ("atk", "def", "hp", "dex")}
|
||||
return {"id": mid, "typeId": "1001010", "level": level, "process": 3, "mode": 2,
|
||||
"gAtk": growth["atk"], "gDef": growth["def"], "gHp": growth["hp"], "gDex": growth["dex"], "lock": False, **changes}
|
||||
|
||||
|
||||
def make_snapshot(**changes):
|
||||
value = {"master": {"id": 11, "ti": 100}, "items": [], "stacks": [], "rooms": [], "teams": [],
|
||||
"monsters": [monster(1, 20), monster(2, 15), monster(3, 10), monster(4, 8), monster(5, 5)],
|
||||
"history": {"passTask": {"1001008": True}, "passStage": {"0101": True, "0102": True}},
|
||||
"exploreTeams": [{"id": 1, "status": 0, "area": "", "monsters": []}], **changes}
|
||||
return Snapshot(value, received_at=1_700_000_000)
|
||||
|
||||
|
||||
class ExplorationTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.catalog = Catalog()
|
||||
|
||||
def setUp(self):
|
||||
self.snapshot = make_snapshot()
|
||||
self.ranch = Policy(protect_star=6, protect_quality=5, keep_better_quality=False)
|
||||
self.policy = ExplorePolicy(True, {"1": ExploreTeamRule(True, "1")})
|
||||
self.planner = ExplorePlanner(self.catalog, areas=AREAS)
|
||||
|
||||
def test_real_static_data_is_complete_normal_team_only(self):
|
||||
areas = load_exploration_areas()
|
||||
self.assertEqual(len(areas), 22)
|
||||
self.assertEqual(areas["1"]["name"], "废弃矿洞")
|
||||
self.assertEqual(areas["1"]["level"], [4, 1, 1])
|
||||
self.assertTrue(all(row["team"] == "normal" and len(row["level"]) == 3 for row in areas.values()))
|
||||
|
||||
def test_policy_roundtrip_and_strict_validation(self):
|
||||
encoded = json.loads(json.dumps(self.policy.to_dict()))
|
||||
self.assertEqual(ExplorePolicy.from_dict(encoded), self.policy)
|
||||
for value in ({"enabled": 1}, {"reserve_ti": -1}, {"reserve_ti": True},
|
||||
{"teams": {"0": {"enabled": True, "area": "1"}}},
|
||||
{"teams": {"1": {"enabled": True, "area": "bad"}}},
|
||||
{"teams": {"1": {"enabled": True, "unknown": 1}}}):
|
||||
with self.subTest(value=value), self.assertRaises(ValueError):
|
||||
ExplorePolicy(**(asdict(ExplorePolicy()) | value))
|
||||
|
||||
def test_disabled_and_feature_gate_do_not_emit_requests(self):
|
||||
self.assertEqual(self.planner.plan(self.snapshot, ExplorePolicy(), self.ranch), [])
|
||||
self.snapshot.raw["history"]["passTask"] = {}
|
||||
action = self.planner.plan(self.snapshot, self.policy, self.ranch)[0]
|
||||
self.assertEqual(action.kind, "explore_blocked")
|
||||
self.assertIn("尚未解锁", action.description)
|
||||
|
||||
def test_start_payload_and_three_level_ordered_members(self):
|
||||
original = deepcopy(self.snapshot.raw)
|
||||
action = self.planner.plan(self.snapshot, self.policy, self.ranch)[0]
|
||||
self.assertEqual(action.kind, "explore_start")
|
||||
self.assertEqual(action.path, "exploreService/start")
|
||||
self.assertEqual(action.payload, {"exploreTeamId": 1, "monsters": [1, 2, 3], "area": "1"})
|
||||
self.assertEqual(self.snapshot.raw, original)
|
||||
for mon in self.snapshot.raw["monsters"]:
|
||||
mon["level"] = 4
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy, self.ranch), [])
|
||||
for mon in self.snapshot.raw["monsters"]:
|
||||
mon["level"] = 20
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy, self.ranch)[0].payload["monsters"], [1, 2, 3])
|
||||
|
||||
def test_protected_and_unavailable_monsters_are_never_selected(self):
|
||||
for field in ("lock", "sysLock", "entangle", "inExploreTeam", "inBuild"):
|
||||
with self.subTest(field=field):
|
||||
snapshot = make_snapshot()
|
||||
snapshot.raw["monsters"][0][field] = True
|
||||
action = self.planner.plan(snapshot, self.policy, self.ranch)[0]
|
||||
self.assertNotIn(1, action.payload["monsters"])
|
||||
snapshot = make_snapshot()
|
||||
snapshot.raw["teams"] = [{"teamName": "teamA", "teamType": "battleTeam", "monsters": [1]}]
|
||||
self.assertNotIn(1, self.planner.plan(snapshot, self.policy, self.ranch)[0].payload["monsters"])
|
||||
snapshot = make_snapshot()
|
||||
self.ranch.feed_targets = {"1": 1}
|
||||
self.assertNotIn(1, self.planner.plan(snapshot, self.policy, self.ranch)[0].payload["monsters"])
|
||||
|
||||
def test_area_unlock_occupancy_reserve_and_status_reasons(self):
|
||||
self.snapshot.raw["history"]["passStage"] = {"0101": True, "0102": True}
|
||||
self.snapshot.raw["master"]["ti"] = 19
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy, self.ranch), [])
|
||||
self.assertEqual(self.planner.rows(self.snapshot, self.policy, self.ranch)[0]["state"], "体力不足")
|
||||
self.policy.reserve_ti = 81
|
||||
self.snapshot.raw["master"]["ti"] = 100
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy, self.ranch), [])
|
||||
self.policy.reserve_ti = 0
|
||||
self.snapshot.raw["exploreTeams"].append({"id": 2, "status": 1, "area": "1", "endTime": 1_800_000_000_000})
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy, self.ranch), [])
|
||||
self.assertEqual(self.planner.rows(self.snapshot, self.policy, self.ranch)[0]["state"], "地区占用")
|
||||
self.snapshot.raw["history"]["passStage"] = {"0102": True}
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy, self.ranch), [])
|
||||
self.snapshot.raw["exploreTeams"].pop()
|
||||
self.snapshot.raw["history"]["passStage"]["0101"] = True
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy, self.ranch)[0].kind, "explore_start")
|
||||
|
||||
def test_finish_takes_priority_and_uses_seconds_or_milliseconds(self):
|
||||
self.snapshot.raw["exploreTeams"][0].update(status=1, area="1", endTime=1_699_000_000_000,
|
||||
monsters=[1, 2, 3])
|
||||
action = self.planner.plan(self.snapshot, self.policy, self.ranch)[0]
|
||||
self.assertEqual((action.kind, action.path), ("explore_finish", "exploreService/finish"))
|
||||
self.assertEqual(action.payload, {"exploreTeamId": 1})
|
||||
self.assertEqual(self.planner.rows(self.snapshot, self.policy, self.ranch)[0]["state"], "可领取")
|
||||
|
||||
def test_unknown_write_is_never_replayed_and_state_can_resume(self):
|
||||
action = self.planner.plan(self.snapshot, self.policy, self.ranch)[0]
|
||||
self.planner.mark_started(self.snapshot, action)
|
||||
with self.assertRaises(ValueError):
|
||||
self.planner.mark_started(self.snapshot, action)
|
||||
self.planner.mark_uncertain(self.snapshot, action)
|
||||
blocked = self.planner.plan(self.snapshot, self.policy, self.ranch)[0]
|
||||
self.assertEqual(blocked.kind, "explore_blocked")
|
||||
self.assertIn("禁止", blocked.description)
|
||||
state = self.planner.export_state()
|
||||
restored = ExplorePlanner(self.catalog, areas=AREAS)
|
||||
restored.restore_state(deepcopy(state))
|
||||
self.assertEqual(restored.plan(self.snapshot, self.policy, self.ranch)[0].kind, "explore_blocked")
|
||||
self.assertTrue(self.planner.acknowledge(self.snapshot, action, {}))
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy, self.ranch)[0].kind, "explore_start")
|
||||
|
||||
def test_finish_ack_clears_pending_without_modifying_snapshot(self):
|
||||
self.snapshot.raw["exploreTeams"][0].update(status=1, area="1", endTime=1)
|
||||
action = self.planner.plan(self.snapshot, self.policy, self.ranch)[0]
|
||||
original = deepcopy(self.snapshot.raw)
|
||||
self.planner.mark_started(self.snapshot, action)
|
||||
self.assertTrue(self.planner.acknowledge(self.snapshot, action, {"resCode": 0}))
|
||||
self.assertEqual(self.snapshot.raw, original)
|
||||
|
||||
|
||||
class ExplorationGuiTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
from PySide6 import QtWidgets as W
|
||||
cls.app = W.QApplication.instance() or W.QApplication([])
|
||||
|
||||
def test_native_page_controls_autosave_and_render(self):
|
||||
from types import SimpleNamespace
|
||||
from ranch_assistant.exploration_gui import ExplorationPages
|
||||
|
||||
class Window(ExplorationPages):
|
||||
pass
|
||||
|
||||
window = Window()
|
||||
window.closed = window.loading_config = False
|
||||
window.pending_policy = None
|
||||
window.catalog = Catalog()
|
||||
snapshot = make_snapshot()
|
||||
window.engine = SimpleNamespace(snapshot=snapshot, policy=Policy(protect_star=6, protect_quality=5),
|
||||
explore_policy=ExplorePolicy(), explore_planner=ExplorePlanner(window.catalog, areas=AREAS))
|
||||
window.settings_changed = lambda: setattr(window, "saved", True)
|
||||
window.tabs = __import__("PySide6.QtWidgets", fromlist=["QTabWidget"]).QTabWidget()
|
||||
window.busy = False
|
||||
window.exploration_tab()
|
||||
try:
|
||||
window.render_exploration()
|
||||
self.assertEqual(window.exploration_table.rowCount(), 1)
|
||||
window._exploration_controls["1"]["enabled"].setCheckState(__import__("PySide6.QtCore", fromlist=["Qt"]).Qt.CheckState.Checked)
|
||||
window.exploration_item_changed(window._exploration_controls["1"]["enabled"])
|
||||
self.assertTrue(window.read_explore_policy().teams["1"].enabled)
|
||||
self.assertTrue(window.saved)
|
||||
window.engine.explore_policy = window.read_explore_policy()
|
||||
window._exploration_controls["1"]["area"].setCurrentIndex(0)
|
||||
window.engine.explore_policy = window.read_explore_policy()
|
||||
window.render_exploration()
|
||||
self.assertEqual(window.exploration_table.item(0, 3).text(), "可出发")
|
||||
window.explore_enabled.setChecked(True)
|
||||
self.assertTrue(window.engine.explore_policy.enabled)
|
||||
window.explore_reserve_ti.setValue(10)
|
||||
self.assertEqual(window.engine.explore_policy.reserve_ti, 10)
|
||||
window.apply_explore_policy({"enabled": False, "reserve_ti": 0,
|
||||
"teams": {"1": {"enabled": True, "area": "1"}}})
|
||||
window.render_exploration()
|
||||
self.assertEqual(window.exploration_table.item(0, 3).text(), "可出发")
|
||||
self.assertIn("测试矿洞", window._exploration_controls["1"]["area"].currentText())
|
||||
finally:
|
||||
window.tabs.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -756,12 +756,12 @@ class ProgressionGuiTests(unittest.TestCase):
|
||||
original = copy.deepcopy(records)
|
||||
engine = SimpleNamespace(snapshot=object(), progression_rows=lambda: [], progression_records=lambda: records)
|
||||
rows = prepare_progression_views(engine).records
|
||||
for row, outcome in zip(rows, ("战斗胜利", "打不过", "暂不支持")):
|
||||
self.assertEqual(row["values"][4], outcome + "(模拟近似)")
|
||||
self.assertIn("结果近似", row["detail"])
|
||||
for row, outcome in zip(rows, ("胜利", "打不过", "暂不支持")):
|
||||
self.assertEqual(row["values"][4], outcome + "(实验近似)")
|
||||
self.assertIn("近似,未完整验证", row["detail"])
|
||||
self.assertIn("能力检查未通过", rows[2]["detail"])
|
||||
self.assertEqual(rows[3]["values"][4], "战斗胜利")
|
||||
self.assertIn("原版战斗运行时", rows[3]["detail"])
|
||||
self.assertEqual(rows[3]["values"][4], "胜利")
|
||||
self.assertIn("原版运行时", rows[3]["detail"])
|
||||
self.assertIn("记录未标明", rows[4]["detail"])
|
||||
self.assertEqual(records, original)
|
||||
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
import copy
|
||||
import unittest
|
||||
import unittest.mock
|
||||
from dataclasses import asdict
|
||||
from unittest.mock import Mock
|
||||
|
||||
from ranch_assistant.breakthrough import PATH as BREAKTHROUGH_PATH
|
||||
from ranch_assistant.engine import Engine
|
||||
from ranch_assistant.exploration import ExplorePolicy
|
||||
from ranch_assistant.model import Action, Catalog, EggRule, Policy
|
||||
from ranch_assistant.tests.test_breakthrough import snapshot_with
|
||||
from ranch_assistant.tests.test_core import workspace_temp
|
||||
|
||||
|
||||
class RanchAutomationIntegrationTests(unittest.TestCase):
|
||||
def test_breakthrough_is_opt_in_ordered_and_called_with_original_payload(self):
|
||||
client = Mock()
|
||||
snapshot = snapshot_with()
|
||||
client.snapshot.return_value = snapshot
|
||||
engine = Engine(Catalog(), client)
|
||||
engine.snapshot = snapshot
|
||||
engine.policy = Policy(feed_targets={"900": 1}, breakthrough_targets={"900": 1},
|
||||
egg_rules={}, enabled=True)
|
||||
engine.policy.breakthrough_targets = {}
|
||||
self.assertFalse(any(action.kind == "breakthrough" for action in engine.plans()))
|
||||
engine.policy.breakthrough_targets = {"900": 1}
|
||||
# A checked breakthrough is also a feeding target; it uses the same order.
|
||||
action = engine.plans()[0]
|
||||
self.assertEqual((action.kind, action.path, action.payload),
|
||||
("breakthrough", BREAKTHROUGH_PATH, {"monId": 900, "itemIds": [600]}))
|
||||
client.call.return_value = {"resCode": 0}
|
||||
engine.auto = True
|
||||
with unittest.mock.patch.object(engine, "read_snapshot"):
|
||||
# Integration route uses the ordinary Action executor, no custom URL.
|
||||
engine.explore_policy = ExplorePolicy()
|
||||
self.assertEqual(action.description.split("(")[0], "突破 #900 绿色史莱姆 → 2 级")
|
||||
|
||||
def test_egg_keep_count_is_in_policy_and_export(self):
|
||||
from ranch_assistant.policy_io import portable_policy
|
||||
rule = EggRule(enabled=True, action="keep", keep_count=2)
|
||||
policy = Policy(egg_rules={"1001010": asdict(rule)}, breakthrough_targets={"900": 2})
|
||||
value = portable_policy(policy)
|
||||
self.assertEqual(value["policy"]["egg_rules"]["1001010"]["keep_count"], 2)
|
||||
self.assertEqual(value["targetSpecies"]["breakthrough"], [{"typeId": "", "priority": 2}])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -64,11 +64,11 @@ class RanchTreeTests(unittest.TestCase):
|
||||
self.assertIs(tree.itemWidget(item, 9), priority)
|
||||
self.assertTrue(check.isChecked())
|
||||
self.assertEqual(priority.value(), 2)
|
||||
self.assertTrue(tree.itemWidget(item, 19).isChecked())
|
||||
self.assertEqual(tree.itemWidget(item, 20).value(), 3)
|
||||
self.assertTrue(tree.itemWidget(item, 17).isChecked())
|
||||
self.assertEqual(tree.itemWidget(item, 18).value(), 3)
|
||||
self.assertFalse(tree.group_items["room:1"].isExpanded())
|
||||
self.assertEqual(tree.selected_monster_ids(), [900])
|
||||
self.assertTrue(item.text(17).startswith("30 /"))
|
||||
self.assertTrue(item.text(15).startswith("30 /"))
|
||||
finally:
|
||||
tree.row_batch.stop()
|
||||
tree.close()
|
||||
@@ -129,8 +129,8 @@ class RanchTreeTests(unittest.TestCase):
|
||||
item = tree.monster_items[900]
|
||||
tree.itemWidget(item, 8).setChecked(True)
|
||||
tree.itemWidget(item, 9).setValue(4)
|
||||
tree.itemWidget(item, 19).setChecked(True)
|
||||
tree.itemWidget(item, 20).setValue(5)
|
||||
tree.itemWidget(item, 17).setChecked(True)
|
||||
tree.itemWidget(item, 18).setValue(5)
|
||||
self.assertEqual(window.read_policy().feed_targets, {"900": 4})
|
||||
self.assertEqual(window.read_policy().gift_targets, {"900": 5})
|
||||
tree.setCurrentItem(item)
|
||||
|
||||
@@ -101,7 +101,7 @@ class RuleEditingTests(unittest.TestCase):
|
||||
self.app.processEvents()
|
||||
parent = tree.group_items["room:1"] if grouped else tree.invisibleRootItem()
|
||||
self.assertEqual([parent.child(i).data(0, C.Qt.ItemDataRole.UserRole) for i in range(3)], [902, 901, 900])
|
||||
tree.sortByColumn(19, C.Qt.SortOrder.DescendingOrder)
|
||||
tree.sortByColumn(17, C.Qt.SortOrder.DescendingOrder)
|
||||
self.app.processEvents()
|
||||
self.assertEqual(parent.child(0).data(0, C.Qt.ItemDataRole.UserRole), 901)
|
||||
self.assertTrue(tree.monster_items[901].textAlignment(2) & C.Qt.AlignmentFlag.AlignHCenter)
|
||||
|
||||
@@ -172,7 +172,7 @@ class V11GuiTests(unittest.TestCase):
|
||||
self.app.processEvents()
|
||||
QTest.qWait(2)
|
||||
target_item = window.monsters.monster_items[900]
|
||||
window.monsters.itemWidget(target_item, 19).setChecked(True)
|
||||
window.monsters.itemWidget(target_item, 17).setChecked(True)
|
||||
self.assertIn("900", window.read_policy().gift_targets)
|
||||
window.monster_view.setCurrentIndex(1)
|
||||
self.assertFalse(window.monsters.rootIsDecorated())
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
"""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")
|
||||
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))
|
||||
@@ -39,7 +39,7 @@ with zipfile.ZipFile(apk) as archive:
|
||||
if name == "stack_price":
|
||||
tables["stack_meta"] = {"total": int(value["total"])}
|
||||
print(name, len(tables[name]))
|
||||
fields = {"type", "name", "star", "element", "job", "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 |= {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 = repair_names(tables)
|
||||
@@ -53,8 +53,7 @@ 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")} |
|
||||
{"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")}
|
||||
tables["potential_info"] = {k: tables["potential_info"][k] for k in
|
||||
("potentialLevelMaxAdd", "maxPotentialLevel", "potential", "potentialLevelItem", "elementItem")}
|
||||
tables["potential_info"] = {k: tables["potential_info"][k] for k in ("potentialLevelMaxAdd", "maxPotentialLevel")}
|
||||
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()}}
|
||||
for r in tables["stage_info"]}
|
||||
|
||||
Reference in New Issue
Block a user