Add ranch retention, breakthroughs and exploration
This commit is contained in:
@@ -0,0 +1,293 @@
|
||||
"""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
|
||||
Reference in New Issue
Block a user