Files

263 lines
12 KiB
Python

"""Validated, portable strategy configuration shared by Web controls and workers.
No running switch or account/session information belongs in this document.
"""
from __future__ import annotations
from copy import deepcopy
from dataclasses import asdict
import math
import re
from ranch_assistant.model import EggRule, Policy
from ranch_assistant.daily import DailyPolicy
from ranch_assistant.quests import QuestPolicy
from ranch_assistant.sweeping import SweepPolicy
from ranch_assistant.progression import ProgressionPolicy
from ranch_assistant.exploration import ExplorePolicy
from ranch_assistant import policy_io
from . import __version__
POLICY_CLASSES = {
"policy": Policy, "quest_policy": QuestPolicy, "daily_policy": DailyPolicy,
"sweep_policy": SweepPolicy, "progression_policy": ProgressionPolicy,
"explore_policy": ExplorePolicy,
}
DAILY_CHOICES = ("gift", "check", "loop", "vip", "mail")
MAX_COUNT = 1_000_000_000
IDENTIFIER = re.compile(r"[A-Za-z0-9_]{1,64}\Z")
def default_config():
value = {key: asdict(cls()) for key, cls in POLICY_CLASSES.items()}
# The current desktop configures individual eggs and always uses its
# experimental battle simulator. Keep those defaults, not legacy widgets.
value["policy"]["manual_eggs"] = True
value["progression_policy"]["battle_mode"] = "experimental"
return value | {"auto_relogin": {"enabled": False, "delay_minutes": 30},
"interval": 30, "overrides": {}, "yield_stars": [1, 2, 3, 4, 5],
"log_visible": True, "log_sizes": [420, 140]}
def _object(value, label, allowed=None):
if not isinstance(value, dict) or any(type(key) is not str for key in value):
raise ValueError(label + "必须是对象,字段名必须是字符串")
if allowed is not None and set(value) - set(allowed):
raise ValueError(label + "含未知或不允许的字段")
return value
def _int(value, label, low=0, high=MAX_COUNT):
if type(value) is not int or not low <= value <= high:
raise ValueError(f"{label}须为 {low} 至 {high} 的整数")
return value
def _number(value, label, high=MAX_COUNT):
if type(value) not in (int, float) or not math.isfinite(value) or not 0 <= value <= high:
raise ValueError(label + "须为范围内的非负有限数值")
def _id(key, label):
if type(key) is not str or not key.isascii() or not key.isdigit() or int(key) <= 0:
raise ValueError(label + "须使用正整数编号")
def _counts(value, label, *, priority=False):
_object(value, label)
result = {}
for key, count in value.items():
_id(key, label)
_int(count, label, 1 if priority else 0, 999 if priority else MAX_COUNT)
result[str(int(key))] = count
return result
def _choice(value, options, label):
if value not in options:
raise ValueError(label + "选项无效")
def _section(value, defaults, label):
_object(value, label, defaults)
result = deepcopy(defaults)
result.update(deepcopy(value))
for key, default in defaults.items():
actual = result[key]
if type(default) is bool:
if type(actual) is not bool:
raise ValueError(label + "." + key + "须为布尔值")
elif label == "policy" and key in ("coins_per_exp", "min_gold_per_hour", "min_exp_per_hour"):
_number(actual, label + "." + key)
elif type(default) is int:
_int(actual, label + "." + key)
elif type(default) is float:
_number(actual, label + "." + key)
elif type(actual) is not type(default):
raise ValueError(label + "." + key + "类型错误")
return result
def validate_config(config):
"""Fill absent defaults and reject unknown paths *before* core coercion.
A partial HTTP PUT is merged with the saved config by the account worker;
passing a partial document here fills from defaults, not previous state.
"""
defaults = default_config()
_object(config, "配置", defaults)
result = deepcopy(defaults)
for key, cls in POLICY_CLASSES.items():
result[key] = _section(config.get(key, {}), defaults[key], key)
result["auto_relogin"] = _section(config.get("auto_relogin", {}), defaults["auto_relogin"], "自动重登")
_int(result["auto_relogin"]["delay_minutes"], "自动重登等待分钟", 1, 10080)
p = result["policy"]
# read_policy() in the current desktop always enables per-species rules.
# Normalize a validated legacy False so importing hidden old settings can
# never authorize incubation of eggs left unchecked in the Web controls.
p["manual_eggs"] = True
_choice(p["strategy"], ("wiki", "gold", "experience", "keep"), "培育策略")
_choice(p["egg_order"], ("shortest", "longest", "gold", "experience"), "蛋排序")
for key, low, high in (("protect_star", 1, 6), ("protect_quality", 1, 6),
("hatch_max_star", 1, 5), ("buy_batch", 1, 100),
("egg_stock", 1, 1000), ("target_level", 1, 999)):
_int(p[key], key, low, high)
_number(p["coins_per_exp"], "金币经验比", 10000)
for key in ("min_gold_per_hour", "min_exp_per_hour"):
_number(p[key], key, 1_000_000)
if not IDENTIFIER.fullmatch(p["market_id"]):
raise ValueError("默认市场编号无效")
if any(type(key) is not int or key <= 0 for key in p["reserved_types"]):
raise ValueError("额外保留魔物须为正整数编号列表")
p["reserved_types"] = list(dict.fromkeys(p["reserved_types"]))
for key in ("reserved_eggs", "feed_targets", "gift_targets", "breakthrough_targets"):
p[key] = _counts(p[key], key, priority=key.endswith("targets"))
_object(p["egg_rules"], "魔物蛋规则")
egg_defaults = asdict(EggRule())
for key, raw in p["egg_rules"].items():
_id(key, "魔物蛋")
rule = _section(raw, egg_defaults, "魔物蛋规则")
if rule["market_id"] and not IDENTIFIER.fullmatch(rule["market_id"]):
raise ValueError("补货市场编号无效")
p["egg_rules"][key] = asdict(EggRule(**rule))
_object(p["gift_items"], "赠礼物品")
for key, raw in p["gift_items"].items():
_id(key, "赠礼物品")
p["gift_items"][key] = _section(raw, {"enabled": False, "reserve": 0}, "赠礼物品")
for section in ("quest_policy", "progression_policy"):
result[section]["item_reserves"] = _counts(result[section]["item_reserves"], "交付保留物品")
q = result["quest_policy"]
_int(q["city"], "委托城市", 0, 999)
daily = result["daily_policy"]
if any(type(key) is not str or key not in DAILY_CHOICES for key in daily["selected"]):
raise ValueError("每日领取项目无效")
daily["selected"] = list(dict.fromkeys(daily["selected"]))
sweep = result["sweep_policy"]
_object(sweep["rules"], "刷图规则")
for key, raw in sweep["rules"].items():
if not IDENTIFIER.fullmatch(key):
raise ValueError("关卡编号无效")
rule = _section(raw, {"enabled": False, "level": "3", "limit": 3}, "刷图规则")
_choice(rule["level"], ("1", "2", "3"), "难度")
_int(rule["limit"], "本日上限", 0, 999)
sweep["rules"][key] = rule
for section in ("sweep_policy", "progression_policy"):
_choice(result[section]["team"], ("teamA", "teamB", "teamC"), "战队")
_int(result["progression_policy"]["stop_after_loss"], "连续失败停止次数", 1, 999)
_object(result["explore_policy"]["teams"], "探险队伍")
for key, raw in result["explore_policy"]["teams"].items():
_id(key, "探险队伍")
rule = _section(raw, {"enabled": False, "area": "", "monsters": []}, "探险队伍")
for mid in rule["monsters"]:
_int(mid, "探险魔物编号", 1)
result["explore_policy"]["teams"][key] = rule
for key, cls in POLICY_CLASSES.items():
try:
result[key] = asdict(cls(**result[key]))
except (TypeError, AttributeError, KeyError) as exc:
raise ValueError(key + "配置格式错误") from exc
# Current desktop forces the hidden legacy selector to its simulator.
# Validate the supplied mode first so unknown values are still rejected.
result["progression_policy"]["battle_mode"] = "experimental"
interval = config.get("interval", defaults["interval"])
if type(interval) is not int or interval not in (30, 60, 120, 300):
raise ValueError("随机刷新间隔须为30、60、120或300秒")
result["interval"] = interval
stars = config.get("yield_stars", defaults["yield_stars"])
if not isinstance(stars, list) or any(type(star) is not int or star not in range(1, 6) for star in stars):
raise ValueError("收益星级筛选无效")
result["yield_stars"] = list(dict.fromkeys(stars))
overrides = _object(config.get("overrides", {}), "收益资料")
result["overrides"] = deepcopy(overrides)
for key, row in overrides.items():
_id(key, "收益魔物")
_object(row, "收益资料", ("sell_money", "sell_exp", "time_total"))
for field, number in row.items():
_number(number, "收益资料." + field)
visible = config.get("log_visible", True)
if type(visible) is not bool:
raise ValueError("日志显示开关须为布尔值")
result["log_visible"] = visible
sizes = config.get("log_sizes", defaults["log_sizes"])
if not isinstance(sizes, list) or len(sizes) != 2:
raise ValueError("日志分隔高度须为两个整数")
for size in sizes:
_int(size, "日志高度", 0, 100000)
if not sum(sizes):
raise ValueError("日志分隔高度不能同时为0")
result["log_sizes"] = list(sizes)
return result
def apply_config(engine, config):
value = validate_config(config)
policies = {key: cls(**deepcopy(value[key])) for key, cls in POLICY_CLASSES.items()}
for key, policy in policies.items():
setattr(engine, key, policy)
engine.catalog.overrides = deepcopy(value["overrides"])
return value
def export_config(config, snapshot=None):
# Login preferences stay local to this account tab; portable strategy
# imports cannot opt another account into password authentication.
value = policy_io.portable_config(validate_config(config), snapshot)
value["assistantVersion"] = __version__
return value
def import_config(value, snapshot=None):
allowed = {"format", "schema", "assistantVersion", "gameVersion", "policy", "targetSpecies",
"quest_policy", "daily_policy", "sweep_policy", "progression_policy", "explore_policy",
"interval", "overrides", "yield_stars"}
_object(value, "策略导入文件", allowed)
value = deepcopy(value)
# Legacy desktop bundles sometimes stored difficulty as an integer.
rules = (value.get("sweep_policy") or {}).get("rules", {}) if isinstance(value.get("sweep_policy", {}), dict) else {}
if isinstance(rules, dict):
for rule in rules.values():
if isinstance(rule, dict) and type(rule.get("level")) is int and rule["level"] in (1, 2, 3):
rule["level"] = str(rule["level"])
# Validate source policy too: core's legacy loader intentionally coerces
# several values. Web imports must reject ambiguous booleans and secrets.
validate_config({key: raw for key, raw in value.items()
if key in default_config() and key != "explore_policy"})
targets = _object(value.get("targetSpecies", {}), "培养种类", ("feed", "gift", "breakthrough"))
for rules in targets.values():
if not isinstance(rules, list):
raise ValueError("培养种类必须是列表")
for rule in rules:
_object(rule, "培养种类规则", ("typeId", "priority"))
if not isinstance(rule.get("typeId"), str):
raise ValueError("培养种类编号无效")
if rule["typeId"]:
_id(rule["typeId"], "培养种类")
_int(rule.get("priority"), "培养优先级", 1, 999)
try:
loaded = policy_io.import_config(deepcopy(value), snapshot)
except (TypeError, KeyError, AttributeError) as exc:
raise ValueError("策略文件格式错误") from exc
return validate_config(loaded)