from __future__ import annotations from copy import copy, deepcopy from dataclasses import replace from functools import wraps import json from pathlib import Path import threading import time 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 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.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.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._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 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("有待核对的任务 / 战斗,已暂停牧场、赠礼和任务写操作;请先刷新核对") 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): 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 _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" and not self._commission_offer_supported(value(intent, "task_type_id")): intent = replace(intent, block_reason=self._commission_offer_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 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() 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 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, allow_items=quest.allow_items, allow_monsters=quest.allow_monsters, max_money=quest.max_money, item_reserves=dict(quest.item_reserves)) 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: ready, _, _ = self.progression_planner.requirement(self.snapshot, step, {}, self._intent_policy({"task_type_id": str(type_id)}), self.policy) if not ready: 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: 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) 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": self.progression_planner.mark_uncertain(self.snapshot, intent, "战斗待核对,禁止重放") 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): 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.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 = self.battle_journal.pending(self.snapshot) or {} return self.snapshot, [], message + ";" + (pending.get("message") or "有待核对的任务 / 战斗,已暂停冲突操作") try: plans = self.plans() except (ValueError, TypeError, KeyError, AttributeError) as error: self.auto = False return self.snapshot, [], "状态已读取;策略暂不可用:" + str(error) actions = 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 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 == "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 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 [] sweep = self.sweeper.next(self.snapshot, self.sweep_policy) if self.sweep_policy.enabled and not self.demo else None sweep_actions = [Action(kind="sweep", path="", payload={}, description=f"扫荡 {sweep.number} {sweep.name} / 难度{sweep.level}")] if sweep else [] gifts = self.gift_planner.plan(self.snapshot, policy, self.quest_policy) ranch = self.planner.plan(self.snapshot, policy, left) self.planner.notes.extend(self.gift_planner.notes) 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] if quests and quests[0].kind == "quest_reset": return daily + quests + progression[:1] + gifts + ranch + sweep_actions return daily + progression[:1] + quests + 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}})