Add hatch retention, automatic breakthroughs and exploration

This commit is contained in:
AttilaNet
2026-11-09 11:27:29 +08:00
parent 26be820ff2
commit 9f819d828a
32 changed files with 6207 additions and 83 deletions
+272
View File
@@ -0,0 +1,272 @@
"""Plan one original-client potential operation from a fresh snapshot.
This module never calls a Client or updates snapshot state. The runner must read
the snapshot again after executing either returned Action. ``potentialLevel``
is the material-based PotentialPanel stage; feeding's ``tpLevel/tpExp`` is a
separate progression and deliberately does not affect readiness here.
"""
from __future__ import annotations
from dataclasses import dataclass
from .model import Action
PATH = "monsterService/monsterPotentialLevelUpgrade"
POTENTIAL_PATH = "monsterService/monsterPotentialUpgrade"
STATS = ("atk", "def", "hp", "dex")
LABELS = {"atk": "攻击", "def": "防御", "hp": "生命", "dex": "敏捷"}
def integer(value):
"""Accept integer-valued server numbers, not lossy bool/NaN conversions."""
if isinstance(value, bool) or value is None:
return None
if isinstance(value, str):
try:
return int(value.strip())
except (ValueError, OverflowError):
return None
try:
result = int(value)
except (TypeError, ValueError, OverflowError):
return None
try:
return result if result == value else None
except (TypeError, ValueError):
return None
def field(row, name, default=None):
if isinstance(row, dict):
return row.get(name, default)
return getattr(row, name, default)
@dataclass(frozen=True)
class Material:
type_id: int
required: int
available: int
item_ids: tuple[int, ...]
@dataclass(frozen=True)
class Candidate:
monster: dict
next_level: int
materials: tuple[Material, ...]
reason: str
@property
def ready(self):
return bool(self.materials) and not self.reason
class BreakthroughPlanner:
"""Plan PotentialPanel writes; each call returns at most one operation."""
def __init__(self, catalog):
self.catalog = catalog
self.notes = []
@staticmethod
def target_ids(policy, targets=None):
"""Explicit targets replace feeding, including an explicitly empty map."""
if targets is None:
targets = field(policy, "feed_targets")
if targets:
pass
else:
legacy = integer(field(policy, "feed_target", 0))
return [legacy] if legacy is not None and legacy > 0 else []
if not isinstance(targets, dict):
return []
pairs = []
for mid, priority in targets.items():
mid, priority = integer(mid), integer(priority)
if mid is not None and mid > 0 and priority is not None:
pairs.append((priority, mid))
return [mid for _, mid in sorted(pairs)]
@staticmethod
def reserves(policy, type_id):
"""Combine the target-item switch with ranch and quest reservations."""
key = str(type_id)
quest = field(policy, "quest_policy", {})
gift_rule = field(policy, "gift_items", {}).get(key, {})
values = [field(policy, "reserved_eggs", {}).get(key, 0),
field(policy, "item_reserves", {}).get(key, 0),
field(quest, "item_reserves", {}).get(key, 0),
field(gift_rule, "reserve", 0)]
parsed = [integer(value) for value in values]
if any(value is None or value < 0 for value in parsed):
return None
return max(parsed, default=0)
def stacks(self, snapshot, policy):
groups, seen = {}, set()
for item in snapshot.raw["items"]:
item_id, type_id, count = (integer(item.get(key)) for key in ("id", "typeId", "num"))
if item_id is None or type_id is None or count is None or item_id <= 0 or count <= 0:
continue
if item_id in seen:
raise ValueError("背包材料实例重复,暂不操作")
seen.add(item_id)
groups.setdefault(type_id, []).append((item_id, count, item))
usable = {}
for type_id, entries in groups.items():
reserve = self.reserves(policy, type_id)
if reserve is None:
raise ValueError("突破道具保留数量配置无效")
entries = [entry for entry in entries if not entry[2].get("lock") and not entry[2].get("feedLock")]
total = sum(count for _, count, _ in entries)
usable[type_id] = {"entries": entries, "available": max(0, total - reserve), "total": total}
return usable
def select_stack(self, usable, type_id, amount, reserved=None):
"""Select one sufficient stack; do not aggregate stock for itemIds."""
stock = usable.get(type_id, {"entries": [], "available": 0})
if stock["available"] < amount:
return None
entries = stock["entries"] if reserved is None else [
entry for entry in stock["entries"] if entry[0] not in reserved]
eligible = [entry for entry in entries if entry[1] >= amount]
if not eligible:
return None
item_id, count, _ = min(eligible, key=lambda entry: (entry[1], entry[0]))
return item_id, count
def caps(self, mon):
info = self.catalog.data.get("potential_info", {})
row = self.catalog.monster(mon.get("typeId"))
level = integer(mon.get("potentialLevel"))
if level is None or level < 1 or not row:
return None, None, "突破等级或魔物资料尚未同步"
maximum = integer(info.get("maxPotentialLevel"))
if maximum is not None and level >= maximum:
return None, None, "已达到最高突破等级"
caps = (info.get("potential") or {}).get(str(row.get("job")), {}).get(str(row.get("star")))
if not caps:
return None, None, "当前突破配置缺失"
result = {}
for stat in STATS:
base, increment = integer(caps.get(stat)), integer(caps.get(stat + "TpAdd"))
current = integer(mon.get("p" + stat.capitalize()))
if base is None or increment is None or current is None:
return None, None, "潜能数据尚未同步"
cap = base + (level - 1) * increment
if cap < 0 or current < 0:
return None, None, "潜能数据异常"
result[stat] = (current, cap)
return level, result, ""
def potential_action(self, mon, caps, usable):
"""One original addPotential call consumes exactly one type-ID item."""
row = self.catalog.monster(mon.get("typeId"))
type_id = integer((self.catalog.data.get("potential_info", {}).get("potentialElementItem") or {}).get(str(row.get("element"))))
if type_id is None:
return None, "当前补潜能材料配置缺失"
selected = self.select_stack(usable, type_id, 1)
incomplete = [stat for stat in STATS if caps[stat][0] < caps[stat][1]]
if selected is None:
total = usable.get(type_id, {}).get("available", 0)
return None, f"补潜能材料不足或受保留数量限制:{self.catalog.item_name(type_id)} {total}/1"
stat = min(incomplete, key=lambda key: (caps[key][1] - caps[key][0], STATS.index(key)))
item_id, count = selected
current, cap = caps[stat]
description = (f"补潜能 {self.catalog.monster_label(mon)} {LABELS[stat]} {current}/{cap}"
f"(消耗 {self.catalog.item_name(type_id)}×1;成功后重新读取,四项满再突破)")
return Action("potential", description, POTENTIAL_PATH,
{"traceInfo": {"itemTypeId": item_id, "itemNum": count},
"monId": integer(mon["id"]), "itemId": item_id, "monsterAttr": stat}), ""
def evaluate(self, mon, items, policy=None, snapshot=None):
"""Compatibility helper for stage evaluation with the same stock rules."""
if snapshot is None:
snapshot = type("ItemsSnapshot", (), {"raw": {"items": items}})()
policy = policy if policy is not None else type("ItemPolicy", (), {
"gift_items": {}})()
level, caps, reason = self.caps(mon)
if level is None:
return Candidate(mon, 0, (), reason)
incomplete = [f"{LABELS[stat]} {current}/{cap}" for stat, (current, cap) in caps.items() if current < cap]
if incomplete:
return Candidate(mon, level + 1, (), "潜能未满:" + ",".join(incomplete))
info = self.catalog.data.get("potential_info", {})
row = self.catalog.monster(mon.get("typeId"))
need = (info.get("potentialLevelItem") or {}).get(str(row.get("star")), {}).get(str(level))
elements = (info.get("elementItem") or {}).get(str(row.get("element")))
if not need or not elements:
return Candidate(mon, level + 1, (), "当前突破配置缺失")
try:
usable = self.stacks(snapshot, policy)
except ValueError as error:
return Candidate(mon, level + 1, (), str(error))
requirements = {}
for level_key in sorted(need, key=lambda key: integer(key[2:]) or 999):
type_id, amount = integer(elements.get(level_key)), integer(need[level_key])
if type_id is None or amount is None or amount <= 0:
return Candidate(mon, level + 1, (), "当前突破材料配置异常")
requirements[type_id] = requirements.get(type_id, 0) + amount
materials, missing, selected_ids = [], [], set()
for type_id, amount in requirements.items():
selected = self.select_stack(usable, type_id, amount)
available = usable.get(type_id, {}).get("available", 0)
materials.append(Material(type_id, amount, available, (selected[0],) if selected else ()))
if selected is None:
missing.append(f"{self.catalog.item_name(type_id)} 可用单堆不足 {available}/{amount}")
else:
selected_ids.add(selected[0])
return Candidate(mon, level + 1, tuple(materials), "材料不足:" + ",".join(missing) if missing else "")
def plan(self, snapshot, policy, *, targets=None, enabled=True):
self.notes = []
if not enabled or field(policy, "enabled", True) is not True:
return None
ids = self.target_ids(policy, targets)
if not ids:
self.notes.append("未选择自动突破目标")
return None
for mid in ids:
mon = snapshot.monsters.get(mid)
if not mon:
self.notes.append(f"#{mid} 已不在角色数据中")
continue
label = self.catalog.monster_label(mon)
if mon.get("process") != 3:
self.notes.append(f"{label} 不在牧场")
continue
if mon.get("inExploreTeam") or mon.get("inBuild"):
self.notes.append(f"{label} 正在探险或建筑,暂停自动突破")
continue
level, caps, reason = self.caps(mon)
if level is None:
self.notes.append(f"{label}:{reason}")
continue
try:
usable = self.stacks(snapshot, policy)
except ValueError as error:
self.notes.append(f"{label}:{error}")
continue
if any(current < cap for current, cap in caps.values()):
action, reason = self.potential_action(mon, caps, usable)
if action:
self.notes.append(f"{label} 先补满四项潜能,再提升至 {level + 1} 阶段;每轮仅操作一次")
return action
self.notes.append(f"{label}:{reason}")
continue
candidate = self.evaluate(mon, snapshot.raw["items"], policy, snapshot)
if not candidate.ready:
self.notes.append(f"{label}:{candidate.reason}")
continue
item_ids = [item_id for material in candidate.materials for item_id in material.item_ids]
cost = "、".join(f"{self.catalog.item_name(m.type_id)}×{m.required}" for m in candidate.materials)
self.notes.append(f"{label} 可提升至 {candidate.next_level} 阶段")
return Action("breakthrough", f"突破 {label} → {candidate.next_level} 阶段({cost};不消耗tp经验)",
PATH, {"monId": mid, "itemIds": item_ids})
return None
def plan_breakthrough(catalog, snapshot, policy, *, targets=None, enabled=True):
return BreakthroughPlanner(catalog).plan(snapshot, policy, targets=targets, enabled=enabled)