Files
myrzx_bot/ranch_assistant/engine.py
T

1480 lines
85 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.
from __future__ import annotations
from copy import copy, deepcopy
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
from .sweeping import SweepPolicy, SweepRunner
from .quests import QuestPolicy, TaskPlanner
from .market import PurchaseBudget
from .management import expansion_quote, manual_monster_actions
from .gifts import GiftPlanner
from .master_sync import MasterSync
from .stage_cache import StageCache
from .drop_statistics import reward_text
from .cultivation import CultivationSelector
from .battles import BattleJournal, BattleOrchestrator, CancelledBeforeDispatch, digest, gameplay_response, public_data, value
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):
"""Serialize whole operations, not just individual Client.call requests."""
@wraps(method)
def invoke(self, *args, **kwargs):
with self.battle_journal.lock:
return method(self, *args, **kwargs)
return invoke
def single_flight(method):
@wraps(method)
def invoke(self, *args, **kwargs):
generation = self._progression_cancel_generation
if not self.battle_journal.lock.acquire(blocking=False):
return self.snapshot, [], "同账号已有任务 / 战斗正在执行"
try:
with self._progression_cancel_lock:
if self.auto and generation == self._progression_cancel_generation and self._progression_cancel.is_set():
self._progression_cancel = threading.Event()
return method(self, *args, **kwargs)
finally:
self.battle_journal.lock.release()
return invoke
class Engine:
def __init__(self, catalog, client=None, budget_path=None, *, game_data=None, battle_runtime=None, experimental_runtime=None):
self.catalog, self.client = catalog, client
folder = Path(budget_path).parent if budget_path else None
self.cultivation = CultivationSelector(catalog, folder / "cultivation_choices.json" if folder else None)
self.planner = Planner(catalog, self.cultivation)
self.hatch_planner = Planner(catalog, self.cultivation)
self.pending_hatches = []
self.gift_planner = GiftPlanner(catalog, self.cultivation)
self.policy = Policy()
self.quest_policy = QuestPolicy()
self.tasks = TaskPlanner(catalog)
self.snapshot = None
self.demo = client is None
self.auto = False
self.last_heartbeat = 0
self.last_pending_check = 0
self.heartbeat_enabled = True
self.purchase_budget = PurchaseBudget(budget_path)
self.last_draw = ""
self.growth_cache = {}
self.growth_attempts = {}
self.master_sync = MasterSync(catalog)
self.last_executed = False
self.stage_cache = StageCache(catalog, folder / "maps.json" if folder else None)
self.daily_policy = DailyPolicy()
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
self.game_data = game_data
self._progression_namespace = str(folder.resolve()) if folder else ""
self._progression_state_loaded = False
self._battle_catalog_ready = False
self.battle_journal = BattleJournal(folder / "progression" / "journal.json" if folder else None)
self.battles = BattleOrchestrator(catalog, self.battle_journal, battle_runtime, self.sweeper,
request_builder=self._battle_request, observer=self._battle_observer)
self._progression_cancel = threading.Event()
self._progression_cancel_lock = threading.Lock()
self._progression_cancel_generation = 0
self._progression_cache_key = None
self._progression_rows = []
self._progression_intents = []
self._commission_planner_available = False
self._commission_offer_reason = ""
self._commission_offer_checks = {}
self._map_challenge_reasons = {}
self._map_reason_snapshot = None
self._map_reason_team = ""
self._progression_records = []
self._progression_error = ""
self._planner_pending = False
self._capability_cache = {}
self._battle_snapshot_source = None
self._battle_snapshot_digest = ""
self._battle_roster_digest = None
self._battle_roster = None
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:
self.auto = False
self._progression_cancel_generation += 1
self._progression_cancel.set()
def progression_rows(self):
"""A cached view only. Full-table planning always runs in an account worker."""
return deepcopy(self._progression_rows)
def progression_records(self):
return deepcopy(self._progression_records)
def _progression_pending(self):
return self.snapshot is not None and (self.battle_journal.pending(self.snapshot)
or self.sweeper.state.get("pending") or self._planner_pending)
def _require_no_battle(self):
if self._progression_pending():
raise ValueError("有待核对的任务 / 战斗,已暂停冲突写操作;后台每2分钟自动核对")
def _ensure_progression(self):
if self.game_data is None:
from .game_data import load_progression_data
self.game_data = load_progression_data()
if self.progression_planner is None:
self.progression_planner = ProgressionPlanner(self.catalog, self.game_data, account_key=self._progression_namespace)
if not self._progression_state_loaded and self.snapshot is not None:
stored = deepcopy(self.battle_journal.role(self.snapshot).get("planner_state"))
if stored:
for account in stored.get("accounts", {}).values():
pending = account.get("pending")
if pending:
pending["token"] = pending.pop("intent_id", "")
pending["intent"]["token"] = pending["intent"].pop("intent_id", "")
self.progression_planner.restore_state(stored)
self._progression_state_loaded = True
# A separate view preserves the commission-only legacy catalog.
if not self._battle_catalog_ready:
battle_catalog = copy(self.catalog)
positions = dict(self.catalog.data.get("stage_task_positions", {}))
for key, task in self.game_data.tasks.items():
positions[str(key)] = [step.get("position", "") for step in task.get("steps", [])]
battle_catalog.data = self.catalog.data | {"stage_info": self.game_data.stages,
"stage_sp": self.game_data.stage_sp, "stage_task_positions": positions,
"game_setting": self.game_data.game_setting}
self.battles.catalog = battle_catalog
self._battle_catalog_ready = True
self._select_battle_runtime(self.progression_policy.battle_mode)
def _select_battle_runtime(self, mode):
if mode not in ("original", "experimental"):
raise ValueError("未知战斗模式,未开始战斗")
if self.battles.runtime is not None:
self._battle_runtimes[self._selected_battle_mode] = self.battles.runtime
self._selected_battle_mode = mode
runtime = self._battle_runtimes.get(mode)
if runtime is None:
try:
if mode == "experimental":
from .battle_simulator import ExperimentalBattleRuntime as Runtime
else:
from .battle_runtime import BattleRuntime as Runtime
except ImportError:
pass
else:
runtime = self._battle_runtimes[mode] = Runtime()
self.battles.runtime = runtime
def _persist_progression(self, *, save=True):
state = self.progression_planner.export_state()
self._planner_pending = any(account.get("pending") for account in state.get("accounts", {}).values())
for account in state.get("accounts", {}).values():
account["applied"] = account["applied"][-1000:]
account["received"] = {key: {field: task[field] for field in ("id", "typeId", "curStep", "stepValue") if field in task}
for key, task in account["received"].items()}
pending = account.get("pending")
if pending:
# These are planner-issued hashes, not authentication tokens.
# Store them under an unambiguous local name on disk.
pending["intent_id"] = pending.pop("token")
pending["intent"]["intent_id"] = pending["intent"].pop("token")
for task in account["tasks"].values():
cutoff = min(task.get("cursor", 0), task.get("server_step", 0))
for field in ("before", "after", "acknowledged"):
task[field] = [number for number in task.get(field, []) if number >= cutoff]
state = public_data(state)
target = self.battle_journal.role(self.snapshot)
if target.get("planner_state") != state:
target["planner_state"] = state
if save:
self.battle_journal.save()
def _battle_observer(self, event, intent, response):
if value(intent, "kind") == "map_battle":
stage = SimpleNamespace(stage_id=str(value(intent, "stage_id")), level=str(value(intent, "difficulty")))
key = self.sweeper.key(self.snapshot, stage)
if event == "started":
record = self.battle_journal.pending(self.snapshot)
if record is not None:
record["map_roster_signature"] = self._map_roster_signature(self.snapshot, value(intent, "team", self.sweep_policy.team))
self.sweeper.state["counts"][key] = self.sweeper.used(self.snapshot, stage) + 1
self.sweeper.save()
elif event == "cancelled_before_start":
self.sweeper.state["counts"][key] = max(0, self.sweeper.used(self.snapshot, stage) - 1)
self.sweeper.save()
elif event == "loss":
record = self.battle_journal.pending(self.snapshot) or {}
self.sweeper.state.setdefault("challenge_failures", {})[key] = record.get("map_roster_signature") or self._map_roster_signature(self.snapshot, value(intent, "team", self.sweep_policy.team))
self.sweeper.save()
elif event in ("settled", "event"):
self.sweeper.state.setdefault("challenge_failures", {}).pop(key, None)
self.sweeper.save()
return None
farming = self._is_farm(intent)
if value(intent, "kind") != "progression_battle" and not farming:
return None
planner = self.progression_planner
if event == "cancelled_before_start":
self._cancel_unsent_progression(intent)
return None
if farming:
if event == "started":
planner.mark_started(self.snapshot, intent) # validates the issued ordinary intent only
# Farming is a normal map action. Its journal and fresh server
# snapshot govern the result; it never acknowledges a task step.
return None
if event == "validate":
account = planner.export_state().get("accounts", {}).get(intent.account_key, {})
task = account.get("tasks", {}).get(f"{intent.task_id}:{intent.task_type_id}", {})
return task.get("cursor") == intent.step_number
if event == "started":
planner.mark_started(self.snapshot, intent)
elif event in ("settled", "event"):
if not planner.acknowledge(self.snapshot, intent, gameplay_response(response)):
raise ValueError("任务战斗结算已返回,但任务步骤确认未完成")
elif event == "loss":
planner.battle_lost(self.snapshot, intent)
self._persist_progression()
def _cancel_unsent_progression(self, intent):
"""Rollback only the matching planner send marker, before dispatch."""
state = self.progression_planner.export_state()
account = state.get("accounts", {}).get(value(intent, "account_key"), {})
pending = account.get("pending")
if pending:
if pending.get("token") != value(intent, "token") or pending.get("intent") != intent.to_dict():
raise ValueError("取消的未发送请求与任务检查点不匹配")
account["pending"] = None
self.progression_planner.restore_state(state)
self._persist_progression(save=False)
def _recover_confirmed_progression(self):
"""Replay only local acknowledgement of a durably received success."""
record = self.battle_journal.pending(self.snapshot)
if (not record or str(record.get("role_id")) != str(self.snapshot.raw["master"].get("id"))
or not str(record.get("kind", "")).startswith("progression_")):
return
battle = record["kind"] == "progression_battle"
confirmed = record.get("phase") == ("settlement_acknowledged" if battle else "acknowledged")
confirmed = confirmed or record.get("settlement_confirmed" if battle else "response_confirmed") is True
response = record.get("response")
if not confirmed or not isinstance(response, dict) or response.get("resCode", 0) not in (0, "0"):
return
path = record.get("path") or ""
if battle and path != "taskService/taskCompleteStep":
return
if not battle and path not in {"taskService/taskReceive", "taskService/taskLoopReceive", "taskService/taskLoopFlush",
"taskService/taskCompleteStep", "taskService/taskComplete", "taskService/taskUpdate"}:
return
state = self.progression_planner.export_state()
account = state.get("accounts", {}).get(record.get("account_key"), {})
intent_id = record.get("intent_id")
applied = bool(intent_id and intent_id in account.get("applied", []))
if not applied:
pending = self.progression_planner.pending(self.snapshot)
if not pending or not isinstance(pending.get("intent"), dict):
return
intent = ProgressionIntent(**pending["intent"])
if (pending.get("token") != intent.token or intent.blocked
or intent_id and intent.token != intent_id
or record.get("account_key") and intent.account_key != record["account_key"]):
return
if any(str(value(intent, field)) != str(record.get(field))
for field in ("kind", "task_id", "task_type_id", "step_number")):
return
# The current restore_state API restores durable accounts but not
# its transient issued-token registry. Rehydrate only this exact
# saved pending intent after validating the successful receipt.
# Cursor/story effects still belong exclusively to acknowledge.
issued = self.progression_planner._issued
if intent.token in issued and issued[intent.token] != intent.to_dict():
raise ValueError("持久化确认与已签发任务意图不匹配")
issued[intent.token] = intent.to_dict()
if not self.progression_planner.acknowledge(self.snapshot, intent, response):
return
self._persist_progression(save=False)
self.battle_journal.finish(self.snapshot, record, "win" if battle else "task",
"已从持久化成功回包恢复本地任务检查点;未重发请求")
def pending_recovery_due(self):
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)
if not self.auto or self._progression_cancel.is_set() or not self.battles.resumable_task_clock(record):
return ""
if record.get("kind") == "map_battle":
intent = {key: record.get(key) for key in ("kind", "task_id", "task_type_id", "step_number",
"stage_id", "difficulty", "battle_kind", "team", "path")}
return self.battles.resume_task_clock(self.client, self.snapshot, intent, self._map_policy(), cancel=self._progression_cancel)
pending = self.progression_planner.pending(self.snapshot) if self.progression_planner else None
if not pending or not isinstance(pending.get("intent"), dict):
return ""
intent = ProgressionIntent(**pending["intent"])
if (pending.get("token") != intent.token or intent.token != record.get("intent_id")
or intent.account_key != record.get("account_key")):
return ""
issued = self.progression_planner._issued
if intent.token in issued and issued[intent.token] != intent.to_dict():
return ""
issued[intent.token] = intent.to_dict()
return self.battles.resume_task_clock(self.client, self.snapshot, intent, self._intent_policy(intent),
cancel=self._progression_cancel)
def _battle_capability(self, intent):
try:
if self._is_commission(intent) and not self.quest_policy.battle_tasks:
return False, "战斗委托未启用;未开始战斗"
if self.battles.runtime is None:
return False, ("实验模型" if self.progression_policy.battle_mode == "experimental" else "原始战斗运行时") + "尚未提供,未开始战斗"
policy = self._intent_policy(intent)
preview = bool(value(intent, "task_type_id")) and not value(intent, "task_id") and not self._is_farm(intent)
if not preview:
reason = self.battles.resource_reason(self.snapshot, intent, policy, self.policy)
if reason:
return False, reason
key = digest({"snapshot": self._battle_snapshot_digest, "runtime": id(self.battles.runtime), "team": policy.team, "mode": policy.battle_mode,
**{name: value(intent, name) for name in ("task_type_id", "step_number", "stage_id", "difficulty", "battle_kind")}})
if key not in self._capability_cache:
request = self.battles.request(self.snapshot, intent, policy)
self._capability_cache[key] = self.battles.inspect(request)
while len(self._capability_cache) > 64:
self._capability_cache.pop(next(iter(self._capability_cache)))
return self._capability_cache[key]
except (ImportError, OSError, ValueError, TypeError, KeyError, AttributeError) as error:
return False, "战斗输入或运行时未就绪:" + str(error)
def _overlay_battle_capabilities(self, rows, intents):
battle_kinds = {"task", "battle", "passStage", "task_battle", "task_pass_stage", "ordinary_stage", "stage", "map_battle", "hidden"}
reasons = {}
adjusted = []
for intent in intents:
if value(intent, "kind") == "progression_loop_accept":
key = str(value(intent, "task_type_id"))
if key not in self._commission_offer_checks:
self._check_commission_offer(key)
supported, reason = self._commission_offer_checks[key]
if not supported:
intent = replace(intent, block_reason=reason)
if (value(intent, "kind") in ("progression_battle", "battle", "task_battle", "stage_battle", "map_battle")
or self._is_farm(intent) and not self._is_sweep_intent(intent)) and not value(intent, "block_reason"):
supported, reason = self._battle_capability(intent)
reasons[str(value(intent, "source_task_type_id") or value(intent, "task_type_id"))] = (supported, reason)
if not supported:
intent = replace(intent, block_reason=reason) if not isinstance(intent, dict) else intent | {"block_reason": reason}
adjusted.append(intent)
commissions = {str(value(intent, "task_type_id")): intent for intent in adjusted if self._is_commission(intent)}
farms = {str(value(intent, "source_task_type_id")): intent for intent in adjusted if self._is_farm(intent)}
for row in rows:
source_supported = row.get("supported") is not False
check = self._commission_offer_checks.get(str(row.get("task_type_id")))
if row.get("category") == "commission" and row.get("state") == "offered" and check is not None:
row.update(block_reason=check[1], next_action="接取城市委托" if check[0] else "暂不接取:" + check[1])
commission = commissions.get(str(row.get("task_type_id")))
if commission is not None:
row.update(next_action=value(commission, "description"), block_reason=value(commission, "block_reason", ""))
farm = farms.get(str(row.get("task_type_id")))
if farm is not None:
row.update(next_action=value(farm, "description"), block_reason=value(farm, "block_reason", ""),
battle_kind="sweep" if self._is_sweep_intent(farm) else "ordinary_stage",
stage_id=value(farm, "stage_id"), difficulty=value(farm, "difficulty"))
reason = row.get("block_reason") or row.get("blocked_reason") or ""
if row.get("battle_kind") in battle_kinds:
supported, runtime_reason = reasons.get(str(row.get("task_type_id")),
(False, "战斗运行时能力尚未核对;配置存在不代表已支持实战"))
row["supported"] = bool(source_supported and supported and not reason)
reason = reason or runtime_reason
else:
row["supported"] = bool(source_supported and not reason)
row["block_reason"] = row["blocked_reason"] = reason
return rows, adjusted
def _battle_request(self, snapshot, intent, policy, request):
self._ensure_progression()
self._select_battle_runtime(policy.battle_mode)
if self._battle_snapshot_source is not snapshot:
self._battle_snapshot_source = snapshot
self._battle_snapshot_digest = digest(snapshot.raw)
if self._battle_roster_digest != self._battle_snapshot_digest:
self._battle_roster = deepcopy(snapshot.raw)
self._battle_roster_digest = self._battle_snapshot_digest
task = bool(value(intent, "task_type_id")) and value(intent, "battle_kind") in ("task", "battle", "passStage", "task_battle", "task_pass_stage")
kind = value(intent, "battle_kind")
battle = self.game_data.task_battle(value(intent, "task_type_id"), value(intent, "step_number")) if task else \
self.game_data.stage_battle(value(intent, "stage_id"), value(intent, "difficulty", "1"))
prepared = request | {"snapshot": self._battle_roster,
"battle_mode": policy.battle_mode,
"context": "task_pass_stage" if task and kind == "passStage" else "task_battle" if task else "ordinary_stage",
"original_data": {"battle": battle, "manifest": self.game_data.manifest},
"roster": self._battle_roster, "task_id": value(intent, "task_id"),
"step_index": int(value(intent, "step_number", 1) or 1) - 1 if task else None}
if policy.battle_mode == "original":
from .battle_runtime import BattleRuntime
if isinstance(self.battles.runtime, BattleRuntime):
source = self.game_data.manifest.get("source", {})
prepared["runtime_request"] = {name: prepared[name] for name in (
"context", "roster", "stage_id", "task_id", "step_index")}
prepared["runtime_request"].update(difficulty=int(value(intent, "difficulty", 1) or 1), purpose="settlement",
original_data={"source": "original_apk", "resource_identity": {
"apk_sha256": source.get("apk_sha256"), "main_swf_sha256": source.get("main_swf_sha256")}})
return prepared
def _is_commission(self, intent):
if value(intent, "kind") in ("progression_loop_accept", "progression_loop_reset"):
return True
info = self.game_data.task(value(intent, "source_task_type_id") or value(intent, "task_type_id")) if self.game_data else None
return bool(info and info.get("type") == 4)
@staticmethod
def _is_farm(intent):
return bool(value(intent, "source_task_type_id")) and not value(intent, "task_id") and bool(value(intent, "stage_id"))
@staticmethod
def _is_sweep_intent(intent):
return value(intent, "kind") in ("sweep", "progression_sweep", "progression_farm_sweep", "progression_map_sweep") or value(intent, "battle_kind") == "sweep"
def _intent_policy(self, intent):
if value(intent, "kind") == "map_battle":
return self._map_policy()
if not self._is_commission(intent):
return self.progression_policy
quest = self.quest_policy
return replace(self.progression_policy, enabled=quest.enabled, mainline=False, sidequests=False,
commissions=True, accept=quest.accept, auto_farm=True, allow_items=quest.allow_items, allow_monsters=quest.allow_monsters,
max_money=quest.max_money, item_reserves=dict(quest.item_reserves))
def _check_commission_offer(self, type_id):
supported = self._commission_offer_supported(type_id)
self._commission_offer_checks[str(type_id)] = (supported,
"" if supported else self._commission_offer_reason or "委托后续步骤当前无法自动完成")
return supported
def _commission_offer_supported(self, type_id):
self._commission_offer_reason = "委托后续条件、剧情或战斗未验证支持,未消耗接取次数"
info = self.game_data.task(type_id)
if not info or info.get("type") != 4:
return False
for number, step in enumerate(info.get("steps", []), 1):
for name in (step.get("story"), step.get("afterStory")):
if name and (self.game_data.script(name) or {}).get("supported") is not True:
return False
kind = step.get("statusType")
if kind in ("battle", "passStage"):
if not self.quest_policy.battle_tasks:
return False
intent = {"kind": "progression_battle", "task_type_id": str(type_id), "task_id": 0,
"step_number": number, "battle_kind": "passStage" if kind == "passStage" else "task",
"stage_id": (step.get("statusValue") or {}).get("stage"),
"difficulty": (step.get("statusValue") or {}).get("level", 1)}
supported, reason = self._battle_capability(intent)
if not supported:
self._commission_offer_reason = reason
return False
else:
policy = self._intent_policy({"task_type_id": str(type_id)})
ready, _, _ = self.progression_planner.requirement(self.snapshot, step, {}, policy, self.policy)
if not ready:
sources = self.progression_planner.farming_intents(self.snapshot, step,
{"id": 0, "typeId": str(type_id), "curStep": number}, policy, self.policy)
if not any(self._is_sweep_intent(source) or self._battle_capability(source)[0] for source in sources):
return False
return bool(info.get("steps"))
def _refresh_progression_cache(self, *, force=False):
if self.snapshot is None:
return
if not (force or self.progression_view_active or self.progression_policy.enabled or self.quest_policy.enabled):
return
try:
self._ensure_progression()
self._recover_confirmed_progression()
self._battle_snapshot_source = self.snapshot
self._battle_snapshot_digest = digest(self.snapshot.raw)
key = digest({"snapshot": self._battle_snapshot_digest, "policy": vars(self.progression_policy),
"quests": vars(self.quest_policy), "ranch": vars(self.policy), "local_state": self.progression_planner.state_signature(self.snapshot),
"pending": self._progression_pending(), "runtime": id(self.battles.runtime), "day": int(self.snapshot.now // 86400)})
if force or key != self._progression_cache_key:
self._commission_offer_checks = {}
rows = self.progression_planner.rows(self.snapshot, self.progression_policy, self.policy, quest_policy=self.quest_policy)
intents = self.progression_planner.plan(self.snapshot, self.progression_policy, self.policy)
commission_plan = getattr(self.progression_planner, "commission_plan", None)
self._commission_planner_available = callable(commission_plan)
if self._commission_planner_available:
intents += commission_plan(self.snapshot, self.quest_policy, self.policy,
battle_policy=self.progression_policy, accept_supported=self._check_commission_offer)
intents.sort(key=lambda intent: not self._is_commission(intent))
self._progression_rows, self._progression_intents = self._overlay_battle_capabilities(rows, intents)
self._persist_progression()
self._progression_cache_key = digest({"snapshot": self._battle_snapshot_digest, "policy": vars(self.progression_policy),
"quests": vars(self.quest_policy), "ranch": vars(self.policy), "local_state": self.progression_planner.state_signature(self.snapshot),
"pending": self._progression_pending(), "runtime": id(self.battles.runtime), "day": int(self.snapshot.now // 86400)})
self._progression_error = ""
except (ImportError, OSError, ValueError, TypeError, KeyError, AttributeError) as error:
self._progression_error = "任务规划暂不可用:" + str(error)
self._progression_rows = [{"state": "unsupported", "supported": False, "blocked_reason": self._progression_error}]
self._progression_intents = []
self._progression_records = self.battle_journal.records(self.snapshot)
@account_serial
def refresh_progression(self):
if not self.demo:
self.read_snapshot(sync_master=False)
elif self.snapshot is None:
self.snapshot = demo_snapshot(self.catalog)
self._refresh_progression_cache(force=True)
pending = self.battle_journal.pending(self.snapshot)
message = self._progression_error or (pending.get("message") or "存在待核对的任务 / 战斗") if pending else self._progression_error or "已刷新任务与战斗记录"
return self.snapshot, self.plans(), message
@single_flight
@account_serial
def run_progression_once(self):
self.last_executed = False
if not self.demo:
self.read_snapshot(sync_master=False)
elif self.snapshot is None:
self.snapshot = demo_snapshot(self.catalog)
self._refresh_progression_cache()
return self._run_progression_intent()
def _run_progression_intent(self, intent=None):
if not self.progression_policy.enabled and not self.quest_policy.enabled:
return self.snapshot, self.plans(), "自动主线策略未启用"
if self._progression_pending():
return self.snapshot, [], "有待核对的任务 / 战斗;未重复提交"
if self._progression_cancel.is_set():
return self.snapshot, self.plans(), "任务推进已取消"
intents = self._progression_intents
if intent is None:
intent = next((i for i in intents if not value(i, "block_reason")), None)
if intent is None:
reasons = [str(value(i, "block_reason")) for i in intents if value(i, "block_reason")]
return self.snapshot, self.plans(), self._progression_error or (";".join(dict.fromkeys(reasons)) if reasons else "当前没有可执行的任务步骤")
if self.demo:
return self.snapshot, self.plans(), "演示只展示任务;不会伪造战斗、任务进度或奖励"
if value(intent, "block_reason"):
return self.snapshot, self.plans(), str(value(intent, "block_reason"))
effective_policy = self._intent_policy(intent)
if not effective_policy.enabled:
return self.snapshot, self.plans(), "对应任务策略未启用"
try:
self.last_executed = True
kind = value(intent, "kind")
if kind in ("progression_battle", "battle", "task_battle", "stage_battle", "map_battle", "sweep") or self._is_farm(intent):
message = self.battles.run(self.client, self.snapshot, intent, effective_policy,
cancel=self._progression_cancel, ranch=self.policy)
else:
message = self._execute_task_intent(intent)
if self.battle_journal.pending(self.snapshot) and kind == "progression_battle":
record = self.battle_journal.pending(self.snapshot)
reason = ("战果已保存;后台每2分钟核对,开启策略后自动续交" if self.battles.resumable_task_clock(record)
else "战斗待核对;后台每2分钟查询服务器状态,禁止重复提交")
self.progression_planner.mark_uncertain(self.snapshot, intent, reason)
self._persist_progression()
if not self._progression_cancel.is_set():
self.read_snapshot(sync_master=False)
return self.snapshot, self.plans(), message
except Exception:
if self.battle_journal.pending(self.snapshot) and not self._is_farm(intent) and value(intent, "kind", "").startswith("progression_"):
self.progression_planner.mark_uncertain(self.snapshot, intent, "任务 / 战斗结果待核对,禁止重放")
self._persist_progression()
raise
finally:
self._refresh_progression_cache(force=True)
def _execute_task_intent(self, intent):
path, kind = value(intent, "path", "") or "", value(intent, "kind")
payload = deepcopy(value(intent, "payload", {}) or {})
allowed = {"taskService/taskReceive": {"taskTypeId"}, "taskService/taskLoopReceive": {"taskTypeId", "city"},
"taskService/taskCompleteStep": {"taskId", "taskTypeId", "removeIds"},
"taskService/taskComplete": {"taskId", "taskTypeId"}, "taskService/taskLoopFlush": set(),
"taskService/taskUpdate": {"unlockTasks", "receiveTasks", "removeTasks"}}
local = kind in ("progression_navigate", "progression_dialogue", "progression_local_step") and not path
if not local and (path not in allowed or set(payload) != allowed[path]):
return "任务请求字段或本地剧情类型未受支持,未执行"
if path.endswith("taskUpdate") and (not all(isinstance(payload[k], list) for k in allowed[path])
or not any(payload.values())):
return "任务补链必须提供计算后的三个数组;未发送查询或空补链"
if self._progression_cancel.is_set():
return "任务推进已取消"
record = self.battle_journal.begin(self.snapshot, intent)
if local:
self.progression_planner.acknowledge(self.snapshot, intent)
self._persist_progression(save=False)
self.battle_journal.finish(self.snapshot, record, "local", "已保存普通剧情的本地检查点")
return "已推进普通剧情并保存本地检查点"
try:
self.progression_planner.mark_started(self.snapshot, intent)
self._persist_progression(save=False)
self.battle_journal.update(record, "request_pending")
try:
response = self.battles._call(self.client, path, payload, cancel=self._progression_cancel)
except CancelledBeforeDispatch:
self._cancel_unsent_progression(intent)
self.battle_journal.finish(self.snapshot, record, "cancelled", "任务请求尚未发送,已取消")
return record["message"]
self.battle_journal.update(record, "acknowledged", response=gameplay_response(response), response_confirmed=True)
acknowledged = self.progression_planner.acknowledge(self.snapshot, intent, gameplay_response(response))
self._persist_progression(save=False)
if acknowledged:
self.battle_journal.finish(self.snapshot, record, "task", "服务器已确认任务请求,已保存本地检查点")
else:
self.battle_journal.update(record, "unknown", message="任务成功回包缺少有效状态,等待核对")
return value(intent, "description", "任务请求已确认")
except Exception as error:
self.battle_journal.update(record, "unknown", message="任务请求结果未确认,禁止自动重试", error_type=type(error).__name__)
raise
@account_serial
def read_snapshot(self, *, sync_master=True):
if self._progression_pending():
self.last_pending_check = time.monotonic()
self.snapshot = self.client.snapshot()
self.battle_journal.reconcile(self.snapshot, trusted=True)
self.master_sync.apply(self.snapshot)
if sync_master and not self._progression_pending():
self.master_sync.settle(self.client, self.snapshot)
present = self.snapshot.monsters
self.growth_cache = {mid: entry for mid, entry in self.growth_cache.items() if mid in present}
self.growth_attempts = {key: stamp for key, stamp in self.growth_attempts.items() if key[0] in present}
rows = []
fields = ("gAtk", "gDef", "gHp", "gDex")
for mon in self.snapshot.raw["monsters"]:
mid = int(mon["id"])
entry = self.growth_cache.get(mid)
if entry:
start = seconds(mon.get("timeStart"))
if str(mon.get("typeId")) != entry["type"] or start > 0 and entry["start"] > 0 and start != entry["start"]:
self.growth_cache.pop(mid, None)
else:
confirmed = int(mon.get("mode") or 0) >= entry.get("mode", 0)
if entry.get("mode") == 2:
confirmed = confirmed and all(q is not None for q in self.catalog.quality(mon))
for field in fields:
if field in entry and mon.get(field) != entry[field]:
confirmed = False
if confirmed:
self.growth_cache.pop(mid, None)
else:
mon = dict(mon)
mon["mode"] = max(int(mon.get("mode") or 0), entry.get("mode", 0))
mon.update({field: entry[field] for field in fields if field in entry})
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
def master_sync_due(self):
return not self.demo and not self._progression_pending() and bool(self.master_sync.pending(self.snapshot))
@account_serial
def sync_master(self):
self.read_snapshot()
return self.snapshot, self.plans(), "已同步等级 / 体力"
@account_serial
def refresh_stages(self):
self.auto = False
if not self.demo:
self.read_snapshot()
elif self.snapshot is None:
self.snapshot = demo_snapshot(self.catalog)
self.stage_cache.get(self.snapshot, refresh=True)
return self.snapshot, self.plans(), "已刷新关卡并保存当前账号的地图缓存"
def remember_growth(self, response):
# MonsterCenter.checkGrowUpHandler treats these two arrays as the
# authoritative stage and growth values, including after a stale read.
if not isinstance(response, dict):
return
current = self.snapshot.monsters
for key in ("datas", "stackMonsterInfos"):
for row in response.get(key) or []:
if not isinstance(row, dict) or row.get("monsterId") is None:
continue
mid = int(row["monsterId"])
mon = current.get(mid)
if mon is None:
continue
entry = self.growth_cache.setdefault(mid, {"type": str(mon.get("typeId")), "start": seconds(mon.get("timeStart"))})
if key == "datas" and row.get("mode") in (0, 1, 2):
entry["mode"] = max(entry.get("mode", 0), int(row["mode"]))
else:
entry.update({field: row[field] for field in ("gAtk", "gDef", "gHp", "gDex") if row.get(field) is not None})
def settle_pending_growth(self, force=False):
if self._progression_pending():
return False
pending = self.snapshot.growth_pending(self.catalog)
now = time.monotonic()
if not pending or not force and all(now - self.growth_attempts.get(key, -1e12) < 60 for key in pending):
return False
for key in pending:
self.growth_attempts[key] = now
response = self.client.settle_growth()
self.remember_growth(response)
self.read_snapshot()
return True
def growth_sync_due(self):
if self.snapshot is None or self._progression_pending():
return False
now = time.monotonic()
return any(now - self.growth_attempts.get(key, -1e12) >= 60 for key in self.snapshot.growth_pending(self.catalog))
@account_serial
def sync_growth(self):
if self.demo:
if self.snapshot is None:
self.snapshot = demo_snapshot(self.catalog)
for mon in self.snapshot.raw["monsters"]:
if mon.get("process") == 2:
mon["mode"] = self.snapshot.expected_growth_mode(mon, self.catalog)
else:
self.read_snapshot()
self.settle_pending_growth()
pending = self.snapshot.growth_pending(self.catalog)
message = "已自动同步孵化 / 成长状态"
if pending:
message += f";仍有 {len(pending)} 只等待服务器确认阶段或资质"
return self.snapshot, self.plans(), message
@account_serial
def keep_alive(self):
if self.demo:
return "离线演示无需心跳"
self.last_heartbeat = time.monotonic()
self.client.call("heartBeatService/keepAlive")
return "会话心跳已更新"
@single_flight
@account_serial
def poll(self, *, hatch_only=False, defer_hatch=False):
self.last_executed = False
settled = False
if self.demo:
if self.snapshot is None:
self.snapshot = demo_snapshot(self.catalog)
for mon in self.snapshot.raw["monsters"]:
if mon.get("process") == 2:
mon["mode"] = self.snapshot.expected_growth_mode(mon, self.catalog)
else:
self.read_snapshot(sync_master=not hatch_only)
if not hatch_only:
settled = self.settle_pending_growth()
message = "状态已刷新" + (";已请求孵化 / 成长结算" if settled else "")
if self.sweeper.recovered_event:
message += ";已解除旧版对已结算奖励事件的误阻塞"
self.sweeper.recovered_event = False
if self.snapshot.growth_pending(self.catalog):
message += ";成长状态等待服务器确认,将自动检查"
if self.demo:
self._refresh_progression_cache()
if self._progression_pending():
self.pending_hatches = []
pending_map = (self.battle_journal.pending(self.snapshot) or {}).get("kind") == "map_battle"
recovered = self._resume_pending_task_clock() if not self.demo else ""
if recovered:
self.last_executed = True
if not self.battle_journal.pending(self.snapshot):
self.read_snapshot(sync_master=False)
if pending_map:
self.stage_cache.get(self.snapshot, refresh=True)
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:
self.auto = False
return self.snapshot, [], "状态已读取;策略暂不可用:" + str(error)
commission_actions = [action for action in plans if action.kind.startswith("quest_") or
action.kind == "progression" and self._is_commission(action.payload["intent"])]
actions = (commission_actions or self.pending_hatches) if hatch_only else plans
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":
return self._run_progression_intent(action.payload["intent"])
if action.kind == "daily":
entry = next(row for row in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger) if row.action == action)
self.claim_daily_entry(entry)
return self.snapshot, self.plans(), ("[演示] " if self.demo else "") + action.description
if action.kind == "sweep":
stage = self.sweeper.next(self.snapshot, self.sweep_policy)
if self.demo:
return self.snapshot, plans, "扫荡需要登录真实账号;演示不会提交战斗"
result = self.sweeper.run(self.client, self.snapshot, stage, self.sweep_policy)
self.read_snapshot()
label = "探索奖励事件已结算" if self.sweeper.last_outcome == "event" else "扫荡完成"
message = f"{label}:{stage.number} {stage.name} / 难度{stage.level};" + reward_text(self.sweeper.last_reward)
if self.sweeper.statistics_error:
message += ";" + self.sweeper.statistics_error
return self.snapshot, self.plans(), message
if action.kind == "map_challenge":
return self._run_map_challenge(action.payload["intent"])
if action.kind == "buy":
price = int(self.catalog.data["markets"][action.payload["id"]]["money"])
self.purchase_budget.record(self.snapshot.now, price * action.payload["num"], self.policy.daily_buy_money)
if self.demo:
self.apply_demo(action)
else:
response = self._execute_legacy_task(action) if action.kind.startswith("quest_") else self.client.call(action.path, action.payload)
if action.kind == "buy":
self.record_draw(response.get("eggs") or [])
if action.kind == "gift":
try:
self.gift_planner.remember_success(self.snapshot, action, response)
except ValueError:
self.auto = False
raise
self.read_snapshot(sync_master=not hatch_only)
if action.kind == "hatch":
stack_id = action.payload["eggs"][0]["stackId"]
slot = next((slot for slot in self.snapshot.raw["stacks"] if int(slot["id"]) == stack_id), None)
if slot is None or int(slot.get("monsterId") or 0) <= 0:
self.auto = False
raise ValueError("装填已返回,但坑位状态尚未同步;已停止,请刷新核对后再继续")
if action.kind == "feed" and any(mid in self.snapshot.monsters for mid in action.payload["foods"]):
self.auto = False
raise ValueError("喂养已返回,但素材状态尚未同步;已停止,请刷新核对后再继续")
message = ("[演示] " if self.demo else "") + action.description
if action.kind == "buy" and self.last_draw:
message += ";" + self.last_draw
try:
plans = self.plans()
except (ValueError, TypeError, KeyError, AttributeError) as error:
self.auto = False
plans = []
message += ";状态已读取,策略暂不可用:" + str(error)
if not plans and self.planner.notes:
message += ";" + ";".join(dict.fromkeys(self.planner.notes))
return self.snapshot, plans, message
def _execute_legacy_task(self, action):
"""Keep the commission scheduler, with the same durable replay barrier."""
payload = action.payload
task = next((task for task in self.snapshot.raw.get("currentTasks", [])
if str(task.get("id")) == str(payload.get("taskId"))), {})
intent = {"kind": action.kind, "description": action.description, "path": action.path, "payload": payload,
"task_id": payload.get("taskId"), "task_type_id": payload.get("taskTypeId"), "step_number": task.get("curStep")}
record = self.battle_journal.begin(self.snapshot, intent)
try:
self.battle_journal.update(record, "request_pending")
response = self.battles._call(self.client, action.path, payload)
self.battle_journal.update(record, "acknowledged", response=gameplay_response(response))
return response
except Exception as error:
self.battle_journal.update(record, "unknown", message="委托请求结果未确认,禁止自动重试", error_type=type(error).__name__)
raise
def _map_policy(self):
return SimpleNamespace(enabled=self.sweep_policy.enabled and self.sweep_policy.allow_challenge,
team=self.sweep_policy.team, reserve_ti=self.sweep_policy.keep_stamina,
max_money=max(0, int(self.snapshot.raw["master"].get("money") or 0)) if self.snapshot else 0,
allow_items=True, item_reserves=dict(self.quest_policy.item_reserves),
stop_after_loss=0, battle_mode="experimental")
def _map_roster_signature(self, snapshot, team):
selected = next((row for row in snapshot.raw.get("teams", []) if row.get("teamName") == team
and row.get("teamType") == "battleTeam"), {})
ids = {int(mid) for mid in selected.get("monsters", []) if mid and int(mid) > 0}
transient = {"exp", "timeStart", "nicName", "roomId"}
return digest({"team": selected,
"master": {key: val for key, val in snapshot.raw["master"].items() if key == "level" or key.startswith("global")},
"monsters": sorted([{key: val for key, val in mon.items() if key not in transient}
for mon in snapshot.raw.get("monsters", []) if int(mon["id"]) in ids], key=lambda mon: int(mon["id"])),
"attributes": sorted([row for row in snapshot.raw.get("monsterAttributes", []) or [] if int(row.get("monsterId") or 0) in ids],
key=lambda row: int(row["monsterId"]))})
def map_stage_reason(self, snapshot, stage, policy, *, team_ids=None):
"""Lightweight page status; runtime inspection belongs to the account worker."""
if self._progression_pending():
return "有待核对的任务 / 战斗,后台会自动检查"
reason = self.sweeper.reason(snapshot, stage, policy, team_ids=team_ids, challenge=not stage.sweep)
if reason:
return battle_message(reason)
rule = policy.rules.get(stage.stage_id) or {}
if rule.get("enabled") and self.sweeper.used(snapshot, stage) >= max(0, int(rule.get("limit") or 0)):
return "已达本日次数上限"
if stage.sweep:
return ""
if not policy.allow_challenge:
return "未开启未满星时自动挑战"
failed = self.sweeper.state.get("challenge_failures", {}).get(self.sweeper.key(snapshot, stage))
if failed and failed == self._map_roster_signature(snapshot, policy.team):
return "打不过;调整战队或提升魔物属性后自动重试"
if self._map_reason_snapshot is snapshot and self._map_reason_team == policy.team:
return self._map_challenge_reasons.get((stage.stage_id, stage.level), "")
return ""
def _next_map_action(self):
if not self.sweep_policy.enabled or self.demo:
return None
self._map_challenge_reasons = {}
self._map_reason_snapshot, self._map_reason_team = self.snapshot, self.sweep_policy.team
for stage in sorted(stages(self.catalog, self.snapshot), key=lambda row: (row.city, row.number, row.stage_id, row.level)):
rule = self.sweep_policy.rules.get(stage.stage_id) or {}
if not rule.get("enabled") or str(rule.get("level", "3")) != stage.level:
continue
if self.map_stage_reason(self.snapshot, stage, self.sweep_policy):
continue
if stage.sweep:
return Action("sweep", f"扫荡 {stage.number} {stage.name} / 难度{stage.level}", "", {})
self._ensure_progression()
if self.progression_planner.pending(self.snapshot):
self._planner_pending = True
return None
self._select_battle_runtime("experimental")
self._battle_snapshot_digest = digest(self.snapshot.raw)
intent = {"kind": "map_battle", "description": f"挑战 {stage.number} {stage.name} / 难度{stage.level}",
"path": "stageService/stageStart", "task_id": 0, "task_type_id": "", "step_number": 0,
"stage_id": stage.stage_id, "difficulty": int(stage.level), "battle_kind": "ordinary_stage",
"position": f"city{stage.city}_wild_stage{stage.stage_id}_level{stage.level}",
"team": self.sweep_policy.team, "battle_mode": "experimental"}
supported, reason = self._battle_capability(intent)
self._map_challenge_reasons[(stage.stage_id, stage.level)] = battle_message(reason)
if supported:
return Action("map_challenge", intent["description"], "", {"intent": intent})
return None
def _run_map_challenge(self, intent):
stage = next((row for row in stages(self.catalog, self.snapshot) if row.stage_id == str(value(intent, "stage_id"))
and row.level == str(value(intent, "difficulty"))), None)
if stage is None or not self.sweep_policy.enabled or not self.sweep_policy.allow_challenge:
return self.snapshot, self.plans(), "自动挑战已关闭或关卡状态已改变"
reason = self.map_stage_reason(self.snapshot, stage, self.sweep_policy)
if reason:
return self.snapshot, self.plans(), reason
self._ensure_progression()
self._select_battle_runtime("experimental")
message = self.battles.run(self.client, self.snapshot, intent, self._map_policy(),
cancel=self._progression_cancel, ranch=self.policy)
if not self._progression_cancel.is_set():
self.read_snapshot(sync_master=False)
if not self._progression_pending():
self.stage_cache.get(self.snapshot, refresh=True)
return self.snapshot, self.plans(), battle_message(message)
def plans(self):
if self.snapshot is None or self._progression_pending():
self.pending_hatches = []
return []
if self.policy.keep_better_quality or self.policy.gift_auto_representative:
self.cultivation.select(self.snapshot)
# One owner for commission writes; never accept the same offer through
# both the legacy planner and the full progression planner.
quests = [] if self._commission_planner_available else self.tasks.plan(self.snapshot, self.quest_policy, self.policy)
types, eggs = self.tasks.reservations(self.snapshot)
reserved = dict(self.policy.reserved_eggs)
for key, count in eggs.items():
reserved[key] = max(reserved.get(key, 0), count)
policy = replace(self.policy, reserved_types=list(set(self.policy.reserved_types) | types), reserved_eggs=reserved)
self.hatch_planner.notes = []
self.pending_hatches = self.hatch_planner.hatch_actions(self.snapshot, policy)
left = self.purchase_budget.remaining(self.snapshot.now, policy.daily_buy_money)
daily = [row.action for row in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger)] if self.daily_policy.enabled else []
map_action = self._next_map_action()
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] + 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):
self._require_no_battle()
self.daily_ledger.record(self.snapshot, entry.key)
if not self.demo:
self.client.call(entry.action.path, entry.action.payload)
self.read_snapshot()
@account_serial
def claim_daily(self):
self.auto = False
if not self.demo:
self.read_snapshot()
self._require_no_battle()
# Fresh status after every claim, bounded by the initially available IDs.
keys = [row.key for row in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger)]
done = 0
for key in keys:
row = next((r for r in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger) if r.key == key), None)
if row:
self.claim_daily_entry(row)
done += 1
return self.snapshot, self.plans(), ("[演示] " if self.demo else "") + f"已处理 {done} 项勾选奖励;自动执行已暂停"
def record_draw(self, eggs):
totals = {}
for egg in eggs:
if isinstance(egg, dict) and egg.get("typeId") is not None:
key = str(egg["typeId"])
totals[key] = totals.get(key, 0) + int(egg.get("num") or 0)
parts = [f"{self.catalog.monster(key).get('name', key)} ×{count}" for key, count in totals.items()]
self.last_draw = f"抽蛋完成,共 {sum(totals.values())} 枚:" + "、".join(parts[:8]) + ("…" if len(parts) > 8 else "")
@account_serial
def set_monster_lock(self, monster_ids, locked):
self.auto = False
ids = list(dict.fromkeys(int(mid) for mid in monster_ids))
if not ids or any(mid <= 0 for mid in ids):
raise ValueError("请先选择需要锁定 / 解锁的魔物")
if not self.demo:
self.read_snapshot()
self._require_no_battle()
monsters = self.snapshot.monsters
if any(mid not in monsters for mid in ids):
raise ValueError("选中的魔物已不存在,请刷新后重新选择")
if not locked and any(monsters[mid].get("sysLock") for mid in ids):
raise ValueError("选中包含系统锁定魔物,普通解锁不能解除系统锁,请重新选择")
changed = 0
for mid in ids:
if bool(monsters[mid].get("lock")) == bool(locked):
continue
if self.demo:
monsters[mid]["lock"] = int(locked)
else:
self.client.call("monsterService/monsterLock", {"monsterId": mid, "lock": int(locked)})
self.read_snapshot()
if bool(self.snapshot.monsters.get(mid, {}).get("lock")) != bool(locked):
raise ValueError("服务器返回的锁定状态未更新,已停止后续操作")
changed += 1
message = ("[演示] " if self.demo else "") + f"已{'锁定' if locked else '解锁'} {changed} 只魔物;自动执行已暂停"
return self.snapshot, self.plans(), message
@account_serial
def manage_monsters(self, kind, monster_ids, target_id=0):
self.auto = False
if not self.demo:
self.read_snapshot()
self._require_no_battle()
actions = manual_monster_actions(self.catalog, self.snapshot, kind, monster_ids, target_id)
for action in actions:
if self.demo:
field = "foods" if kind == "feed" else "monsterId" if "monsterId" in action.payload else "monsterIds"
for mid in action.payload[field]:
self.apply_demo(replace(action, payload=action.payload | {field: [mid]}))
else:
self.client.call(action.path, action.payload)
self.read_snapshot()
consumed = action.payload.get("foods") or action.payload.get("monsterId") or action.payload.get("monsterIds") or []
if any(int(mid) in self.snapshot.monsters for mid in consumed):
raise ValueError("操作已返回,但魔物记录尚未更新;请刷新核对,不会重复提交")
return self.snapshot, self.plans(), ("[演示] " if self.demo else "") + ";".join(a.description for a in actions) + ";自动执行已暂停"
@account_serial
def expand(self, quote):
self.auto = False
if not self.demo:
self.read_snapshot()
self._require_no_battle()
fresh = expansion_quote(self.catalog, self.snapshot, quote.kind, quote.currency, quote.position)
if fresh != quote:
raise ValueError("扩建费用或次数已变化,请刷新后重新确认")
old_rooms = {int(r["id"]) for r in self.snapshot.raw["rooms"]}
if self.demo:
raw = self.snapshot.raw
raw["master"][quote.currency] -= quote.cost
counter = ("numAdd" if quote.currency == "money" else "numKeAdd") + ("Stack" if quote.kind == "stack" else "Room")
raw["history"][counter] += 1
if quote.kind == "stack":
raw["stacks"].append({"id": max([int(s["id"]) for s in raw["stacks"]] + [0]) + 1,
"position": quote.position, "monsterId": -1, "openType": quote.payload["openType"]})
else:
type_id = 1000 if "1000" in self.catalog.data["room_info"] else int(raw["rooms"][0]["typeId"])
raw["rooms"].append({"id": max(old_rooms or {0}) + 1, "typeId": type_id, "openType": 1 if quote.currency == "money" else 2})
else:
self.client.call(quote.path, quote.payload)
self.read_snapshot()
verified = (any(int(s.get("position", -1)) == quote.position for s in self.snapshot.raw["stacks"]) if quote.kind == "stack"
else bool({int(r["id"]) for r in self.snapshot.raw["rooms"]} - old_rooms))
if not verified:
raise ValueError("扩建请求已返回,但尚未读取到新增记录;请刷新核对,不会自动重复提交")
return self.snapshot, self.plans(), ("[演示] " if self.demo else "") + quote.description + ",已完成"
def apply_demo(self, action):
if action.kind == "collect" and sum(len(d["monsterId"]) for d in action.payload["datas"]) > 1:
for data in action.payload["datas"]:
for mid in data["monsterId"]:
self.apply_demo(replace(action, payload={"datas": [{"monsterId": [mid], "roomId": data["roomId"]}]}))
return
if action.kind == "feed" and len(action.payload["foods"]) > 1:
for mid in action.payload["foods"]:
self.apply_demo(replace(action, payload=action.payload | {"foods": [mid]}))
return
raw = self.snapshot.raw
if action.kind.startswith("quest_"):
self.apply_demo_quest(action)
return
if action.kind == "buy":
market = self.catalog.data["markets"][action.payload["id"]]
count = action.payload["num"]
gift_every = int(market.get("freegift") or 0)
received = count + (count // gift_every if gift_every > 0 else 0)
# Deterministic offline example, not a prediction of the server draw.
type_id = int(next(iter(market["eggs"].values()))[0])
item = next((i for i in raw["items"] if int(i["typeId"]) == type_id), None)
if item:
item["num"] += received
else:
raw["items"].append({"id": max([int(i["id"]) for i in raw["items"]] + [500]) + 1, "typeId": type_id, "num": received})
raw["master"]["money"] -= int(market["money"]) * count
self.record_draw([{"typeId": type_id, "num": received}])
return
if action.kind == "collect":
data = action.payload["datas"][0]
mid = data["monsterId"][0]
self.snapshot.monsters[mid].update(process=3, roomId=data["roomId"])
elif action.kind in ("sell", "feed"):
mid = (action.payload.get("monsterId") or action.payload.get("monsterIds") or action.payload.get("foods"))[0]
mon = self.snapshot.monsters[mid]
if action.kind == "sell":
raw["master"]["money"] += self.catalog.monster(mon["typeId"])["sell_money"]
else:
target = self.snapshot.monsters[action.payload["targetId"]]
target["exp"] = target.get("exp", 0) + self.catalog.feed_exp(mon)
raw["monsters"] = [m for m in raw["monsters"] if m["id"] != mid]
elif action.kind == "gift":
target = self.snapshot.monsters[action.payload["monsterId"]]
item = next(i for i in raw["items"] if int(i["id"]) == action.payload["itemId"])
gain = int(self.catalog.monster(target.get("typeId")).get("like", {}).get(str(item["typeId"]), 0))
target["feel"] = max(0, min(self.catalog.max_feel(target), int(target.get("feel") or 0) + gain))
target["giftTime"] = int(time.time())
item["num"] -= 1
return
else:
egg = action.payload["eggs"][0]
item = next(i for i in raw["items"] if i["id"] == egg["itemId"])
item["num"] -= 1
mid = max([m["id"] for m in raw["monsters"]] + [100]) + 1
row = self.catalog.monster(item["typeId"])
mon = {"id": mid, "typeId": item["typeId"], "process": 2, "mode": 0, "level": 1, "exp": 0, "timeStart": int(time.time() * 1000), "roomId": 0}
mon.update({"g" + s.capitalize(): row[s + "_grow_min"] for s in ("atk", "def", "hp", "dex")})
raw["monsters"].append(mon)
next(s for s in raw["stacks"] if s["id"] == egg["stackId"])["monsterId"] = mid
return
for slot in raw["stacks"]:
if slot.get("monsterId") == mid:
slot["monsterId"] = 0
def apply_demo_quest(self, action):
raw = self.snapshot.raw
history = raw.setdefault("history", {})
tasks = raw.setdefault("currentTasks", [])
if action.kind == "quest_reset":
history["loopTaskTime"] = int(time.time())
history["loopTaskNum"] = self.catalog.data["game_setting"].get("loopTaskMaxNum", 6)
elif action.kind == "quest_accept":
type_id = action.payload["taskTypeId"]
tasks.append({"id": max([t["id"] for t in tasks] + [1000]) + 1, "typeId": type_id, "curStep": 1, "stepValue": 0})
history["loopTaskNum"] -= 1
offers = history["loopTask"][str(action.payload["city"])]
offers[:] = [t for t in offers if str(t) != type_id]
else:
task = next(t for t in tasks if int(t["id"]) == action.payload["taskId"])
info = self.catalog.data["task_info"][str(task["typeId"])]
if action.kind == "quest_complete":
raw["master"]["money"] += int(info.get("reward", {}).get("money", 0))
raw["master"]["ke"] = raw["master"].get("ke", 0) + int(info.get("reward", {}).get("ke", 0))
tasks.remove(task)
else:
step = info["steps"][task["curStep"] - 1]
value = step.get("statusValue") or {}
if value.get("remove"):
ids = action.payload.get("removeIds") or []
if step["statusType"] == "getMoney":
raw["master"]["money"] -= int(value["money"])
elif step["statusType"] == "getItem" or int(value.get("mode", 2)) == 0:
left = int(value["num"])
for item in raw["items"]:
if int(item["id"]) in ids:
used = min(left, int(item["num"]))
item["num"] -= used
left -= used
else:
raw["monsters"] = [m for m in raw["monsters"] if int(m["id"]) not in ids]
for slot in raw["stacks"]:
if slot.get("monsterId") in ids:
slot["monsterId"] = 0
task["curStep"] += 1
def demo_snapshot(catalog):
types = [int(k) for k, row in catalog.monsters.items() if row.get("star") == 1 and not row.get("npc")][:4]
monsters = []
for i, type_id in enumerate(types):
row = catalog.monster(type_id)
mon = {"id": 101 + i, "typeId": type_id, "level": 1, "exp": 0, "process": 2, "mode": 2 if i < 2 else 0,
"timeStart": int((time.time() - catalog.total_time(type_id) + (0 if i < 2 else 200)) * 1000), "roomId": 0, "lock": 0}
mon.update({"g" + s.capitalize(): row[s + "_grow_min"] for s in ("atk", "def", "hp", "dex")})
monsters.append(mon)
target = dict(monsters[0]) | {"id": 900, "process": 3, "mode": 2, "level": 20, "potentialLevel": 7, "roomId": 1, "lock": 1}
room_type = next(k for k, row in catalog.data["room_info"].items() if row.get("maxNum", 0) >= 10)
return Snapshot({"master": {"id": 1, "roleName": "离线演示", "level": 62, "exp": 456789, "money": 12345, "ke": 2000, "ti": 100},
"stacks": [{"id": i + 1, "position": i, "monsterId": 101 + i if i < 4 else 0, "openType": 3} for i in range(6)],
"monsters": monsters + [target], "items": [{"id": 501 + i, "typeId": t, "num": 8} for i, t in enumerate(types)] + [{"id": 600, "typeId": 20047, "num": 3}],
"rooms": [{"id": 1, "typeId": int(room_type), "openType": 3, "name": "主牧场"}], "teams": [{"monsters": [900]}], "activityHistory": {},
"history": {"unlockCity": {"1": True}, "openFarmBuild": True, "numAddStack": 0, "numKeAddStack": 0, "numAddRoom": 0, "numKeAddRoom": 0}})