Files
myrzx_bot/ranch_assistant/model.py
T

878 lines
46 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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, quality_rank, quality_summary
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 = ""
keep_count: int = 1
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下限表示不自动补货")
value = self.keep_count
if isinstance(value, bool) or not isinstance(value, (int, str)):
raise ValueError("牧场保留数量须为0至1000的整数")
try:
count = int(value)
except (TypeError, ValueError) as error:
raise ValueError("牧场保留数量须为0至1000的整数") from error
if isinstance(value, str) and value != str(count):
raise ValueError("牧场保留数量须为0至1000的整数")
self.keep_count = count
if not 0 <= count <= 1000:
raise ValueError("牧场保留数量须为0至1000")
@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
allow_single_draw: bool = False
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
breakthrough_targets: dict[str, int] = field(default_factory=dict)
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.breakthrough_targets = self._validated_targets(self.breakthrough_targets, "自动突破")
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()}
@staticmethod
def _validated_targets(targets, label):
if not isinstance(targets, dict):
raise ValueError(f"{label}目标须为“魔物ID: 优先级”字典")
result = {}
for key, priority in targets.items():
if isinstance(key, bool) or isinstance(priority, bool):
raise ValueError(f"{label}目标ID须为正整数,优先级须为1至999")
try:
monster_id, rank = int(key), int(priority)
except (TypeError, ValueError) as error:
raise ValueError(f"{label}目标ID须为正整数,优先级须为1至999") from error
if isinstance(key, float) and not key.is_integer() or isinstance(priority, float) and not priority.is_integer():
raise ValueError(f"{label}目标ID须为正整数,优先级须为1至999")
if isinstance(key, str) and key.strip() != str(monster_id) or isinstance(priority, str) and priority.strip() != str(rank):
raise ValueError(f"{label}目标ID须为正整数,优先级须为1至999")
if monster_id <= 0 or not 1 <= rank <= 999:
raise ValueError(f"{label}目标ID须为正整数,优先级须为1至999")
if str(monster_id) in result:
raise ValueError(f"{label}目标ID重复:{monster_id}")
result[str(monster_id)] = rank
return result
@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 = {}
self.retained = set()
self.retention_reasons = {}
self.representatives = {}
self.preparing_retention = False
self.retention_signature = None
self.tp_feed_targets = set()
self.food_protection = {}
def protected(self, mon, snapshot, policy):
self.ensure_retention(snapshot, policy)
return bool(self.protection_reason(mon, snapshot, policy))
def ensure_retention(self, snapshot, policy):
if not policy.manual_eggs:
return
signature = (repr(snapshot.raw.get("monsters")), repr(snapshot.raw.get("teams")),
repr((policy.manual_eggs, policy.egg_rules, policy.keep_better_quality,
policy.gift_auto_representative, policy.protect_star, policy.protect_quality,
policy.feed_target, policy.feed_targets, policy.breakthrough_targets, policy.reserved_types)))
if signature != self.retention_signature:
self.prepare_retention(snapshot, policy)
self.retention_signature = signature
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["id"]) in policy.breakthrough_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
if int(mon["id"]) in self.retained:
return self.retention_reasons[int(mon["id"])]
quality = math.ceil(sum(qualities) / 4)
if (policy.keep_better_quality or policy.gift_auto_representative) and not policy.manual_eggs:
representative = (self.representatives if policy.manual_eggs else self.cultivation.select(snapshot)).get(str(mon.get("typeId")))
if policy.gift_auto_representative and representative and int(representative["id"]) == int(mon["id"]):
return "同种魔物的唯一培养代表(等级、好感、资质优先)"
if policy.keep_better_quality and not self.preparing_retention:
if representative is None:
return "牧场尚无同种魔物,保留首次获得的魔物"
baseline, candidate = quality_rank(self.catalog, representative), quality_rank(self.catalog, mon)
if baseline is None:
return "同种培养代表的资质尚未同步,暂时保留"
if candidate is not None and candidate > baseline:
return (f"资质优于同种培养代表 #{representative['id']}"
f"({quality_summary(self.catalog, mon)} / S项{candidate[0]} > "
f"{quality_summary(self.catalog, representative)} / S项{baseline[0]})")
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 prepare_retention(self, snapshot, policy):
"""Allocate each species quota once for all ranches and this hatch batch."""
self.retained, self.retention_reasons, self.representatives = set(), {}, {}
self.retention_signature = None
if not policy.manual_eggs:
return
self.preparing_retention = True
try:
for mon in snapshot.raw["monsters"]:
if mon.get("process") == 3:
reason = self.protection_reason(mon, snapshot, policy)
if reason:
self.retained.add(int(mon["id"]))
self.retention_reasons[int(mon["id"])] = reason
finally:
self.preparing_retention = False
self.representatives = self.cultivation.select(snapshot)
groups = {}
for mon in snapshot.raw["monsters"]:
if mon.get("process") in (2, 3) and int(mon.get("mode") or 0) == 2:
groups.setdefault(str(mon.get("typeId")), []).append(mon)
for key, rule in policy.egg_rules.items():
if not rule.get("enabled"):
continue
members = groups.get(key, [])
representative = self.representatives.get(key)
if representative is None and members:
representative = min(members, key=lambda row: (quality_rank(self.catalog, row) is None,
tuple(-value for value in (quality_rank(self.catalog, row) or ())), int(row["id"])))
quota = int(rule.get("keep_count", 1))
occupied = sum(row.get("process") == 3 and int(row["id"]) in self.retained for row in members)
if quota > 0 and representative is not None and representative.get("process") == 3 and occupied < quota:
mid = int(representative["id"])
already_retained = mid in self.retained
self.retained.add(mid)
self.retention_reasons[mid] = f"同种稳定培养代表,牧场保留数量 1 / {quota}"
occupied += int(representative.get("process") == 3 and not already_retained)
ranch = [row for row in members if row.get("process") == 3 and int(row["id"]) not in self.retained]
ranch.sort(key=lambda row: (quality_rank(self.catalog, row) is None,
tuple(-value for value in (quality_rank(self.catalog, row) or ())), int(row["id"])))
used = occupied
quality_baseline = [quality_rank(self.catalog, row) for row in members
if row.get("process") == 3 and int(row["id"]) in self.retained]
quality_baseline = [value for value in quality_baseline if value is not None]
for row in ranch:
if used >= quota:
break
used += 1
self.retained.add(int(row["id"]))
self.retention_reasons[int(row["id"])] = f"同种牧场保留数量 {used} / {quota}"
rank = quality_rank(self.catalog, row)
if rank is not None:
quality_baseline.append(rank)
incubator = [row for row in members if row.get("process") == 2 and int(row["id"]) not in self.retained]
incubator.sort(key=lambda row: (quality_rank(self.catalog, row) is None,
tuple(-value for value in (quality_rank(self.catalog, row) or ())), int(row["id"])))
for row in incubator:
if used >= quota:
break
used += 1
self.retained.add(int(row["id"]))
self.retention_reasons[int(row["id"])] = f"同种牧场及培育室保留数量 {used} / {quota}"
rank = quality_rank(self.catalog, row)
if rank is not None:
quality_baseline.append(rank)
# Compare with the best retained ranch quality, not repeatedly
# with an inferior locked monster. Select at most one improvement
# per snapshot, including the newly collected batch as one group.
if policy.keep_better_quality and quality_baseline:
baseline = max(quality_baseline)
candidates = [(quality_rank(self.catalog, row), row) for row in members
if int(row["id"]) not in self.retained]
candidates = [(rank, row) for rank, row in candidates if rank is not None and rank > baseline]
if candidates:
rank, row = min(candidates, key=lambda pair: (-pair[0][0], -pair[0][1], -pair[0][2], -pair[0][3], int(pair[1]["id"])))
self.retained.add(int(row["id"]))
self.retention_reasons[int(row["id"])] = (
f"额外保留更优资质 {quality_summary(self.catalog, row)} / S项{rank[0]},"
f"牧场已保留最高资质 S项{baseline[0]}")
# If the only mature monster is still incubating, it becomes the
# representative upon collection rather than being disposed first.
if quota > 0 and not any(int(row["id"]) in self.retained for row in members) and members:
row = members[0]
self.retained.add(int(row["id"]))
self.retention_reasons[int(row["id"])] = f"同种本批培养代表,牧场保留数量 1 / {quota}"
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 tp_thresholds(self, target):
"""Cumulative TP thresholds, indexed by species star rating (AS3 GameMath.tpExp)."""
table = self.catalog.data.get("game_setting", {}).get("tpExp")
star = self.catalog.monster(target.get("typeId")).get("star")
if isinstance(table, dict):
table = table.get(str(star), table.get(star))
if isinstance(table, list) and table and not isinstance(table[0], (list, dict)) and star is not None:
table = table[int(star)] if int(star) < len(table) else None
if isinstance(table, dict):
table = [value for _, value in sorted(table.items(), key=lambda pair: int(pair[0]))]
if not isinstance(table, list) or len(table) < 5:
return None
try:
return [int(value) for value in table[:5]]
except (TypeError, ValueError):
return None
def tp_feeding_remaining(self, target):
# GameMath.maxTpLevel is hardcoded to 4; potentialLevel is unrelated.
if target.get("tpLevel") is None or target.get("tpExp") is None:
return None
level = max(0, int(target.get("tpLevel")))
if level >= 4:
return 0
thresholds = self.tp_thresholds(target)
if thresholds is None:
return None
return max(0, thresholds[4] - int(target.get("tpExp")))
def same_species_feeding_target(self, mon, snapshot, policy, exclude=()):
"""Prefer an unfinished same-species TP target; never consume a representative."""
if mon.get("process") != 3:
return None, "素材尚未收取到牧场"
excluded = {int(mid) for mid in exclude} | {int(mon["id"])}
candidates = [row for row in snapshot.raw["monsters"] if row.get("process") == 3
and str(row.get("typeId")) == str(mon.get("typeId"))
and int(row["id"]) != int(mon["id"])
and not self.food_protection.get(int(row["id"]))
and (quality_rank(self.catalog, mon) is None or quality_rank(self.catalog, row) is not None
and quality_rank(self.catalog, row) >= quality_rank(self.catalog, mon))
and (int(row["id"]) in self.managed or self.protected(row, snapshot, policy))]
candidates.sort(key=lambda row: (int(policy.feed_targets.get(str(row["id"]), 9999)),
int(policy.breakthrough_targets.get(str(row["id"]), 9999)), -int(row.get("level") or 1), int(row["id"])))
unknown = False
for target in candidates:
remaining = self.tp_feeding_remaining(target)
if remaining is None:
unknown = True
continue
# TP food works even at the ordinary experience cap. Do not use
# potentialLevel here: it controls the separate material breakthrough.
if remaining > 0:
self.tp_feed_targets.add(int(target["id"]))
return target, f"优先同种突破喂养 #{target['id']}(tpLevel {int(target.get('tpLevel') or 0)} / 4)"
cap = self.catalog.max_level(target)
if remaining == 0 and cap is not None and int(target.get("level") or 1) < cap and self.catalog.feed_remaining(target, cap) != 0:
self.tp_feed_targets.add(int(target["id"]))
return target, f"同种突破已满,继续普通经验喂养 #{target['id']}"
if unknown:
return None, "缺少game_setting.tpExp累计门槛,暂停同种突破喂养"
ordinary = [target for target in candidates if self.tp_feeding_remaining(target) == 0
and self.catalog.max_level(target) is not None and int(target.get("level") or 1) < self.catalog.max_level(target)
and self.catalog.feed_remaining(target, self.catalog.max_level(target)) != 0]
if ordinary:
target = ordinary[0]
self.tp_feed_targets.add(int(target["id"]))
return target, f"同种突破已满,继续普通经验喂养 #{target['id']}"
return None, "同种魔物均已完成突破,不继续消耗同种素材"
def is_same_species_tp_feed(self, target, food):
return self.tp_food_value(target, food) > 0 and (self.tp_feeding_remaining(target) or 0) > 0
def tp_food_value(self, target, food):
settings = self.catalog.data.get("game_setting", {})
target_star = int(self.catalog.monster(target.get("typeId")).get("star") or 0)
return int(str(food.get("typeId")) == str(target.get("typeId"))
or str(food.get("typeId")) == str(settings.get("specialFood"))
or target_star < 5 and str(food.get("typeId")) == str(settings.get("specialFood14")))
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 not policy.allow_single_draw:
count = min(missing, max(10, policy.buy_batch), affordable) // 10 * 10
if count < 10:
self.notes.append(f"十连等待:单抽已关闭,补货缺口 {missing};十连需 {price * 10} 可用金币,保留 {policy.keep_money},额度剩余 {left};补货目标至少设为10")
return []
elif policy.buy_ten and missing >= 10 and affordable >= 10:
count = min(missing, max(10, policy.buy_batch), affordable) // 10 * 10
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.tp_feed_targets = set()
self.food_protection = {}
self.managed.update(int(s["monsterId"]) for s in snapshot.raw["stacks"] if int(s.get("monsterId") or 0) > 0)
self.ensure_retention(snapshot, policy)
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 = (None, "")
if not policy.feed_target and not policy.feed_targets:
self.food_protection[mid] = self.protection_reason(mon, snapshot, policy)
target, reason = self.same_species_feeding_target(mon, snapshot, policy, exclude=self.retained)
if target is None:
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)
# Feeding can be unavailable while another mature monster still needs
# collection. Returning the hatch now would hide that pending batch.
if policy.collect and any(a.kind == "collect" for a in actions):
return []
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"]
merged_collect = None
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()]})
merged_collect = merged
actions = [a for a in actions if a.kind != "collect"]
if merged_collect is not None:
# Refresh after collection before disposing of old ranch monsters.
return [merged_collect]
feeds = [a for a in actions if a.kind == "feed"]
if not feeds:
return ([merged_collect] if merged_collect else []) + actions
target_id = feeds[0].payload["targetId"]
target = monsters[target_id]
feeds = [action for action in feeds if action.payload["targetId"] == target_id
and all(mid != target_id and mid in self.managed and not self.protected(monsters[mid], snapshot, policy)
for mid in action.payload["foods"])]
if not feeds:
return ([merged_collect] if merged_collect else [])
stop_level = self.catalog.max_level(target)
need = self.catalog.feed_remaining(target, stop_level)
same_species = target_id in self.tp_feed_targets and all(self.is_same_species_tp_feed(target, monsters[mid])
for action in feeds if action.payload["targetId"] == target_id for mid in action.payload["foods"])
tp_need = self.tp_feeding_remaining(target) if same_species else 0
ids, experience, tp_experience = [], 0, 0
for action in feeds:
for mid in action.payload["foods"]:
if mid in ids or mid == target_id:
continue
ids.append(mid)
experience += self.catalog.feed_exp(monsters[mid])
tp_experience += self.tp_food_value(target, monsters[mid])
if same_species and tp_need is not None and tp_experience >= tp_need or not same_species and need is not None and experience >= need:
break
if same_species and tp_need is not None and tp_experience >= tp_need or not same_species and need is not None and experience >= need:
break
label = self.catalog.monster_label(target)
foods = "、".join(self.catalog.monster_label(monsters[mid]) for mid in ids)
if not ids:
return ([merged_collect] if merged_collect else []) + [a for a in actions if a not in feeds]
merged = Action("feed", f"喂养 {label} ← {len(ids)} 只素材:{foods}(经验 {experience})", "monsterService/monsterIntensify", {"targetId": target_id, "foods": ids})
return ([merged_collect] if merged_collect else []) + [merged] + [a for a in actions if a not in feeds]