108 lines
5.5 KiB
Python
108 lines
5.5 KiB
Python
"""The built-in three-difficulty-cleared sweep path from StageStartPanel."""
|
|
from dataclasses import dataclass, field
|
|
import json
|
|
from pathlib import Path
|
|
|
|
from .daily import day
|
|
from .maps import stages
|
|
|
|
|
|
@dataclass
|
|
class SweepPolicy:
|
|
enabled: bool = False
|
|
rules: dict = field(default_factory=dict)
|
|
keep_stamina: int = 0
|
|
team: str = "teamA"
|
|
|
|
|
|
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}
|
|
|
|
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):
|
|
if self.state.get("pending"):
|
|
return "有未完成的扫荡,请先在游戏内检查"
|
|
if not stage.sweep:
|
|
return stage.reason
|
|
if not (self.team_ids(snapshot, policy) if team_ids is None else team_ids):
|
|
return "所选战队无有效魔物"
|
|
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):
|
|
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):
|
|
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": "开始请求待确认"}
|
|
self.save() # Reserve before the first non-retryable write, including timeouts.
|
|
started = client.call("stageService/stageStart", {"stageTypeId": stage.stage_id, "stageLevel": stage.level})
|
|
flag = started.get("triggerEvent")
|
|
if flag is not False and not (type(flag) is int and flag == 0):
|
|
self.state["pending"]["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.state["pending"] = None
|
|
self.save()
|
|
client.call("battleService/recordBattleResult", {"stageId": stage.stage_id, "cityId": stage.stage_id[1:2], "result": 1})
|
|
return result
|