Files
myrzx_bot/ranch_assistant/policy_io.py
T

209 lines
11 KiB
Python

"""Portable rule sets; credentials, sessions and local paths never enter files."""
import copy
import math
from dataclasses import asdict
from .model import Policy
from .daily import DailyPolicy
from .quests import QuestPolicy
from .sweeping import SweepPolicy
from .progression import ProgressionPolicy
from .exploration import ExplorePolicy
FORMAT = "ranch-helper-policies"
VERSION = 1
CONFIG_VERSION = 2
def checked_policy(cls, data):
if not isinstance(data, dict):
raise ValueError("策略配置必须是对象")
for key, default in asdict(cls()).items():
if key not in data:
continue
value = data[key]
if cls.__annotations__.get(key) in (float, "float"):
valid = type(value) in (int, float) and math.isfinite(value)
else:
valid = type(value) is type(default)
if not valid:
raise ValueError("策略字段类型错误:" + key)
try:
return cls(**data)
except (AttributeError, TypeError, KeyError) as error:
raise ValueError("策略字段格式错误") from error
def checked_progression_policy(data):
"""Reject ambiguous or unsafe task choices before applying any settings."""
if not isinstance(data, dict):
raise ValueError("主线策略必须是对象")
raw = asdict(ProgressionPolicy()) | data
for key in ("reserve_ti", "max_money"):
if type(raw[key]) is not int or not 0 <= raw[key] <= 1_000_000_000:
raise ValueError("主线策略数量超出范围:" + key)
if type(raw["stop_after_loss"]) is not int or not 1 <= raw["stop_after_loss"] <= 999:
raise ValueError("连续失败停止次数须为1至999")
if not isinstance(raw["item_reserves"], dict) or any(not isinstance(key, str) or not key.isdigit() or int(key) <= 0
or type(count) is not int or not 0 <= count <= 1_000_000_000
for key, count in raw["item_reserves"].items()):
raise ValueError("主线保留物品须为正整数编号和非负整数数量")
return checked_policy(ProgressionPolicy, data)
def portable_policy(policy, snapshot=None):
value = asdict(policy)
value["enabled"] = False
for field in ("buy", "collect", "dispatch", "feed", "fill", "gift_enabled"):
value[field] = False
if value["feed_target"] and not value["feed_targets"]:
value["feed_targets"] = {str(value["feed_target"]): 1}
value["feed_target"] = value["room_id"] = 0
targets = {}
for kind, field in (("feed", "feed_targets"), ("gift", "gift_targets"), ("breakthrough", "breakthrough_targets")):
targets[kind] = []
for key, priority in sorted(value.pop(field).items(), key=lambda pair: pair[1]):
mon = snapshot.monsters.get(int(key)) if snapshot else None
targets[kind].append({"typeId": str(mon.get("typeId")) if mon else "", "priority": priority})
return {"format": FORMAT, "schema": VERSION, "assistantVersion": "1.2.0.dev1", "gameVersion": "1.9.68",
"policy": value, "targetSpecies": targets}
def import_policy(value, snapshot=None):
if not isinstance(value, dict) or value.get("format") != FORMAT or value.get("schema") != VERSION or not isinstance(value.get("policy"), dict):
raise ValueError("不是受支持的辅助策略文件")
policy = checked_policy(Policy, value["policy"])
policy.feed_target = policy.room_id = 0
if snapshot:
used = {"feed": set(), "gift": set(), "breakthrough": set()}
for kind, field in (("feed", "feed_targets"), ("gift", "gift_targets"), ("breakthrough", "breakthrough_targets")):
result = {}
targets = value.get("targetSpecies", {})
if not isinstance(targets, dict) or not isinstance(targets.get(kind, []), list):
raise ValueError("培养目标配置格式错误")
for rule in targets.get(kind, []):
if not isinstance(rule, dict) or not 1 <= int(rule.get("priority", 0)) <= 999:
raise ValueError("培养目标优先级格式错误")
key = str(rule.get("typeId", ""))
for mon in sorted(snapshot.raw["monsters"], key=lambda m: int(m["id"])):
if str(mon.get("typeId")) == key and mon.get("process") == 3 and int(mon["id"]) not in used[kind]:
result[str(mon["id"])] = int(rule["priority"])
used[kind].add(int(mon["id"]))
break
setattr(policy, field, result)
else:
policy.feed_targets, policy.gift_targets, policy.breakthrough_targets = {}, {}, {}
return policy
def portable_config(config, snapshot=None):
"""One portable file for all strategies, independent of session/UI state."""
policy = Policy(**config.get("policy", {}))
value = portable_policy(policy, snapshot)
value["schema"] = CONFIG_VERSION
# These are configuration choices. The GUI execution switch is deliberately
# outside the portable document and stays stopped on import.
for field in ("enabled", "buy", "collect", "dispatch", "feed", "fill", "gift_enabled"):
value["policy"][field] = getattr(policy, field)
for key, cls in (("quest_policy", QuestPolicy), ("daily_policy", DailyPolicy), ("sweep_policy", SweepPolicy)):
value[key] = asdict(cls(**config.get(key, {})))
value["progression_policy"] = asdict(checked_progression_policy(config.get("progression_policy", {})))
value["interval"] = config.get("interval", 30)
value["overrides"] = copy.deepcopy(config.get("overrides", {}))
value["yield_stars"] = list(config.get("yield_stars", [1, 2, 3, 4, 5]))
value["explore_policy"] = portable_explore_policy(ExplorePolicy.from_dict(config.get("explore_policy", {})), snapshot)
return value
def portable_explore_policy(policy, snapshot=None):
"""Team and monster IDs are account-local; preserve positions, not identities."""
value = policy.to_dict()
teams = [team for team in (snapshot.raw.get("exploreTeams", []) if snapshot else [])
if isinstance(team, dict) and str(team.get("id")) in value["teams"]]
teams.sort(key=lambda team: int(team["id"]))
if snapshot is None:
teams = list(value["teams"])
result = []
for position, team in enumerate(teams):
key = str(team.get("id")) if isinstance(team, dict) else str(team)
rule = value["teams"][key]
species = []
if snapshot:
for mid in rule["monsters"]:
mon = snapshot.monsters.get(int(mid))
species.append(str(mon.get("typeId")) if mon and mon.get("process") == 3 else "")
result.append({"position": position, "enabled": rule["enabled"], "area": rule["area"], "memberSpecies": species})
return {"enabled": False, "reserve_ti": value["reserve_ti"], "teams": result}
def import_explore_policy(value, snapshot=None):
if not isinstance(value, dict) or set(value) - {"enabled", "reserve_ti", "teams"} or not isinstance(value.get("teams"), list):
raise ValueError("自动探险策略格式错误")
teams = [team for team in (snapshot.raw.get("exploreTeams", []) if snapshot else []) if isinstance(team, dict)]
teams.sort(key=lambda team: int(team["id"]))
used = set()
result = {}
for index, rule in enumerate(value["teams"]):
if (not isinstance(rule, dict) or set(rule) != {"position", "enabled", "area", "memberSpecies"}
or type(rule["position"]) is not int or rule["position"] != index):
raise ValueError("自动探险队伍顺序配置无效")
if index >= len(teams):
continue
members = []
if rule["memberSpecies"]:
if len(rule["memberSpecies"]) != 3:
raise ValueError("自动探险手动队员须恰好三只")
for type_id in rule["memberSpecies"]:
match = next((mon for mon in sorted(snapshot.raw["monsters"], key=lambda row: int(row["id"]))
if mon.get("process") == 3 and str(mon.get("typeId")) == str(type_id) and int(mon["id"]) not in used), None)
if match is None:
raise ValueError("当前账号无法完整匹配探险手动队员;请重新选择")
used.add(int(match["id"]))
members.append(int(match["id"]))
result[str(int(teams[index]["id"]))] = {"enabled": rule["enabled"], "area": rule["area"], "monsters": members}
# Never copy the exported enable switch or any source-account instance IDs.
return ExplorePolicy(enabled=False, reserve_ti=value.get("reserve_ti", 0), teams=result).to_dict()
def import_config(value, snapshot=None):
if not isinstance(value, dict) or value.get("format") != FORMAT:
raise ValueError("不是受支持的辅助策略文件")
if value.get("schema") == VERSION:
return {"policy": asdict(import_policy(value, snapshot))}
if value.get("schema") != CONFIG_VERSION:
raise ValueError("不支持此策略文件版本")
config = {"policy": asdict(import_policy(value | {"schema": VERSION}, snapshot))}
if "explore_policy" in value:
config["explore_policy"] = import_explore_policy(value["explore_policy"], snapshot)
for key, cls in (("quest_policy", QuestPolicy), ("daily_policy", DailyPolicy), ("sweep_policy", SweepPolicy)):
if not isinstance(value.get(key), dict):
raise ValueError("策略文件缺少 " + key)
config[key] = asdict(checked_policy(cls, value[key]))
# An additive section preserves schema-2 compatibility with older bundles.
if "progression_policy" in value:
config["progression_policy"] = asdict(checked_progression_policy(value["progression_policy"]))
interval = value.get("interval", 30)
if interval not in (30, 60, 120, 300):
raise ValueError("刷新间隔须为30、60、120或300秒")
overrides, stars = value.get("overrides", {}), value.get("yield_stars", [1, 2, 3, 4, 5])
if not isinstance(overrides, dict) or not isinstance(stars, list) or any(type(s) is not int or s not in range(1, 6) for s in stars):
raise ValueError("收益资料配置格式错误")
for key, row in overrides.items():
if (not str(key).isdigit() or not isinstance(row, dict)
or any(field not in ("sell_money", "sell_exp", "time_total") or type(number) not in (int, float)
or not math.isfinite(number) or number < 0 for field, number in row.items())):
raise ValueError("收益资料配置格式错误")
for rule in config["sweep_policy"]["rules"].values():
if (not isinstance(rule, dict) or str(rule.get("level", "3")) not in ("1", "2", "3")
or type(rule.get("limit", 3)) is not int or not 0 <= rule.get("limit", 3) <= 999
or type(rule.get("enabled", False)) is not bool):
raise ValueError("扫荡规则格式错误")
if any(not isinstance(key, str) for key in config["daily_policy"]["selected"]):
raise ValueError("每日事务规则格式错误")
if any(not str(key).isdigit() or type(count) is not int or count < 0
for key, count in config["quest_policy"]["item_reserves"].items()):
raise ValueError("委托保留物品规则格式错误")
config.update(interval=interval, overrides=copy.deepcopy(overrides), yield_stars=list(stars))
return config