Add hatch retention, automatic breakthroughs and exploration

This commit is contained in:
AttilaNet
2026-11-09 11:27:29 +08:00
parent 26be820ff2
commit 9f819d828a
32 changed files with 6207 additions and 83 deletions
+274 -18
View File
@@ -5,7 +5,7 @@ import json
import math
from pathlib import Path
import time
from .cultivation import CultivationSelector, growth_score
from .cultivation import CultivationSelector, growth_score, quality_rank, quality_summary
WIKI = "https://wiki.biligame.com/myrzx/魔物收益表"
@@ -258,12 +258,25 @@ class EggRule:
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
@@ -303,14 +316,39 @@ class Policy:
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:
@@ -328,10 +366,29 @@ class Planner:
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)
@@ -340,30 +397,124 @@ class Planner:
(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:
representative = self.cultivation.select(snapshot).get(str(mon.get("typeId")))
if representative and int(representative["id"]) == int(mon["id"]):
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:
if policy.keep_better_quality and not self.preparing_retention:
if representative is None:
return "牧场尚无同种魔物,保留首次获得的魔物"
baseline, candidate = growth_score(self.catalog, representative), growth_score(self.catalog, mon)
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 + 1e-8:
return f"综合成长资质高于同种培养代表 #{representative['id']}({candidate:.1%} > {baseline:.1%})"
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"
@@ -403,6 +554,85 @@ class Planner:
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 = []
@@ -491,7 +721,10 @@ class Planner:
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 []
@@ -542,7 +775,12 @@ class Planner:
else:
self.notes.append(f"{name} 等待收取:牧场没有空位")
elif disposition == "feed" and mon.get("process") == 3:
target, reason = self.feeding_target(snapshot, policy)
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:
@@ -551,6 +789,10 @@ class Planner:
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):
@@ -586,6 +828,7 @@ class Planner:
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:
@@ -594,28 +837,41 @@ class Planner:
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"]
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 actions
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)
ids, experience = [], 0
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:
if action.payload["targetId"] != target_id:
continue
for mid in action.payload["foods"]:
if mid in ids:
if mid in ids or mid == target_id:
continue
ids.append(mid)
experience += self.catalog.feed_exp(monsters[mid])
if need is None or experience >= need:
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 need is None or experience >= need:
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] + [a for a in actions if a.kind != "feed"]
return ([merged_collect] if merged_collect else []) + [merged] + [a for a in actions if a not in feeds]