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
+239 -4
View File
@@ -1,11 +1,13 @@
from __future__ import annotations
from copy import copy, deepcopy
from dataclasses import replace
from dataclasses import asdict, replace
from functools import wraps
import json
import os
from pathlib import Path
import threading
import time
import uuid
from types import SimpleNamespace
from .model import Action, Catalog, Planner, Policy, Snapshot, seconds
from .daily import DailyLedger, DailyPolicy, selected_entries
@@ -22,6 +24,8 @@ from .battles import BattleJournal, BattleOrchestrator, CancelledBeforeDispatch,
from .progression import ProgressionIntent, ProgressionPlanner, ProgressionPolicy
from .battle_messages import battle_message
from .maps import stages
from .exploration import ExplorePlanner, ExplorePolicy
from .breakthrough import BreakthroughPlanner
def account_serial(method):
@@ -78,6 +82,17 @@ class Engine:
self.daily_ledger = DailyLedger(folder / "daily_claims.json" if folder else None)
self.sweep_policy = SweepPolicy()
self.sweeper = SweepRunner(catalog, folder / "sweep_runs.json" if folder else None)
self.explore_planner = ExplorePlanner(catalog)
self.explore_policy = ExplorePolicy()
self.breakthrough_planner = BreakthroughPlanner(catalog)
self.automation_state_path = folder / "automation_state.json" if folder else None
self._explore_pending_last_check = 0
self._explore_pending_confirmed = False
self._breakthrough_pending = None
self._breakthrough_pending_last_check = 0
self._breakthrough_pending_confirmed = False
self._automation_load_error = ""
self._load_automation_state()
self.progression_policy = ProgressionPolicy()
self.progression_view_active = False
self.progression_planner = None
@@ -111,6 +126,193 @@ class Engine:
self._battle_runtimes = {"original": battle_runtime, "experimental": experimental_runtime}
self._selected_battle_mode = "original"
def _load_automation_state(self):
if not self.automation_state_path:
return
if not self.automation_state_path.exists():
self._automation_state = {"version": 1, "exploration": self.explore_planner.export_state(), "breakthrough": None}
self._save_automation_state()
return
try:
state = json.loads(self.automation_state_path.read_text(encoding="utf-8"))
if not isinstance(state, dict) or state.get("version") != 1 or set(state) != {"version", "exploration", "breakthrough"}:
raise ValueError("自动操作策略状态版本或结构无效")
if not isinstance(state["exploration"], dict):
raise ValueError("探险持久化状态无效")
self.explore_planner.restore_state(state["exploration"])
self._automation_state = deepcopy(state)
pending = state.get("breakthrough")
if pending is not None:
required = {"kind", "monster_id", "type_id", "attribute", "before", "item_type_ids", "path", "payload", "uncertain", "message", "role_id"}
if (not isinstance(pending, dict) or set(pending) != required or pending["kind"] not in ("potential", "breakthrough")
or type(pending["monster_id"]) is not int or pending["monster_id"] <= 0
or not isinstance(pending["role_id"], str) or not pending["role_id"]
or not isinstance(pending["payload"], dict) or not isinstance(pending["item_type_ids"], list)):
raise ValueError("突破待核对状态无效,保留文件并禁止重发")
if pending["kind"] == "potential":
if pending["attribute"] not in ("atk", "def", "hp", "dex") or type(pending["before"]) not in (int, float):
raise ValueError("补潜能待核对状态无效")
elif type(pending["before"]) is not int:
raise ValueError("潜能阶段待核对状态无效")
pending = deepcopy(pending)
pending.update(uncertain=True, message="上次进程突破请求结果未知,需由快照核对,禁止重放")
self._breakthrough_pending = pending
except (OSError, ValueError, TypeError, KeyError, AttributeError) as error:
# A failed restore stays fail-closed in memory; do not overwrite the evidence.
self._breakthrough_pending = {"kind": "invalid", "role_id": "", "message": "自动操作策略状态无法读取,禁止重发", "uncertain": True}
self._explore_pending_confirmed = False
self._automation_load_error = str(error)
def _save_automation_state(self):
if not self.automation_state_path:
return
if self._automation_load_error:
self.auto = False
raise ValueError("自动操作策略状态无法读取;保留原文件,禁止覆盖或重发")
value = {"version": 1, "exploration": self.explore_planner.export_state(), "breakthrough": self._breakthrough_pending}
if self._automation_state == value:
return
self.automation_state_path.parent.mkdir(parents=True, exist_ok=True)
temporary = self.automation_state_path.with_name(self.automation_state_path.name + "." + uuid.uuid4().hex + ".tmp")
try:
with temporary.open("w", encoding="utf-8") as stream:
json.dump(value, stream, ensure_ascii=False, indent=2, allow_nan=False)
stream.flush()
os.fsync(stream.fileno())
temporary.replace(self.automation_state_path)
self._automation_state = deepcopy(value)
except OSError:
self.auto = False
raise
finally:
temporary.unlink(missing_ok=True)
@staticmethod
def _automation_pending_message(planner, snapshot):
pending = planner.pending(snapshot)
return pending.get("message") if pending else ""
def _reconcile_exploration(self):
if self._automation_load_error:
return
pending = self.explore_planner.pending(self.snapshot)
if not pending:
return
if pending.get("uncertain"):
self.explore_planner.reconcile(self.snapshot)
else:
# A transport reply is not proof of server state; use the same fresh
# team fingerprint validation as an unknown-result recovery.
pending["uncertain"] = True
self.explore_planner.reconcile(self.snapshot)
self._save_automation_state()
def _discard_unsent_automation(self, *, explore=False, before=None):
"""Rollback is valid only before the host has invoked Client.call."""
if explore:
if before is not None:
self.explore_planner.restore_state(before)
else:
self._breakthrough_pending = None
self._save_automation_state()
def _reconcile_breakthrough(self):
pending = self._breakthrough_pending
if not pending:
return
if pending.get("kind") == "invalid":
return
if str(self.snapshot.raw.get("master", {}).get("id")) != pending.get("role_id"):
return
mon = self.snapshot.monsters.get(int(pending.get("monster_id", 0)))
if not mon or str(mon.get("typeId")) != str(pending.get("type_id")):
return
if pending["kind"] == "potential":
current, previous = mon.get("p" + pending["attribute"].capitalize()), pending.get("before")
if current is None or previous is None:
return
try:
confirmed = float(current) > float(previous)
except (TypeError, ValueError, OverflowError):
return
else:
try:
confirmed = int(mon.get("potentialLevel") or 0) > int(pending.get("before"))
except (TypeError, ValueError, OverflowError):
return
if confirmed:
self._breakthrough_pending = None
self._save_automation_state()
def _execute_explore(self, action):
before = self.explore_planner.export_state()
try:
self.explore_planner.mark_started(self.snapshot, action)
try:
self._save_automation_state()
except Exception:
# No wire call occurred: only this pre-dispatch failure may roll back.
self.explore_planner.restore_state(before)
self.auto = False
raise
if not self.auto or self._progression_cancel.is_set():
self._discard_unsent_automation(explore=True, before=before)
return self.snapshot, self.plans(), "探险请求尚未发送,已取消"
try:
response = self.client.call(action.path, deepcopy(action.payload))
self.explore_planner.acknowledge(self.snapshot, action, response)
self._save_automation_state()
except Exception as error:
self.explore_planner.mark_uncertain(self.snapshot, action, "探险请求结果未知:" + str(error))
self._save_automation_state()
self.auto = False
raise
self._explore_pending_last_check = time.monotonic()
self._explore_pending_confirmed = False
self.read_snapshot(sync_master=False)
return self.snapshot, self.plans(), action.description + ";已读取新快照核对"
except Exception:
self.auto = False
raise
def _execute_breakthrough(self, action):
if self._breakthrough_pending:
return self.snapshot, [], "突破请求待核对,禁止重发"
mon = self.snapshot.monsters[int(action.payload["monId"])]
attribute = action.payload.get("monsterAttr", "")
before = mon.get("p" + attribute.capitalize()) if action.kind == "potential" else mon.get("potentialLevel")
item_ids = ([int(action.payload["traceInfo"]["itemTypeId"])] if action.kind == "potential" else
[int(item_id) for item_id in action.payload["itemIds"]])
self._breakthrough_pending = {"kind": action.kind, "monster_id": int(mon["id"]), "type_id": str(mon.get("typeId")),
"attribute": attribute, "before": before, "item_type_ids": item_ids,
"path": action.path, "payload": deepcopy(action.payload), "uncertain": False,
"role_id": str(self.snapshot.raw.get("master", {}).get("id") or ""),
"message": action.description + ":请求进行中"}
try:
self._save_automation_state() # Must persist before any material request.
except Exception:
self._breakthrough_pending = None
self.auto = False
raise
if not self.auto or self._progression_cancel.is_set():
self._discard_unsent_automation()
return self.snapshot, self.plans(), "突破请求尚未发送,已取消"
try:
response = self.client.call(action.path, deepcopy(action.payload))
if not isinstance(response, dict) or response.get("resCode", 0) not in (0, "0"):
raise ValueError("突破请求尚未确认成功")
self._breakthrough_pending["message"] = action.description + ":请求已确认,等待新快照核对"
self._save_automation_state()
except Exception as error:
self._breakthrough_pending.update(uncertain=True, message="突破请求结果未知,禁止自动重发:" + str(error))
self._save_automation_state()
self.auto = False
raise
self._breakthrough_pending_last_check = time.monotonic()
self._breakthrough_pending_confirmed = False
self.read_snapshot(sync_master=False)
return self.snapshot, self.plans(), action.description + ";已读取新快照核对"
def cancel_progression(self):
"""Safe on Qt's thread while a worker is running; never waits or calls APIs."""
with self._progression_cancel_lock:
@@ -313,7 +515,11 @@ class Engine:
"已从持久化成功回包恢复本地任务检查点;未重发请求")
def pending_recovery_due(self):
return not self.demo and bool(self._progression_pending()) and time.monotonic() - self.last_pending_check >= 120
now = time.monotonic()
automation = bool(self.snapshot and (
self.explore_planner.pending(self.snapshot) and now - self._explore_pending_last_check >= 120
or self._breakthrough_pending and now - self._breakthrough_pending_last_check >= 120))
return not self.demo and bool(automation or self._progression_pending() and now - self.last_pending_check >= 120)
def _resume_pending_task_clock(self):
record = self.battle_journal.pending(self.snapshot)
@@ -678,6 +884,8 @@ class Engine:
rows.append(mon)
self.snapshot.raw["monsters"] = rows
self.gift_planner.apply_confirmed(self.snapshot)
self._reconcile_exploration()
self._reconcile_breakthrough()
self.sweeper.recover_reward_event(self.snapshot, getattr(getattr(self.client, "trace", None), "path", None))
self._refresh_progression_cache()
return self.snapshot
@@ -801,6 +1009,14 @@ class Engine:
return self.snapshot, self.plans(), recovered
pending = self.battle_journal.pending(self.snapshot) or {}
return self.snapshot, [], message + ";" + (pending.get("message") or "有待核对的任务 / 战斗,已暂停冲突操作") + ";后台每2分钟自动核对"
explore_pending = self.explore_planner.pending(self.snapshot)
if explore_pending or self._breakthrough_pending:
self.pending_hatches = []
if explore_pending:
message += ";" + explore_pending.get("message", "探险请求待核对") + ";后台每2分钟自动核对"
if self._breakthrough_pending:
message += ";" + self._breakthrough_pending.get("message", "突破请求待核对") + ";后台每2分钟自动核对"
return self.snapshot, [], message
try:
plans = self.plans()
except (ValueError, TypeError, KeyError, AttributeError) as error:
@@ -812,6 +1028,19 @@ class Engine:
action = actions[0] if actions else None
if action and defer_hatch and action.kind == "hatch":
action = None
if self.auto and action and action.kind.startswith("explore_"):
if action.kind == "explore_blocked" or not action.path:
blocked = next((candidate for candidate in plans if candidate.path and not candidate.kind.startswith("explore_")), None)
if blocked is None:
return self.snapshot, plans, action.description
self.planner.notes.append(action.description)
action = blocked
else:
self.last_executed = True
return self._execute_explore(action)
if self.auto and action and action.kind in ("potential", "breakthrough"):
self.last_executed = True
return self._execute_breakthrough(action)
if self.auto and action is not None:
self.last_executed = True
if action.kind == "progression":
@@ -998,14 +1227,20 @@ 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)
explore = self.explore_planner.plan(self.snapshot, self.explore_policy, policy)
breakthrough_policy = SimpleNamespace(**(asdict(policy) | {"item_reserves": dict(self.quest_policy.item_reserves)}))
breakthrough = self.breakthrough_planner.plan(self.snapshot, breakthrough_policy,
targets=policy.breakthrough_targets, enabled=not self._breakthrough_pending) if policy.breakthrough_targets else None
self.planner.notes.extend(self.gift_planner.notes)
self.planner.notes.extend(self.breakthrough_planner.notes)
breakthroughs = [breakthrough] if breakthrough else []
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]
commission = [action for action in progression if self._is_commission(action.payload["intent"])]
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 + sweep_actions
return quests + commission[:1] + daily + progression[:1] + explore + breakthroughs + gifts + ranch + sweep_actions
return commission[:1] + quests + daily + progression[:1] + explore + breakthroughs + gifts + ranch + sweep_actions
@account_serial
def claim_daily_entry(self, entry):