Files
myrzx_bot/ranch_assistant/sweeping.py
T
AttilaNet eaaad3488b Fix fast automation routing and blocked quest navigation loops
Isolate hatch, gift, exploration and breakthrough timers; cancel queued automation after settings change. Check battle readiness before local quest navigation and reject exploring teams or disabled sweeps before entry.
2026-11-09 12:14:47 +08:00

221 lines
11 KiB
Python

"""The built-in three-difficulty-cleared sweep path from StageStartPanel."""
from dataclasses import dataclass, field
import json
from pathlib import Path
import sqlite3
import uuid
from .daily import day
from .maps import stages
from .drop_statistics import SweepStatistics, event_reward, normalize_reward
from .team_availability import team_availability_reason
def settled_reward_event(response):
return event_reward(response) is not None
@dataclass
class SweepPolicy:
enabled: bool = False
rules: dict = field(default_factory=dict)
keep_stamina: int = 0
team: str = "teamA"
allow_challenge: bool = True
class SweepRunner:
def __init__(self, catalog, path=None):
self.catalog = catalog
self.path = Path(path) if path else None
self.state = json.loads(self.path.read_text(encoding="utf-8")) if self.path and self.path.exists() else {"counts": {}, "pending": None}
self.last_outcome = ""
self.recovery_checked = False
self.recovered_event = False
self.statistics = SweepStatistics(catalog, self.path.with_name("sweep_rewards.sqlite3") if self.path else None)
self.last_reward = None
self.statistics_error = ""
def remember_reward(self, client, snapshot, stage, kind, reward, response):
self.last_outcome = kind
self.last_reward = None
self.statistics_error = ""
try:
self.last_reward = normalize_reward(self.catalog, reward)
source = "run:" + self.state["pending"]["sampleId"]
operation = "stageService/stageStart" if kind == "event" else "battleService/battleEnd"
for event in reversed(getattr(getattr(client, "trace", None), "events", [])):
if event.get("operation") == operation and event.get("kind") == "response" and event.get("request_id"):
source = "request:" + event["request_id"]
break
cost = (response.get("stageEvent") or {}).get("costTi") if kind == "event" else response.get("costTi")
self.statistics.record(snapshot.raw["master"]["id"], stage.stage_id, stage.level, kind, source,
snapshot.now, reward, cost)
except (OSError, sqlite3.Error, ValueError, TypeError) as error:
# A local statistics failure must never repeat an awarded request.
self.statistics_error = "奖励统计未写入:" + str(error)
def recover_reward_event(self, snapshot, trace_path):
"""Repair only old reward-event blocks with a role-matched log reply.
This never replays a start or settlement request. Missing/ambiguous
evidence leaves the pending record intact.
"""
pending = self.state.get("pending")
if (self.recovery_checked or not trace_path or not pending
or pending.get("phase") != "遇到事件或响应缺少事件状态,请在游戏内处理"):
return False
self.recovery_checked = True
role, requests, last_reply = None, {}, None
owner = snapshot.raw["master"]["id"]
path = Path(trace_path)
try:
for file in (path.with_name("network_debug.previous.jsonl"), path):
if not file.exists():
continue
with file.open(encoding="utf-8") as stream:
for line in stream:
try:
event = json.loads(line)
except ValueError:
continue
body = event.get("body")
if not isinstance(body, dict):
continue
if event.get("operation") == "读取角色" and event.get("kind") == "response":
role = (body.get("master") or {}).get("id")
if event.get("operation") != "stageService/stageStart":
continue
identifier = event.get("request_id")
if not isinstance(identifier, str) or not identifier:
continue
if event.get("kind") == "request":
matched = (str(role) == str(owner) and str(body.get("stageTypeId")) == pending["stage"]
and str(body.get("stageLevel")) == str(pending["level"]))
requests[identifier] = matched
if matched:
last_reply = None
elif event.get("kind") == "response" and requests.get(identifier):
last_reply = body if event.get("http_status") == 200 and body.get("resCode") in (0, "0") else None
except (OSError, ValueError, TypeError, AttributeError):
return False
if last_reply and settled_reward_event(last_reply):
self.state["pending"] = None
self.save()
self.recovered_event = True
return True
return False
def save(self):
if self.path:
self.path.parent.mkdir(parents=True, exist_ok=True)
temp = self.path.with_suffix(".tmp")
temp.write_text(json.dumps(self.state, ensure_ascii=False), encoding="utf-8")
temp.replace(self.path)
def key(self, snapshot, stage):
return f"{snapshot.raw['master']['id']}:{day(snapshot.now)}:{stage.stage_id}:{stage.level}"
def used(self, snapshot, stage):
return int(self.state["counts"].get(self.key(snapshot, stage), 0))
def team_ids(self, snapshot, policy):
team = next((t for t in snapshot.raw.get("teams", []) if t.get("teamName") == policy.team and t.get("teamType") == "battleTeam"), {})
ids = [int(mid) for mid in team.get("monsters", []) if mid and int(mid) > 0]
monsters = snapshot.monsters
return [mid for mid in ids if mid in monsters]
def reason(self, snapshot, stage, policy, *, team_ids=None, challenge=False):
if not policy.enabled:
return "扫荡 / 自动挑战已关闭,禁止新的入场"
if self.state.get("pending"):
return "有未完成的扫荡,请先在游戏内检查"
if challenge:
config = self.catalog.data.get("stage_info", {}).get(stage.stage_id, {})
if not stage.unlocked or not stage.open:
return "关卡尚未解锁或当前未开放"
if config.get("special") or config.get("posmode"):
return "特殊关卡当前不支持自动挑战"
elif not stage.sweep:
return stage.reason
reason = team_availability_reason(snapshot, policy.team)
if reason:
return reason
positions = self.catalog.data.get("stage_task_positions", {})
for task in snapshot.raw.get("currentTasks", []):
steps = positions.get(str(task.get("typeId")), [])
index = int(task.get("curStep") or 1) - 1
position = steps[index] if 0 <= index < len(steps) else ""
if position == f"city{stage.city}_wild_stage{stage.stage_id}_level{stage.level}":
return "该难度有当前剧情任务,请先在游戏内完成"
base = self.catalog.data["stage_info"][stage.stage_id].get("cost") or {}
master = snapshot.raw["master"]
if float(master.get("ti") or 0) < stage.stamina + policy.keep_stamina:
return "体力不足或已达保留体力"
if base.get("ke"):
return "需要氪金,未启用"
if float(master.get("money") or 0) < float(base.get("money") or 0):
return "金币不足"
for item in base.get("items") or []:
owned = sum(int(i.get("num") or 0) for i in snapshot.raw.get("items", []) if str(i.get("typeId")) == str(item["typeId"]))
if owned < int(item["num"]):
return "入场券不足"
return ""
def next(self, snapshot, policy):
if not policy.enabled:
return None
for stage in sorted(stages(self.catalog, snapshot), key=lambda s: (s.city, s.number, s.stage_id, s.level)):
rule = policy.rules.get(stage.stage_id) or {}
if not rule.get("enabled") or str(rule.get("level", "3")) != stage.level:
continue
if self.used(snapshot, stage) < max(0, int(rule.get("limit") or 0)) and not self.reason(snapshot, stage, policy):
return stage
return None
def run(self, client, snapshot, stage, policy):
self.last_outcome = ""
self.last_reward = None
rule = policy.rules.get(stage.stage_id) or {}
if not rule.get("enabled") or str(rule.get("level")) != stage.level or self.used(snapshot, stage) >= int(rule.get("limit") or 0):
raise ValueError("此关卡未勾选或已达本日次数上限")
reason = self.reason(snapshot, stage, policy)
if reason:
raise ValueError(reason)
key = self.key(snapshot, stage)
self.state["counts"][key] = self.used(snapshot, stage) + 1
self.state["pending"] = {"stage": stage.stage_id, "level": stage.level, "phase": "开始请求待确认", "sampleId": uuid.uuid4().hex}
self.save() # Reserve before the first non-retryable write, including timeouts.
started = client.call("stageService/stageStart", {"stageTypeId": stage.stage_id, "stageLevel": stage.level})
if settled_reward_event(started):
# StageCenter.startStageHandler applies stageEvent.result directly;
# StageStartPanel shows it and returns, without battleEnd.
self.remember_reward(client, snapshot, stage, "event", started["stageEvent"]["result"], started)
self.state["pending"] = None
self.save()
self.last_outcome = "event"
return started
flag = started.get("triggerEvent")
if flag is not False and not (type(flag) is int and flag == 0):
event = started.get("stageEvent")
if isinstance(event, dict) and event.get("hideStageId") is not None:
phase = "遭遇隐藏关卡,请在游戏内手动战斗"
else:
phase = "事件结果或开始状态尚未确认,请在游戏内检查"
self.state["pending"]["phase"] = phase
self.save()
raise ValueError(self.state["pending"]["phase"])
# Exactly the official doSaodangBattle data; only for its eligible stages.
battle = {"battlePosition": {"battleType": "stage", "stageId": stage.stage_id, "stageLevel": stage.level, "taskTypeId": None, "taskStep": 0},
"win": True, "cheatNum": 0, "cheatRecords": "", "killMonster": {}, "battleMonIds": self.team_ids(snapshot, policy),
**{name: 0 for name in ("leftTime", "killNum", "totalDamage", "bossDamage", "deadNum", "aliveNum", "apLeft")}}
self.state["pending"]["phase"] = "扫荡结算待确认"
self.save()
result = client.call("battleService/battleEnd", {"battleData": battle})
self.remember_reward(client, snapshot, stage, "sweep", result.get("reward"), result)
self.state["pending"] = None
self.save()
client.call("battleService/recordBattleResult", {"stageId": stage.stage_id, "cityId": stage.stage_id[1:2], "result": 1})
self.last_outcome = "sweep"
return result