619 lines
31 KiB
Python
619 lines
31 KiB
Python
from __future__ import annotations
|
||
from dataclasses import asdict, dataclass, field, replace
|
||
import csv
|
||
import json
|
||
import math
|
||
from pathlib import Path
|
||
import time
|
||
from .cultivation import CultivationSelector, growth_score
|
||
|
||
WIKI = "https://wiki.biligame.com/myrzx/魔物收益表"
|
||
|
||
|
||
def seconds(value):
|
||
value = float(value or 0)
|
||
return value / 1000 if value > 100_000_000_000 else value
|
||
|
||
|
||
def duration(value):
|
||
if value is None:
|
||
return "未知"
|
||
value = max(0, int(value))
|
||
return f"{value // 3600:02}:{value // 60 % 60:02}:{value % 60:02}"
|
||
|
||
|
||
class Catalog:
|
||
def __init__(self, path=None):
|
||
self.data = json.loads(Path(path or Path(__file__).with_name("data") / "catalog.json").read_text(encoding="utf-8"))
|
||
self.monsters = self.data["monster_info"]
|
||
self.overrides = {}
|
||
|
||
def monster(self, type_id):
|
||
return self.monsters.get(str(type_id), {}) | self.overrides.get(str(type_id), {})
|
||
|
||
def import_prices(self, path):
|
||
path = Path(path)
|
||
if path.suffix.lower() == ".xlsx":
|
||
import openpyxl
|
||
workbook = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
||
rows = iter(workbook.active.values)
|
||
headers = next(rows)
|
||
records = [dict(zip(headers, row)) for row in rows]
|
||
workbook.close()
|
||
else:
|
||
with path.open(encoding="utf-8-sig", newline="") as stream:
|
||
records = list(csv.DictReader(stream))
|
||
aliases = {"编号": "typeId", "魔物ID": "typeId", "派遣金币": "sell_money", "强化经验": "sell_exp", "孵化秒数": "time_total"}
|
||
changes = {}
|
||
for row in records:
|
||
row = {aliases.get(k, k): v for k, v in row.items()}
|
||
key = str(int(row["typeId"]))
|
||
if key not in self.monsters:
|
||
raise ValueError(f"未知魔物编号 {key}")
|
||
changes[key] = {k: float(row[k]) for k in ("sell_money", "sell_exp", "time_total") if row.get(k) not in (None, "")}
|
||
self.overrides.update(changes)
|
||
return len(changes)
|
||
|
||
def total_time(self, type_id):
|
||
row = self.monster(type_id)
|
||
return row.get("time_total", row.get("time_1", 0) + row.get("time_2", 0))
|
||
|
||
def quality(self, row):
|
||
if row.get("process") == 2 and int(row.get("mode") or 0) < 2:
|
||
return [None] * 4
|
||
table = self.monster(row.get("typeId"))
|
||
result = []
|
||
for stat in ("atk", "def", "hp", "dex"):
|
||
value = row.get("g" + stat.capitalize())
|
||
low, high = table.get(stat + "_grow_min"), table.get(stat + "_grow_max")
|
||
if value is None or low is None or high is None or high <= low:
|
||
result.append(None)
|
||
continue
|
||
value = float(f"{float(value):.3f}")
|
||
if not math.isfinite(value) or value < low - 0.001:
|
||
result.append(None)
|
||
continue
|
||
scale = (value - low) / (high - low)
|
||
result.append(min(4, max(1, math.floor(round(scale * 4, 10)) + 1)))
|
||
return result
|
||
|
||
def quality_text(self, row):
|
||
if row.get("process") == 2 and int(row.get("mode") or 0) < 2:
|
||
return "待成熟后生成"
|
||
values = self.quality(row)
|
||
if all(q is None for q in values):
|
||
return "资质待同步"
|
||
return "/".join("?" if q is None else "CBAS"[q - 1] for q in values)
|
||
|
||
def feed_exp(self, mon):
|
||
row = self.monster(mon.get("typeId"))
|
||
return int(row.get("sell_exp", 0)) + int(float(mon.get("exp", 0)) * self.data["game_setting"].get("monExpScale", 0.2))
|
||
|
||
def monster_label(self, mon):
|
||
species = self.monster(mon.get("typeId")).get("name", "未知魔物")
|
||
nickname = mon.get("nicName")
|
||
return f"#{mon['id']} {species}" + (f"({nickname})" if nickname and nickname != species else "")
|
||
|
||
def feed_remaining(self, mon, stop_level):
|
||
table = self.data.get("monster_level", {})
|
||
limit = table.get(str(stop_level))
|
||
current = table.get(str(mon.get("level", 1)))
|
||
if limit is None or current is None:
|
||
return None
|
||
return max(0, int(limit) - max(int(mon.get("exp") or 0), int(current)))
|
||
|
||
def max_level(self, mon):
|
||
info = self.data.get("potential_info", {})
|
||
potential = mon.get("potentialLevel")
|
||
if potential is None or not 1 <= int(potential) <= int(info.get("maxPotentialLevel", 0)):
|
||
return None
|
||
increment = int(info.get("potentialLevelMaxAdd", 0))
|
||
return int(potential) * increment if increment > 0 else None
|
||
|
||
def markets_for(self, type_id):
|
||
return [key for key, market in self.data.get("markets", {}).items()
|
||
if str(type_id) in {str(t) for pool in (market.get("eggs") or {}).values() for t in pool}]
|
||
|
||
def reference_stats(self, mon):
|
||
if mon.get("process") == 2 and any(q is None for q in self.quality(mon)):
|
||
return ["?"] * 4
|
||
row = self.monster(mon.get("typeId"))
|
||
level = int(mon.get("level") or 1) + min(4, int(mon.get("tpLevel") or 0)) - 1
|
||
bonus = min(200, max(0, int(mon.get("feel") or 0))) / 2000
|
||
bonus += float(self.data["game_setting"].get("upStarAdd", 0)) * int(mon.get("upStar") or 0)
|
||
result = []
|
||
for stat in ("atk", "def", "hp", "dex"):
|
||
grow = mon.get("g" + stat.capitalize())
|
||
if row.get(stat) is None or grow is None:
|
||
result.append("?")
|
||
else:
|
||
base = float(row[stat]) + float(grow) * level + float(mon.get("p" + stat.capitalize()) or 0)
|
||
result.append(int(base * (1 + bonus)))
|
||
return result
|
||
|
||
def likes_text(self, type_id):
|
||
likes = self.monster(type_id).get("like") or {}
|
||
names = self.data.get("item_names", {})
|
||
return "、".join(f"{names.get(str(key), str(key))}(+{value})" for key, value in sorted(likes.items(), key=lambda pair: pair[1], reverse=True) if value > 0) or "无已知偏好"
|
||
|
||
def master_experience(self, master):
|
||
level = int(master.get("level") or 1)
|
||
table = self.data.get("farm_level", {})
|
||
current, following = table.get(str(level)), table.get(str(level + 1))
|
||
if following is None:
|
||
return f"{master.get('exp', '?')} / 已满级"
|
||
return f"{master.get('exp', 0)} / {following}"
|
||
|
||
def max_feel(self, mon):
|
||
table = self.data.get("entangle_info", {}).get("haoganMax", {})
|
||
return int(table.get(str(int(mon.get("entangleLevel") or 0)), 100))
|
||
|
||
def item(self, type_id):
|
||
return self.data.get("item_info", {}).get(str(type_id), {})
|
||
|
||
def item_name(self, type_id):
|
||
return self.monster(type_id).get("name") or self.item(type_id).get("name") or self.data.get("item_names", {}).get(str(type_id), str(type_id))
|
||
|
||
def item_type(self, type_id):
|
||
return 6 if str(type_id) in self.monsters else int(self.item(type_id).get("itemType") or 4)
|
||
|
||
|
||
@dataclass
|
||
class Snapshot:
|
||
raw: dict
|
||
received_at: float = field(default_factory=time.time)
|
||
server_offset: float = 0
|
||
|
||
def __post_init__(self):
|
||
if not isinstance(self.raw.get("master"), dict):
|
||
raise ValueError("角色快照缺少 master")
|
||
for name in ("stacks", "monsters", "items", "rooms", "teams"):
|
||
if not isinstance(self.raw.get(name), list):
|
||
raise ValueError(f"角色快照缺少 {name} 数组")
|
||
self.raw = dict(self.raw)
|
||
for name in ("history", "activityHistory"):
|
||
if self.raw.get(name) is None:
|
||
self.raw[name] = {}
|
||
for name in ("currentTasks", "exploreTeams"):
|
||
if self.raw.get(name) is None:
|
||
self.raw[name] = []
|
||
|
||
@property
|
||
def now(self):
|
||
return time.time() + self.server_offset
|
||
|
||
@property
|
||
def monsters(self):
|
||
return {int(m["id"]): m for m in self.raw["monsters"]}
|
||
|
||
@property
|
||
def team_ids(self):
|
||
return {int(mid) for t in self.raw["teams"] for mid in (t.get("monsters") or []) if mid}
|
||
|
||
def city_unlocked(self, city):
|
||
value = self.raw.get("history", {}).get("unlockCity")
|
||
if isinstance(value, dict):
|
||
return bool(value.get(str(city), value.get(city, False)))
|
||
if isinstance(value, list):
|
||
if value and all(v is None or isinstance(v, bool) for v in value):
|
||
return str(city).isdigit() and int(city) < len(value) and value[int(city)] is True
|
||
return str(city) in {str(v) for v in value if isinstance(v, (str, int)) and not isinstance(v, bool)}
|
||
return False
|
||
|
||
def eggs(self, catalog):
|
||
return [e for e in self.raw["items"] if str(e.get("typeId")) in catalog.monsters and int(e.get("num", 0)) > 0]
|
||
|
||
def remaining(self, mon, catalog):
|
||
total = catalog.total_time(mon.get("typeId"))
|
||
start = seconds(mon.get("timeStart"))
|
||
return max(0, start + total - self.now) if total and start > 0 else None
|
||
|
||
def expected_growth_mode(self, mon, catalog):
|
||
mode = int(mon.get("mode") or 0)
|
||
start = seconds(mon.get("timeStart"))
|
||
row = catalog.monster(mon.get("typeId"))
|
||
total = catalog.total_time(mon.get("typeId"))
|
||
if mon.get("process") != 2 or start <= 0 or not total:
|
||
return mode
|
||
elapsed = self.now - start
|
||
stage = 0 if elapsed < float(row.get("time_1") or 0) else 1 if elapsed < total else 2
|
||
return max(mode, stage)
|
||
|
||
def growth_pending(self, catalog):
|
||
pending = []
|
||
for mon in self.raw["monsters"]:
|
||
if mon.get("process") != 2:
|
||
continue
|
||
mode = int(mon.get("mode") or 0)
|
||
expected = self.expected_growth_mode(mon, catalog)
|
||
if expected > mode or mode == 2 and any(q is None for q in catalog.quality(mon)):
|
||
pending.append((int(mon["id"]), mode, expected))
|
||
return pending
|
||
|
||
def phase_text(self, mon, catalog):
|
||
mode = int(mon.get("mode") or 0)
|
||
expected = self.expected_growth_mode(mon, catalog)
|
||
if expected > mode:
|
||
return "成熟待同步" if expected == 2 else "孵化结束,待同步成长"
|
||
if mode == 2 and any(q is None for q in catalog.quality(mon)):
|
||
return "资质待同步"
|
||
return {0: "孵化中", 1: "幼体成长", 2: "已成熟"}.get(mode, "未知阶段")
|
||
|
||
def room_available(self, catalog, preferred=0):
|
||
for room in self.raw["rooms"]:
|
||
if preferred and int(room["id"]) != preferred:
|
||
continue
|
||
table = catalog.data["room_info"].get(str(room.get("typeId")), {})
|
||
used = sum(m.get("process") == 3 and int(m.get("roomId") or 0) == int(room["id"]) for m in self.raw["monsters"])
|
||
if used < int(table.get("maxNum") or 0):
|
||
return int(room["id"])
|
||
return None
|
||
|
||
|
||
@dataclass
|
||
class EggRule:
|
||
enabled: bool = False
|
||
priority: int = 100
|
||
action: str = "sell"
|
||
refill_below: int = 1
|
||
refill_target: int = 10
|
||
market_id: str = ""
|
||
|
||
def __post_init__(self):
|
||
if self.action not in ("sell", "feed", "keep") or not 1 <= self.priority <= 999:
|
||
raise ValueError("魔物蛋规则的优先级或孵化后去向无效")
|
||
if not 0 <= self.refill_below <= 1000 or not max(1, self.refill_below) <= self.refill_target <= 1000:
|
||
raise ValueError("补货目标不能低于补货下限,0下限表示不自动补货")
|
||
|
||
|
||
@dataclass
|
||
class Policy:
|
||
enabled: bool = True
|
||
strategy: str = "wiki"
|
||
protect_star: int = 3
|
||
protect_quality: int = 3
|
||
reserved_types: list[int] = field(default_factory=list)
|
||
reserved_eggs: dict[str, int] = field(default_factory=dict)
|
||
feed_target: int = 0 # Legacy single-target policies; the GUI migrates to feed_targets.
|
||
target_level: int = 70 # Legacy file compatibility; automatic feeding uses the current cap.
|
||
room_id: int = 0
|
||
coins_per_exp: float = 5.0
|
||
fill: bool = True
|
||
egg_order: str = "shortest"
|
||
min_gold_per_hour: float = 0
|
||
min_exp_per_hour: float = 0
|
||
collect: bool = True
|
||
dispatch: bool = True
|
||
feed: bool = True
|
||
hatch_max_star: int = 5
|
||
buy: bool = False
|
||
market_id: str = "sc_city1"
|
||
egg_stock: int = 12
|
||
buy_batch: int = 5
|
||
buy_ten: bool = True
|
||
keep_money: int = 1000
|
||
daily_buy_money: int = 5000
|
||
manual_eggs: bool = False
|
||
egg_rules: dict[str, dict] = field(default_factory=dict)
|
||
feed_targets: dict[str, int] = field(default_factory=dict)
|
||
gift_enabled: bool = False
|
||
gift_targets: dict[str, int] = field(default_factory=dict)
|
||
gift_items: dict[str, dict] = field(default_factory=dict)
|
||
gift_liked_only: bool = True
|
||
gift_auto_representative: bool = False
|
||
keep_better_quality: bool = False
|
||
|
||
def __post_init__(self):
|
||
self.egg_rules = {str(int(key)): asdict(EggRule(**rule)) for key, rule in self.egg_rules.items()}
|
||
self.feed_targets = {str(int(key)): int(priority) for key, priority in self.feed_targets.items() if int(key) > 0 and 1 <= int(priority) <= 999}
|
||
self.gift_targets = {str(int(key)): int(priority) for key, priority in self.gift_targets.items() if int(key) > 0 and 1 <= int(priority) <= 999}
|
||
self.gift_items = {str(int(key)): {"enabled": bool(rule.get("enabled")), "reserve": max(0, int(rule.get("reserve", 0)))}
|
||
for key, rule in self.gift_items.items()}
|
||
|
||
|
||
@dataclass
|
||
class Action:
|
||
kind: str
|
||
description: str
|
||
path: str
|
||
payload: dict
|
||
|
||
|
||
class Planner:
|
||
def __init__(self, catalog, cultivation=None):
|
||
self.catalog = catalog
|
||
self.cultivation = cultivation or CultivationSelector(catalog)
|
||
self.managed = set()
|
||
self.notes = []
|
||
self.restocking = set()
|
||
self.statuses = {}
|
||
|
||
def protected(self, mon, snapshot, policy):
|
||
return bool(self.protection_reason(mon, snapshot, policy))
|
||
|
||
def protection_reason(self, mon, snapshot, policy):
|
||
row = self.catalog.monster(mon.get("typeId"))
|
||
qualities = self.catalog.quality(mon)
|
||
for condition, reason in ((not row, "魔物资料未知"), (int(mon["id"]) in snapshot.team_ids, "在队魔物"),
|
||
(mon.get("lock"), "已锁定"), (mon.get("sysLock"), "系统锁定"), (mon.get("entangle"), "羁绊魔物"),
|
||
(mon.get("inExploreTeam"), "正在探索"), (mon.get("inBuild"), "正在建筑中"),
|
||
(any(mon.get(f"equip{i}", 0) for i in range(1, 6)), "携带装备"),
|
||
(int(mon["id"]) == policy.feed_target or str(mon["id"]) in policy.feed_targets, "已选为喂养目标"),
|
||
(str(mon.get("typeId")) in {str(t) for t in policy.reserved_types}, "保留种类或委托保留"),
|
||
(row.get("star", 0) >= policy.protect_star, f"{row.get('star', '?')}星达到保留星级{policy.protect_star}"),
|
||
(any(q is None for q in qualities), "资质尚未确定 / 未同步")):
|
||
if condition:
|
||
return reason
|
||
quality = math.ceil(sum(qualities) / 4)
|
||
if policy.keep_better_quality or policy.gift_auto_representative:
|
||
representative = self.cultivation.select(snapshot).get(str(mon.get("typeId")))
|
||
if representative and int(representative["id"]) == int(mon["id"]):
|
||
return "同种魔物的唯一培养代表(等级、好感、资质优先)"
|
||
if policy.keep_better_quality:
|
||
if representative is None:
|
||
return "牧场尚无同种魔物,保留首次获得的魔物"
|
||
baseline, candidate = growth_score(self.catalog, representative), growth_score(self.catalog, mon)
|
||
if baseline is None:
|
||
return "同种培养代表的资质尚未同步,暂时保留"
|
||
if candidate is not None and candidate > baseline + 1e-8:
|
||
return f"综合成长资质高于同种培养代表 #{representative['id']}({candidate:.1%} > {baseline:.1%})"
|
||
if policy.protect_quality == 6:
|
||
return "攻/防/生命/敏捷四项资质全S(4S)" if all(q == 4 for q in qualities) else ""
|
||
if quality >= policy.protect_quality:
|
||
return f"综合资质{'CBAS'[quality - 1]}达到保留资质{'CBAS'[policy.protect_quality - 1]}"
|
||
return ""
|
||
|
||
def disposition(self, mon, snapshot, policy):
|
||
if self.protected(mon, snapshot, policy):
|
||
return "keep"
|
||
if policy.manual_eggs:
|
||
rule = policy.egg_rules.get(str(mon["typeId"]), {})
|
||
return rule.get("action", "keep") if rule.get("enabled") else "keep"
|
||
if policy.strategy == "keep":
|
||
return "keep"
|
||
if policy.strategy in ("gold", "experience"):
|
||
return "sell" if policy.strategy == "gold" else "feed"
|
||
money = self.catalog.monster(mon["typeId"]).get("sell_money", 0)
|
||
exp = self.catalog.feed_exp(mon)
|
||
return "feed" if exp > 0 and money / exp < policy.coins_per_exp else "sell"
|
||
|
||
def feeding_target(self, snapshot, policy):
|
||
ids = [int(key) for key, _ in sorted(policy.feed_targets.items(), key=lambda pair: pair[1])] if policy.feed_targets else [policy.feed_target]
|
||
reason = "未选择牧场中的喂养目标"
|
||
for mid in ids:
|
||
target = snapshot.monsters.get(mid)
|
||
if not target or target.get("process") != 3:
|
||
continue
|
||
cap = self.catalog.max_level(target)
|
||
if cap is None:
|
||
reason = "目标突破上限未知,暂停喂养"
|
||
continue
|
||
limit = cap
|
||
level = int(target.get("level", 1))
|
||
reason = f"目标 {self.catalog.monster_label(target)} Lv.{level};当前突破上限 {cap}"
|
||
if level < limit:
|
||
if self.catalog.feed_remaining(target, limit) == 0:
|
||
reason = f"目标 {self.catalog.monster_label(target)} 经验已达到当前突破上限,等待服务器同步"
|
||
continue
|
||
return target, reason
|
||
return None, reason
|
||
|
||
def feed_status(self, snapshot, policy):
|
||
target, reason = self.feeding_target(snapshot, policy)
|
||
return target is not None, reason
|
||
|
||
def available_eggs(self, snapshot, policy):
|
||
reserves = dict(policy.reserved_eggs)
|
||
result = []
|
||
for egg in snapshot.eggs(self.catalog):
|
||
key = str(egg["typeId"])
|
||
if policy.manual_eggs and not policy.egg_rules.get(key, {}).get("enabled"):
|
||
continue
|
||
row = self.catalog.monster(egg["typeId"])
|
||
hours = self.catalog.total_time(egg["typeId"]) / 3600
|
||
if not hours or egg.get("lock") or egg.get("feedLock"):
|
||
continue
|
||
if not policy.manual_eggs and (int(row.get("star", 99)) > policy.hatch_max_star or
|
||
row.get("sell_money", 0) / hours < policy.min_gold_per_hour and row.get("sell_exp", 0) / hours < policy.min_exp_per_hour):
|
||
continue
|
||
held = min(int(egg["num"]), max(0, int(reserves.get(key, 0))))
|
||
reserves[key] = max(0, int(reserves.get(key, 0)) - held)
|
||
count = int(egg["num"]) - held
|
||
if count:
|
||
result.append((egg, count))
|
||
return result
|
||
|
||
def manual_purchase(self, snapshot, policy, daily_left):
|
||
stocks = {}
|
||
for egg, count in self.available_eggs(snapshot, policy):
|
||
key = str(egg["typeId"])
|
||
stocks[key] = stocks.get(key, 0) + count
|
||
rules = [(key, rule) for key, rule in policy.egg_rules.items() if rule["enabled"] and rule["refill_below"] > 0]
|
||
self.restocking.intersection_update(key for key, _ in rules)
|
||
for key, rule in sorted(rules, key=lambda pair: pair[1]["priority"]):
|
||
stock = stocks.get(key, 0)
|
||
if stock >= rule["refill_target"]:
|
||
self.restocking.discard(key)
|
||
if stock < rule["refill_below"]:
|
||
self.restocking.add(key)
|
||
if key not in self.restocking:
|
||
continue
|
||
market_id = rule["market_id"] or policy.market_id
|
||
name = self.catalog.monster(key).get("name", key)
|
||
if market_id not in self.catalog.markets_for(key):
|
||
self.notes.append(f"{name} 补货暂停:所选市场蛋池不包含它")
|
||
continue
|
||
buying = replace(policy, manual_eggs=False, market_id=market_id, egg_stock=rule["refill_target"])
|
||
actions = self.purchase(snapshot, buying, daily_left, stock=stock)
|
||
if actions:
|
||
actions[0].description = f"为 {name} 补货(剩{stock},目标{rule['refill_target']}):" + actions[0].description
|
||
return actions
|
||
return []
|
||
|
||
def purchase(self, snapshot, policy, daily_left, *, stock=None):
|
||
if not policy.buy:
|
||
return []
|
||
if policy.manual_eggs:
|
||
return self.manual_purchase(snapshot, policy, daily_left)
|
||
market = self.catalog.data.get("markets", {}).get(policy.market_id)
|
||
if not market or not policy.market_id.startswith("sc_city") or int(market.get("ke", -1)) != 0 or int(market.get("money", 0)) <= 0:
|
||
self.notes.append("所选市场不是已确认的金币市场,暂停购蛋")
|
||
return []
|
||
if not snapshot.city_unlocked(market["city"]):
|
||
self.notes.append("所选市场城市尚未解锁,暂停购蛋")
|
||
return []
|
||
if stock is None:
|
||
stock = sum(count for _, count in self.available_eggs(snapshot, policy))
|
||
missing = max(0, policy.egg_stock - stock)
|
||
if not missing:
|
||
self.notes.append(f"可孵蛋库存 {stock},已达到补货目标 {policy.egg_stock}")
|
||
return []
|
||
price = int(market["money"])
|
||
money = int(snapshot.raw["master"].get("money", 0))
|
||
left = min(max(0, policy.daily_buy_money), daily_left) if daily_left is not None else max(0, policy.daily_buy_money)
|
||
affordable = min(int(market.get("max") or 1), max(0, money - policy.keep_money) // price, left // price)
|
||
if policy.buy_ten and policy.egg_stock >= 10 and missing >= 10 and affordable >= 10:
|
||
count = min(missing, max(10, policy.buy_batch), affordable) // 10 * 10
|
||
elif policy.buy_ten and policy.egg_stock >= 10 and stock > 0:
|
||
self.notes.append(f"十连等待:可孵蛋库存 {stock},补货缺口 {missing};十连需 {price * 10} 可用金币,保留 {policy.keep_money},额度剩余 {left}")
|
||
return []
|
||
else:
|
||
count = min(missing, max(0, policy.buy_batch), affordable)
|
||
if count <= 0:
|
||
self.notes.append(f"购蛋暂停:余额需保留 {policy.keep_money} 金币,今日额度剩余 {left}")
|
||
return []
|
||
return [Action("buy", f"{market['name']}市场{'十连抽蛋' if count == 10 else '购蛋 / 抽蛋'} ×{count},花费 {price * count} 金币(赠蛋以实际返回为准)", "gachaService/gachaGetEggs",
|
||
{"id": policy.market_id, "num": count, "voucherNum": 0, "traceInfo": {"money": money, "ke": int(snapshot.raw["master"].get("ke", 0))}})]
|
||
|
||
def plan(self, snapshot, policy, daily_left=None):
|
||
self.notes = []
|
||
self.statuses = {}
|
||
self.managed.update(int(s["monsterId"]) for s in snapshot.raw["stacks"] if int(s.get("monsterId") or 0) > 0)
|
||
if not policy.enabled:
|
||
self.notes.append("牧场策略未启用")
|
||
return []
|
||
if policy.manual_eggs and not any(rule["enabled"] for rule in policy.egg_rules.values()):
|
||
self.notes.append("请到“背包魔物蛋”勾选要孵化的蛋,并设置优先级和孵出后的去向")
|
||
return []
|
||
actions = []
|
||
free_rooms = {}
|
||
for room in snapshot.raw["rooms"]:
|
||
rid = int(room["id"])
|
||
if policy.room_id and rid != policy.room_id:
|
||
continue
|
||
capacity = int(self.catalog.data["room_info"].get(str(room.get("typeId")), {}).get("maxNum") or 0)
|
||
used = sum(m.get("process") == 3 and int(m.get("roomId") or 0) == rid for m in snapshot.raw["monsters"])
|
||
free_rooms[rid] = max(0, capacity - used)
|
||
for mon in snapshot.raw["monsters"]:
|
||
mid = int(mon["id"])
|
||
if mid not in self.managed or mon.get("process") not in (2, 3):
|
||
continue
|
||
if policy.manual_eggs and not policy.egg_rules.get(str(mon["typeId"]), {}).get("enabled"):
|
||
self.statuses[mid] = "该魔物未启用孵蛋规则"
|
||
continue
|
||
if mon.get("process") == 2 and int(mon.get("mode") or 0) != 2:
|
||
self.statuses[mid] = snapshot.phase_text(mon, self.catalog)
|
||
if snapshot.expected_growth_mode(mon, self.catalog) > int(mon.get("mode") or 0):
|
||
self.notes.append(self.statuses[mid] + ",资质尚未生成")
|
||
continue
|
||
name = self.catalog.monster(mon["typeId"]).get("name", str(mid))
|
||
if mon.get("process") == 2 and any(q is None for q in self.catalog.quality(mon)):
|
||
self.statuses[mid] = "资质未同步,等待成长结算;暂不派遣、喂养或收取"
|
||
self.notes.append(f"{name}:" + self.statuses[mid])
|
||
continue
|
||
disposition = self.disposition(mon, snapshot, policy)
|
||
reason = self.protection_reason(mon, snapshot, policy) or "手动规则选择保留"
|
||
if disposition == "sell" and not policy.dispatch or disposition == "feed" and not policy.feed:
|
||
reason = "自动派遣开关已关闭" if disposition == "sell" else "自动喂养开关已关闭"
|
||
disposition = "keep"
|
||
self.statuses[mid] = "保留:" + reason if disposition == "keep" else "待派遣" if disposition == "sell" else "待喂养"
|
||
if disposition == "sell":
|
||
# MonsterCenter also routes mature incubator monsters through
|
||
# NetMonster.sellMonsters, whose active parameter is plural.
|
||
actions.append(Action("sell", f"派遣 {name} #{mid}", "monsterService/monsterSell", {"monsterIds": [mid]}))
|
||
elif mon.get("process") == 2 and policy.collect:
|
||
room = next((rid for rid, free in free_rooms.items() if free > 0), None)
|
||
if room is not None:
|
||
free_rooms[room] -= 1
|
||
actions.append(Action("collect", f"收取 {name} #{mid} → 牧场 {room}", "stackService/stackTransferMonster", {"datas": [{"monsterId": [mid], "roomId": room}]}))
|
||
else:
|
||
self.notes.append(f"{name} 等待收取:牧场没有空位")
|
||
elif disposition == "feed" and mon.get("process") == 3:
|
||
target, reason = self.feeding_target(snapshot, policy)
|
||
if target:
|
||
actions.append(Action("feed", f"{name} #{mid} → 喂养 #{target['id']}", "monsterService/monsterIntensify", {"targetId": int(target["id"]), "foods": [mid]}))
|
||
else:
|
||
self.notes.append("暂停喂养:" + reason)
|
||
elif disposition == "keep":
|
||
self.notes.append(f"{name} 已保留:{reason}")
|
||
if actions:
|
||
return self.batch_actions(actions, snapshot, policy)
|
||
return self.hatch_actions(snapshot, policy) or self.purchase(snapshot, policy, daily_left)
|
||
|
||
def hatch_actions(self, snapshot, policy):
|
||
if not policy.enabled or not policy.fill:
|
||
return []
|
||
actions = []
|
||
vip_info = snapshot.raw.get("activityHistory", {}).get("vipInfo") or {}
|
||
vip = seconds(vip_info.get("vipTime")) > snapshot.now
|
||
empty = [s for s in snapshot.raw["stacks"] if policy.fill and int(s.get("monsterId") or 0) <= 0 and (int(s.get("position", -1)) != 3 or vip)]
|
||
eggs = self.available_eggs(snapshot, policy)
|
||
def score(entry):
|
||
egg, _ = entry
|
||
row = self.catalog.monster(egg["typeId"])
|
||
total = max(1, self.catalog.total_time(egg["typeId"]))
|
||
if policy.manual_eggs:
|
||
return (-policy.egg_rules[str(egg["typeId"])]["priority"], -total)
|
||
return {"shortest": -total, "gold": row.get("sell_money", 0) / total,
|
||
"experience": row.get("sell_exp", 0) / total, "longest": total}[policy.egg_order]
|
||
eggs.sort(key=score, reverse=True)
|
||
for egg, available in eggs:
|
||
row = self.catalog.monster(egg["typeId"])
|
||
for slot in empty[:available]:
|
||
actions.append(Action("hatch", f"装填 {row.get('name')} → 坑位 {int(slot['position']) + 1}", "stackService/stackAddMonster", {"eggs": [{"itemId": int(egg["id"]), "stackId": int(slot["id"])}]}))
|
||
empty = empty[min(available, len(empty)):]
|
||
if not empty:
|
||
break
|
||
if not actions and empty:
|
||
self.notes.append("有空坑,当前没有符合已勾选规则和保留数量的蛋" if policy.manual_eggs else "有空坑,当前没有符合星级、收益和保留数量设置的蛋")
|
||
if not actions and not self.notes:
|
||
self.notes.append("等待孵化 / 成长,成熟后按保护条件处理")
|
||
return actions
|
||
|
||
def batch_actions(self, actions, snapshot, policy):
|
||
monsters = snapshot.monsters
|
||
collects = [a for a in actions if a.kind == "collect"]
|
||
if collects:
|
||
rooms = {}
|
||
for action in collects:
|
||
for data in action.payload["datas"]:
|
||
rooms.setdefault(data["roomId"], []).extend(data["monsterId"])
|
||
ids = [mid for mids in rooms.values() for mid in mids]
|
||
description = "批量收取 " + "、".join(self.catalog.monster_label(monsters[mid]) for mid in ids)
|
||
merged = Action("collect", description, "stackService/stackTransferMonster", {"datas": [{"monsterId": mids, "roomId": room} for room, mids in rooms.items()]})
|
||
return [merged] + [a for a in actions if a.kind != "collect"]
|
||
feeds = [a for a in actions if a.kind == "feed"]
|
||
if not feeds:
|
||
return actions
|
||
target_id = feeds[0].payload["targetId"]
|
||
target = monsters[target_id]
|
||
stop_level = self.catalog.max_level(target)
|
||
need = self.catalog.feed_remaining(target, stop_level)
|
||
ids, experience = [], 0
|
||
for action in feeds:
|
||
if action.payload["targetId"] != target_id:
|
||
continue
|
||
for mid in action.payload["foods"]:
|
||
if mid in ids:
|
||
continue
|
||
ids.append(mid)
|
||
experience += self.catalog.feed_exp(monsters[mid])
|
||
if need is None or experience >= need:
|
||
break
|
||
if need is None or experience >= need:
|
||
break
|
||
label = self.catalog.monster_label(target)
|
||
foods = "、".join(self.catalog.monster_label(monsters[mid]) for mid in ids)
|
||
merged = Action("feed", f"喂养 {label} ← {len(ids)} 只素材:{foods}(经验 {experience})", "monsterService/monsterIntensify", {"targetId": target_id, "foods": ids})
|
||
return [merged] + [a for a in actions if a.kind != "feed"]
|