Files
myrzx_bot/ranch_assistant/breakthrough.py
T

175 lines
7.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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)