"""Plain-data desktop parity views. Called only on an account worker thread.""" from __future__ import annotations from collections import Counter from copy import deepcopy from dataclasses import asdict from datetime import datetime, timedelta, timezone from ranch_assistant.model import EggRule, duration, seconds from ranch_assistant.maps import reward_summary from ranch_assistant.daily import entries from ranch_assistant.drop_statistics import analyze from ranch_assistant.presentation import monster_rows from ranch_assistant.battle_messages import battle_message from ranch_assistant.resource_stages import available_item_count, item_requirements, with_resource_data from .policies import default_config, validate_config PAGES = [ ("login", "登录"), ("incubator", "培育室"), ("bag", "背包"), ("ranch", "牧场"), ("daily", "每日事务"), ("hatching", "自动孵蛋"), ("mainline", "自动主线"), ("battles", "战斗记录"), ("gifts", "自动赠礼"), ("commissions", "自动委托"), ("exploration", "自动探险"), ("maps", "自动扫荡"), ("statistics", "数据分析"), ("plans", "执行计划"), ("yields", "收益资料"), ] ITEM_TYPES = {0: "全部物品", 6: "魔物蛋", 1: "可使用", 2: "消耗品", 3: "材料", 4: "其他", 5: "装备"} BAG_CATEGORIES = [("eggs", "魔物蛋"), ("usable", "可使用"), ("consumables", "消耗品"), ("materials", "材料"), ("other", "其他"), ("equipment", "装备")] def _options(pairs): return [{"value": value, "label": label} for value, label in pairs] def _field(path, label, kind="boolean", **extra): return {"path": list(path), "label": label, "type": kind, **extra} def _policy_field(key, label, kind="boolean", **extra): return _field(["policy", key], label, kind, **extra) def _strategy_fields(catalog): """Only controls retained by the current GUI; legacy Policy fields stay hidden.""" markets = _options([(key, row.get("name", key) + "市场") for key, row in catalog.data.get("markets", {}).items()]) team_options = _options([(key, key) for key in ("teamA", "teamB", "teamC")]) hatch = [_policy_field(key, label, group="孵蛋策略") for key, label in ( ("enabled", "启用培育室自动管理"), ("buy", "自动从金币市场购蛋 / 抽蛋"), ("allow_single_draw", "允许单抽"), ("buy_ten", "优先十连"), ("fill", "自动填充空坑位"), ("dispatch", "成熟后按策略自动派遣"), ("collect", "自动收取到牧场"))] hatch += [_policy_field("market_id", "新增规则默认市场", "select", options=markets, group="孵蛋策略")] hatch += [_policy_field(key, label, "integer", min=low, max=high, group="孵蛋策略") for key, label, low, high in ( ("buy_batch", "单抽时每批上限", 1, 100), ("keep_money", "至少保留金币", 0, 1_000_000_000), ("daily_buy_money", "每日购蛋金币额度(0=不购买)", 0, 1_000_000_000))] hatch += [_policy_field("protect_star", "保留此星级及以上", "integer", min=1, max=6, group="牧场策略"), _policy_field("protect_quality", "资质保留条件", "select", group="牧场策略", options=_options([ (4, "S及以上"), (3, "A及以上"), (2, "B及以上"), (1, "全部资质"), (5, "不按资质保留"), (6, "四项全S(4S)才保留")])), _policy_field("keep_better_quality", "保留资质高于牧场同种培养代表的新魔物", group="牧场策略"), _policy_field("room_id", "收取到牧场", "select", options=_options([(0, "自动选择有空位的牧场")]), group="牧场策略"), _policy_field("reserved_types", "额外保留魔物编号", "id_list", group="牧场策略"), _policy_field("reserved_eggs", "保留蛋数量", "id_counts", group="牧场策略"), _policy_field("feed", "按策略喂养选定目标(受当前突破上限限制)", group="喂养策略")] gift = [_policy_field(key, label) for key, label in ( ("gift_enabled", "启用自动赠礼"), ("gift_auto_representative", "每种魔物只培养一只,自动选择培养代表"), ("gift_liked_only", "仅赠送目标喜欢的物品"))] quest = [_field(["quest_policy", key], label) for key, label in ( ("enabled", "启用委托自动接取 / 推进 / 领奖"), ("accept", "按氪金奖励优先接取(20 → 15 → 10)"), ("allow_items", "允许提交道具(遵守保留数量)"), ("allow_monsters", "允许提交1级魔物(遵守锁定、星级和资质保留)"), ("battle_tasks", "也接取需要实战的委托"))] quest += [_field(["quest_policy", "city"], "城市编号(0=所有已解锁城市)", "integer", min=0, max=99), _field(["quest_policy", "max_money"], "单次最多提交金币", "integer", min=0, max=10_000_000), _field(["quest_policy", "item_reserves"], "保留道具", "id_counts")] progression_labels = [("enabled", "启用自动主线策略"), ("mainline", "主线"), ("sidequests", "支线"), ("commissions", "委托(仅诊断)"), ("accept", "接取已确认的任务"), ("auto_dialogue", "自动推进已支持的对话"), ("repair_chain", "补全已确认的任务链"), ("allow_items", "允许提交物品"), ("allow_monsters", "允许提交魔物"), ("allow_sweep", "允许用扫荡完成已通关目标"), ("auto_farm", "自动收集任务材料 / 击杀目标")] progression = [_field(["progression_policy", key], label) for key, label in progression_labels] progression += [_field(["progression_policy", "team"], "推进战斗队伍", "select", options=team_options)] progression += [_field(["progression_policy", key], label, "integer", min=low, max=high) for key, label, low, high in ( ("reserve_ti", "保留体力", 0, 1_000_000_000), ("max_money", "单次交付金币上限(0=不交金币)", 0, 1_000_000_000), ("stop_after_loss", "连续失败后停止次数", 1, 999))] progression += [_field(["progression_policy", "item_reserves"], "交付后至少保留物品", "id_counts")] maps = [_field(["sweep_policy", key], label) for key, label in ( ("enabled", "启用勾选关卡自动刷图"), ("allow_challenge", "未满星时自动挑战"), ("allow_special", "允许矿洞 / 门票关卡"))] maps += [_field(["sweep_policy", "team"], "使用战队", "select", options=team_options)] maps += [_field(["sweep_policy", key], label, "integer", min=0, max=1_000_000_000) for key, label in ( ("keep_stamina", "保留体力"), ("keep_tickets", "每种门票 / 工具保留"))] return {"hatching": hatch, "gifts": gift, "commissions": quest, "mainline": progression, "maps": maps, "daily": [_field(["daily_policy", "enabled"], "启用每日奖励领取"), _field(["daily_policy", "selected"], "领取项目", "multiselect", options=_options([ ("gift", "每日签到礼包"), ("check", "七日签到"), ("loop", "累计奖励"), ("vip", "VIP日奖"), ("mail", "邮件附件")]))], "exploration": [_field(["explore_policy", "enabled"], "自动安排再次探险(完成后自动领奖)"), _field(["explore_policy", "reserve_ti"], "保留体力", "integer", min=0, max=1_000_000_000)], "yields": [_field(["yield_stars"], "星级", "multiselect", options=_options([(i, f"{i}星") for i in range(1, 6)]))], "login": [_field(["auto_relogin", "enabled"], "掉线后自动重新登录", value=False, help="需在服务端记住账号和密码,并已保存原区服和角色;开启后,掉线或服务重启均等待设定时长,再返回原区服、原角色。"), _field(["auto_relogin", "delay_minutes"], "重登等待时长(分钟)", "integer", min=1, max=10080, value=30, help="1~10080 的整数分钟,默认 30 分钟。重登成功恢复监控,策略保持停止;关闭页面不影响服务端自动重登,手动退出登录可取消本次安排。")], "incubator": [], "bag": [], "ranch": [], "battles": [], "statistics": [], "plans": []} def schema(catalog): fields = _strategy_fields(catalog) return {"version": 1, "pages": [{"key": key, "title": title, "form": fields[key]} for key, title in PAGES], "settings": [_field(["interval"], "随机刷新间隔", "select", options=_options([ (30, "0~30秒"), (60, "0~60秒"), (120, "0~120秒"), (300, "0~300秒")])), _field(["log_visible"], "显示日志"), _field(["log_sizes"], "页面 / 日志高度", "sizes")], "defaults": default_config()} def _value(config, path): value = config for key in path: value = value[key] return deepcopy(value) def _column(key, label, kind=None, edit=None): return {"key": key, "label": label, **({"type": kind} if kind else {}), **({"edit": edit} if edit else {})} def build_view(engine, page, config, query=None): if page not in dict(PAGES): raise ValueError("未知页面") config = validate_config(config) if page == "login": config.setdefault("auto_relogin", {"enabled": False, "delay_minutes": 30}) fields = _strategy_fields(engine.catalog)[page] dto = {"page": page, "title": dict(PAGES)[page], "columns": [], "rows": [], "summary": "", "form": [field | {"value": _value(config, field["path"])} for field in fields], "filters": [], "details": {}, "actions": [{"operation": "refresh", "label": "刷新本页", "payload": {"page": page}}]} builder = _BUILDERS.get(page) if engine.snapshot is None and page not in ("login", "yields", "statistics"): dto["summary"] = "请先登录或打开离线演示" return dto if builder is not None: builder(dto, engine, config, query or {}) elif engine.snapshot is None: dto["summary"] = "请先登录或打开离线演示" return dto _BUILDERS = {} def _filter(key, label, value, pairs=None, kind="select"): return {"key": key, "label": label, "type": kind, "value": value, **({"options": _options(pairs)} if pairs is not None else {})} def _search(dto, query): search = str(query.get("search", "")).strip().casefold() dto["filters"].append(_filter("search", "搜索", query.get("search", ""), kind="text")) return search def _boolean(value, default=False): return value if type(value) is bool else str(value).lower() in ("true", "1", "yes") if value is not None else default def _edit(path, kind, **extra): return {"path": list(path), "type": kind, **extra} def _row_column(key, label, section, *, kind="integer", **extra): return _column(key, label, kind, _edit([*section, "{id}", key], kind, **extra)) def _login(dto, engine, config, query): dto["columns"] = [_column("name", "服务器"), _column("role_name", "角色")] dto["summary"] = "离线演示,无游戏网络连接" if engine.demo else "请在此账号登录或恢复已保存的角色" # Runtime adds only public saved-session/server metadata via login_view(). dto["servers"], dto["saved_sessions"], dto["has_saved_password"] = [], [], False dto["actions"] = [{"operation": "login", "label": "账号密码登录"}, {"operation": "restore_session", "label": "恢复保存角色"}, {"operation": "logout", "label": "退出当前角色"}, {"operation": "forget_login", "label": "忘记登录信息"}] def _plans(engine): # Only kind and description are public. Action paths/payloads may contain # instance IDs, protocol evidence or non-JSON progression intents. return [{"id": str(i), "kind": action.kind, "description": action.description} for i, action in enumerate(engine.plans())] def _incubator(dto, engine, config, query): snapshot, catalog = engine.snapshot, engine.catalog dto["columns"] = [_column(k, label) for k, label in ( ("position_label", "坑位"), ("stack_id", "坑位ID"), ("status", "开启状态"), ("name", "魔物"), ("star", "星"), ("phase", "阶段"), ("remaining_text", "剩余时间"), ("quality", "资质 攻/防/血/敏"), ("decision", "策略预览"))] opened = {int(row.get("position", -1)): row for row in snapshot.raw["stacks"]} total = max(int(catalog.data.get("stack_meta", {}).get("total", 0)), max(opened, default=-1) + 1) vip = seconds((snapshot.raw.get("activityHistory", {}).get("vipInfo") or {}).get("vipTime")) > snapshot.now engine.plans() # Refresh core disposition/status calculations without executing. for position in range(total): slot = opened.get(position) mon = snapshot.monsters.get(int(slot.get("monsterId") or 0)) if slot else None info = catalog.monster(mon.get("typeId")) if mon else {} remaining = snapshot.remaining(mon, catalog) if mon else None dto["rows"].append({"id": str(position), "position": position, "position_label": position + 1, "stack_id": slot.get("id", "") if slot else "", "opened": bool(slot), "vip": position == 3, "status": ("VIP已激活" if vip else "VIP未激活") if slot and position == 3 else "已开启" if slot else "VIP专用" if position == 3 else "未开启", "name": info.get("name", "未知") if mon else "空位" if slot else "", "star": info.get("star", ""), "monster_id": int(mon["id"]) if mon else None, "phase": snapshot.phase_text(mon, catalog) if mon else "", "remaining": remaining, "remaining_text": duration(remaining) if mon else "", "quality": catalog.quality_text(mon) if mon else "", "decision": engine.planner.statuses.get(int(mon["id"]), "等待成长 / 预览规则") if mon else "", "can_expand": slot is None and position != 3}) dto["summary"] = f"已开启 {len(opened)} / {total} 个坑位;第4坑为VIP专用({'已激活' if vip else '未激活'})" dto["actions"] += [{"operation": "quote_expansion", "label": "开启选中普通坑位", "selection": "position", "payload": {"kind": "stack"}, "currencies": _options([("money", "金币"), ("ke", "氪金")])}] def _default_egg_rule(catalog, type_id, preferred_market): markets = catalog.markets_for(type_id) market = preferred_market if preferred_market in markets else markets[0] if markets else "" return asdict(EggRule(market_id=market)) def _egg_rows(dto, engine, config, query): catalog, snapshot = engine.catalog, engine.snapshot groups = {} for egg in snapshot.eggs(catalog): key = str(egg["typeId"]) group = groups.setdefault(key, {"count": 0, "inventory_ids": []}) group["count"] += int(egg.get("num") or 0) group["inventory_ids"].append(int(egg["id"])) rules = config["policy"]["egg_rules"] search = str(query.get("search", "")).strip().casefold() dto["columns"] = [_column(k, label) for k, label in (("name", "魔物蛋"), ("star", "星"), ("count", "数量"))] for key, label, kind, extra in ( ("enabled", "孵化", "boolean", {}), ("priority", "优先级", "integer", {"min": 1, "max": 999}), ("action", "孵出后", "select", {"options": _options([("sell", "派遣"), ("feed", "喂养"), ("keep", "保留")])}), ("refill_below", "低于补货", "integer", {"min": 0, "max": 1000}), ("refill_target", "补至", "integer", {"min": 1, "max": 1000}), ("market_id", "补货市场", "select", {})): dto["columns"].append(_row_column(key, label, ["policy", "egg_rules"], kind=kind, **extra)) dto["columns"] += [_column(k, label) for k, label in ( ("time_text", "培育时间"), ("sell_money", "派遣金币"), ("sell_exp", "基础经验"), ("gold_per_hour", "金币/小时"), ("exp_per_hour", "经验/小时"), ("inventory_text", "物品ID"))] dto["columns"].append(_row_column("keep_count", "牧场保留", ["policy", "egg_rules"], min=0, max=1000, help="已启用规则跨牧场至少保留此数量;0不保留名额,硬保护仍有效")) for key in dict.fromkeys([*groups, *rules]): info = catalog.monster(key) if not info or search and search not in (key + str(info.get("name", ""))).casefold(): continue markets = catalog.markets_for(key) defaults = _default_egg_rule(catalog, key, config["policy"]["market_id"]) rule = defaults | rules.get(key, {}) total = max(1, catalog.total_time(key)) money, exp = info.get("sell_money", 0), info.get("sell_exp", 0) options = _options([(market, catalog.data["markets"][market]["name"] + "市场") for market in markets]) dto["rows"].append({"id": key, "type_id": key, "name": info.get("name", key), "star": info.get("star", "?"), **groups.get(key, {"count": 0, "inventory_ids": []}), **rule, "time_total": total, "time_text": duration(total), "sell_money": money, "sell_exp": exp, "gold_per_hour": round(money * 3600 / total, 2), "exp_per_hour": round(exp * 3600 / total, 2), "inventory_text": ", ".join(map(str, groups.get(key, {}).get("inventory_ids", []))), "rule_defaults": defaults, "rule_path": ["policy", "egg_rules", key], "edits": {"market_id": _edit(["policy", "egg_rules", key, "market_id"], "select", options=options or _options([("", "金币市场无此蛋")]))}}) dto["summary"] = f"{len(dto['rows'])} 种魔物蛋规则;已启用 {sum(row['enabled'] for row in dto['rows'])} 种" dto["form"].append(_field(["policy", "egg_rules"], "添加魔物蛋规则", "add_rule", value=None, options=_options([(key, row.get("name", key)) for key, row in catalog.monsters.items()]), defaults=asdict(EggRule()), defaults_by_id={key: _default_egg_rule(catalog, key, config["policy"]["market_id"]) for key in catalog.monsters}, help="可配置背包当前没有的蛋;按孵化优先级、去向、补货和牧场保留规则自动执行")) def _bag(dto, engine, config, query): category = str(query.get("category", "eggs")) if category not in dict(BAG_CATEGORIES) and category != "all": raise ValueError("背包分类无效") dto["filters"].append(_filter("category", "背包分类", category, BAG_CATEGORIES)) search = _search(dto, query) if category == "eggs": _egg_rows(dto, engine, config, query) return category_code = {"all": 0, "usable": 1, "consumables": 2, "materials": 3, "other": 4, "equipment": 5}[category] catalog = engine.catalog groups = {} for item in engine.snapshot.raw["items"]: key = str(item.get("typeId")) if int(item.get("num") or 0) <= 0 or category_code and catalog.item_type(key) != category_code: continue if search and search not in (key + catalog.item_name(key)).casefold(): continue group = groups.setdefault(key, {"count": 0, "inventory_ids": []}) group["count"] += int(item["num"]) group["inventory_ids"].append(int(item["id"])) dto["columns"] = [_column(k, label) for k, label in (("inventory_text", "物品ID"), ("name", "名称"), ("category", "分类"), ("quality", "品质"), ("count", "数量"), ("sell_money", "售价"))] dto["columns"] += [_row_column("enabled", "允许赠礼", ["policy", "gift_items"], kind="boolean"), _row_column("reserve", "至少保留", ["policy", "gift_items"], min=0, max=1_000_000_000)] for key, group in groups.items(): info = catalog.item(key) code = catalog.item_type(key) eligible = code not in (5, 6) and bool(info.get("sellable")) rule = {"enabled": False, "reserve": 0} | config["policy"]["gift_items"].get(key, {}) dto["rows"].append({"id": key, "type_id": key, "name": catalog.item_name(key), "category": ITEM_TYPES.get(code, "其他"), "quality": info.get("quality", ""), **group, "inventory_text": ", ".join(map(str, group["inventory_ids"])), "sell_money": info.get("sellMoney", ""), **rule, "gift_eligible": eligible, "rule_defaults": {"enabled": False, "reserve": 0}, "rule_path": ["policy", "gift_items", key], "edits": {field: _edit(["policy", "gift_items", key, field], kind, disabled=not eligible, reason="此类物品不进入自动赠礼" if not eligible else "") for field, kind in (("enabled", "boolean"), ("reserve", "integer"))}}) dto["summary"] = f"{len(groups)} 类物品 / {sum(row['count'] for row in groups.values())} 件;同种库存合并显示" def _ranch(dto, engine, config, query): snapshot, catalog = engine.snapshot, engine.catalog grouped = _boolean(query.get("grouped"), False) try: room_id = int(query.get("room_id") or 0) except (ValueError, TypeError) as exc: raise ValueError("牧场编号无效") from exc dto["filters"] = [_filter("grouped", "按牧场分组", grouped, kind="boolean"), _filter("room_id", "牧场", room_id, [(0, "全部牧场")] + [(int(room["id"]), f"{room.get('name') or '牧场'} #{room['id']}") for room in snapshot.raw["rooms"]])] search = _search(dto, query) keys = ["monster_id", "name", "star", "level_text", "quality", "location", "locked", "scope", "feed_selected", "feed_priority", "potential_level", "attack", "defense", "health", "dexterity", "feel_text", "likes", "gift_selected", "gift_priority", "breakthrough_selected", "breakthrough_priority", "tp_level_text", "tp_exp_text"] labels = ["牧场 / 魔物ID", "名称", "星", "等级 / 当前上限", "资质 攻/防/血/敏", "位置", "锁定", "管理范围", "喂养目标", "喂养优先级", "潜能阶段", "参考攻击", "参考防御", "参考生命", "参考敏捷", "好感 / 当前上限", "喜欢的物品", "赠礼", "赠礼优先级", "自动突破目标", "突破优先级", "同种突破", "突破经验"] dto["columns"] = [_column(key, label) for key, label in zip(keys, labels)] for prefix, mapping in (("feed", "feed_targets"), ("gift", "gift_targets"), ("breakthrough", "breakthrough_targets")): for column in dto["columns"]: if column["key"] == prefix + "_selected": column.update(type="boolean", edit=_edit(["policy", mapping, "{id}"], "target", default=100, unchecked="delete")) elif column["key"] == prefix + "_priority": column.update(type="integer", edit=_edit(["policy", mapping, "{id}"], "integer", min=1, max=999, optional=True)) managed = engine.planner.managed rows = monster_rows(catalog, snapshot, managed) counts = Counter("incubator" if mon.get("process") == 2 else f"room:{int(mon.get('roomId') or 0)}" for mon in snapshot.raw["monsters"]) dto["groups"] = [] if grouped: for room in snapshot.raw["rooms"]: rid = int(room["id"]) if room_id and rid != room_id: continue info = catalog.data.get("room_info", {}).get(str(room.get("typeId")), {}) group_key = f"room:{rid}" capacity = info.get("maxNum") dto["groups"].append({"id": group_key, "label": f"{room.get('name') or info.get('name') or '牧场'} #{rid}", "count": counts[group_key], "capacity": capacity, "free": max(0, int(capacity) - counts[group_key]) if capacity is not None else None, "collapsed": False}) for mon, values in zip(snapshot.raw["monsters"], rows): if room_id and (mon.get("process") != 3 or int(mon.get("roomId") or 0) != room_id): continue if search and search not in " ".join(map(str, values)).casefold(): continue key = str(int(mon["id"])) row = dict(zip(keys, values)) | {"id": key, "type_id": str(mon["typeId"]), "level": int(mon.get("level") or 1), "max_level": catalog.max_level(mon), "process": mon.get("process"), "room_id": int(mon.get("roomId") or 0), "group": "incubator" if mon.get("process") == 2 else f"room:{int(mon.get('roomId') or 0)}", "edits": {}} for prefix, mapping in (("feed", "feed_targets"), ("gift", "gift_targets"), ("breakthrough", "breakthrough_targets")): targets = config["policy"][mapping] selected = key in targets row[prefix + "_selected"], row[prefix + "_priority"] = selected, targets.get(key, 100) row["edits"][prefix + "_selected"] = _edit(["policy", mapping, key], "target", default=100, unchecked="delete", disabled=mon.get("process") != 3) row["edits"][prefix + "_priority"] = _edit(["policy", mapping, key], "integer", min=1, max=999, optional=True, disabled=not selected or mon.get("process") != 3) dto["rows"].append(row) dto["details"][key] = {"name": row["name"], "species": catalog.monster(mon["typeId"]).get("name", "未知"), "id": int(mon["id"]), "level": row["level_text"], "quality": row["quality"], "reference_stats": catalog.reference_stats(mon), "growth": {name: mon.get("g" + name.capitalize()) for name in ("atk", "def", "hp", "dex")}, "likes": row["likes"], "feel": row["feel_text"], "feed_exp": catalog.feed_exp(mon), "scope": row["scope"]} if grouped: known = {group["id"] for group in dto["groups"]} for row in dto["rows"]: if row["group"] not in known: known.add(row["group"]) dto["groups"].append({"id": row["group"], "label": "培育室" if row["group"] == "incubator" else "未归属牧场", "count": counts[row["group"]], "collapsed": False}) dto["summary"] = f"{len(snapshot.raw['rooms'])} 座牧场;显示 {len(dto['rows'])} 只魔物;勾选目标按较小优先级先执行" targets = [{"value": int(mon["id"]), "label": f"{catalog.monster_label(mon)} Lv.{mon.get('level', 1)}/{catalog.max_level(mon)}"} for mon in snapshot.raw["monsters"] if mon.get("process") == 3 and catalog.max_level(mon) is not None and int(mon.get("level", 1)) < catalog.max_level(mon)] dto["feed_targets"] = targets dto["actions"] += [{"operation": operation, "label": label, "selection": "monster_ids", **extra} for operation, label, extra in ( ("lock", "锁定选中魔物", {}), ("unlock", "解锁选中魔物", {}), ("sell", "派遣选中魔物", {"confirm": "将消耗选中魔物,无法撤销"}), ("feed", "喂给指定魔物", {"confirm": "将消耗选中魔物作为经验素材,无法撤销", "target_options": targets}))] dto["actions"].append({"operation": "quote_expansion", "label": "新建牧场", "payload": {"kind": "room"}, "currencies": _options([("money", "金币"), ("ke", "氪金")])}) def _daily(dto, engine, config, query): dto["columns"] = [_column(k, label) for k, label in (("name", "项目 / 邮件"), ("status", "状态"), ("reward", "奖励 / 附件"))] for row in entries(engine.catalog, engine.snapshot, engine.daily_ledger): dto["rows"].append({"id": row.key, "name": row.name, "status": row.status, "reward": row.reward, "claimable": row.action is not None}) dto["summary"] = "刷新只更新状态;领取勾选项目立即处理可领奖励;自动领取需要开启顶部策略" dto["actions"].append({"operation": "claim_daily", "label": "领取勾选项目", "payload": {}}) def _hatching(dto, engine, config, query): for field in dto["form"]: if field["path"] == ["policy", "room_id"]: field["options"] += _options([(int(room["id"]), f"{room.get('name') or '牧场'} #{room['id']}") for room in engine.snapshot.raw["rooms"]]) dto["tabs"] = [{"key": label, "title": label} for label in ("孵蛋策略", "牧场策略", "喂养策略")] dto["columns"] = [_column("kind", "类型"), _column("description", "下一步 / 等待条件")] dto["rows"] = _plans(engine) policy = engine.policy dto["summary"] = "先在背包魔物蛋配置规则,再开启顶部策略;空坑按优先级随机1~2秒装填" dto["details"] = {"feed_status": engine.planner.feed_status(engine.snapshot, policy), "last_draw": engine.last_draw or "尚无记录", "notes": list(dict.fromkeys(engine.planner.notes)), "preset": {"label": "绿色史莱姆金币预设(仅孵此蛋)", "patch": { "policy": {"enabled": True, "buy": True, "fill": True, "dispatch": True, "collect": True, "buy_ten": True, "allow_single_draw": False, "feed": False, "strategy": "gold", "market_id": "sc_city1", "egg_order": "shortest", "protect_quality": 3, "protect_star": 4, "hatch_max_star": 3, "min_gold_per_hour": 0, "min_exp_per_hour": 0}}, "egg_rules": {key: rule | {"enabled": False} for key, rule in config["policy"]["egg_rules"].items()} | { "1001010": asdict(EggRule(enabled=True, priority=1, action="sell", refill_below=1, refill_target=10, market_id="sc_city1"))}, "help": "只更改策略并保存;开启顶部策略后运行"}} def _gifts(dto, engine, config, query): catalog, snapshot = engine.catalog, engine.snapshot dto["columns"] = [_column(k, label) for k, label in (("species", "魔物种类"), ("monster_id", "培养对象 ID"), ("level", "等级"), ("feel_text", "好感 / 上限"), ("quality", "资质 攻/防/血/敏"), ("likes", "喜欢的物品"), ("cooldown", "赠礼冷却"))] representatives = engine.cultivation.select(snapshot) if engine.policy.gift_auto_representative else {} candidates = list(representatives.values()) if representatives else engine.gift_planner.candidates(snapshot, engine.policy) cooldown = int(catalog.data["game_setting"].get("monGiftTime", 7200)) for mon in candidates: remaining = max(0, seconds(mon.get("giftTime")) + cooldown - snapshot.now) dto["rows"].append({"id": str(mon["id"]), "species": catalog.monster(mon["typeId"]).get("name", "未知"), "monster_id": int(mon["id"]), "level": mon.get("level", 1), "feel_text": f"{mon.get('feel', 0)} / {catalog.max_feel(mon)}", "quality": catalog.quality_text(mon), "likes": catalog.likes_text(mon["typeId"]), "remaining": remaining, "cooldown": duration(remaining) if remaining else "可赠礼"}) engine.gift_planner.plan(snapshot, engine.policy, engine.quest_policy) dto["summary"] = "自动代表按等级 → 好感 → 综合成长资质选择并记住;满好感或冷却时不换喂同种另一只" dto["details"] = {"notes": list(engine.gift_planner.notes), "next_ready_at": engine.gift_planner.next_ready_at, "inventory_page": "bag", "targets_page": "ranch"} CATEGORIES = {"mainline": "主线", "sidequest": "支线", "commission": "委托", "event": "活动(暂不自动)", "bond": "羁绊(暂不自动)", "unknown": "其他 / 未知"} BATTLE_KINDS = {"mainline": "主线战斗", "sidequest": "支线战斗", "commission": "委托战斗", "battle": "普通战斗", "map_battle": "地图战斗", "sweep": "扫荡", "map_reward_event": "地图奖励事件", "ordinary_stage": "普通关卡战斗", "resource_stage": "资源关卡战斗", "task_battle": "任务战斗", "task_pass_stage": "任务通关战斗", "unknown": "其他 / 未知"} BATTLE_ALIASES = {"task": "task_battle", "passStage": "task_pass_stage", "event": "map_reward_event", "reward_event": "map_reward_event", "normal": "battle"} STATES = {"available": "可接取", "unaccepted": "未接取", "active": "进行中", "in_progress": "进行中", "ready": "待交付", "completed": "已完成", "complete": "已完成", "claimed": "已领奖", "received": "进行中", "unlocked": "已解锁 / 待接取", "offered": "待接取", "locked": "未解锁", "finished": "已完成", "ready_to_reward": "待领取任务奖励", "blocked": "受阻", "unsupported": "暂不支持", "unknown": "未知"} STATE_ALIASES = {"active": "received", "in_progress": "received", "available": "unlocked", "unaccepted": "unlocked", "offered": "unlocked", "ready": "ready_to_reward", "completed": "finished", "complete": "finished", "claimed": "finished", "blocked": "received"} STATE_FILTERS = [("current", "当前(进行中 + 待接取 + 待领奖)"), ("received", "进行中"), ("unlocked", "待接取"), ("ready_to_reward", "待领奖"), ("finished", "已完成"), ("locked", "未解锁"), ("", "全部状态")] OUTCOMES = {"win": "胜利", "loss": "打不过", "unsupported": "暂不支持", "event": "地图奖励事件", "completed": "已完成", "cancelled": "已取消", "timeout": "超时", "unknown": "结果待核对"} CHINA_TIME = timezone(timedelta(hours=8)) def _text(value, empty="—"): # Display only scalars. Arbitrary raw structures must never reach a detail # drawer through json.dumps (battle records may contain responses/secrets). return str(value) if isinstance(value, (str, int, float, bool)) and value != "" else empty def _category(value): value = {"main": "mainline", "side": "sidequest", "sidequests": "sidequest", "commissions": "commission", "主线": "mainline", "支线": "sidequest", "委托": "commission"}.get(value, value) if isinstance(value, str) else "unknown" return value if value in CATEGORIES else "unknown" def _mainline(dto, engine, config, query): selected, state = str(query.get("category", "mainline")), str(query.get("state", "current")) dto["filters"] = [_filter("category", "任务类别", selected, [("", "全部类别"), *CATEGORIES.items()]), _filter("state", "任务状态", state, STATE_FILTERS)] search = _search(dto, query) dto["columns"] = [_column(key, label) for key, label in (("task_type_id", "编号"), ("category_label", "类别"), ("name", "任务"), ("state_label", "状态"), ("step", "步骤"), ("location", "目标 / 位置"), ("requirement", "需求"), ("next_action", "下一步"), ("battle", "战斗类型"), ("support", "支持状态 / 阻塞原因"))] sources = engine.progression_rows() for index, source in enumerate(sources): category = _category(source.get("category")) raw_state = _text(source.get("state"), "unknown") lifecycle = STATE_ALIASES.get(raw_state, raw_state) if selected and category != selected or state == "current" and lifecycle not in ("received", "unlocked", "ready_to_reward") or state not in ("", "current") and lifecycle != state: continue reason = battle_message(source.get("blocked_reason") or source.get("block_reason") or source.get("reason") or "") support = "受阻:" + reason if reason else "已支持" if source.get("supported") is True else "暂不支持" if source.get("supported") is False else "支持状态未确认" battle = _text(source.get("battle_kind"), "未确认") battle = BATTLE_ALIASES.get(battle, battle) row = {"id": str(source.get("task_id") or source.get("task_type_id") or index), "task_type_id": _text(source.get("task_type_id")), "category": category, "category_label": CATEGORIES[category], "name": _text(source.get("name")), "state": raw_state, "lifecycle_state": lifecycle, "state_label": STATES.get(raw_state, raw_state), "step": _text(source.get("step_number")) + " / " + _text(source.get("total_steps")), "location": _text(source.get("location_text") or source.get("location") or source.get("position")), "requirement": _text(source.get("requirement")), "next_action": _text(source.get("next_action")), "battle": BATTLE_KINDS.get(battle, battle), "support": support} detail = {"任务": row["name"], "类别": row["category_label"], "状态": row["state_label"], "步骤": row["step"], "目标 / 位置": row["location"], "NPC": _text(source.get("npc_name")), "需求": row["requirement"], "对话": _text(source.get("dialogue") or source.get("dialogue_text") or source.get("dialogue_status"), "当前未提供对话内容"), "下一步": row["next_action"], "战斗": row["battle"], "运行状态": _text(source.get("status"), row["state_label"]), "支持状态 / 阻塞原因": support} if search and search not in " ".join(map(str, [*row.values(), *detail.values()])).casefold(): continue dto["rows"].append(row) dto["details"][row["id"]] = detail dto["summary"] = f"显示 {len(dto['rows'])} / {len(sources)} 条任务;未支持的步骤显示原因" if sources else "尚未读取任务,请刷新任务 / 预览" dto["tabs"] = [{"key": "status", "title": "任务状态"}, {"key": "policy", "title": "推进策略"}] dto["actions"] = [{"operation": "refresh_tasks", "label": "刷新任务 / 预览", "payload": {}}] dto["battle_mode"] = {"mode": "experimental", "label": "实验模拟(近似,未完整验证)", "damage_rule": "保持原始属性;我方对敌最终伤害10倍,单次最高50000"} def _battles(dto, engine, config, query): selected = str(query.get("category", "")) dto["filters"] = [_filter("category", "战斗类型", selected, [("", "全部类型"), *BATTLE_KINDS.items()])] search = _search(dto, query) dto["columns"] = [_column(key, label) for key, label in (("time", "时间(北京时间)"), ("kind_label", "上下文 / 类型"), ("name", "任务 / 地图"), ("team", "队伍"), ("outcome_label", "结果"), ("message", "详情 / 阻塞原因"))] records = engine.progression_records() for index, source in enumerate(records): raw_kind = source.get("battle_kind") or source.get("kind") or source.get("context") or "unknown" kind = BATTLE_ALIASES.get(raw_kind, raw_kind) if isinstance(raw_kind, str) else "unknown" if source.get("outcome") == "event": kind = "map_reward_event" elif source.get("task_id") and kind == "battle": kind = "task_battle" elif source.get("kind") == "sweep": kind = "sweep" if selected and selected != kind: continue stamp = source.get("finished_at") or source.get("started_at") or source.get("timestamp", source.get("time", source.get("at"))) if type(stamp) in (int, float) and 0 <= stamp <= 253402271999: stamp = datetime.fromtimestamp(stamp, CHINA_TIME).strftime("%Y-%m-%d %H:%M:%S") outcome = source.get("outcome") or source.get("status") or source.get("phase") or source.get("result") if isinstance(outcome, dict): outcome = outcome.get("outcome") or outcome.get("status") outcome = _text(outcome, "unknown") mode = source.get("battle_mode") or source.get("execution_mode") row = {"id": str(index), "time": _text(stamp), "category": kind, "kind_label": BATTLE_KINDS.get(kind, "其他 / 未知"), "name": _text(source.get("name") or source.get("task_type_id") or source.get("stage_id") or source.get("stage") or source.get("description")), "team": _text(source.get("team")), "outcome": outcome, "outcome_label": OUTCOMES.get(outcome, outcome) + ("(实验近似)" if mode == "experimental" else ""), "message": battle_message(_text(source.get("blocked_reason") or source.get("block_reason") or source.get("message") or source.get("reason")))} if search and search not in " ".join(map(str, row.values())).casefold(): continue dto["rows"].append(row) damage = {"client_v4_x10": "我方对敌最终伤害10倍,单次最高50000;角色属性保持原值", "original_1x": "原始1倍;角色属性保持原值"}.get(source.get("damage_profile"), "旧记录未标明伤害倍率") reward = source.get("reward") if isinstance(reward, dict): # Both wire-shaped and already normalized journal rewards occur. shown_reward = reward_summary(engine.catalog, reward) normalized_drops = reward.get("drops") if isinstance(normalized_drops, list): drop_text = [f"{_text(drop.get('name'))} ×{_text(drop.get('num'), '0')}" for drop in normalized_drops if isinstance(drop, dict)] shown_reward += (";" if shown_reward and drop_text else "") + ";".join(drop_text) else: shown_reward = "当前未提供奖励数据" dto["details"][row["id"]] = {"时间(北京时间)": row["time"], "上下文": row["kind_label"], "任务 / 地图": row["name"], "战斗模式": "实验模拟(近似,未完整验证)" if mode == "experimental" else "原版运行时" if mode == "original" else "记录未标明", "队伍": row["team"], "结果": row["outcome_label"], "详情 / 阻塞原因": row["message"], "奖励": shown_reward, "伤害规则": damage} dto["summary"] = f"已读取 {len(records)} 条记录,显示 {len(dto['rows'])} 条" if records else "尚无已读取的战斗记录;未记录结果不代表战斗成功" dto["actions"] = [{"operation": "refresh_tasks", "label": "刷新战斗记录", "payload": {}}] def _commissions(dto, engine, config, query): snapshot, catalog = engine.snapshot, engine.catalog search = _search(dto, query) dto["columns"] = [_column(key, label) for key, label in (("task_type_id", "编号"), ("name", "委托"), ("status", "状态"), ("reward_money", "金币奖励"), ("reward_ke", "氪金奖励"), ("reason", "需求 / 下一步 / 阻塞原因"))] diagnostics = {str(row.get("task_type_id")): row for row in engine.progression_rows() if _category(row.get("category")) == "commission"} source = engine.tasks.rows(snapshot, engine.quest_policy, engine.policy) for index, (key, name, status, text, meta) in enumerate(source): diagnostic = diagnostics.get(str(key), {}) reason = diagnostic.get("block_reason") or diagnostic.get("blocked_reason") if reason: status = "暂不接取" if "city" in meta else "等待条件" text = reason elif diagnostic.get("next_action"): text = diagnostic["next_action"] info = catalog.data.get("task_info", {}).get(str(key), {}) reward = info.get("reward") or {} row = {"id": f"{key}:{index}", "task_type_id": str(key), "name": name, "status": status, "reward_money": reward.get("money", 0), "reward_ke": reward.get("ke", 0), "reason": battle_message(text), "city": meta.get("city"), "active": "city" not in meta} if search and search not in " ".join(map(str, row.values())).casefold(): continue dto["rows"].append(row) dto["details"][row["id"]] = {"描述": info.get("des", ""), "需求 / 下一步": row["reason"], "交付限制": {"允许物品": engine.quest_policy.allow_items, "允许魔物": engine.quest_policy.allow_monsters, "单次金币上限": engine.quest_policy.max_money, "允许已支持战斗": engine.quest_policy.battle_tasks}, "接取优先级": "氪金奖励较高的委托优先;仅接取原规划器确认可支持的委托"} dto["summary"] = f"今日剩余可接次数:{snapshot.raw.get('history', {}).get('loopTaskNum', '未知')};当前委托:{len(engine.tasks.current(snapshot))};按氪金奖励优先" def _exploration(dto, engine, config, query): planner, snapshot = engine.explore_planner, engine.snapshot policy = engine.explore_policy rows = planner.rows(snapshot, policy, engine.policy) area_options = [{"value": key, "label": f"{area.get('name') or key}({key})", "disabled": not planner.area_unlocked(snapshot, area), "reason": "" if planner.area_unlocked(snapshot, area) else f"需通关 {area.get('passStage') or '指定关卡'} 难度1"} for key, area in planner.areas.items()] dto["columns"] = [_row_column("enabled", "启用", ["explore_policy", "teams"], kind="boolean"), _column("team_id", "队伍"), _row_column("area", "地区", ["explore_policy", "teams"], kind="select", options=_options([("", "请选择地区")]) + area_options), _column("state_text", "状态 / 剩余"), _column("monsters", "队长 / 队员 / 队员", "members", _edit(["explore_policy", "teams", "{id}", "monsters"], "members", slots=["队长", "队员(等级不可高于队长)", "队员(等级不可高于队长)"])), _column("cost_text", "体力 / 时间"), _column("reason", "原因 / 选择规则")] for source in rows: key = str(source["team_id"]) rule = {"enabled": False, "area": "", "monsters": []} | config["explore_policy"]["teams"].get(key, {}) disabled = source["state"] in ("探索中", "可领取", "待核对") candidates = planner.member_options(snapshot, int(key), policy, engine.policy) options = [] for candidate in candidates: mon = snapshot.monsters.get(candidate["id"]) manual_reason = planner.monster_exclusion(snapshot, mon, engine.policy, automatic=False) if mon else "快照中不存在" if candidate["reason"] == "正在其他探险队": manual_reason = candidate["reason"] options.append({"value": candidate["id"], "label": f"{candidate['label']} Lv.{candidate['level']}" + (f";{candidate['reason']}" if candidate["reason"] else ""), "level": candidate["level"], "automatic": candidate["automatic"], "automatic_reason": candidate["reason"], "disabled": bool(manual_reason), "reason": manual_reason}) for mid in rule["monsters"]: if not any(option["value"] == mid for option in options): options.append({"value": mid, "label": f"#{mid}(当前快照不存在)", "disabled": True, "reason": "当前快照不存在", "automatic": False, "automatic_reason": "当前快照不存在"}) members_edit = _edit(["explore_policy", "teams", key, "monsters"], "members", options=options, disabled=disabled, slots=["队长", "队员(等级不可高于队长)", "队员(等级不可高于队长)"]) dto["rows"].append({"id": key, "team_id": source["team_id"], **rule, "state": source["state"], "remaining": source["remaining"], "state_text": source["state"] + " / " + (duration(source["remaining"]) if source["remaining"] is not None else "—"), "monster_ids": source["monster_ids"], "monster_labels": [engine.catalog.monster_label(snapshot.monsters[mid]) if mid in snapshot.monsters else f"#{mid}" for mid in source["monster_ids"]], "member_options": options, "cost_ti": source["cost_ti"], "cost_time": source["cost_time"], "cost_text": f"{source['cost_ti']} / {duration(source['cost_time'])}", "manual": source["manual"], "can_auto": source["can_auto"], "reason": source["reason"] or ("手动指定;允许锁定 / 装备" if source["manual"] else "自动选空闲魔物"), "rule_defaults": {"enabled": False, "area": "", "monsters": []}, "rule_path": ["explore_policy", "teams", key], "edits": {"enabled": _edit(["explore_policy", "teams", key, "enabled"], "boolean", disabled=disabled), "area": _edit(["explore_policy", "teams", key, "area"], "select", options=_options([("", "请选择地区")]) + area_options, disabled=disabled), "monsters": members_edit}}) dto["summary"] = f"已有 {len(rows)} 支探险队;配置 {len(policy.teams)} 支;启用 {sum(rule.enabled for rule in policy.teams.values())} 支。完成时自动领奖,再次出发由开关控制。" dto["details"] = {"help": "留空任一槽位恢复自动选人;手动队员必须三只不同魔物,队员等级不可高于队长;不自动花钱开队或召回"} def _maps(dto, engine, config, query): snapshot = engine.snapshot all_rows = engine.stage_cache.get(snapshot) resource_catalog = engine.stage_cache.catalog category = str(query.get("category", "all")) only_unlocked = _boolean(query.get("only_unlocked"), True) if category not in ("all", "ordinary", "resource"): raise ValueError("地图分类无效") dto["filters"] = [_filter("category", "关卡分类", category, [("all", "全部关卡"), ("ordinary", "普通关卡"), ("resource", "矿洞与门票")]), _filter("only_unlocked", "只看账号已解锁", only_unlocked, kind="boolean")] search = _search(dto, query) policy = engine.sweep_policy team_ids = engine.sweeper.team_ids(snapshot, policy) dto["columns"] = [_row_column("enabled", "刷图", ["sweep_policy", "rules"], kind="boolean"), _column("number", "关卡"), _column("name", "名称"), _row_column("level", "难度", ["sweep_policy", "rules"], kind="select", options=_options([(str(i), f"难度{i}") for i in (1, 2, 3)])), _column("stars_text", "星级"), _column("status", "扫荡 / 挑战状态"), _column("cost_text", "体力 / 门票:单次 / 可用 / 保留"), _column("drops", "可能掉落"), _row_column("limit", "本日上限", ["sweep_policy", "rules"], min=0, max=999), _column("used", "本日已开始")] grouped = {} for stage in all_rows: if stage.category in ("mine", "ticket") and stage.level != "1": continue grouped.setdefault(stage.stage_id, []).append(stage) dto["groups"] = [] cities = set() for key, stages in sorted(grouped.items(), key=lambda pair: (pair[1][0].city, pair[1][0].number, pair[0])): first = stages[0] resource = first.category in ("mine", "ticket") if category == "ordinary" and first.category != "ordinary" or category == "resource" and not resource: continue if only_unlocked and not any(stage.unlocked for stage in stages): continue if search and search not in (first.city_name + key + first.number + first.name + " ".join(stage.drops for stage in stages)).casefold(): continue saved = config["sweep_policy"]["rules"].get(key, {}) chosen = next((stage for stage in stages if stage.level == saved.get("level")), None) chosen = chosen or next((stage for stage in reversed(stages) if stage.unlocked), first) defaults = {"enabled": False, "level": chosen.level, "limit": 3} rule = defaults | saved reason = engine.map_stage_reason(snapshot, chosen, policy, team_ids=team_ids) costs = [{"kind": "stamina", "label": "体力", "required": chosen.stamina, "available": int(snapshot.raw["master"].get("ti") or 0), "reserve": policy.keep_stamina}] base = resource_catalog.data.get("stage_info", {}).get(key, {}).get("cost") or {} if resource: for item_id, count in item_requirements(base.get("items") or []).items(): costs.append({"kind": "item", "type_id": item_id, "label": resource_catalog.data.get("item_names", {}).get(item_id, item_id), "required": count, "available": available_item_count(snapshot, item_id), "reserve": policy.keep_tickets}) if not chosen.battle_available: reason = "该资源关卡缺少已提取的战斗配置,未启用" elif not policy.allow_special: reason = "尚未开启“允许矿洞 / 门票关卡”资源关开关" else: insufficient = next((cost for cost in costs if cost["available"] - cost["required"] < cost["reserve"]), None) if insufficient: reason = f"{insufficient['label']}不足:单次需 {insufficient['required']},可用 {insufficient['available']},保留 {insufficient['reserve']}" reason = reason or "将按实际模拟结果挑战;不是扫荡" cost_text = "\n".join(f"{cost['label']} 单次 {cost['required']} / 可用 {cost['available']} / 保留 {cost['reserve']}" for cost in costs) levels = [{"value": stage.level, "label": f"难度 {stage.level}" + ("(已通关)" if stage.passed else ""), "disabled": not (stage.unlocked and stage.open)} for stage in stages] dto["rows"].append({"id": key, "number": first.number, "name": first.name, "group": str(first.city), "city_name": first.city_name, "category": first.category, **rule, "stars": first.stars, "stars_text": "★" * first.stars + "☆" * max(0, 3 - first.stars), "status": reason or ("可扫荡" if chosen.sweep else "将模拟挑战"), "unlocked": chosen.unlocked, "open": chosen.open, "sweep": chosen.sweep, "costs": costs, "cost_text": cost_text, "drops": chosen.drops, "used": engine.sweeper.used(snapshot, chosen), "rule_defaults": defaults, "rule_path": ["sweep_policy", "rules", key], "edits": {"enabled": _edit(["sweep_policy", "rules", key, "enabled"], "boolean", disabled=not any(stage.unlocked and stage.open for stage in stages)), "level": _edit(["sweep_policy", "rules", key, "level"], "select", options=levels)}}) if first.city not in cities: cities.add(first.city) dto["groups"].append({"id": str(first.city), "label": first.city_name, "collapsed": not bool(search)}) pending = engine.sweeper.state.get("pending") dto["summary"] = f"已解锁 {sum(stage.unlocked for stage in all_rows)} 个难度;显示 {len(dto['rows'])} 关;勾选 {sum(bool(rule.get('enabled')) for rule in policy.rules.values())} 关" dto["details"] = {"pending": {"stage": _text(pending.get("stage")), "phase": _text(pending.get("phase"))} if pending else None, "help": "普通关卡三个难度全部通关可扫荡;资源关卡需单独开启并逐关勾选,仅原入口难度1;未支持内容保留具体原因,随机掉落并非必得"} dto["actions"] = [{"operation": "refresh_maps", "label": "刷新关卡", "payload": {}}, {"operation": "reset_map_pending", "label": "核对未完成记录", "payload": {"confirm": True}, "confirm": "按服务器证据核对;证据不完整时会保留记录"}] def _statistics(dto, engine, config, query): catalog = engine.stage_cache.catalog source = str(query.get("source", "all")) metric = str(query.get("metric", "rate")) if metric == "probability": metric = "rate" if source not in ("all", "sweep", "event") or metric not in ("rate", "per_stamina"): raise ValueError("数据分析来源或指标无效") stage_id, level = str(query.get("stage_id") or query.get("stage") or ""), str(query.get("level", "3")) data = engine.sweeper.statistics.snapshot(engine.snapshot.raw["master"]["id"]) if engine.snapshot else {"totals": {}, "drops": {}} dto["filters"] = [_filter("source", "统计范围", source, [("all", "扫荡+奖励事件"), ("sweep", "普通扫荡"), ("event", "奖励事件")]), _filter("metric", "图表指标", metric, [("rate", "实测掉落率"), ("per_stamina", "每点体力数量")])] search = _search(dto, query) stages, choices = [], [] for key, stage in sorted(catalog.data.get("stage_info", {}).items(), key=lambda pair: (int(pair[1].get("city") or 0), pair[1].get("tagname") or pair[0])): label = f"{stage.get('tagname') or key} {stage.get('name') or key}" if search and search not in (key + label).casefold(): continue levels = [{"id": str(number), "level": str(number), "value": str(number), "label": f"{label} / 难度 {number}", "sweep": data["totals"].get(f"{key}:{number}:sweep", {}).get("n", 0), "event": data["totals"].get(f"{key}:{number}:event", {}).get("n", 0)} for number in sorted(stage.get("level", {}), key=int)] city_id = str(int(stage.get("city") or 0)) city = catalog.data["game_setting"].get("cityInfo", {}).get(city_id, {}).get("name", f"地区 {city_id}") stages.append({"id": key, "label": label, "city_id": city_id, "city_name": city, "levels": levels, "sweep": sum(row["sweep"] for row in levels), "event": sum(row["event"] for row in levels)}) choices.append((key, label)) dto["stages"] = stages dto["filters"] += [_filter("stage_id", "关卡", stage_id, [("", "请选择关卡"), *choices])] stage = catalog.data.get("stage_info", {}).get(stage_id) levels = [(str(number), f"难度 {number}") for number in sorted(stage.get("level", {}), key=int)] if stage else [(str(i), f"难度{i}") for i in (1, 2, 3)] dto["filters"].append(_filter("level", "难度", level, levels)) dto["columns"] = [_column(key, label) for key, label in (("name", "掉落物"), ("kind_label", "类别"), ("hits", "出现次数"), ("units", "总数量"), ("samples", "样本数"), ("rate_text", "实测掉落率"), ("average", "平均数量/次"), ("per_stamina", "每点体力数量"), ("interval_text", "95%区间"), ("configured_text", "静态配置"))] dto["chart"] = {"type": "horizontal_bar", "metric": metric, "label": "实测掉落率" if metric == "rate" else "每点体力数量", "series": [], "max": 1 if metric == "rate" else None, "unit": "ratio" if metric == "rate" else "个 / 体力", "empty_reason": "请选择关卡和难度"} dto["charts"] = [dto["chart"]] if not stage_id: dto["summary"] = "请选择关卡和难度;关卡来自本地配置,统计按当前账号读取" return if stage is None or level not in stage.get("level", {}): raise ValueError("数据分析的关卡或难度无效") totals, rows = analyze(catalog, data, stage_id, level, source) counts = {kind: data["totals"].get(f"{stage_id}:{level}:{kind}", {}).get("n", 0) for kind in ("sweep", "event")} dto["totals"] = totals | counts | {"source": source, "stage_id": stage_id, "level": level} for row in rows: interval = row["interval"] dto["rows"].append({"id": row["key"], **row, "kind_label": {"item": "物品", "egg": "魔物蛋", "monster": "魔物"}.get(row["kind"], "未知"), "rate_text": f"{row['rate'] * 100:.2f}%" if row["rate"] is not None else "—", "interval_text": f"{interval[0] * 100:.1f}%~{interval[1] * 100:.1f}%" if interval else "—", "configured_text": "可能掉落" if row["configured"] else "实际观测"}) dto["chart"]["series"] = [{"id": row["key"], "label": row["name"], "value": row[metric], "hits": row["hits"], "samples": row["samples"]} for row in rows if row[metric] is not None] dto["chart"]["empty_reason"] = "尚无此范围的已确认样本" if not totals["n"] else "没有已知的非零体力消耗,暂不计算体力效率" if metric == "per_stamina" and not totals["spent"] else "" if metric == "per_stamina": dto["chart"]["max"] = max([point["value"] for point in dto["chart"]["series"]] + [0]) * 1.15 or 1 dto["summary"] = f"{stage.get('tagname') or stage_id} {stage.get('name') or stage_id} / 难度 {level};扫荡 {counts['sweep']} / 奖励事件 {counts['event']};当前范围 {totals['n']} 个已确认样本;累计金币 {totals['money']}、经验 {totals['exp']};已知体力消耗样本 {totals['known']}/{totals['n']},消耗体力 {totals['spent']},返还体力 {totals['ti']}" dto["details"] = {"help": "掉落率=出现次数/已确认样本数;每点体力数量只计已知消耗样本,不扣减奖励返还体力;实测值不是官方掉率;95%区间反映样本不确定性", "statistics_error": "本地统计读取失败,请查看服务器日志" if data.get("error") else ""} def _execution_plans(dto, engine, config, query): dto["columns"] = [_column("kind", "类型"), _column("description", "计划动作")] dto["rows"] = _plans(engine) dto["summary"] = f"{len(dto['rows'])} 项计划;仅预览,开启顶部策略后由原引擎执行" dto["details"] = {"notes": list(dict.fromkeys(engine.planner.notes))} def _yields(dto, engine, config, query): search = _search(dto, query) dto["columns"] = [_column(key, label) for key, label in (("type_id", "魔物编号"), ("name", "名称"), ("star", "星"), ("time_text", "培育时间"), ("sell_money", "派遣金币"), ("sell_exp", "基础经验"), ("gold_per_hour", "金币/小时"), ("exp_per_hour", "经验/小时"), ("ratio", "金币/经验"), ("recommendation", "建议(未计保留条件)"))] threshold = config["policy"]["coins_per_exp"] for type_id in engine.catalog.monsters: info = engine.catalog.monster(type_id) if int(info.get("star", 0)) not in config["yield_stars"] or search and search not in (type_id + str(info.get("name", ""))).casefold(): continue total = engine.catalog.total_time(type_id) if not total: continue money, exp = info.get("sell_money", 0), info.get("sell_exp", 0) ratio = money / exp if exp else None dto["rows"].append({"id": type_id, "type_id": int(type_id), "name": info.get("name", "未知"), "star": info.get("star", "?"), "time_total": total, "time_text": duration(total), "sell_money": money, "sell_exp": exp, "gold_per_hour": round(money * 3600 / total, 2), "exp_per_hour": round(exp * 3600 / total, 2), "ratio": round(ratio, 3) if ratio is not None else "无经验", "recommendation": "适合喂养" if ratio is not None and ratio < threshold else "适合派遣"}) dto["summary"] = f"本地资料共 {len(engine.catalog.monsters)} 种魔物,当前显示 {len(dto['rows'])} 种;CSV/XLSX覆盖值仅影响收益计算" dto["actions"].append({"operation": "import_yields", "label": "导入CSV / XLSX收益资料", "accept": ".csv,.xlsx"}) dto["details"] = {"import_columns": ["typeId / 编号 / 魔物ID", "sell_money / 派遣金币", "sell_exp / 强化经验", "time_total / 孵化秒数"]} _BUILDERS.update({"login": _login, "incubator": _incubator, "bag": _bag, "ranch": _ranch, "daily": _daily, "hatching": _hatching, "mainline": _mainline, "battles": _battles, "gifts": _gifts, "commissions": _commissions, "exploration": _exploration, "maps": _maps, "statistics": _statistics, "plans": _execution_plans, "yields": _yields})