Files
myrzx_bot/ranch_assistant/model.py
T

945 lines
49 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
from .team_availability import _exploring_ids
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.backups = {}
self.retention_owner = None
self.dispatch_extras = set()
self.preparing_retention = False
self.retention_signature = None
self.tp_feed_targets = set()
self.food_protection = {}
def protected(self, mon, snapshot, policy):
return bool(self.protection_reason(mon, snapshot, policy))
def ensure_retention(self, snapshot, policy):
if self.preparing_retention:
return
signature = (str(snapshot.raw["master"]["id"]),
repr(snapshot.raw.get("monsters")), repr(snapshot.raw.get("teams")),
repr(snapshot.raw.get("exploreTeams")),
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.gift_targets,
policy.breakthrough_targets, policy.reserved_types)))
if signature != self.retention_signature:
self.prepare_retention(snapshot, policy)
self.retention_signature = signature
@staticmethod
def species_rule(mon, policy):
rule = policy.egg_rules.get(str(mon.get("typeId")), {}) if policy.manual_eggs else {}
return rule if rule.get("enabled") else {}
def hard_protection_reason(self, mon, snapshot, policy):
"""Explicit reservations and incomplete data are independent of slot limits."""
row = self.catalog.monster(mon.get("typeId"))
qualities = self.catalog.quality(mon)
legacy_protection = not self.species_rule(mon, policy)
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") or int(mon["id"]) in _exploring_ids(snapshot), "正在探索"),
(mon.get("inBuild"), "正在建筑中"),
(any(mon.get(f"equip{i}", 0) for i in range(1, 6)), "携带装备"),
(legacy_protection and (int(mon["id"]) == policy.feed_target or str(mon["id"]) in policy.feed_targets), "已选为喂养目标"),
(legacy_protection and str(mon["id"]) in policy.gift_targets, "已选为赠礼目标"),
(legacy_protection and str(mon["id"]) in policy.breakthrough_targets, "已选为自动突破目标"),
(str(mon.get("typeId")) in {str(t) for t in policy.reserved_types}, "保留种类或委托保留"),
(legacy_protection and 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
return ""
def protection_reason(self, mon, snapshot, policy):
self.ensure_retention(snapshot, policy)
reason = self.hard_protection_reason(mon, snapshot, policy)
if reason:
return reason
if int(mon["id"]) in self.retained:
return self.retention_reasons[int(mon["id"])]
# Enabled species use fixed primary/backup slots. Automatic grade
# thresholds and legacy keep_count must not protect every duplicate.
if self.species_rule(mon, policy):
return ""
qualities = self.catalog.quality(mon)
quality = math.ceil(sum(qualities) / 4)
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):
"""One primary and one strictly better backup across ranches/incubators."""
owner = str(snapshot.raw["master"]["id"])
previous_backups = self.backups if self.retention_owner == owner else {}
self.retention_owner = owner
self.backups, self.dispatch_extras = {}, set()
self.retained, self.retention_reasons, self.representatives = set(), {}, {}
self.retention_signature = None
self.representatives = dict(self.cultivation.select(snapshot))
groups = {}
for mon in snapshot.raw["monsters"]:
if mon.get("process") == 3 or mon.get("process") == 2 and int(mon.get("mode") or 0) == 2:
groups.setdefault(str(mon.get("typeId")), []).append(mon)
for key, members in groups.items():
mandatory = bool(self.species_rule(members[0], policy))
if not mandatory and not (not policy.manual_eggs and
(policy.keep_better_quality or policy.gift_auto_representative)):
continue
primary = self.representatives.get(key)
if primary is None:
saved_id = getattr(self.cultivation, "choices", {}).get(key)
saved = snapshot.monsters.get(saved_id)
# A saved primary that is still in the roster can be temporarily
# unavailable. Only confirmed removal permits a replacement.
primary = saved if saved is not None and str(saved.get("typeId")) == key else min(
members, key=lambda row: int(row["id"]))
self.representatives[key] = primary
primary_id = int(primary["id"])
self.retained.add(primary_id)
self.retention_reasons[primary_id] = ("牧场尚无同种魔物,保留首次成熟的主培养魔物"
if primary.get("process") != 3 else "同种稳定主培养代表(等级、好感、资质优先)")
baseline = quality_rank(self.catalog, primary)
candidates = [(quality_rank(self.catalog, mon), mon) for mon in members
if int(mon["id"]) != primary_id]
if baseline is None:
for _, mon in candidates:
mid = int(mon["id"])
self.retained.add(mid)
self.retention_reasons[mid] = f"同种主培养代表 #{primary_id} 当前不可用或资质尚未同步,暂时保护"
continue
if mandatory or policy.keep_better_quality:
better = [(rank, mon) for rank, mon in candidates if rank is not None and rank > baseline]
if better:
previous_id = int(previous_backups.get(key, {}).get("id", 0))
rank, backup = min(better, key=lambda pair: (
tuple(-value for value in pair[0]), pair[1].get("process") != 3,
int(pair[1]["id"]) != previous_id, int(pair[1]["id"])))
mid = int(backup["id"])
self.backups[key] = backup
self.retained.add(mid)
self.retention_reasons[mid] = (f"唯一资质备用,优于同种培养代表 #{primary_id}:"
f"{quality_summary(self.catalog, backup)} / S项{rank[0]};不喂养、不赠礼")
for rank, mon in candidates:
mid = int(mon["id"])
if mid in self.retained:
continue
reason = self.hard_protection_reason(mon, snapshot, policy)
if reason:
self.retained.add(mid)
self.retention_reasons[mid] = "同种额外魔物受保护:" + reason
elif mandatory and (rank is not None and rank >= baseline
or mid == int(previous_backups.get(key, {}).get("id", 0))):
self.dispatch_extras.add(mid)
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"]), {})
if not rule.get("enabled"):
return "keep"
# Only recorded hatch ownership authorizes using an old monster as
# food. Enabled-species cleanup separately authorizes dispatch.
if (int(mon["id"]) in self.dispatch_extras or rule.get("action") != "feed"
or int(mon["id"]) not in self.managed):
return "sell"
return "feed"
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
blocked = self.primary_target_reason(target, snapshot)
if blocked:
reason = blocked
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 primary_target_reason(self, target, snapshot):
"""A backup can be protected as food without being a cultivation target."""
primary = self.cultivation.select(snapshot).get(str(target.get("typeId")))
if primary is None:
return "该种主培养魔物尚未收取到牧场,暂停喂养"
if int(primary["id"]) != int(target["id"]):
return f"目标 #{target['id']} 不是同种主培养代表 #{primary['id']},保留原勾选并暂停该目标"
if (target.get("process") != 3 or target.get("inExploreTeam") or int(target["id"]) in _exploring_ids(snapshot)
or target.get("inBuild") or target.get("sysLock")):
return f"同种主培养代表 #{target['id']} 当前不可用,暂停喂养"
return ""
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=()):
"""Feed only the primary; its caps never authorize a duplicate target."""
self.ensure_retention(snapshot, policy)
if mon.get("process") != 3:
return None, "素材尚未收取到牧场"
target = self.cultivation.select(snapshot).get(str(mon.get("typeId")))
if target is None:
return None, "同种主培养魔物尚未收取到牧场,暂停喂养"
blocked = self.primary_target_reason(target, snapshot)
if blocked:
return None, blocked
if int(mon["id"]) == int(target["id"]) or self.protected(mon, snapshot, policy):
return None, "主培养魔物、资质备用或受保护魔物不能作为喂养素材"
if policy.feed_targets or policy.feed_target:
selected = {int(key) for key in policy.feed_targets} if policy.feed_targets else {policy.feed_target}
if int(target["id"]) not in selected:
return None, f"同种主培养代表 #{target['id']} 未勾选为喂养目标,保留原勾选"
remaining = self.tp_feeding_remaining(target)
if remaining is None:
return None, "缺少game_setting.tpExp累计门槛,暂停同种突破喂养"
# TP and ordinary experience have independent caps. Neither cap
# permits falling through to another member of this species.
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 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']}"
return None, f"同种主培养代表 #{target['id']} 突破及当前经验已满或上限未知,暂停喂养"
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 = []
ranch_counts = {}
for mon in snapshot.raw["monsters"]:
if mon.get("process") == 3:
key = str(mon.get("typeId"))
ranch_counts[key] = ranch_counts.get(key, 0) + 1
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"])
rule = self.species_rule(mon, policy)
if (mid not in self.managed and not rule) 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"
if disposition == "keep" and self.hard_protection_reason(mon, snapshot, policy):
reason = "受保护:" + reason
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:
key = str(mon.get("typeId"))
primary = self.representatives.get(key)
if rule and primary and primary.get("process") != 3 and mid != int(primary["id"]):
self.statuses[mid] = f"等待先收取首次主培养魔物 #{primary['id']},刷新后再处理备用"
self.notes.append(f"{name}:" + self.statuses[mid])
continue
if rule and ranch_counts.get(key, 0) >= 2:
if disposition == "feed" and policy.dispatch:
actions.append(Action("sell", f"同种已达两只,派遣多余素材 {name} #{mid}",
"monsterService/monsterSell", {"monsterIds": [mid]}))
self.statuses[mid] = "同种牧场已达两只,待派遣多余素材"
else:
self.statuses[mid] = "等待收取:同种牧场已达两只,需先派遣多余魔物;受保护魔物不自动解除保护"
self.notes.append(f"{name}:" + self.statuses[mid])
continue
room = next((rid for rid, free in free_rooms.items() if free > 0), None)
if room is not None:
free_rooms[room] -= 1
ranch_counts[key] = ranch_counts.get(key, 0) + 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)
self.statuses[mid] = "暂停喂养:" + reason
if rule and policy.dispatch:
actions.append(Action("sell", f"主培养暂不可喂养,派遣多余素材 {name} #{mid}",
"monsterService/monsterSell", {"monsterIds": [mid]}))
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"]
species_dispatches = [a for a in actions if a.kind == "sell" and any(
mid in monsters and self.species_rule(monsters[mid], policy)
for mid in a.payload["monsterIds"])]
if collects and species_dispatches:
# Dispose of rejected duplicates before admitting another monster.
# The next plan must use a refreshed snapshot after this write.
return [a for a in actions if a.kind == "sell"]
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
feeding = self._batch_feeding(feeds, snapshot, policy)
return feeding + [a for a in actions if a.kind != "feed"]
def _batch_feeding(self, feeds, snapshot, policy):
"""Revalidate the primary and every material at the final batch boundary."""
if not policy.enabled or not policy.feed:
return []
self.ensure_retention(snapshot, policy)
monsters = snapshot.monsters
selected, selected_reason = self.feeding_target(snapshot, policy) if policy.feed_targets or policy.feed_target else (None, "")
valid = []
for action in feeds:
target_id = int(action.payload["targetId"])
target = monsters.get(target_id)
reason = self.primary_target_reason(target, snapshot) if target else "喂养目标已不存在"
if not reason and (policy.feed_targets or policy.feed_target) and (selected is None or int(selected["id"]) != target_id):
reason = selected_reason or "目标未勾选为喂养目标"
if reason:
self.notes.append("暂停喂养:" + reason)
continue
foods = [int(mid) for mid in action.payload["foods"] if int(mid) != target_id
and int(mid) in self.managed and int(mid) in monsters
and monsters[int(mid)].get("process") == 3
and not self.protected(monsters[int(mid)], snapshot, policy)
and int(mid) not in self.dispatch_extras]
if foods:
valid.append((target_id, foods))
if not valid:
return []
target_id = valid[0][0]
target = monsters[target_id]
stop_level = self.catalog.max_level(target)
need = self.catalog.feed_remaining(target, stop_level) if stop_level is not None else None
same_species = target_id in self.tp_feed_targets and all(self.is_same_species_tp_feed(target, monsters[mid])
for mid_target, foods in valid if mid_target == target_id for mid in foods)
tp_need = self.tp_feeding_remaining(target) if same_species else 0
if not same_species and (need is None or need == 0 or int(target.get("level") or 1) >= stop_level):
self.notes.append(f"暂停喂养:主培养目标 #{target_id} 当前经验已满或突破上限未知")
return []
ids, experience, tp_experience = [], 0, 0
for mid_target, food_ids in valid:
if mid_target != target_id:
continue
for mid in food_ids:
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 = Action("feed", f"喂养 {label} ← {len(ids)} 只素材:{foods}(经验 {experience})", "monsterService/monsterIntensify", {"targetId": target_id, "foods": ids})
return [merged]