Add hatch retention, automatic breakthroughs and exploration
This commit is contained in:
@@ -0,0 +1,719 @@
|
||||
"""Offline automatic exploration policy, planning and durable send guards.
|
||||
|
||||
Integration contract (the engine owns the snapshot, HTTP client and persistence
|
||||
directory; this module never imports or calls the real API):
|
||||
|
||||
* ``ExplorePolicy(enabled=False, reserve_ti=0, teams={})`` has ``to_dict()``
|
||||
and ``ExplorePolicy.from_dict(mapping)``. Each team rule is
|
||||
``{"enabled": bool, "area": "1", "monsters": [int, int, int]}``.
|
||||
An empty monster list means automatic selection; no other placeholders are
|
||||
accepted. Locked, high-star and equipped monsters are valid explorers.
|
||||
* ``ExplorePlanner(catalog, areas=None, *, path=None, account_key=None)``.
|
||||
``path`` enables internal atomic persistence of account-keyed pending sends.
|
||||
Keys hash the role identity, never an account login, password or token.
|
||||
``account_key`` optionally supplies an already-stable profile namespace.
|
||||
* ``plan(snapshot, policy, ranch_policy) -> list[Action]`` returns zero or one
|
||||
action. ``explore_start`` uses ``exploreService/start`` and payload
|
||||
``{exploreTeamId, monsters, area}``; ``explore_finish`` uses
|
||||
``exploreService/finish`` and payload ``{exploreTeamId}``. Finished teams
|
||||
are always rewarded before a subsequent start. ``explore_blocked`` has an
|
||||
empty path and a diagnostic payload; callers MUST NOT execute it.
|
||||
* ``execute(snapshot, action, call)`` is the smallest runner adapter: pass the
|
||||
existing ``client.call`` callable. It persists before dispatch, confirms only
|
||||
successful responses, and marks every other outcome unresolved. Its return
|
||||
value is the response dictionary. Direct runners instead call
|
||||
``mark_started(snapshot, action)`` BEFORE sending, then
|
||||
``acknowledge(snapshot, action, response)`` after confirmed success, or
|
||||
``mark_uncertain(snapshot, action, reason="...")`` after an ambiguous result.
|
||||
* ``reconcile(snapshot)`` resolves an unresolved send only from an authoritative
|
||||
matching team snapshot. It never invents a success or clears on an unchanged
|
||||
or missing snapshot. ``pending(snapshot)`` returns a small copy.
|
||||
* ``rows(snapshot, policy, ranch_policy)`` and ``member_options(snapshot,
|
||||
team_id, policy, ranch_policy)`` return compact plain data for worker threads.
|
||||
``export_state()`` / ``restore_state(state)`` support host-owned persistence;
|
||||
use one of these mechanisms, not two independent state files.
|
||||
|
||||
The planner never adds a paid team and never recalls an active team.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
from dataclasses import asdict, dataclass, field
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import threading
|
||||
|
||||
from .model import Action, seconds
|
||||
|
||||
|
||||
DATA_PATH = Path(__file__).with_name("data") / "exploration.json"
|
||||
STATE_VERSION = 1
|
||||
WIRE_KINDS = {"explore_start", "explore_finish"}
|
||||
PATHS = {"explore_start": "exploreService/start", "explore_finish": "exploreService/finish"}
|
||||
|
||||
|
||||
def load_exploration_areas(path=DATA_PATH):
|
||||
document = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
if document.get("schema") != 1 or not isinstance(document.get("areas"), list):
|
||||
raise ValueError("探险地区数据格式错误")
|
||||
result = {}
|
||||
for row in document["areas"]:
|
||||
if not isinstance(row, dict) or row.get("team") != "normal":
|
||||
continue
|
||||
try:
|
||||
key = str(_positive_id(row["id"], "地区编号"))
|
||||
levels = row["level"]
|
||||
if not isinstance(levels, list) or len(levels) != 3:
|
||||
raise ValueError
|
||||
levels = [_nonnegative_int(value, "地区等级") for value in levels]
|
||||
cost_ti = _nonnegative_int(row.get("costTi", 0), "地区体力")
|
||||
cost_time = _nonnegative_int(row.get("costTime", 0), "地区时长")
|
||||
except (KeyError, TypeError, ValueError) as error:
|
||||
raise ValueError("探险地区数据格式错误") from error
|
||||
if key in result or not row.get("passStage"):
|
||||
raise ValueError("探险地区数据格式错误")
|
||||
result[key] = dict(row, id=key, level=levels, costTi=cost_ti, costTime=cost_time)
|
||||
if not result:
|
||||
raise ValueError("探险地区数据为空")
|
||||
return result
|
||||
|
||||
|
||||
def _integer(value, default=0):
|
||||
if isinstance(value, bool):
|
||||
return default
|
||||
try:
|
||||
number = float(value)
|
||||
return int(number) if math.isfinite(number) and number.is_integer() else default
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
return default
|
||||
|
||||
|
||||
def _nonnegative_int(value, label):
|
||||
if type(value) is not int or not 0 <= value <= 1_000_000_000:
|
||||
raise ValueError(label + "必须为非负整数")
|
||||
return value
|
||||
|
||||
|
||||
def _positive_id(value, label="魔物编号"):
|
||||
if isinstance(value, bool):
|
||||
raise ValueError(label + "无效")
|
||||
text = str(value)
|
||||
if not text.isdigit() or int(text) <= 0 or int(text) > 9_223_372_036_854_775_807:
|
||||
raise ValueError(label + "无效")
|
||||
return int(text)
|
||||
|
||||
|
||||
def _flag(mapping, key, level=None):
|
||||
"""Match HistoryVo/StageCenter's explicit stage-level dictionary."""
|
||||
if level is not None:
|
||||
if not isinstance(mapping, dict):
|
||||
return False
|
||||
value = mapping.get(str(key), mapping.get(key))
|
||||
if not isinstance(value, dict):
|
||||
# Legacy flat snapshots used {stage: true}; nested is authoritative
|
||||
# whenever the stage has a level map.
|
||||
return value is True
|
||||
return value.get(str(level), value.get(level)) is True
|
||||
if isinstance(mapping, dict):
|
||||
value = mapping.get(str(key), mapping.get(key))
|
||||
return value is True or value == 1 and not isinstance(value, bool)
|
||||
if isinstance(mapping, list):
|
||||
if mapping and all(value is None or isinstance(value, bool) for value in mapping):
|
||||
return str(key).isdigit() and 0 <= int(key) < len(mapping) and mapping[int(key)] is True
|
||||
return str(key) in {str(value) for value in mapping if not isinstance(value, bool)}
|
||||
return False
|
||||
|
||||
|
||||
def _team_monsters(value):
|
||||
# ExploreCenter.makeTeamByData uses ArrayUtil.split(data.monsters, ",").
|
||||
if isinstance(value, str):
|
||||
value = value.split(",")
|
||||
if not isinstance(value, (list, tuple)):
|
||||
return []
|
||||
result = []
|
||||
for item in value:
|
||||
mid = _integer(item)
|
||||
if mid > 0 and mid not in result:
|
||||
result.append(mid)
|
||||
return result
|
||||
|
||||
|
||||
def _target_ids(*mappings):
|
||||
result = set()
|
||||
for mapping in mappings:
|
||||
if isinstance(mapping, dict):
|
||||
for key in mapping:
|
||||
mid = _integer(key)
|
||||
if mid > 0:
|
||||
result.add(mid)
|
||||
return result
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExploreTeamRule:
|
||||
enabled: bool = False
|
||||
area: str = ""
|
||||
monsters: list[int] = field(default_factory=list)
|
||||
|
||||
def __post_init__(self):
|
||||
if type(self.enabled) is not bool:
|
||||
raise ValueError("探险队伍开关必须为布尔值")
|
||||
if not isinstance(self.area, str) or self.area and (not self.area.isdigit() or int(self.area) <= 0):
|
||||
raise ValueError("探险地区编号无效")
|
||||
self.area = str(int(self.area)) if self.area else ""
|
||||
if not isinstance(self.monsters, list) or len(self.monsters) not in (0, 3):
|
||||
raise ValueError("探险队员须为空或恰好三只")
|
||||
self.monsters = [_positive_id(mid) for mid in self.monsters]
|
||||
if len(set(self.monsters)) != len(self.monsters):
|
||||
raise ValueError("探险队员不可重复")
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExplorePolicy:
|
||||
enabled: bool = False
|
||||
teams: dict[str, ExploreTeamRule] = field(default_factory=dict)
|
||||
reserve_ti: int = 0
|
||||
|
||||
def __post_init__(self):
|
||||
if type(self.enabled) is not bool:
|
||||
raise ValueError("自动探险开关必须为布尔值")
|
||||
_nonnegative_int(self.reserve_ti, "探险保留体力")
|
||||
if not isinstance(self.teams, dict):
|
||||
raise ValueError("探险队伍配置必须为对象")
|
||||
rules = {}
|
||||
for key, value in self.teams.items():
|
||||
team_id = _positive_id(key, "探险队伍编号")
|
||||
if isinstance(value, ExploreTeamRule):
|
||||
value = asdict(value)
|
||||
if not isinstance(value, dict) or set(value) - {"enabled", "area", "monsters"}:
|
||||
raise ValueError("探险队伍配置格式错误")
|
||||
rules[str(team_id)] = ExploreTeamRule(**value)
|
||||
self.teams = rules
|
||||
|
||||
def to_dict(self):
|
||||
return {"enabled": self.enabled, "reserve_ti": self.reserve_ti,
|
||||
"teams": {key: asdict(rule) for key, rule in self.teams.items()}}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, value):
|
||||
if not isinstance(value, dict) or set(value) - {"enabled", "teams", "reserve_ti"}:
|
||||
raise ValueError("自动探险策略格式错误")
|
||||
return cls(**value)
|
||||
|
||||
|
||||
class ExplorePlanner:
|
||||
"""Pure snapshot planning plus a serialized, durable unresolved-send guard."""
|
||||
|
||||
def __init__(self, catalog, areas=None, *, path=None, account_key=None):
|
||||
self.catalog = catalog
|
||||
self.areas = load_exploration_areas() if areas is None else {
|
||||
str(key): dict(value, id=str(key)) for key, value in areas.items()}
|
||||
self._namespace = str(account_key) if account_key is not None else ""
|
||||
self._path = Path(path) if path is not None else None
|
||||
self._lock = threading.RLock()
|
||||
self._accounts = {}
|
||||
self._issued = {}
|
||||
self._persistence_error = None
|
||||
self._load_state()
|
||||
|
||||
@staticmethod
|
||||
def role_key(snapshot, namespace=""):
|
||||
raw = snapshot.raw if hasattr(snapshot, "raw") else snapshot
|
||||
master = raw.get("master") if isinstance(raw, dict) else None
|
||||
master = master if isinstance(master, dict) else {}
|
||||
role = master.get("id", master.get("userId"))
|
||||
if role is None or not str(role).strip():
|
||||
raise ValueError("角色快照缺少稳定的角色编号,已暂停探险")
|
||||
# These values are role routing data, not login/account credentials.
|
||||
identity = [str(namespace), str(role), str(raw.get("serverId", "")),
|
||||
str(raw.get("areaId", "")), str(master.get("serverId", ""))]
|
||||
return hashlib.sha256(json.dumps(identity, ensure_ascii=True, separators=(",", ":")).encode()).hexdigest()
|
||||
|
||||
def _scope(self, snapshot):
|
||||
return self.role_key(snapshot, self._namespace)
|
||||
|
||||
def _account(self, snapshot):
|
||||
scope = self._scope(snapshot)
|
||||
account = self._accounts.setdefault(scope, {"pending": None})
|
||||
return scope, account
|
||||
|
||||
def _load_state(self):
|
||||
if self._path is None or not self._path.exists():
|
||||
return
|
||||
try:
|
||||
self.restore_state(json.loads(self._path.read_text(encoding="utf-8")))
|
||||
except (OSError, ValueError, TypeError, json.JSONDecodeError) as error:
|
||||
self._accounts = {}
|
||||
self._persistence_error = "探险请求状态无法读取,已暂停:" + str(error)
|
||||
|
||||
def _save_state(self):
|
||||
if self._path is None:
|
||||
return
|
||||
self._path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = self._path.with_name(self._path.name + ".tmp")
|
||||
data = json.dumps(self.export_state(), ensure_ascii=True, sort_keys=True,
|
||||
indent=2, allow_nan=False) + "\n"
|
||||
try:
|
||||
with temporary.open("w", encoding="utf-8") as stream:
|
||||
stream.write(data)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, self._path)
|
||||
except OSError as error:
|
||||
try:
|
||||
temporary.unlink(missing_ok=True)
|
||||
except OSError:
|
||||
pass
|
||||
raise OSError("探险请求状态未能落盘,已暂停发送") from error
|
||||
|
||||
@staticmethod
|
||||
def _validate_state(state):
|
||||
if not isinstance(state, dict) or state.get("version") != STATE_VERSION or set(state) != {"version", "accounts"}:
|
||||
raise ValueError("探险状态版本无效")
|
||||
if not isinstance(state["accounts"], dict):
|
||||
raise ValueError("探险账号状态无效")
|
||||
encoded = json.dumps(state, allow_nan=False)
|
||||
state = json.loads(encoded)
|
||||
for key, account in state["accounts"].items():
|
||||
if not re.fullmatch(r"[0-9a-f]{64}", key) or not isinstance(account, dict) or set(account) != {"pending"}:
|
||||
raise ValueError("探险账号状态无效")
|
||||
pending = account["pending"]
|
||||
if pending is None:
|
||||
continue
|
||||
required = {"kind", "team_id", "path", "payload", "description", "message", "uncertain", "confirmed", "started_at", "snapshot", "expected"}
|
||||
if not isinstance(pending, dict) or set(pending) != required:
|
||||
raise ValueError("探险待核对状态无效")
|
||||
if pending["kind"] not in WIRE_KINDS or pending["path"] != PATHS[pending["kind"]]:
|
||||
raise ValueError("探险待核对动作无效")
|
||||
if not isinstance(pending["payload"], dict) or _integer(pending["team_id"]) <= 0:
|
||||
raise ValueError("探险待核对队伍无效")
|
||||
if type(pending["uncertain"]) is not bool or type(pending["confirmed"]) is not bool:
|
||||
raise ValueError("探险待核对阶段无效")
|
||||
if pending["uncertain"] and pending["confirmed"] or not isinstance(pending["snapshot"], dict) or not isinstance(pending["expected"], dict):
|
||||
raise ValueError("探险待核对快照无效")
|
||||
return state["accounts"]
|
||||
|
||||
def restore_state(self, state):
|
||||
restored = self._validate_state(state)
|
||||
with self._lock:
|
||||
self._accounts = restored
|
||||
self._issued.clear()
|
||||
for account in self._accounts.values():
|
||||
if account["pending"] and not account["pending"]["confirmed"]:
|
||||
# Restored sends are always unknown, even if the old writer
|
||||
# had not yet marked its network outcome uncertain.
|
||||
account["pending"]["uncertain"] = True
|
||||
account["pending"]["message"] = "上次进程请求结果未知,需由快照核对,禁止重放"
|
||||
|
||||
def export_state(self):
|
||||
with self._lock:
|
||||
return deepcopy({"version": STATE_VERSION, "accounts": self._accounts})
|
||||
|
||||
def pending(self, snapshot):
|
||||
with self._lock:
|
||||
_, account = self._account(snapshot)
|
||||
return deepcopy(account["pending"])
|
||||
|
||||
@staticmethod
|
||||
def _fingerprint(team):
|
||||
return {"id": _integer(team.get("id"), -1), "status": _integer(team.get("status"), -1),
|
||||
"area": str(team.get("area") or ""), "endTime": str(team.get("endTime") or ""),
|
||||
"monsters": _team_monsters(team.get("monsters"))}
|
||||
|
||||
@classmethod
|
||||
def _fingerprint_action(cls, action):
|
||||
payload = action.payload
|
||||
team_id = _positive_id(payload.get("exploreTeamId"), "探险队伍编号")
|
||||
if action.kind == "explore_start":
|
||||
if set(payload) != {"exploreTeamId", "monsters", "area"}:
|
||||
raise ValueError("探险出发字段无效")
|
||||
monsters = [_positive_id(mid) for mid in payload.get("monsters", [])]
|
||||
if len(monsters) != 3 or len(set(monsters)) != 3:
|
||||
raise ValueError("探险出发必须选择三只不同魔物")
|
||||
area = payload.get("area")
|
||||
if not isinstance(area, str) or not area.isdigit() or int(area) <= 0:
|
||||
raise ValueError("探险出发地区无效")
|
||||
return {"id": team_id, "status": 1, "area": str(int(area)), "monsters": monsters}
|
||||
if action.kind == "explore_finish":
|
||||
if set(payload) != {"exploreTeamId"}:
|
||||
raise ValueError("探险领奖字段无效")
|
||||
return {"id": team_id, "status": 0}
|
||||
raise ValueError("该操作不是探险请求")
|
||||
|
||||
@staticmethod
|
||||
def _team(snapshot, team_id):
|
||||
teams = snapshot.raw.get("exploreTeams") or []
|
||||
if not isinstance(teams, list):
|
||||
raise ValueError("探险队快照格式无效")
|
||||
matches = [team for team in teams if isinstance(team, dict) and _integer(team.get("id"), -1) == team_id]
|
||||
if len(matches) > 1:
|
||||
raise ValueError("探险队快照存在重复编号")
|
||||
return matches[0] if matches else None
|
||||
|
||||
def _validate_intent(self, snapshot, action):
|
||||
if not isinstance(action, Action) or action.kind not in WIRE_KINDS:
|
||||
raise ValueError("该操作不是探险请求")
|
||||
if action.path != PATHS[action.kind] or not isinstance(action.payload, dict):
|
||||
raise ValueError("探险请求路径或字段无效")
|
||||
expected = self._fingerprint_action(action)
|
||||
scope, account = self._account(snapshot)
|
||||
issued = self._issued.get(scope)
|
||||
if issued != action or account["pending"] is not None:
|
||||
raise ValueError("探险动作已过期或已有请求待核对")
|
||||
team = self._team(snapshot, expected["id"])
|
||||
if team is None:
|
||||
raise ValueError("探险队已不在角色快照中")
|
||||
if action.kind == "explore_start":
|
||||
if _integer(team.get("status")) != 0:
|
||||
raise ValueError("探险队当前不可出发")
|
||||
area = self.areas.get(expected["area"])
|
||||
if area is None or not self.area_unlocked(snapshot, area):
|
||||
raise ValueError("探险地区已失效或未解锁")
|
||||
if _integer((snapshot.raw.get("master") or {}).get("ti")) < _integer(area.get("costTi")):
|
||||
raise ValueError("当前体力不足以出发")
|
||||
elif _integer(team.get("status")) != 1 or self.remaining(snapshot, team) is None or self.remaining(snapshot, team) > 0:
|
||||
raise ValueError("探险奖励当前不可领取")
|
||||
return scope, account
|
||||
|
||||
def mark_started(self, snapshot, action):
|
||||
with self._lock:
|
||||
if self._persistence_error:
|
||||
raise OSError(self._persistence_error)
|
||||
scope, account = self._validate_intent(snapshot, action)
|
||||
account["pending"] = {"kind": action.kind, "team_id": _integer(action.payload["exploreTeamId"]),
|
||||
"path": action.path, "payload": deepcopy(action.payload), "description": action.description,
|
||||
"message": action.description + ":请求进行中", "uncertain": False, "confirmed": False, "started_at": snapshot.now,
|
||||
"snapshot": self._fingerprint(self._team(snapshot, _integer(action.payload["exploreTeamId"]))),
|
||||
"expected": self._expected_snapshot(action, None)}
|
||||
try:
|
||||
self._save_state() # Durably block replay before the wire call.
|
||||
except Exception:
|
||||
account["pending"] = None
|
||||
raise
|
||||
return deepcopy(account["pending"])
|
||||
|
||||
def acknowledge(self, snapshot, action, response=None, *, _from_snapshot=False):
|
||||
with self._lock:
|
||||
scope, account = self._account(snapshot)
|
||||
pending = account["pending"]
|
||||
if pending is None:
|
||||
return False
|
||||
if not _from_snapshot:
|
||||
if not isinstance(response, dict) or response.get("resCode", 0) not in (0, "0"):
|
||||
raise ValueError("探险请求尚未确认成功")
|
||||
if pending["kind"] != action.kind or pending["path"] != action.path or pending["payload"] != action.payload:
|
||||
raise ValueError("探险回包与待核对动作不匹配")
|
||||
self._verify_response(pending, response)
|
||||
pending.update(confirmed=True, uncertain=False,
|
||||
message=action.description + ":成功已确认,等待角色快照同步,禁止重放",
|
||||
expected=self._expected_snapshot(action, response))
|
||||
self._issued.pop(scope, None)
|
||||
self._save_state()
|
||||
return True
|
||||
|
||||
def _expected_snapshot(self, action, response):
|
||||
expected = self._fingerprint_action(action)
|
||||
team = response.get("exploreTeam") if isinstance(response, dict) else None
|
||||
if action.kind == "explore_start" and isinstance(team, dict):
|
||||
expected["endTime"] = str(team.get("endTime") or "")
|
||||
else:
|
||||
expected["endTime"] = ""
|
||||
return expected
|
||||
|
||||
@staticmethod
|
||||
def _verify_response(pending, response):
|
||||
if pending["kind"] == "explore_start":
|
||||
team = response.get("exploreTeam")
|
||||
if not isinstance(team, dict):
|
||||
# Success is definite; the next snapshot must still supply the
|
||||
# authoritative timer/membership rather than a local guess.
|
||||
return
|
||||
if _integer(team.get("id")) != pending["team_id"] or _integer(team.get("status")) != 1:
|
||||
raise ValueError("探险出发回包的队伍状态不匹配")
|
||||
elif "rewardResult" not in response and "monExp" not in response:
|
||||
return
|
||||
|
||||
def mark_uncertain(self, snapshot, action, reason="请求结果未知,需重新同步"):
|
||||
with self._lock:
|
||||
scope, account = self._account(snapshot)
|
||||
pending = account["pending"]
|
||||
if not pending or pending["kind"] != action.kind or pending["payload"] != action.payload:
|
||||
raise ValueError("没有对应的探险请求")
|
||||
pending.update(uncertain=True, message=str(reason) + ";禁止自动重放")
|
||||
self._save_state()
|
||||
return deepcopy(pending)
|
||||
|
||||
def reconcile(self, snapshot):
|
||||
"""Confirm a changed authoritative team; unchanged/missing stays blocked."""
|
||||
with self._lock:
|
||||
scope, account = self._account(snapshot)
|
||||
pending = account["pending"]
|
||||
if not pending:
|
||||
return False
|
||||
team = self._team(snapshot, pending["team_id"])
|
||||
if team is None:
|
||||
return False
|
||||
current = self._fingerprint(team)
|
||||
if pending["kind"] == "explore_start":
|
||||
expected = pending["expected"]
|
||||
end_time = seconds(team.get("endTime"))
|
||||
confirmed = (current["status"] == expected["status"] and current["area"] == expected["area"]
|
||||
and current["monsters"] == expected["monsters"]
|
||||
and math.isfinite(end_time) and end_time > pending["started_at"])
|
||||
else:
|
||||
# A pending start has a distinguishable active timer. A finish
|
||||
# must additionally have changed the previously active snapshot,
|
||||
# so another role/session's stale idle row cannot acknowledge it.
|
||||
confirmed = current["status"] == 0 and current != pending["snapshot"]
|
||||
if not confirmed:
|
||||
return False
|
||||
account["pending"] = None
|
||||
self._issued.pop(scope, None)
|
||||
self._save_state()
|
||||
return True
|
||||
|
||||
def execute(self, snapshot, action, call):
|
||||
"""Run one host-supplied callable; no real API is referenced here."""
|
||||
self.mark_started(snapshot, action)
|
||||
try:
|
||||
response = call(action.path, deepcopy(action.payload))
|
||||
self.acknowledge(snapshot, action, response)
|
||||
return response
|
||||
except Exception as error:
|
||||
try:
|
||||
self.mark_uncertain(snapshot, action, "探险请求结果未知:" + str(error))
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
raise
|
||||
|
||||
def area_unlocked(self, snapshot, area):
|
||||
# ExploreAreaVo.unlock -> StageCenter.isStagePass(passStage, 1).
|
||||
return _flag((snapshot.raw.get("history") or {}).get("passStage"), area.get("passStage"), 1)
|
||||
|
||||
def open(self, snapshot):
|
||||
# HistoryVo.exploreOpen uses passTask["1001008"].
|
||||
return _flag((snapshot.raw.get("history") or {}).get("passTask"), "1001008")
|
||||
|
||||
def team_rule(self, policy, team_id):
|
||||
return policy.teams.get(str(int(team_id))) or ExploreTeamRule()
|
||||
|
||||
@staticmethod
|
||||
def remaining(snapshot, team):
|
||||
if team.get("endTime") is None:
|
||||
return None
|
||||
try:
|
||||
end_time = seconds(team["endTime"])
|
||||
if not math.isfinite(end_time) or end_time <= 0:
|
||||
return None
|
||||
remaining = end_time - snapshot.now
|
||||
except (TypeError, ValueError, OverflowError):
|
||||
return None
|
||||
return max(0, remaining) if math.isfinite(remaining) else None
|
||||
|
||||
def _occupied(self, snapshot, excluded_team=None):
|
||||
result = set()
|
||||
for team in snapshot.raw.get("exploreTeams") or []:
|
||||
if isinstance(team, dict) and _integer(team.get("id")) != excluded_team and _integer(team.get("status")) == 1:
|
||||
result.add(str(team.get("area") or ""))
|
||||
return result
|
||||
|
||||
def _automatic_targets(self, ranch_policy):
|
||||
# Exploration does not consume monsters. These exclusions prevent
|
||||
# interference with other automation, not original-client eligibility.
|
||||
targets = _target_ids(getattr(ranch_policy, "feed_targets", {}),
|
||||
getattr(ranch_policy, "gift_targets", {}), getattr(ranch_policy, "breakthrough_targets", {}))
|
||||
legacy = _integer(getattr(ranch_policy, "feed_target", 0))
|
||||
if legacy > 0:
|
||||
targets.add(legacy)
|
||||
return targets
|
||||
|
||||
def monster_exclusion(self, snapshot, mon, ranch_policy, *, automatic):
|
||||
if mon.get("process") != 3:
|
||||
return "尚未成熟"
|
||||
if mon.get("inExploreTeam"):
|
||||
return "正在其他探险队"
|
||||
if not automatic:
|
||||
return ""
|
||||
mid = _integer(mon.get("id"))
|
||||
if mid in snapshot.team_ids:
|
||||
return "已占用:战斗队"
|
||||
if mid in _target_ids(getattr(ranch_policy, "feed_targets", {})) or mid == _integer(getattr(ranch_policy, "feed_target", 0)):
|
||||
return "已占用:喂养目标"
|
||||
if mid in _target_ids(getattr(ranch_policy, "gift_targets", {})):
|
||||
return "已占用:赠礼目标"
|
||||
if mid in _target_ids(getattr(ranch_policy, "breakthrough_targets", {})):
|
||||
return "已占用:突破目标"
|
||||
return ""
|
||||
|
||||
def _selection(self, snapshot, area, rule, ranch_policy, *, excluded=()):
|
||||
excluded = set(excluded)
|
||||
monsters = {mid: mon for mon in snapshot.raw.get("monsters") or []
|
||||
if isinstance(mon, dict) and (mid := _integer(mon.get("id"))) > 0}
|
||||
unavailable = {mid for team in snapshot.raw.get("exploreTeams") or [] if isinstance(team, dict)
|
||||
and _integer(team.get("status")) == 1 for mid in _team_monsters(team.get("monsters"))}
|
||||
if rule.monsters:
|
||||
reasons = []
|
||||
leader = monsters.get(rule.monsters[0])
|
||||
for position, mid in enumerate(rule.monsters):
|
||||
mon = monsters.get(mid)
|
||||
if mon is None:
|
||||
reasons.append(f"#{mid} 不存在")
|
||||
continue
|
||||
reason = self.monster_exclusion(snapshot, mon, ranch_policy, automatic=False)
|
||||
if mid in excluded or mid in unavailable:
|
||||
reason = "正在其他探险队"
|
||||
level = _integer(mon.get("level"))
|
||||
minimum = _integer((area.get("level") or [0, 0, 0])[position])
|
||||
if level < minimum:
|
||||
reason = f"等级不足 Lv.{level}/{minimum}"
|
||||
if position and leader is not None and level > _integer(leader.get("level")):
|
||||
reason = "队员等级不可高于队长"
|
||||
if reason:
|
||||
reasons.append(f"#{mid}:{reason}")
|
||||
return list(rule.monsters) if not reasons else None, ";".join(reasons)
|
||||
automatic_targets = self._automatic_targets(ranch_policy)
|
||||
candidates = []
|
||||
for mid, mon in monsters.items():
|
||||
if mid in excluded or mid in unavailable or mid in automatic_targets:
|
||||
continue
|
||||
if self.monster_exclusion(snapshot, mon, ranch_policy, automatic=True):
|
||||
continue
|
||||
candidates.append((mid, _integer(mon.get("level"))))
|
||||
candidates.sort(key=lambda row: (-row[1], row[0]))
|
||||
levels = area.get("level") or []
|
||||
if len(levels) != 3:
|
||||
return None, "地区队员等级配置缺失"
|
||||
leader = next((row for row in candidates if row[1] >= _integer(levels[0])), None)
|
||||
if leader is None:
|
||||
return None, "没有符合队长等级且未被其他自动化占用的魔物;可手动指定"
|
||||
selected = [leader]
|
||||
for position in (1, 2):
|
||||
member = next((row for row in candidates if row not in selected
|
||||
and _integer(levels[position]) <= row[1] <= leader[1]), None)
|
||||
if member is None:
|
||||
return None, "可自动选队员不足三只;可手动选择战斗或培养目标"
|
||||
selected.append(member)
|
||||
return [row[0] for row in selected], ""
|
||||
|
||||
def select_monsters(self, snapshot, area, ranch_policy, rule=None):
|
||||
return self._selection(snapshot, area, rule or ExploreTeamRule(), ranch_policy)[0]
|
||||
|
||||
def _blocked(self, pending):
|
||||
return Action("explore_blocked", pending.get("message", "探险请求待核对,禁止重放"), "",
|
||||
{"team_id": pending.get("team_id"), "pending": True})
|
||||
|
||||
def plan(self, snapshot, policy, ranch_policy):
|
||||
with self._lock:
|
||||
scope, account = self._account(snapshot)
|
||||
if self._persistence_error:
|
||||
return [Action("explore_blocked", self._persistence_error, "", {"pending": True})]
|
||||
if account["pending"]:
|
||||
return [self._blocked(account["pending"])]
|
||||
self._issued.pop(scope, None)
|
||||
if not policy.enabled:
|
||||
return []
|
||||
if not self.open(snapshot):
|
||||
return [Action("explore_blocked", "探险功能尚未解锁", "", {})]
|
||||
teams = [team for team in snapshot.raw.get("exploreTeams") or [] if isinstance(team, dict)]
|
||||
for team in teams:
|
||||
team_id = _integer(team.get("id"), -1)
|
||||
if (team_id > 0 and self.team_rule(policy, team_id).enabled
|
||||
and _integer(team.get("status")) == 1 and self.remaining(snapshot, team) == 0):
|
||||
return [self._issue(scope, Action("explore_finish", f"领取探险队 {team_id} 的奖励",
|
||||
"exploreService/finish", {"exploreTeamId": team_id}))]
|
||||
stamina = _integer((snapshot.raw.get("master") or {}).get("ti"))
|
||||
occupied = self._occupied(snapshot)
|
||||
for team in teams:
|
||||
team_id = _integer(team.get("id"), -1)
|
||||
rule = self.team_rule(policy, team_id)
|
||||
if team_id <= 0 or not rule.enabled or _integer(team.get("status")) != 0:
|
||||
continue
|
||||
area = self.areas.get(rule.area)
|
||||
if area is None or not self.area_unlocked(snapshot, area) or rule.area in occupied:
|
||||
continue
|
||||
cost = _integer(area.get("costTi"))
|
||||
if cost <= 0 or stamina < cost + policy.reserve_ti:
|
||||
continue
|
||||
monsters, _ = self._selection(snapshot, area, rule, ranch_policy)
|
||||
if monsters is None:
|
||||
continue
|
||||
return [self._issue(scope, Action("explore_start", f"探险队 {team_id} → {area.get('name') or rule.area}",
|
||||
"exploreService/start", {"exploreTeamId": team_id, "monsters": monsters, "area": rule.area}))]
|
||||
return []
|
||||
|
||||
def _issue(self, scope, action):
|
||||
self._issued[scope] = deepcopy(action)
|
||||
return action
|
||||
|
||||
def _diagnosis(self, snapshot, team, policy, ranch_policy):
|
||||
team_id = _integer(team.get("id"), -1)
|
||||
rule = self.team_rule(policy, team_id)
|
||||
area = self.areas.get(rule.area)
|
||||
remaining = self.remaining(snapshot, team)
|
||||
status = _integer(team.get("status"))
|
||||
members = _team_monsters(team.get("monsters"))
|
||||
selected, reason = (None, "")
|
||||
if status == 1:
|
||||
state = "可领取" if remaining == 0 else "探索中" if remaining is not None else "状态待同步"
|
||||
else:
|
||||
state = "空闲"
|
||||
if not self.open(snapshot):
|
||||
state, reason = "未解锁", "完成指定主线后解锁探险"
|
||||
elif not rule.enabled:
|
||||
state, reason = "未启用", "勾选此队伍后参与自动探险"
|
||||
elif status != 0:
|
||||
pass
|
||||
elif area is None:
|
||||
state, reason = "待配置", "请选择普通探险地区"
|
||||
elif not self.area_unlocked(snapshot, area):
|
||||
state, reason = "地区未解锁", f"需通关 {area.get('passStage') or '指定关卡'} 难度1"
|
||||
elif rule.area in self._occupied(snapshot):
|
||||
state, reason = "地区占用", "同一地区已有队伍探索"
|
||||
elif _integer((snapshot.raw.get("master") or {}).get("ti")) < _integer(area.get("costTi")) + policy.reserve_ti:
|
||||
state, reason = "体力不足", f"需要 {area.get('costTi')},另保留 {policy.reserve_ti}"
|
||||
else:
|
||||
selected, reason = self._selection(snapshot, area, rule, ranch_policy)
|
||||
state = "可出发" if selected is not None else "队员不足"
|
||||
_, account = self._account(snapshot)
|
||||
if account["pending"]:
|
||||
state = "待核对"
|
||||
reason = account["pending"]["message"]
|
||||
monsters = members if status == 1 else selected or rule.monsters
|
||||
return {"team_id": team_id, "enabled": rule.enabled, "area": rule.area,
|
||||
"area_name": (area or {}).get("name", ""), "state": state, "reason": reason,
|
||||
"remaining": remaining if status == 1 else None, "monster_ids": monsters,
|
||||
"cost_ti": _integer((area or {}).get("costTi")), "cost_time": _integer((area or {}).get("costTime")),
|
||||
"manual": bool(rule.monsters), "can_auto": self._selection(snapshot, area, ExploreTeamRule(), ranch_policy)[0] is not None if area else False}
|
||||
|
||||
def rows(self, snapshot, policy, ranch_policy):
|
||||
with self._lock:
|
||||
return [self._diagnosis(snapshot, team, policy, ranch_policy)
|
||||
for team in snapshot.raw.get("exploreTeams") or [] if isinstance(team, dict)]
|
||||
|
||||
def member_options(self, snapshot, team_id, policy, ranch_policy):
|
||||
"""Small worker DTOs: automatic exclusion is advisory for manual picks."""
|
||||
rule = self.team_rule(policy, team_id)
|
||||
area = self.areas.get(rule.area)
|
||||
if area is None:
|
||||
return []
|
||||
occupied = {mid for team in snapshot.raw.get("exploreTeams") or [] if isinstance(team, dict)
|
||||
and _integer(team.get("id")) != _integer(team_id) and _integer(team.get("status")) == 1
|
||||
for mid in _team_monsters(team.get("monsters"))}
|
||||
result = []
|
||||
for mon in snapshot.raw.get("monsters") or []:
|
||||
if not isinstance(mon, dict):
|
||||
continue
|
||||
mid = _integer(mon.get("id"))
|
||||
if mid <= 0:
|
||||
continue
|
||||
reason = self.monster_exclusion(snapshot, mon, ranch_policy, automatic=True)
|
||||
if mid in occupied:
|
||||
reason = "正在其他探险队"
|
||||
result.append({"id": mid, "level": _integer(mon.get("level")),
|
||||
"label": self.catalog.monster_label(mon), "automatic": not reason, "reason": reason})
|
||||
result.sort(key=lambda row: (-row["level"], row["id"]))
|
||||
return result
|
||||
Reference in New Issue
Block a user