fix: keep automatic cultivation on one stable primary per species
This commit is contained in:
@@ -9,7 +9,9 @@ from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from .cultivation import CultivationSelector
|
||||
from .model import Action
|
||||
from .team_availability import _exploring_ids
|
||||
|
||||
|
||||
PATH = "monsterService/monsterPotentialLevelUpgrade"
|
||||
@@ -43,6 +45,31 @@ def field(row, name, default=None):
|
||||
return getattr(row, name, default)
|
||||
|
||||
|
||||
def primary_target_reason(catalog, cultivation, snapshot, monster_id, *, primaries=None):
|
||||
"""Admission for automatic resources only; saved target maps are not authority."""
|
||||
mid = integer(monster_id)
|
||||
mon = snapshot.monsters.get(mid) if snapshot is not None else None
|
||||
if mon is None:
|
||||
return f"自动培养目标 #{monster_id} 已不在角色数据中"
|
||||
label = catalog.monster_label(mon)
|
||||
if mon.get("process") != 3:
|
||||
return f"{label} 不在牧场,暂停自动培养"
|
||||
primaries = cultivation.select(snapshot) if primaries is None else primaries
|
||||
primary = primaries.get(str(mon.get("typeId")))
|
||||
if primary is None:
|
||||
return f"{label} 尚未确认同种主培养,暂停自动培养"
|
||||
if int(primary["id"]) != mid:
|
||||
return (f"{label} 是同种非主培养(备选 / 重复魔物);"
|
||||
f"仅主培养 #{primary['id']} 可自动喂养、赠礼和突破")
|
||||
if mon.get("inExploreTeam") or mid in _exploring_ids(snapshot):
|
||||
return f"{label} 主培养正在探险,暂停自动培养,不改用备选"
|
||||
if mon.get("inBuild"):
|
||||
return f"{label} 主培养正在建筑,暂停自动培养,不改用备选"
|
||||
if mon.get("sysLock"):
|
||||
return f"{label} 主培养系统锁定,暂停自动培养,不改用备选"
|
||||
return ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Material:
|
||||
type_id: int
|
||||
@@ -66,8 +93,9 @@ class Candidate:
|
||||
class BreakthroughPlanner:
|
||||
"""Plan PotentialPanel writes; each call returns at most one operation."""
|
||||
|
||||
def __init__(self, catalog):
|
||||
def __init__(self, catalog, cultivation=None):
|
||||
self.catalog = catalog
|
||||
self.cultivation = cultivation or CultivationSelector(catalog)
|
||||
self.notes = []
|
||||
|
||||
@staticmethod
|
||||
@@ -228,18 +256,14 @@ class BreakthroughPlanner:
|
||||
if not ids:
|
||||
self.notes.append("未选择自动突破目标")
|
||||
return None
|
||||
primaries = self.cultivation.select(snapshot)
|
||||
for mid in ids:
|
||||
mon = snapshot.monsters.get(mid)
|
||||
if not mon:
|
||||
self.notes.append(f"#{mid} 已不在角色数据中")
|
||||
reason = primary_target_reason(self.catalog, self.cultivation, snapshot, mid, primaries=primaries)
|
||||
if reason:
|
||||
self.notes.append(reason)
|
||||
continue
|
||||
mon = snapshot.monsters[mid]
|
||||
label = self.catalog.monster_label(mon)
|
||||
if mon.get("process") != 3:
|
||||
self.notes.append(f"{label} 不在牧场")
|
||||
continue
|
||||
if mon.get("inExploreTeam") or mon.get("inBuild"):
|
||||
self.notes.append(f"{label} 正在探险或建筑,暂停自动突破")
|
||||
continue
|
||||
level, caps, reason = self.caps(mon)
|
||||
if level is None:
|
||||
self.notes.append(f"{label}:{reason}")
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
"""Choose a single ranch representative per species, independently of gifts."""
|
||||
"""Choose a stable cultivation primary per species, independently of eligibility."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import random
|
||||
import threading
|
||||
|
||||
|
||||
@@ -20,14 +19,11 @@ def growth_score(catalog, mon):
|
||||
|
||||
|
||||
def quality_rank(catalog, mon):
|
||||
"""Compare letter grades before using raw growth to break exact-grade ties."""
|
||||
"""Compare S counts, then the equal-weight mean of all normalized growth."""
|
||||
qualities = catalog.quality(mon)
|
||||
if any(value is None for value in qualities):
|
||||
return None
|
||||
# A and B grades are compared per attribute. A raw average must never
|
||||
# make AASA outrank SSAS (or turn an S-grade advantage into a B-grade one).
|
||||
return (sum(value == 4 for value in qualities), sum(value == 3 for value in qualities),
|
||||
sum(value == 2 for value in qualities), growth_score(catalog, mon))
|
||||
return (sum(value == 4 for value in qualities), growth_score(catalog, mon))
|
||||
|
||||
|
||||
def quality_summary(catalog, mon):
|
||||
@@ -37,6 +33,8 @@ def quality_summary(catalog, mon):
|
||||
|
||||
|
||||
class CultivationSelector:
|
||||
"""Persist primary IDs in the caller's account/role-scoped choices file."""
|
||||
|
||||
def __init__(self, catalog, path=None):
|
||||
self.catalog = catalog
|
||||
self.path = Path(path) if path else None
|
||||
@@ -47,17 +45,23 @@ class CultivationSelector:
|
||||
self.lock = threading.RLock()
|
||||
|
||||
def rank(self, mon):
|
||||
values = growth_values(self.catalog, mon)
|
||||
"""Comparable (level, feel, S count, equal-weight normalized growth)."""
|
||||
return (int(mon.get("level") or 1), int(mon.get("feel") or 0),
|
||||
round(sum(values) / 4, 9) if values is not None else -1,
|
||||
values if values is not None else (-1,) * 4)
|
||||
*(quality_rank(self.catalog, mon) or (-1, -1)))
|
||||
|
||||
def select(self, snapshot):
|
||||
"""Return {str(typeId): current primary row} for mature ranch monsters.
|
||||
|
||||
Initial selection uses rank, then the oldest ID. An existing primary
|
||||
changes only for a strictly higher-level ranch monster or confirmed
|
||||
removal. A saved ID still present outside the ranch blocks fallback.
|
||||
"""
|
||||
with self.lock:
|
||||
owner = str(snapshot.raw["master"]["id"])
|
||||
ranch = [mon for mon in snapshot.raw["monsters"] if mon.get("process") == 3 and mon.get("typeId") is not None]
|
||||
signature = (owner, tuple((int(mon["id"]), str(mon["typeId"]), mon.get("level"), mon.get("feel"),
|
||||
*(mon.get(key) for key in ("gAtk", "gDef", "gHp", "gDex"))) for mon in ranch))
|
||||
monsters = snapshot.raw["monsters"]
|
||||
ranch = [mon for mon in monsters if mon.get("process") == 3 and mon.get("typeId") is not None]
|
||||
signature = (owner, tuple((int(mon["id"]), str(mon.get("typeId")), mon.get("process"), mon.get("level"), mon.get("feel"),
|
||||
*(mon.get(key) for key in ("gAtk", "gDef", "gHp", "gDex"))) for mon in monsters))
|
||||
if self.signature == signature:
|
||||
current = {int(mon["id"]): mon for mon in ranch}
|
||||
self.selected = {key: current[int(mon["id"])] for key, mon in self.selected.items()}
|
||||
@@ -72,17 +76,24 @@ class CultivationSelector:
|
||||
except (OSError, ValueError, TypeError, AttributeError):
|
||||
pass
|
||||
self.owner = owner
|
||||
# Snapshot.monsters is the complete authoritative roster. A removed
|
||||
# ID may be replaced, while a present non-ranch primary stays saved.
|
||||
current_ids = {int(mon["id"]) for mon in monsters}
|
||||
choices = {key: mid for key, mid in self.choices.items() if mid in current_ids}
|
||||
groups = {}
|
||||
for mon in ranch:
|
||||
groups.setdefault(str(mon["typeId"]), []).append(mon)
|
||||
selected = {}
|
||||
for key, members in groups.items():
|
||||
ranked = [(self.rank(mon), mon) for mon in members]
|
||||
highest = max(rank for rank, _ in ranked)
|
||||
tied = [mon for rank, mon in ranked if rank == highest]
|
||||
previous = next((mon for mon in tied if int(mon["id"]) == self.choices.get(key)), None)
|
||||
selected[key] = previous if previous is not None else tied[0] if len(tied) == 1 else random.choice(tied)
|
||||
choices = {key: int(mon["id"]) for key, mon in selected.items()}
|
||||
previous = next((mon for mon in members if int(mon["id"]) == choices.get(key)), None)
|
||||
if previous is None and key in choices:
|
||||
continue
|
||||
highest_level = max(int(mon.get("level") or 1) for mon in members)
|
||||
if previous is not None and int(previous.get("level") or 1) >= highest_level:
|
||||
selected[key] = previous
|
||||
else:
|
||||
selected[key] = max(members, key=lambda mon: (self.rank(mon), -int(mon["id"])))
|
||||
choices.update({key: int(mon["id"]) for key, mon in selected.items()})
|
||||
if choices != self.choices:
|
||||
if self.path:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -27,7 +27,7 @@ from .progression import ProgressionIntent, ProgressionPlanner, ProgressionPolic
|
||||
from .battle_messages import battle_message
|
||||
from .maps import stages
|
||||
from .exploration import ExplorePlanner, ExplorePolicy
|
||||
from .breakthrough import BreakthroughPlanner
|
||||
from .breakthrough import BreakthroughPlanner, primary_target_reason
|
||||
|
||||
|
||||
def account_serial(method):
|
||||
@@ -87,7 +87,7 @@ class Engine:
|
||||
self.sweeper = SweepRunner(catalog, folder / "sweep_runs.json" if folder else None)
|
||||
self.explore_planner = ExplorePlanner(catalog)
|
||||
self.explore_policy = ExplorePolicy()
|
||||
self.breakthrough_planner = BreakthroughPlanner(catalog)
|
||||
self.breakthrough_planner = BreakthroughPlanner(catalog, self.cultivation)
|
||||
self.automation_state_path = folder / "automation_state.json" if folder else None
|
||||
self._explore_pending_last_check = 0
|
||||
self._explore_pending_confirmed = False
|
||||
@@ -283,9 +283,37 @@ class Engine:
|
||||
self.auto = False
|
||||
raise
|
||||
|
||||
def cultivation_target_reason(self, monster_id, *, primaries=None):
|
||||
return primary_target_reason(self.catalog, self.cultivation, self.snapshot, monster_id, primaries=primaries)
|
||||
|
||||
def _automatic_cultivation_reason(self, action, *, primaries=None):
|
||||
recipient_key = {"feed": "targetId", "gift": "monsterId", "potential": "monId", "breakthrough": "monId"}.get(action.kind)
|
||||
return self.cultivation_target_reason(action.payload.get(recipient_key), primaries=primaries) if recipient_key else ""
|
||||
|
||||
def _admit_automatic_cultivation(self, actions):
|
||||
primaries = self.cultivation.select(self.snapshot)
|
||||
admitted = []
|
||||
for action in actions:
|
||||
reason = self._automatic_cultivation_reason(action, primaries=primaries)
|
||||
if reason:
|
||||
self.planner.notes.append("跳过自动操作:" + reason)
|
||||
else:
|
||||
admitted.append(action)
|
||||
return admitted
|
||||
|
||||
def _skip_automatic_cultivation(self, reason):
|
||||
self.last_executed = False
|
||||
plans = self.plans()
|
||||
self.planner.notes.append("跳过自动操作:" + reason)
|
||||
return self.snapshot, plans, "跳过自动操作:" + reason
|
||||
|
||||
def _execute_breakthrough(self, action):
|
||||
self.last_executed = False
|
||||
if self._breakthrough_pending:
|
||||
return self.snapshot, [], "突破请求待核对,禁止重发"
|
||||
reason = self._automatic_cultivation_reason(action)
|
||||
if reason:
|
||||
return self._skip_automatic_cultivation(reason)
|
||||
mon = self.snapshot.monsters[int(action.payload["monId"])]
|
||||
attribute = action.payload.get("monsterAttr", "")
|
||||
before = mon.get("p" + attribute.capitalize()) if action.kind == "potential" else mon.get("potentialLevel")
|
||||
@@ -305,7 +333,14 @@ class Engine:
|
||||
if not self.auto or self._progression_cancel.is_set():
|
||||
self._discard_unsent_automation()
|
||||
return self.snapshot, self.plans(), "突破请求尚未发送,已取消"
|
||||
reason = self._automatic_cultivation_reason(action)
|
||||
if reason:
|
||||
# Only this newly journaled, unsent request may be discarded. An
|
||||
# older pending request returned above and must retain its evidence.
|
||||
self._discard_unsent_automation()
|
||||
return self._skip_automatic_cultivation(reason)
|
||||
try:
|
||||
self.last_executed = True
|
||||
response = self.client.call(action.path, deepcopy(action.payload))
|
||||
if not isinstance(response, dict) or response.get("resCode", 0) not in (0, "0"):
|
||||
raise ValueError("突破请求尚未确认成功")
|
||||
@@ -1061,6 +1096,9 @@ class Engine:
|
||||
self.last_executed = True
|
||||
return self._execute_breakthrough(action)
|
||||
if self.auto and action is not None:
|
||||
reason = self._automatic_cultivation_reason(action)
|
||||
if reason:
|
||||
return self._skip_automatic_cultivation(reason)
|
||||
self.last_executed = True
|
||||
if action.kind == "progression":
|
||||
return self._run_progression_intent(action.payload["intent"])
|
||||
@@ -1146,8 +1184,14 @@ class Engine:
|
||||
if not self.auto or self._progression_cancel.is_set():
|
||||
return self.snapshot, plans, "策略已停止,快速操作未执行"
|
||||
if action is None:
|
||||
return self.snapshot, plans, {"explore": "探险", "breakthrough": "突破",
|
||||
message = {"explore": "探险", "breakthrough": "突破",
|
||||
"gift": "赠礼", "hatch": "孵化"}[kind] + "当前无可执行动作"
|
||||
if self.planner.notes:
|
||||
message += ";" + ";".join(dict.fromkeys(self.planner.notes))
|
||||
return self.snapshot, plans, message
|
||||
reason = self._automatic_cultivation_reason(action)
|
||||
if reason:
|
||||
return self._skip_automatic_cultivation(reason)
|
||||
self.last_executed = True
|
||||
if kind == "explore":
|
||||
return self._execute_explore(action)
|
||||
@@ -1298,8 +1342,7 @@ class Engine:
|
||||
if self.snapshot is None or self._progression_pending():
|
||||
self.pending_hatches = []
|
||||
return []
|
||||
if self.policy.keep_better_quality or self.policy.gift_auto_representative:
|
||||
self.cultivation.select(self.snapshot)
|
||||
primaries = self.cultivation.select(self.snapshot)
|
||||
# One owner for commission writes; never accept the same offer through
|
||||
# both the legacy planner and the full progression planner.
|
||||
quests = [] if self._commission_planner_available else self.tasks.plan(self.snapshot, self.quest_policy, self.policy)
|
||||
@@ -1318,18 +1361,29 @@ class Engine:
|
||||
ranch = self.planner.plan(self.snapshot, policy, left)
|
||||
explore = self.explore_planner.plan(self.snapshot, self.explore_policy, policy)
|
||||
breakthrough_policy = SimpleNamespace(**(asdict(policy) | {"item_reserves": dict(self.quest_policy.item_reserves)}))
|
||||
self.breakthrough_planner.notes = []
|
||||
breakthrough = self.breakthrough_planner.plan(self.snapshot, breakthrough_policy,
|
||||
targets=policy.breakthrough_targets, enabled=not self._breakthrough_pending) if policy.breakthrough_targets else None
|
||||
self.planner.notes.extend(self.gift_planner.notes)
|
||||
self.planner.notes.extend(self.breakthrough_planner.notes)
|
||||
feed_targets = policy.feed_targets or ({str(policy.feed_target): 1} if policy.feed_target else {})
|
||||
for enabled, targets in (
|
||||
(policy.enabled and policy.feed, feed_targets),
|
||||
(policy.gift_enabled and not policy.gift_auto_representative, policy.gift_targets),
|
||||
(policy.enabled, policy.breakthrough_targets)):
|
||||
if enabled:
|
||||
for mid in targets:
|
||||
reason = self.cultivation_target_reason(mid, primaries=primaries)
|
||||
if reason:
|
||||
self.planner.notes.append("跳过自动目标:" + reason)
|
||||
breakthroughs = [breakthrough] if breakthrough else []
|
||||
progression = [Action("progression", value(intent, "description", "推进任务"), "", {"intent": intent})
|
||||
for intent in self._progression_intents if not value(intent, "block_reason") and self._intent_policy(intent).enabled]
|
||||
commission = [action for action in progression if self._is_commission(action.payload["intent"])]
|
||||
progression = [action for action in progression if not self._is_commission(action.payload["intent"])]
|
||||
if quests and quests[0].kind == "quest_reset":
|
||||
return quests + commission[:1] + daily + progression[:1] + explore + breakthroughs + gifts + ranch + sweep_actions
|
||||
return commission[:1] + quests + daily + progression[:1] + explore + breakthroughs + gifts + ranch + sweep_actions
|
||||
return self._admit_automatic_cultivation(quests + commission[:1] + daily + progression[:1] + explore + breakthroughs + gifts + ranch + sweep_actions)
|
||||
return self._admit_automatic_cultivation(commission[:1] + quests + daily + progression[:1] + explore + breakthroughs + gifts + ranch + sweep_actions)
|
||||
|
||||
@account_serial
|
||||
def claim_daily_entry(self, entry):
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import math
|
||||
from .model import Action, seconds
|
||||
from .cultivation import CultivationSelector
|
||||
from .team_availability import _exploring_ids
|
||||
|
||||
|
||||
def item_reserve(item_type, ranch, quests):
|
||||
@@ -40,11 +41,16 @@ class GiftPlanner:
|
||||
mon.update(feel=entry["feel"], giftTime=entry["giftTime"])
|
||||
|
||||
def candidates(self, snapshot, policy):
|
||||
# Select identity before checking availability; a busy primary must
|
||||
# never cause its quality backup to receive cultivation resources.
|
||||
primaries = self.cultivation.select(snapshot)
|
||||
exploring = _exploring_ids(snapshot)
|
||||
available = {int(mon["id"]): mon for mon in primaries.values()
|
||||
if not mon.get("inExploreTeam") and not mon.get("inBuild") and int(mon["id"]) not in exploring}
|
||||
if policy.gift_auto_representative:
|
||||
return sorted(self.cultivation.select(snapshot).values(), key=lambda mon: self.cultivation.rank(mon), reverse=True)
|
||||
monsters = snapshot.monsters
|
||||
return [monsters[int(key)] for key, _ in sorted(policy.gift_targets.items(), key=lambda pair: pair[1])
|
||||
if int(key) in monsters and monsters[int(key)].get("process") == 3]
|
||||
return sorted(available.values(), key=lambda mon: self.cultivation.rank(mon), reverse=True)
|
||||
return [available[int(key)] for key, _ in sorted(policy.gift_targets.items(), key=lambda pair: pair[1])
|
||||
if int(key) in available]
|
||||
|
||||
def target(self, snapshot, policy):
|
||||
for mon in self.candidates(snapshot, policy):
|
||||
|
||||
+222
-155
@@ -6,6 +6,7 @@ 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/魔物收益表"
|
||||
|
||||
@@ -369,57 +370,70 @@ class Planner:
|
||||
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):
|
||||
self.ensure_retention(snapshot, policy)
|
||||
return bool(self.protection_reason(mon, snapshot, policy))
|
||||
|
||||
def ensure_retention(self, snapshot, policy):
|
||||
if not policy.manual_eggs:
|
||||
if self.preparing_retention:
|
||||
return
|
||||
signature = (repr(snapshot.raw.get("monsters")), repr(snapshot.raw.get("teams")),
|
||||
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.breakthrough_targets, policy.reserved_types)))
|
||||
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
|
||||
|
||||
def protection_reason(self, mon, snapshot, policy):
|
||||
@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"), "正在探索"), (mon.get("inBuild"), "正在建筑中"),
|
||||
(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)), "携带装备"),
|
||||
(int(mon["id"]) == policy.feed_target or str(mon["id"]) in policy.feed_targets, "已选为喂养目标"),
|
||||
(str(mon["id"]) in policy.breakthrough_targets, "已选为自动突破目标"),
|
||||
(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}, "保留种类或委托保留"),
|
||||
(row.get("star", 0) >= policy.protect_star, f"{row.get('star', '?')}星达到保留星级{policy.protect_star}"),
|
||||
(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.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:
|
||||
@@ -427,100 +441,82 @@ class Planner:
|
||||
return ""
|
||||
|
||||
def prepare_retention(self, snapshot, policy):
|
||||
"""Allocate each species quota once for all ranches and this hatch batch."""
|
||||
"""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
|
||||
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)
|
||||
|
||||
self.representatives = dict(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:
|
||||
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, rule in policy.egg_rules.items():
|
||||
if not rule.get("enabled"):
|
||||
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
|
||||
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}"
|
||||
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"]), {})
|
||||
return rule.get("action", "keep") if rule.get("enabled") else "keep"
|
||||
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"):
|
||||
@@ -536,6 +532,10 @@ class Planner:
|
||||
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 = "目标突破上限未知,暂停喂养"
|
||||
@@ -550,6 +550,18 @@ class Planner:
|
||||
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
|
||||
@@ -584,44 +596,35 @@ class Planner:
|
||||
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."""
|
||||
"""Feed only the primary; its caps never authorize a duplicate target."""
|
||||
self.ensure_retention(snapshot, policy)
|
||||
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:
|
||||
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累计门槛,暂停同种突破喂养"
|
||||
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]
|
||||
# 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, "同种魔物均已完成突破,不继续消耗同种素材"
|
||||
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
|
||||
@@ -732,6 +735,11 @@ class Planner:
|
||||
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"])
|
||||
@@ -742,7 +750,8 @@ class Planner:
|
||||
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):
|
||||
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] = "该魔物未启用孵蛋规则"
|
||||
@@ -762,15 +771,33 @@ class Planner:
|
||||
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} 等待收取:牧场没有空位")
|
||||
@@ -785,6 +812,10 @@ class Planner:
|
||||
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:
|
||||
@@ -828,6 +859,13 @@ class Planner:
|
||||
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 = {}
|
||||
@@ -845,21 +883,50 @@ class Planner:
|
||||
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
|
||||
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:
|
||||
for mid in action.payload["foods"]:
|
||||
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)
|
||||
@@ -872,6 +939,6 @@ class Planner:
|
||||
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]
|
||||
return []
|
||||
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]
|
||||
return [merged]
|
||||
|
||||
@@ -252,6 +252,10 @@ class AutomationTests(unittest.TestCase):
|
||||
def test_encrypted_http_buy_hatch_mature_dispatch_and_balance(self):
|
||||
state = copy.deepcopy(self.snapshot.raw)
|
||||
state["stacks"][0]["monsterId"] = -1
|
||||
state["monsters"] = [{"id": 900, "typeId": 1001010, "process": 3, "mode": 2,
|
||||
"level": 20, "roomId": 1, "lock": 0,
|
||||
**{"g" + stat.capitalize(): self.catalog.monster(1001010)[stat + "_grow_min"]
|
||||
for stat in ("atk", "def", "hp", "dex")}}]
|
||||
initial_money = state["master"]["money"]
|
||||
calls, catalog = [], self.catalog
|
||||
with workspace_temp() as folder:
|
||||
@@ -274,13 +278,13 @@ class AutomationTests(unittest.TestCase):
|
||||
mon = {"id": 101, "typeId": 1001010, "mode": 0, "process": 2,
|
||||
"timeStart": time.time() * 1000, "level": 1}
|
||||
mon.update({"g" + s.capitalize(): catalog.monster(1001010)[s + "_grow_min"] for s in ("atk", "def", "hp", "dex")})
|
||||
state["monsters"] = [mon]
|
||||
state["monsters"].append(mon)
|
||||
state["stacks"][0]["monsterId"] = 101
|
||||
elif name == "stackCheckProcess":
|
||||
state["monsters"][0]["mode"] = 2
|
||||
next(mon for mon in state["monsters"] if mon["id"] == 101)["mode"] = 2
|
||||
elif name == "monsterSell":
|
||||
assert body["monsterIds"] == [101]
|
||||
state["monsters"] = []
|
||||
state["monsters"] = [mon for mon in state["monsters"] if mon["id"] != 101]
|
||||
state["stacks"][0]["monsterId"] = -1
|
||||
state["master"]["money"] += 150
|
||||
elif name != "masterQueryDetail":
|
||||
@@ -310,10 +314,11 @@ class AutomationTests(unittest.TestCase):
|
||||
self.assertEqual(state["master"]["money"], initial_money - 1000)
|
||||
self.assertIn("共 11 枚", engine.last_draw)
|
||||
engine.poll() # Hatch, re-read, wait.
|
||||
state["monsters"][0]["timeStart"] = (time.time() - 601) * 1000
|
||||
next(mon for mon in state["monsters"] if mon["id"] == 101)["timeStart"] = (time.time() - 601) * 1000
|
||||
snapshot, _, _ = engine.poll() # Settle growth, dispatch, re-read.
|
||||
self.assertEqual(snapshot.raw["master"]["money"], initial_money - 850)
|
||||
self.assertEqual(snapshot.raw["stacks"][0]["monsterId"], -1)
|
||||
self.assertEqual(set(snapshot.monsters), {900})
|
||||
self.assertEqual([n for n, _ in calls if n != "masterQueryDetail"],
|
||||
["gachaGetEggs", "stackAddMonster", "stackCheckProcess", "monsterSell"])
|
||||
engine.poll()
|
||||
|
||||
@@ -36,12 +36,17 @@ class BatchFeedingTests(unittest.TestCase):
|
||||
target["level"] = 20
|
||||
self.assertFalse(any(a.kind == "feed" for a in self.planner.plan(self.snapshot, self.policy)))
|
||||
|
||||
def test_full_first_target_advances_to_next_priority(self):
|
||||
def test_full_primary_skips_duplicate_and_advances_to_different_species_priority(self):
|
||||
first = self.snapshot.monsters[900]
|
||||
first.update(level=20, potentialLevel=2)
|
||||
self.snapshot.raw["monsters"].append(copy.deepcopy(first) | {"id": 901, "level": 1, "exp": 0})
|
||||
self.policy.feed_targets = {"900": 1, "901": 2}
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy)[0].payload["targetId"], 901)
|
||||
self.snapshot.raw["monsters"].extend([
|
||||
copy.deepcopy(first) | {"id": 901, "level": 1, "exp": 0},
|
||||
copy.deepcopy(first) | {"id": 902, "typeId": 1002010, "level": 1, "exp": 0},
|
||||
])
|
||||
self.policy.feed_targets = {"900": 1, "901": 2, "902": 3}
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy)[0].payload["targetId"], 902)
|
||||
del self.policy.feed_targets["902"]
|
||||
self.assertFalse(any(a.kind == "feed" for a in self.planner.plan(self.snapshot, self.policy)))
|
||||
|
||||
def test_priority_target_uses_current_cap_instead_of_legacy_stop_level(self):
|
||||
target = self.snapshot.monsters[900]
|
||||
@@ -56,7 +61,7 @@ class BatchFeedingTests(unittest.TestCase):
|
||||
first.update(level=19, potentialLevel=2, exp=self.catalog.data["monster_level"]["20"])
|
||||
self.snapshot.raw["monsters"].extend([
|
||||
copy.deepcopy(first) | {"id": 901, "potentialLevel": None},
|
||||
copy.deepcopy(first) | {"id": 902, "level": 1, "exp": 0},
|
||||
copy.deepcopy(first) | {"id": 902, "typeId": 1002010, "level": 1, "exp": 0},
|
||||
])
|
||||
self.policy.feed_targets = {"902": 3, "901": 2, "900": 1}
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy)[0].payload["targetId"], 902)
|
||||
|
||||
@@ -117,8 +117,12 @@ class BreakthroughTests(unittest.TestCase):
|
||||
|
||||
def test_independent_targets_replace_feed_targets_and_empty_is_empty(self):
|
||||
other = copy.deepcopy(self.snapshot.monsters[900])
|
||||
other["id"] = 901
|
||||
row = self.catalog.monster(1003010)
|
||||
caps = self.catalog.data["potential_info"]["potential"][str(row["job"])][str(row["star"])]
|
||||
other.update(id=901, typeId=1003010,
|
||||
**{"p" + stat.capitalize(): caps[stat] for stat in ("atk", "def", "hp", "dex")})
|
||||
self.snapshot.raw["monsters"].append(other)
|
||||
self.assertEqual(self.planner.plan(self.snapshot, self.policy).payload["monId"], 900)
|
||||
action = self.planner.plan(self.snapshot, self.policy, targets={"901": 1})
|
||||
self.assertEqual(action.payload["monId"], 901)
|
||||
self.assertIsNone(self.planner.plan(self.snapshot, self.policy, targets={}))
|
||||
|
||||
@@ -55,20 +55,33 @@ class CultivationTests(unittest.TestCase):
|
||||
rows[1]["level"] = 12
|
||||
self.assertEqual(selector.select(self.snapshot)["1001010"]["id"], 2)
|
||||
|
||||
def test_ties_are_chosen_once_persisted_and_do_not_leak_to_other_role(self):
|
||||
def test_ties_preserve_older_ranch_member_across_refresh_restart_and_role_change(self):
|
||||
self.snapshot.raw["monsters"] = [monster(self.catalog, 1), monster(self.catalog, 2)]
|
||||
with workspace_temp() as folder:
|
||||
path = folder / "choices.json"
|
||||
with patch("ranch_assistant.cultivation.random.choice", side_effect=lambda choices: choices[-1]) as draw:
|
||||
selector = CultivationSelector(self.catalog, path)
|
||||
self.assertEqual(selector.select(self.snapshot)["1001010"]["id"], 2)
|
||||
selector.select(self.snapshot)
|
||||
self.assertEqual(draw.call_count, 1)
|
||||
with patch("ranch_assistant.cultivation.random.choice", side_effect=AssertionError("Re-selected an exact tie")):
|
||||
self.assertEqual(CultivationSelector(self.catalog, path).select(self.snapshot)["1001010"]["id"], 2)
|
||||
selector = CultivationSelector(self.catalog, path)
|
||||
self.assertEqual(selector.select(self.snapshot)["1001010"]["id"], 1)
|
||||
self.snapshot.raw["monsters"].reverse()
|
||||
self.assertEqual(selector.select(self.snapshot)["1001010"]["id"], 1)
|
||||
self.assertEqual(CultivationSelector(self.catalog, path).select(self.snapshot)["1001010"]["id"], 1)
|
||||
self.snapshot.raw["master"]["id"] += 1
|
||||
with patch("ranch_assistant.cultivation.random.choice", side_effect=lambda choices: choices[0]):
|
||||
self.assertEqual(CultivationSelector(self.catalog, path).select(self.snapshot)["1001010"]["id"], 1)
|
||||
self.snapshot.raw["monsters"] = [monster(self.catalog, 12), monster(self.catalog, 11)]
|
||||
self.assertEqual(CultivationSelector(self.catalog, path).select(self.snapshot)["1001010"]["id"], 11)
|
||||
|
||||
def test_present_non_ranch_primary_holds_but_confirmed_absence_promotes_once(self):
|
||||
primary, duplicate = monster(self.catalog, 1, level=20), monster(self.catalog, 2, level=10)
|
||||
self.snapshot.raw["monsters"] = [primary, duplicate]
|
||||
with workspace_temp() as folder:
|
||||
path = folder / "choices.json"
|
||||
selector = CultivationSelector(self.catalog, path)
|
||||
self.assertEqual(selector.select(self.snapshot)["1001010"]["id"], 1)
|
||||
primary["process"] = 2
|
||||
self.assertNotIn("1001010", selector.select(self.snapshot))
|
||||
self.assertEqual(selector.choices["1001010"], 1)
|
||||
self.assertNotIn("1001010", CultivationSelector(self.catalog, path).select(self.snapshot))
|
||||
self.snapshot.raw["monsters"].remove(primary)
|
||||
self.assertEqual(selector.select(self.snapshot)["1001010"]["id"], 2)
|
||||
self.assertEqual(CultivationSelector(self.catalog, path).select(self.snapshot)["1001010"]["id"], 2)
|
||||
|
||||
def test_cached_selection_uses_current_cooldown_and_bond_cap(self):
|
||||
self.snapshot.raw["monsters"] = [monster(self.catalog, 1)]
|
||||
@@ -80,17 +93,24 @@ class CultivationTests(unittest.TestCase):
|
||||
self.assertIs(chosen, updated.raw["monsters"][0])
|
||||
self.assertEqual((chosen["giftTime"], chosen["entangleLevel"]), (123456789, 2))
|
||||
|
||||
def test_better_growth_is_kept_independently_of_four_s_and_equal_or_worse_is_not(self):
|
||||
def test_better_backup_is_mandatory_despite_legacy_flags_and_equal_or_worse_is_not(self):
|
||||
representative = monster(self.catalog, 1, level=50, feel=90, scale=.3)
|
||||
hatched = monster(self.catalog, 2, level=1, scale=.4, process=2)
|
||||
self.snapshot.raw["monsters"] = [representative, hatched]
|
||||
planner = Planner(self.catalog)
|
||||
policy = Policy(strategy="gold", protect_star=6, protect_quality=6, keep_better_quality=True)
|
||||
self.assertEqual(planner.disposition(hatched, self.snapshot, policy), "keep")
|
||||
self.assertIn("同种培养代表 #1", planner.protection_reason(hatched, self.snapshot, policy))
|
||||
policy = Policy(manual_eggs=True, protect_star=6, protect_quality=5,
|
||||
gift_auto_representative=False, keep_better_quality=False,
|
||||
egg_rules={"1001010": asdict(EggRule(enabled=True, action="sell", keep_count=1))})
|
||||
for keep_better in (False, True):
|
||||
for keep_count in (0, 1, 4):
|
||||
with self.subTest(keep_better=keep_better, keep_count=keep_count):
|
||||
policy.keep_better_quality = keep_better
|
||||
policy.egg_rules["1001010"]["keep_count"] = keep_count
|
||||
self.assertEqual(planner.disposition(representative, self.snapshot, policy), "keep")
|
||||
self.assertEqual(planner.disposition(hatched, self.snapshot, policy), "keep")
|
||||
self.assertEqual(planner.retained, {1, 2})
|
||||
policy.keep_better_quality = False
|
||||
self.assertEqual(planner.disposition(hatched, self.snapshot, policy), "sell")
|
||||
policy.keep_better_quality = True
|
||||
policy.egg_rules["1001010"]["keep_count"] = 1
|
||||
for scale in (.3, .2):
|
||||
self.snapshot.raw["monsters"][1] = monster(self.catalog, 2, scale=scale, process=2)
|
||||
self.assertEqual(planner.disposition(self.snapshot.monsters[2], self.snapshot, policy), "sell")
|
||||
@@ -146,6 +166,10 @@ class CultivationTests(unittest.TestCase):
|
||||
self.assertAlmostEqual(growth_score(self.catalog, mon), .5, places=3)
|
||||
mon["gHp"] = self.catalog.monster(1001010)["hp_grow_max"]
|
||||
self.assertAlmostEqual(growth_score(self.catalog, mon), .625, places=3)
|
||||
self.assertGreater(quality_rank(self.catalog, graded_monster(self.catalog, 2, "SCCC")),
|
||||
quality_rank(self.catalog, graded_monster(self.catalog, 3, "AAAC")))
|
||||
self.assertGreater(quality_rank(self.catalog, graded_monster(self.catalog, 4, "SSBB")),
|
||||
quality_rank(self.catalog, graded_monster(self.catalog, 5, "SSAC")))
|
||||
|
||||
|
||||
class CultivationGuiTests(unittest.TestCase):
|
||||
|
||||
@@ -9,6 +9,7 @@ class GiftTargetSelectionTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.catalog = Catalog()
|
||||
self.snapshot = gift_snapshot(self.catalog)
|
||||
self.snapshot.raw["monsters"][0]["level"] += 1
|
||||
self.planner = GiftPlanner(self.catalog)
|
||||
self.representative = next(iter(self.planner.cultivation.select(self.snapshot).values()))
|
||||
self.manual_target = next(mon for mon in self.snapshot.raw["monsters"]
|
||||
@@ -27,13 +28,20 @@ class GiftTargetSelectionTests(unittest.TestCase):
|
||||
self.assertEqual([action.payload["monsterId"] for action in self.planner.plan(self.snapshot, policy)],
|
||||
[self.representative["id"]])
|
||||
|
||||
def test_manual_mode_uses_gift_targets_instead_of_representative(self):
|
||||
def test_manual_mode_requires_the_primary_to_be_explicitly_checked(self):
|
||||
policy = self.policy()
|
||||
|
||||
self.assertEqual(self.planner.candidates(self.snapshot, policy), [])
|
||||
self.assertEqual(self.planner.plan(self.snapshot, policy), [])
|
||||
|
||||
policy.gift_targets[str(self.representative["id"])] = 2
|
||||
self.assertEqual([mon["id"] for mon in self.planner.candidates(self.snapshot, policy)],
|
||||
[self.manual_target["id"]])
|
||||
[self.representative["id"]])
|
||||
self.assertEqual([action.payload["monsterId"] for action in self.planner.plan(self.snapshot, policy)],
|
||||
[self.manual_target["id"]])
|
||||
[self.representative["id"]])
|
||||
|
||||
self.representative["feel"] = self.catalog.max_feel(self.representative)
|
||||
self.assertEqual(self.planner.plan(self.snapshot, policy), [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -63,19 +63,27 @@ class GiftTimingTests(unittest.TestCase):
|
||||
def test_success_response_updates_each_monster_despite_stale_queries(self):
|
||||
with patch("ranch_assistant.model.time.time", return_value=NOW):
|
||||
client = GiftClient(self.catalog)
|
||||
client.raw["monsters"][1].update(typeId=1002010,
|
||||
**{"g" + stat.capitalize(): self.catalog.monster(1002010)[stat + "_grow_min"]
|
||||
for stat in ("atk", "def", "hp", "dex")})
|
||||
engine = Engine(self.catalog, client)
|
||||
engine.policy = gift_policy()
|
||||
engine.auto = True
|
||||
first, _, _ = engine.poll()
|
||||
self.assertEqual(first.monsters[1]["feel"], 10)
|
||||
self.assertEqual(first.monsters[1]["giftTime"], NOW)
|
||||
engine.poll()
|
||||
second, _, _ = engine.poll()
|
||||
self.assertEqual(second.monsters[2]["feel"], 10)
|
||||
self.assertEqual(second.monsters[2]["giftTime"], NOW)
|
||||
engine.poll()
|
||||
self.assertEqual([payload["monsterId"] for _, payload in client.calls], [1, 2])
|
||||
|
||||
def test_next_due_uses_earliest_eligible_cooldown_and_ignores_full_targets(self):
|
||||
with patch("ranch_assistant.model.time.time", return_value=NOW):
|
||||
snapshot = gift_snapshot(self.catalog)
|
||||
snapshot.monsters[2].update(typeId=1002010,
|
||||
**{"g" + stat.capitalize(): self.catalog.monster(1002010)[stat + "_grow_min"]
|
||||
for stat in ("atk", "def", "hp", "dex")})
|
||||
snapshot.monsters[1]["giftTime"] = (NOW - 7200 + 120) * 1000
|
||||
snapshot.monsters[2]["giftTime"] = (NOW - 7200 + 15) * 1000
|
||||
planner = GiftPlanner(self.catalog)
|
||||
|
||||
@@ -56,7 +56,7 @@ class GrowthClient:
|
||||
def call(self, path, payload):
|
||||
self.calls.append((path, payload))
|
||||
if path == "monsterService/monsterSell":
|
||||
self.raw["monsters"] = []
|
||||
self.raw["monsters"] = [mon for mon in self.raw["monsters"] if mon["id"] not in payload["monsterIds"]]
|
||||
self.raw["stacks"][0]["monsterId"] = -1
|
||||
return {"resCode": 0}
|
||||
|
||||
@@ -69,6 +69,10 @@ class GrowthTests(unittest.TestCase):
|
||||
self.addCleanup(self.clock.stop)
|
||||
|
||||
def engine(self, client):
|
||||
row = self.catalog.monster(1001010)
|
||||
client.raw["monsters"].append({"id": 900, "typeId": 1001010, "process": 3, "mode": 2,
|
||||
"level": 20, "roomId": 1, "lock": 0,
|
||||
**{"g" + stat.capitalize(): row[stat + "_grow_min"] for stat in ("atk", "def", "hp", "dex")}})
|
||||
engine = Engine(self.catalog, client)
|
||||
engine.policy = Policy(manual_eggs=True, fill=False, buy=False, collect=False, protect_star=4, protect_quality=3,
|
||||
egg_rules={"1001010": asdict(EggRule(enabled=True, action="sell", keep_count=0))})
|
||||
|
||||
@@ -60,6 +60,7 @@ class HatchTimingTests(unittest.TestCase):
|
||||
def test_fast_hatching_skips_other_actions_and_retains_vip_and_reserve_limits(self):
|
||||
catalog = Catalog()
|
||||
client = HatchClient(catalog)
|
||||
client.value["monsters"].append(client.template | {"id": 900, "process": 3, "level": 20, "roomId": 1})
|
||||
client.value["monsters"].append(client.template)
|
||||
client.value["stacks"][0]["monsterId"] = client.template["id"]
|
||||
engine = Engine(catalog, client)
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
"""Offline regressions for stable cultivation primaries and gift target consent."""
|
||||
from copy import deepcopy
|
||||
import json
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from ranch_assistant.cultivation import CultivationSelector, growth_score, quality_rank
|
||||
from ranch_assistant.gifts import GiftPlanner
|
||||
from ranch_assistant.model import Catalog, Policy, Snapshot
|
||||
|
||||
|
||||
NOW = 1_800_000_000
|
||||
SPECIES = 1030010
|
||||
MAIN = 949626937
|
||||
STATS = ("atk", "def", "hp", "dex")
|
||||
|
||||
|
||||
def monster(catalog, mid, grades="SASS", *, species=SPECIES, level=10, **values):
|
||||
row = catalog.monster(species)
|
||||
mon = {"id": mid, "typeId": species, "process": 3, "mode": 2, "level": level,
|
||||
"feel": 0, "entangleLevel": 0, "giftTime": 0, "roomId": 1, "lock": 0}
|
||||
for stat, grade in zip(STATS, grades):
|
||||
low, high = row[stat + "_grow_min"], row[stat + "_grow_max"]
|
||||
mon["g" + stat.capitalize()] = low + (high - low) * {"C": .125, "B": .375, "A": .625, "S": .875}[grade]
|
||||
return mon | values
|
||||
|
||||
|
||||
def snapshot(*members, owner=101):
|
||||
return Snapshot({"master": {"id": owner}, "monsters": list(members), "teams": [], "stacks": [],
|
||||
"items": [{"id": 91, "typeId": 30005, "num": 10}], "rooms": [{"id": 1}, {"id": 8}]})
|
||||
|
||||
|
||||
def policy(*, auto=False, targets=None, **values):
|
||||
return Policy(gift_enabled=True, gift_auto_representative=auto, keep_better_quality=False,
|
||||
gift_targets=targets or {}, gift_liked_only=False,
|
||||
gift_items={"30005": {"enabled": True, "reserve": 2}}, **values)
|
||||
|
||||
|
||||
class PrimarySelectionTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.catalog = Catalog()
|
||||
|
||||
def test_highest_level_locked_main_wins_across_rooms_and_incubation(self):
|
||||
main = monster(self.catalog, MAIN, level=20, lock=1, roomId=8)
|
||||
rows = [monster(self.catalog, MAIN + 1, "SSSA", feel=99),
|
||||
monster(self.catalog, MAIN + 2, "SSSS"), main,
|
||||
monster(self.catalog, MAIN + 3, "SSSS", level=99, process=2)]
|
||||
chosen = CultivationSelector(self.catalog).select(snapshot(*rows))
|
||||
self.assertEqual(chosen, {str(SPECIES): main})
|
||||
self.assertIs(chosen[str(SPECIES)], main)
|
||||
|
||||
def test_initial_selection_uses_level_then_feel_then_letter_grades(self):
|
||||
low = monster(self.catalog, 1, "SSSS", level=9, feel=100)
|
||||
no_feel = monster(self.catalog, 2, "SSSS")
|
||||
high_average = monster(self.catalog, 3, "AAAA", feel=1)
|
||||
more_s = monster(self.catalog, 4, "SCCC", feel=1)
|
||||
self.assertGreater(growth_score(self.catalog, high_average), growth_score(self.catalog, more_s))
|
||||
chosen = CultivationSelector(self.catalog).select(snapshot(low, no_feel, high_average, more_s))
|
||||
self.assertEqual(chosen[str(SPECIES)]["id"], 4)
|
||||
|
||||
def normalized_catalog(self):
|
||||
# Exact three-decimal values remove client rounding noise from equal-weight comparisons.
|
||||
self.catalog.overrides[str(SPECIES)] = {
|
||||
stat + suffix: value for stat, bounds in zip(STATS, ((1, 9), (10, 18), (100, 900), (2, 10)))
|
||||
for suffix, value in zip(("_grow_min", "_grow_max"), bounds)}
|
||||
|
||||
def test_rank_weights_all_four_attributes_equally_without_positional_ties(self):
|
||||
self.normalized_catalog()
|
||||
selector = CultivationSelector(self.catalog)
|
||||
ranks = [selector.rank(monster(self.catalog, index + 1, grades))
|
||||
for index, grades in enumerate(("SCCC", "CSCC", "CCSC", "CCCS"))]
|
||||
self.assertTrue(all(rank == ranks[0] for rank in ranks), ranks)
|
||||
qualities = [quality_rank(self.catalog, monster(self.catalog, 1, grades))
|
||||
for grades in ("SASS", "SSSA", "SSAS", "ASSS")]
|
||||
self.assertTrue(all(rank == qualities[0] for rank in qualities), qualities)
|
||||
|
||||
def test_normalized_growth_gives_health_the_same_weight_as_other_stats(self):
|
||||
self.normalized_catalog()
|
||||
scores = []
|
||||
for stat in STATS:
|
||||
mon = monster(self.catalog, 1, "AAAA")
|
||||
row = self.catalog.monster(SPECIES)
|
||||
mon["g" + stat.capitalize()] = row[stat + "_grow_max"]
|
||||
scores.append(growth_score(self.catalog, mon))
|
||||
self.assertEqual(scores, [.71875] * 4)
|
||||
|
||||
def test_equal_s_counts_compare_all_attributes_instead_of_a_count_first(self):
|
||||
self.normalized_catalog()
|
||||
balanced = monster(self.catalog, 1, "SSBB")
|
||||
weaker_average = monster(self.catalog, 2, "SSAC")
|
||||
row = self.catalog.monster(SPECIES)
|
||||
weaker_average["gDex"] = row["dex_grow_min"] + .1 * (row["dex_grow_max"] - row["dex_grow_min"])
|
||||
self.assertEqual(self.catalog.quality(balanced).count(4), self.catalog.quality(weaker_average).count(4))
|
||||
self.assertGreater(growth_score(self.catalog, balanced), growth_score(self.catalog, weaker_average))
|
||||
self.assertGreater(quality_rank(self.catalog, balanced), quality_rank(self.catalog, weaker_average))
|
||||
self.assertGreater(CultivationSelector(self.catalog).rank(balanced), CultivationSelector(self.catalog).rank(weaker_average))
|
||||
|
||||
def test_initial_exact_ties_always_choose_the_oldest_id(self):
|
||||
rows = [monster(self.catalog, mid) for mid in (9, 2, 7)]
|
||||
with patch("random.choice", side_effect=lambda members: max(members, key=lambda mon: mon["id"])):
|
||||
for ordered in (rows, list(reversed(rows)), rows[1:] + rows[:1]):
|
||||
self.assertEqual(CultivationSelector(self.catalog).select(snapshot(*ordered))[str(SPECIES)]["id"], 2)
|
||||
|
||||
def test_persisted_same_level_primary_cannot_be_stolen_by_better_newborn(self):
|
||||
main = monster(self.catalog, MAIN, "CCCC", level=1)
|
||||
data = snapshot(main)
|
||||
with TemporaryDirectory() as folder:
|
||||
path = Path(folder) / "cultivation_choices.json"
|
||||
selector = CultivationSelector(self.catalog, path)
|
||||
selector.select(data)
|
||||
newborn = monster(self.catalog, MAIN + 1, "SSSS", level=1)
|
||||
data.raw["monsters"] = [newborn, main]
|
||||
self.assertGreater(selector.rank(newborn), selector.rank(main))
|
||||
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], MAIN)
|
||||
self.assertEqual(CultivationSelector(self.catalog, path).select(data)[str(SPECIES)]["id"], MAIN)
|
||||
self.assertEqual(json.loads(path.read_text(encoding="utf-8"))["choices"], {str(SPECIES): MAIN})
|
||||
|
||||
def test_same_level_feel_change_does_not_replace_an_established_primary(self):
|
||||
main = monster(self.catalog, 9, "CCCC")
|
||||
data = snapshot(main)
|
||||
selector = CultivationSelector(self.catalog)
|
||||
selector.select(data)
|
||||
data.raw["monsters"] = [monster(self.catalog, 2, "SSSS", feel=99), main]
|
||||
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], 9)
|
||||
|
||||
def test_a_strictly_higher_level_mature_monster_can_take_over(self):
|
||||
main = monster(self.catalog, 1, "SSSS", feel=99)
|
||||
other = monster(self.catalog, 2, "CCCC", level=9)
|
||||
data = snapshot(main, other)
|
||||
selector = CultivationSelector(self.catalog)
|
||||
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], 1)
|
||||
other["level"] = 11
|
||||
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], 2)
|
||||
main["level"] = 11
|
||||
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], 2)
|
||||
|
||||
def test_cache_rebinds_to_current_cooldown_cap_and_task_flags(self):
|
||||
main = monster(self.catalog, 1)
|
||||
data = snapshot(main)
|
||||
selector = CultivationSelector(self.catalog)
|
||||
selector.select(data)
|
||||
fresh = Snapshot(deepcopy(data.raw))
|
||||
fresh.monsters[1].update(giftTime=NOW, entangleLevel=2, inExploreTeam=1)
|
||||
selected = selector.select(fresh)[str(SPECIES)]
|
||||
self.assertIs(selected, fresh.monsters[1])
|
||||
self.assertEqual((selected["giftTime"], selected["entangleLevel"], selected["inExploreTeam"]), (NOW, 2, 1))
|
||||
|
||||
def test_present_non_ranch_primary_never_promotes_a_backup(self):
|
||||
main = monster(self.catalog, 1, level=20)
|
||||
backup = monster(self.catalog, 2, "SSSS")
|
||||
data = snapshot(main, backup)
|
||||
with TemporaryDirectory() as folder:
|
||||
path = Path(folder) / "choices.json"
|
||||
selector = CultivationSelector(self.catalog, path)
|
||||
selector.select(data)
|
||||
for process in (4, 2):
|
||||
data.raw["monsters"] = [main | {"process": process}, backup]
|
||||
self.assertEqual(selector.select(data), {})
|
||||
self.assertEqual(CultivationSelector(self.catalog, path).select(data), {})
|
||||
data.raw["monsters"] = [backup, main]
|
||||
self.assertEqual(CultivationSelector(self.catalog, path).select(data)[str(SPECIES)]["id"], 1)
|
||||
|
||||
def test_confirmed_removal_promotes_one_replacement_and_persists_it(self):
|
||||
main = monster(self.catalog, 1, level=20)
|
||||
backup = monster(self.catalog, 2, "AAAA")
|
||||
data = snapshot(main, backup)
|
||||
with TemporaryDirectory() as folder:
|
||||
path = Path(folder) / "choices.json"
|
||||
selector = CultivationSelector(self.catalog, path)
|
||||
selector.select(data)
|
||||
data.raw["monsters"] = [main | {"process": 4}, backup]
|
||||
self.assertEqual(selector.select(data), {})
|
||||
data.raw["monsters"] = [backup]
|
||||
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], 2)
|
||||
data.raw["monsters"].insert(0, monster(self.catalog, 3, "SSSS"))
|
||||
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], 2)
|
||||
self.assertEqual(CultivationSelector(self.catalog, path).select(data)[str(SPECIES)]["id"], 2)
|
||||
|
||||
def test_empty_full_roster_clears_removed_choices_and_allows_a_new_first(self):
|
||||
data = snapshot(monster(self.catalog, 1))
|
||||
selector = CultivationSelector(self.catalog)
|
||||
selector.select(data)
|
||||
data.raw["monsters"] = []
|
||||
self.assertEqual(selector.select(data), {})
|
||||
self.assertEqual(selector.choices, {})
|
||||
data.raw["monsters"] = [monster(self.catalog, 2)]
|
||||
self.assertEqual(selector.select(data)[str(SPECIES)]["id"], 2)
|
||||
|
||||
def test_account_paths_and_owner_checks_isolate_prior_choices(self):
|
||||
with TemporaryDirectory() as folder:
|
||||
paths = [Path(folder) / account / "roles" / "101" / "choices.json" for account in ("a", "b")]
|
||||
first, second = monster(self.catalog, 1), monster(self.catalog, 2)
|
||||
for path, main in zip(paths, (first, second)):
|
||||
CultivationSelector(self.catalog, path).select(snapshot(main))
|
||||
for path, expected in zip(paths, (1, 2)):
|
||||
self.assertEqual(CultivationSelector(self.catalog, path).select(snapshot(second, first))[str(SPECIES)]["id"], expected)
|
||||
self.assertEqual(CultivationSelector(self.catalog, paths[1]).select(snapshot(second, first, owner=202))[str(SPECIES)]["id"], 1)
|
||||
|
||||
def test_unknown_quality_and_incubating_rows_are_not_mutated_or_promoted(self):
|
||||
main = monster(self.catalog, 1, level=20, gHp=None)
|
||||
young = monster(self.catalog, 3, "SSSS", level=99, process=2, mode=0)
|
||||
data = snapshot(monster(self.catalog, 2, "SSSS"), young, main)
|
||||
before = deepcopy(data.raw)
|
||||
self.assertIsNone(quality_rank(self.catalog, main))
|
||||
self.assertIsNone(quality_rank(self.catalog, young))
|
||||
self.assertEqual(CultivationSelector(self.catalog).select(data)[str(SPECIES)]["id"], 1)
|
||||
self.assertEqual(CultivationSelector(self.catalog).select(snapshot(young)), {})
|
||||
self.assertEqual(data.raw, before)
|
||||
|
||||
def test_species_variants_with_the_same_name_remain_separate_types(self):
|
||||
variants = [monster(self.catalog, index + 1, species=species)
|
||||
for index, species in enumerate((1030010, 1030012, 1030013, 1030014))]
|
||||
chosen = CultivationSelector(self.catalog).select(snapshot(*variants))
|
||||
self.assertEqual(set(chosen), {"1030010", "1030012", "1030013", "1030014"})
|
||||
|
||||
|
||||
class PrimaryGiftTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.catalog = Catalog()
|
||||
self.enterContext(patch("ranch_assistant.model.time.time", return_value=NOW))
|
||||
self.main = monster(self.catalog, MAIN, level=20, lock=1, roomId=8)
|
||||
self.backup = monster(self.catalog, MAIN + 1, "SSSS")
|
||||
self.equal_copy = monster(self.catalog, MAIN + 2, "SSSA")
|
||||
self.other = monster(self.catalog, 30, "AAAA", species=1002010, level=15)
|
||||
self.data = snapshot(self.backup, self.equal_copy, self.main, self.other)
|
||||
self.planner = GiftPlanner(self.catalog)
|
||||
|
||||
def action_ids(self, selected_policy):
|
||||
return [action.payload["monsterId"] for action in self.planner.plan(self.data, selected_policy)]
|
||||
|
||||
def test_only_checked_backups_never_authorize_the_unchecked_primary(self):
|
||||
selected_policy = policy(targets={str(self.backup["id"]): 1, str(self.equal_copy["id"]): 2})
|
||||
before = deepcopy(self.data.raw)
|
||||
self.assertEqual(self.planner.candidates(self.data, selected_policy), [])
|
||||
self.assertEqual(self.action_ids(selected_policy), [])
|
||||
self.assertEqual(self.data.raw, before)
|
||||
|
||||
def test_manual_mode_intersects_primaries_and_keeps_multi_species_priorities(self):
|
||||
selected_policy = policy(targets={str(self.backup["id"]): 1, str(self.other["id"]): 2,
|
||||
str(self.main["id"]): 3, str(self.equal_copy["id"]): 4})
|
||||
self.assertEqual([mon["id"] for mon in self.planner.candidates(self.data, selected_policy)], [30, MAIN])
|
||||
self.assertEqual(self.action_ids(selected_policy), [30, MAIN])
|
||||
|
||||
def test_auto_mode_selects_all_species_primaries_under_old_quality_flag(self):
|
||||
selected_policy = policy(auto=True, targets={str(self.backup["id"]): 1})
|
||||
self.assertFalse(selected_policy.keep_better_quality)
|
||||
self.assertEqual(self.action_ids(selected_policy), [MAIN, 30])
|
||||
|
||||
def test_full_cooling_or_busy_main_never_falls_back_in_either_mode(self):
|
||||
for auto in (False, True):
|
||||
for flags in ({"feel": self.catalog.max_feel(self.main)}, {"giftTime": NOW * 1000},
|
||||
{"inExploreTeam": 1}, {"inBuild": 1}):
|
||||
with self.subTest(auto=auto, flags=flags):
|
||||
main = self.main | flags
|
||||
self.data.raw["monsters"] = [self.backup, self.equal_copy, main, self.other]
|
||||
selected_policy = policy(auto=auto, targets={str(MAIN): 1, str(self.backup["id"]): 2, "30": 3})
|
||||
self.assertEqual(self.action_ids(selected_policy), [30])
|
||||
self.assertEqual(self.planner.cultivation.select(self.data)[str(SPECIES)]["id"], MAIN)
|
||||
|
||||
def test_active_exploration_team_without_an_individual_flag_has_no_backup_fallback(self):
|
||||
self.data.raw["exploreTeams"] = [{"id": 7, "status": 1, "monsters": str(MAIN)}]
|
||||
for auto in (False, True):
|
||||
with self.subTest(auto=auto):
|
||||
selected_policy = policy(auto=auto, targets={str(MAIN): 1, str(self.backup["id"]): 2, "30": 3})
|
||||
self.assertEqual(self.action_ids(selected_policy), [30])
|
||||
|
||||
def test_non_ranch_primary_stays_unselected_after_it_was_chosen(self):
|
||||
selected_policy = policy(auto=True)
|
||||
self.assertEqual(self.action_ids(selected_policy), [MAIN, 30])
|
||||
for process in (4, 2):
|
||||
self.data.raw["monsters"] = [self.backup, self.main | {"process": process}, self.other]
|
||||
self.assertEqual(self.action_ids(selected_policy), [30])
|
||||
|
||||
def test_removed_primary_does_not_authorize_an_unchecked_replacement_in_manual_mode(self):
|
||||
selected_policy = policy(targets={str(MAIN): 1})
|
||||
self.assertEqual(self.action_ids(selected_policy), [MAIN])
|
||||
self.data.raw["monsters"] = [self.backup, self.other]
|
||||
self.assertEqual(self.action_ids(selected_policy), [])
|
||||
self.assertEqual(self.planner.cultivation.select(self.data)[str(SPECIES)]["id"], self.backup["id"])
|
||||
|
||||
def test_earliest_due_only_uses_eligible_primaries_and_ignores_backups(self):
|
||||
self.main["giftTime"] = (NOW - 7200 + 120) * 1000
|
||||
self.backup["giftTime"] = (NOW - 7200 + 15) * 1000
|
||||
self.other["giftTime"] = (NOW - 7200 + 60) * 1000
|
||||
selected_policy = policy(targets={str(MAIN): 1, str(self.backup["id"]): 2, "30": 3})
|
||||
self.assertEqual(self.action_ids(selected_policy), [])
|
||||
self.assertEqual(self.planner.next_ready_at, NOW + 60)
|
||||
self.other["feel"] = self.catalog.max_feel(self.other)
|
||||
self.assertEqual(self.action_ids(selected_policy), [])
|
||||
self.assertEqual(self.planner.next_ready_at, NOW + 120)
|
||||
self.main["feel"] = self.catalog.max_feel(self.main)
|
||||
self.assertEqual(self.action_ids(selected_policy), [])
|
||||
self.assertIsNone(self.planner.next_ready_at)
|
||||
|
||||
def test_stock_reserves_and_item_locks_still_block_all_species(self):
|
||||
selected_policy = policy(auto=True)
|
||||
self.data.raw["items"][0]["num"] = 2
|
||||
self.assertEqual(self.action_ids(selected_policy), [])
|
||||
self.data.raw["items"][0]["num"] = 10
|
||||
self.data.raw["items"][0]["feedLock"] = 1
|
||||
self.assertEqual(self.action_ids(selected_policy), [])
|
||||
self.data.raw["items"][0]["feedLock"] = 0
|
||||
self.assertEqual(self.action_ids(selected_policy), [MAIN, 30])
|
||||
self.assertTrue(all(action.payload["itemId"] == 91 for action in self.planner.plan(self.data, selected_policy)))
|
||||
|
||||
def test_current_confirmed_cooldown_prevents_gifts_to_same_species_copies(self):
|
||||
selected_policy = policy(targets={str(MAIN): 1, str(self.backup["id"]): 2})
|
||||
action = self.planner.plan(self.data, selected_policy)[0]
|
||||
self.planner.remember_success(self.data, action, {"feel": 10, "giftDate": NOW * 1000})
|
||||
stale = Snapshot(deepcopy(self.data.raw))
|
||||
self.planner.apply_confirmed(stale)
|
||||
self.assertEqual(self.planner.plan(stale, selected_policy), [])
|
||||
self.assertEqual(stale.monsters[self.backup["id"]]["giftTime"], 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,437 @@
|
||||
"""Offline integration: only the current primary may receive automatic resources."""
|
||||
from copy import deepcopy
|
||||
from dataclasses import asdict, replace
|
||||
import json
|
||||
from pathlib import Path
|
||||
from tempfile import TemporaryDirectory
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from ranch_assistant.breakthrough import PATH, POTENTIAL_PATH
|
||||
from ranch_assistant.engine import Engine
|
||||
from ranch_assistant.model import Action, Catalog, Policy, Snapshot
|
||||
from ranch_web.policies import default_config, export_config
|
||||
from ranch_web.views import build_view, schema
|
||||
|
||||
|
||||
SPECIES = 1001010
|
||||
MAIN, BACKUP, EXTRA = 900, 901, 902
|
||||
FEED = "monsterService/monsterIntensify"
|
||||
GIFT = "monsterService/monsterSendGift"
|
||||
RECIPIENT_KEYS = {"feed": "targetId", "gift": "monsterId", "potential": "monId", "breakthrough": "monId"}
|
||||
|
||||
|
||||
def monster(catalog, mid, *, level=1, quality=0, **values):
|
||||
species = values.get("typeId", SPECIES)
|
||||
info = catalog.monster(species)
|
||||
mon = {"id": mid, "typeId": species, "process": 3, "mode": 2, "level": level,
|
||||
"potentialLevel": 1, "pAtk": 3, "pDef": 8, "pHp": 105, "pDex": 1,
|
||||
"feel": 0, "giftTime": 0, "exp": 0, "tpLevel": 0, "tpExp": 0, "roomId": 1, "lock": 0}
|
||||
for stat in ("atk", "def", "hp", "dex"):
|
||||
low, high = info[stat + "_grow_min"], info[stat + "_grow_max"]
|
||||
mon["g" + stat.capitalize()] = low + quality * (high - low)
|
||||
return mon | values
|
||||
|
||||
|
||||
class OfflineClient:
|
||||
"""In-memory server with a recorded write/read boundary; never opens a socket."""
|
||||
def __init__(self, catalog, *, complete=False):
|
||||
self.raw = {"master": {"id": 1, "level": 30, "ti": 100, "money": 0, "ke": 0},
|
||||
"monsters": [monster(catalog, MAIN, level=9, lock=1, pAtk=4 if complete else 3),
|
||||
monster(catalog, BACKUP, quality=1), monster(catalog, EXTRA, level=2)],
|
||||
"items": [{"id": 600, "typeId": 30058, "num": 100}, {"id": 601, "typeId": 30005, "num": 10}],
|
||||
"rooms": [{"id": 1, "typeId": 1000}], "teams": [], "stacks": [],
|
||||
"currentTasks": [], "history": {}, "activityHistory": {}, "exploreTeams": []}
|
||||
self.calls, self.events = [], []
|
||||
self.apply_writes = True
|
||||
|
||||
def snapshot(self):
|
||||
self.events.append("snapshot")
|
||||
return Snapshot(deepcopy(self.raw))
|
||||
|
||||
def call(self, path, payload):
|
||||
self.calls.append((path, deepcopy(payload)))
|
||||
self.events.append(path)
|
||||
if not self.apply_writes:
|
||||
return {"resCode": 0}
|
||||
monsters = {int(mon["id"]): mon for mon in self.raw["monsters"]}
|
||||
if path == POTENTIAL_PATH:
|
||||
mon = monsters[payload["monId"]]
|
||||
mon["p" + payload["monsterAttr"].capitalize()] += 1
|
||||
elif path == PATH:
|
||||
monsters[payload["monId"]]["potentialLevel"] += 1
|
||||
elif path == GIFT:
|
||||
mon = monsters[payload["monsterId"]]
|
||||
mon.update(feel=mon["feel"] + 10, giftTime=int(time.time()) * 1000)
|
||||
return {"feel": mon["feel"], "giftDate": mon["giftTime"], "resCode": 0}
|
||||
elif path in (FEED, "monsterService/monsterSell"):
|
||||
consumed = set(payload["foods"] if path == FEED else payload["monsterIds"])
|
||||
self.raw["monsters"] = [mon for mon in self.raw["monsters"] if mon["id"] not in consumed]
|
||||
else:
|
||||
raise AssertionError("Unexpected offline write: " + path)
|
||||
return {"resCode": 0}
|
||||
|
||||
|
||||
class PrimaryResourceAdmissionTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.catalog = Catalog()
|
||||
|
||||
def engine(self, *, complete=False):
|
||||
temporary = TemporaryDirectory(prefix="primary-admission-")
|
||||
self.addCleanup(temporary.cleanup)
|
||||
client = OfflineClient(self.catalog, complete=complete)
|
||||
engine = Engine(self.catalog, client, Path(temporary.name) / "budget.json")
|
||||
engine.master_sync.settle = lambda *args: None
|
||||
engine.settle_pending_growth = lambda *args, **kwargs: False
|
||||
engine.policy = Policy(fill=False, collect=False, dispatch=False, feed=False,
|
||||
manual_eggs=True, protect_star=6, protect_quality=5, keep_better_quality=False,
|
||||
gift_auto_representative=False,
|
||||
egg_rules={str(SPECIES): {"enabled": True, "action": "feed", "keep_count": 0}})
|
||||
engine.snapshot = client.snapshot()
|
||||
engine.auto = True
|
||||
return engine, client
|
||||
|
||||
def action(self, kind, recipient):
|
||||
payload = {RECIPIENT_KEYS[kind]: recipient}
|
||||
if kind == "feed":
|
||||
payload["foods"] = [EXTRA]
|
||||
elif kind == "gift":
|
||||
payload["itemId"] = 601
|
||||
elif kind == "potential":
|
||||
payload.update(itemId=600, monsterAttr="atk", traceInfo={"itemTypeId": 600, "itemNum": 100})
|
||||
else:
|
||||
payload["itemIds"] = [600]
|
||||
return Action(kind, "offline " + kind, {"feed": FEED, "gift": GIFT, "potential": POTENTIAL_PATH, "breakthrough": PATH}[kind], payload)
|
||||
|
||||
def config(self, engine):
|
||||
config = default_config()
|
||||
config["policy"] = asdict(engine.policy)
|
||||
return config
|
||||
|
||||
def test_stale_breakthrough_targets_never_spend_or_enable_the_unchecked_primary(self):
|
||||
for complete in (False, True):
|
||||
for fast in (False, True):
|
||||
with self.subTest(complete=complete, fast=fast):
|
||||
engine, client = self.engine(complete=complete)
|
||||
engine.policy.breakthrough_targets = {str(BACKUP): 1}
|
||||
before = asdict(engine.policy)
|
||||
_, plans, message = engine.poll_automation("breakthrough") if fast else engine.poll()
|
||||
self.assertEqual(client.calls, [])
|
||||
self.assertFalse(any(action.kind in ("potential", "breakthrough") for action in plans))
|
||||
self.assertIn("非主培养", message)
|
||||
self.assertIn("#900", message)
|
||||
self.assertEqual(asdict(engine.policy), before)
|
||||
self.assertIsNone(engine._breakthrough_pending)
|
||||
self.assertFalse(engine.last_executed)
|
||||
|
||||
def test_stale_priority_cannot_bypass_primary_admission_on_either_scheduler(self):
|
||||
for complete in (False, True):
|
||||
for fast in (False, True):
|
||||
with self.subTest(complete=complete, fast=fast):
|
||||
engine, client = self.engine(complete=complete)
|
||||
engine.policy.breakthrough_targets = {str(BACKUP): 1, str(MAIN): 2}
|
||||
before = asdict(engine.policy)
|
||||
engine.poll_automation("breakthrough") if fast else engine.poll()
|
||||
self.assertEqual(client.calls, [(PATH if complete else POTENTIAL_PATH,
|
||||
{"monId": MAIN, "itemIds": [600]} if complete else
|
||||
{"monId": MAIN, "itemId": 600, "monsterAttr": "atk", "traceInfo": {"itemTypeId": 600, "itemNum": 100}})])
|
||||
self.assertEqual(client.events[-1], "snapshot")
|
||||
self.assertIsNone(engine._breakthrough_pending)
|
||||
self.assertEqual(asdict(engine.policy), before)
|
||||
|
||||
def test_engine_filters_stale_actions_even_if_a_source_planner_returns_them(self):
|
||||
for kind in RECIPIENT_KEYS:
|
||||
with self.subTest(kind=kind):
|
||||
engine, client = self.engine()
|
||||
source = engine.planner if kind == "feed" else engine.gift_planner if kind == "gift" else engine.breakthrough_planner
|
||||
stale = self.action(kind, BACKUP)
|
||||
if kind in ("potential", "breakthrough"):
|
||||
engine.policy.breakthrough_targets = {str(BACKUP): 1}
|
||||
with patch.object(source, "plan", return_value=stale if kind in ("potential", "breakthrough") else [stale]):
|
||||
_, plans, message = engine.poll()
|
||||
self.assertFalse(any(action.kind == kind for action in plans))
|
||||
self.assertEqual(client.calls, [])
|
||||
self.assertIn("非主培养", message)
|
||||
|
||||
def test_current_recipient_is_checked_after_planning_on_both_dispatch_paths(self):
|
||||
for kind in RECIPIENT_KEYS:
|
||||
for fast in (False, True):
|
||||
if fast and kind == "feed":
|
||||
continue
|
||||
with self.subTest(kind=kind, fast=fast):
|
||||
engine, client = self.engine()
|
||||
engine.cultivation.select(engine.snapshot)
|
||||
action = self.action(kind, MAIN)
|
||||
def stale_plan():
|
||||
# A newer roster makes the queued recipient a duplicate.
|
||||
engine.snapshot.monsters[BACKUP]["level"] = 30
|
||||
return [action]
|
||||
with patch.object(engine, "plans", side_effect=stale_plan):
|
||||
_, _, message = engine.poll_automation("gift" if kind == "gift" else "breakthrough") if fast else engine.poll()
|
||||
self.assertEqual(client.calls, [])
|
||||
self.assertIn("非主培养", message)
|
||||
self.assertFalse(engine.last_executed)
|
||||
self.assertIsNone(engine._breakthrough_pending)
|
||||
self.assertEqual(engine.gift_planner.confirmed, {})
|
||||
|
||||
def test_busy_primary_blocks_real_resource_plans_without_falling_back(self):
|
||||
for busy in ("team_list", "team_string", "inExploreTeam", "inBuild", "sysLock"):
|
||||
for complete in (False, True):
|
||||
for scheduler in ("poll", "gift", "breakthrough"):
|
||||
with self.subTest(busy=busy, complete=complete, scheduler=scheduler):
|
||||
engine, client = self.engine(complete=complete)
|
||||
client.raw["monsters"][0] = monster(self.catalog, MAIN, level=9, quality=.5,
|
||||
lock=1, pAtk=4 if complete else 3)
|
||||
client.raw["monsters"][2] = monster(self.catalog, EXTRA, level=2, quality=.125)
|
||||
if busy.startswith("team_"):
|
||||
# Authoritative team membership can arrive without the per-monster marker.
|
||||
client.raw["exploreTeams"] = [{"id": 77, "status": 1,
|
||||
"monsters": [MAIN] if busy == "team_list" else str(MAIN)}]
|
||||
else:
|
||||
client.raw["monsters"][0][busy] = 1
|
||||
targets = {str(MAIN): 1, str(BACKUP): 2}
|
||||
engine.policy = replace(engine.policy, feed=True, feed_targets=targets,
|
||||
gift_enabled=True, gift_targets=targets, gift_liked_only=False,
|
||||
gift_items={"30005": {"enabled": True, "reserve": 0}}, breakthrough_targets=targets)
|
||||
engine.planner.managed.add(EXTRA)
|
||||
before = asdict(engine.policy)
|
||||
_, plans, _ = engine.poll() if scheduler == "poll" else engine.poll_automation(scheduler)
|
||||
self.assertEqual(client.calls, [])
|
||||
self.assertFalse(any(action.kind in RECIPIENT_KEYS for action in plans))
|
||||
self.assertEqual(engine.cultivation.select(engine.snapshot)[str(SPECIES)]["id"], MAIN)
|
||||
self.assertEqual(asdict(engine.policy), before)
|
||||
self.assertIsNone(engine._breakthrough_pending)
|
||||
|
||||
def test_exploration_becoming_active_after_planning_blocks_queued_resources(self):
|
||||
for kind in RECIPIENT_KEYS:
|
||||
for fast in (False, True):
|
||||
if fast and kind == "feed":
|
||||
continue
|
||||
with self.subTest(kind=kind, fast=fast):
|
||||
engine, client = self.engine()
|
||||
action = self.action(kind, MAIN)
|
||||
def busy_plan():
|
||||
engine.snapshot.raw["exploreTeams"] = [{"id": 77, "status": 1, "monsters": str(MAIN)}]
|
||||
return [action]
|
||||
with patch.object(engine, "plans", side_effect=busy_plan):
|
||||
_, _, message = engine.poll_automation("gift" if kind == "gift" else "breakthrough") if fast else engine.poll()
|
||||
self.assertEqual(client.calls, [])
|
||||
self.assertIn("正在探险", message)
|
||||
self.assertFalse(engine.last_executed)
|
||||
self.assertIsNone(engine._breakthrough_pending)
|
||||
|
||||
def test_material_recipient_is_rechecked_after_unsent_intent_is_persisted(self):
|
||||
engine, client = self.engine()
|
||||
action = self.action("potential", MAIN)
|
||||
save = engine._save_automation_state
|
||||
def newer_roster_after_save():
|
||||
save()
|
||||
engine.snapshot.monsters[BACKUP]["level"] = 30
|
||||
with patch.object(engine, "_save_automation_state", side_effect=newer_roster_after_save):
|
||||
_, _, message = engine._execute_breakthrough(action)
|
||||
self.assertEqual(client.calls, [])
|
||||
self.assertIn("非主培养", message)
|
||||
self.assertIsNone(engine._breakthrough_pending)
|
||||
self.assertIsNone(json.loads(engine.automation_state_path.read_text(encoding="utf-8"))["breakthrough"])
|
||||
self.assertFalse(engine.last_executed)
|
||||
|
||||
def test_existing_pending_evidence_survives_loss_of_primary_and_restart(self):
|
||||
for complete in (False, True):
|
||||
with self.subTest(complete=complete):
|
||||
engine, client = self.engine(complete=complete)
|
||||
client.apply_writes = False
|
||||
engine.policy.breakthrough_targets = {str(MAIN): 1}
|
||||
engine.poll_automation("breakthrough")
|
||||
pending = deepcopy(engine._breakthrough_pending)
|
||||
self.assertIsNotNone(pending)
|
||||
client.raw["monsters"][1]["level"] = 30
|
||||
engine.poll_automation("breakthrough")
|
||||
self.assertEqual(engine._breakthrough_pending, pending)
|
||||
self.assertEqual(len(client.calls), 1)
|
||||
self.assertEqual(json.loads(engine.automation_state_path.read_text(encoding="utf-8"))["breakthrough"], pending)
|
||||
restored = Engine(self.catalog, client, engine.automation_state_path.parent / "budget.json")
|
||||
restored.master_sync.settle = lambda *args: None
|
||||
restored.policy, restored.auto = engine.policy, True
|
||||
restored.poll_automation("breakthrough")
|
||||
self.assertEqual(restored._breakthrough_pending["payload"], pending["payload"])
|
||||
self.assertEqual(len(client.calls), 1)
|
||||
# Confirmation belongs to the original recipient, even now a backup.
|
||||
original = client.raw["monsters"][0]
|
||||
original["potentialLevel" if complete else "pAtk"] += 1
|
||||
restored.poll_automation("breakthrough")
|
||||
self.assertIsNone(restored._breakthrough_pending)
|
||||
self.assertEqual(len(client.calls), 1)
|
||||
|
||||
def test_preexisting_pending_record_is_not_discarded_when_rejecting_a_new_target(self):
|
||||
engine, client = self.engine()
|
||||
pending = {"kind": "invalid", "role_id": "1", "uncertain": True, "message": "retain evidence"}
|
||||
engine._breakthrough_pending = deepcopy(pending)
|
||||
engine._save_automation_state()
|
||||
persisted = engine.automation_state_path.read_bytes()
|
||||
engine._execute_breakthrough(self.action("potential", BACKUP))
|
||||
self.assertEqual(engine._breakthrough_pending, pending)
|
||||
self.assertEqual(engine.automation_state_path.read_bytes(), persisted)
|
||||
self.assertEqual(client.calls, [])
|
||||
|
||||
def test_actual_gift_dispatch_uses_only_checked_primary_without_enabling_it(self):
|
||||
for fast in (False, True):
|
||||
for include_primary in (False, True):
|
||||
with self.subTest(fast=fast, include_primary=include_primary):
|
||||
engine, client = self.engine()
|
||||
targets = {str(BACKUP): 1} | ({str(MAIN): 2} if include_primary else {})
|
||||
engine.policy = replace(engine.policy, gift_enabled=True, gift_targets=targets,
|
||||
gift_liked_only=False, gift_items={"30005": {"enabled": True, "reserve": 0}})
|
||||
before = asdict(engine.policy)
|
||||
_, _, message = engine.poll_automation("gift") if fast else engine.poll()
|
||||
self.assertEqual([payload["monsterId"] for path, payload in client.calls if path == GIFT],
|
||||
[MAIN] if include_primary else [])
|
||||
if not include_primary:
|
||||
self.assertIn("非主培养", message)
|
||||
self.assertEqual(asdict(engine.policy), before)
|
||||
|
||||
def test_actual_feeding_dispatches_only_the_primary_with_legacy_flags_off(self):
|
||||
for explicit in (False, True):
|
||||
with self.subTest(explicit=explicit):
|
||||
engine, client = self.engine()
|
||||
# Equal-quality extras are dispatched; this case exercises feeding inferior material.
|
||||
client.raw["monsters"][0] = monster(self.catalog, MAIN, level=9, quality=.5, lock=1)
|
||||
client.raw["monsters"][2] = monster(self.catalog, EXTRA, level=2, quality=.125)
|
||||
engine.policy = replace(engine.policy, feed=True, gift_auto_representative=True,
|
||||
feed_targets={str(BACKUP): 1, str(MAIN): 2} if explicit else {})
|
||||
engine.planner.managed.add(EXTRA)
|
||||
before = asdict(engine.policy)
|
||||
engine.poll()
|
||||
self.assertEqual(client.calls, [(FEED, {"targetId": MAIN, "foods": [EXTRA]})])
|
||||
self.assertEqual(set(engine.snapshot.monsters), {MAIN, BACKUP})
|
||||
self.assertEqual(client.events[-1], "snapshot")
|
||||
self.assertEqual(asdict(engine.policy), before)
|
||||
|
||||
def test_full_primary_and_stale_explicit_selection_cannot_feed_a_backup(self):
|
||||
for explicit in (False, True):
|
||||
with self.subTest(explicit=explicit):
|
||||
engine, client = self.engine()
|
||||
engine.policy = replace(engine.policy, feed=True, gift_auto_representative=True,
|
||||
feed_targets={str(BACKUP): 1} if explicit else {})
|
||||
if not explicit:
|
||||
main = client.raw["monsters"][0]
|
||||
main.update(level=self.catalog.max_level(main), tpLevel=4,
|
||||
tpExp=engine.planner.tp_thresholds(main)[4])
|
||||
engine.planner.managed.add(EXTRA)
|
||||
before = asdict(engine.policy)
|
||||
engine.poll()
|
||||
self.assertEqual(client.calls, [])
|
||||
self.assertEqual(set(engine.snapshot.monsters), {MAIN, BACKUP, EXTRA})
|
||||
self.assertEqual(asdict(engine.policy), before)
|
||||
|
||||
def test_manual_explicit_feed_can_still_target_a_backup(self):
|
||||
engine, client = self.engine()
|
||||
engine.manage_monsters("feed", [EXTRA], BACKUP)
|
||||
self.assertEqual(client.calls, [(FEED, {"targetId": BACKUP, "foods": [EXTRA]})])
|
||||
self.assertNotIn(EXTRA, engine.snapshot.monsters)
|
||||
self.assertFalse(engine.auto)
|
||||
|
||||
def test_web_roles_disable_stale_selections_but_preserve_config_and_manual_targets(self):
|
||||
engine, client = self.engine()
|
||||
engine.policy = replace(engine.policy, feed_targets={str(BACKUP): 1},
|
||||
gift_targets={str(BACKUP): 2}, breakthrough_targets={str(BACKUP): 3})
|
||||
before = asdict(engine.policy)
|
||||
config = self.config(engine)
|
||||
config_before = deepcopy(config)
|
||||
dto = build_view(engine, "ranch", config)
|
||||
rows = {row["id"]: row for row in dto["rows"]}
|
||||
self.assertEqual([rows[str(mid)]["cultivation_role_key"] for mid in (MAIN, BACKUP, EXTRA)],
|
||||
["primary", "backup", "duplicate"])
|
||||
for prefix in ("feed", "gift", "breakthrough"):
|
||||
self.assertTrue(rows[str(BACKUP)][prefix + "_selected"])
|
||||
self.assertFalse(rows[str(MAIN)][prefix + "_selected"])
|
||||
for mid in (BACKUP, EXTRA):
|
||||
edit = rows[str(mid)]["edits"][prefix + "_selected"]
|
||||
self.assertTrue(edit["disabled"])
|
||||
self.assertIn("#900", edit["reason"])
|
||||
self.assertFalse(rows[str(MAIN)]["edits"][prefix + "_selected"]["disabled"])
|
||||
self.assertIn(BACKUP, [option["value"] for option in dto["feed_targets"]])
|
||||
self.assertEqual(asdict(engine.policy), before)
|
||||
self.assertEqual(config, config_before)
|
||||
self.assertEqual(client.calls, [])
|
||||
|
||||
def test_web_retention_is_fixed_and_legacy_values_round_trip_without_a_toggle(self):
|
||||
for stored in (0, 1, 8):
|
||||
with self.subTest(stored=stored):
|
||||
engine, client = self.engine()
|
||||
engine.policy.egg_rules[str(SPECIES)]["keep_count"] = stored
|
||||
config = self.config(engine)
|
||||
before = deepcopy(config)
|
||||
dto = build_view(engine, "bag", config, {"category": "eggs"})
|
||||
row = next(row for row in dto["rows"] if row["id"] == str(SPECIES))
|
||||
column = next(column for column in dto["columns"] if column["key"] == "retention_text")
|
||||
self.assertEqual(row["retention_text"], "主培养1 + 更优备选≤1")
|
||||
self.assertFalse(column.get("edit"))
|
||||
self.assertFalse(any(column["key"] == "keep_count" and column.get("edit") for column in dto["columns"]))
|
||||
fields = [field for page in schema(self.catalog)["pages"] for field in page["form"]]
|
||||
self.assertFalse(any(field["path"] == ["policy", "keep_better_quality"] for field in fields))
|
||||
self.assertEqual(export_config(config, engine.snapshot)["policy"]["egg_rules"][str(SPECIES)]["keep_count"], stored)
|
||||
self.assertEqual(config, before)
|
||||
self.assertEqual(client.calls, [])
|
||||
|
||||
def test_busy_primary_keeps_its_web_role_while_automatic_controls_are_disabled(self):
|
||||
engine, client = self.engine()
|
||||
client.raw["exploreTeams"] = [{"id": 77, "status": 1, "monsters": str(MAIN)}]
|
||||
engine.snapshot = client.snapshot()
|
||||
engine.policy = replace(engine.policy, feed_targets={str(MAIN): 1},
|
||||
gift_targets={str(MAIN): 1}, breakthrough_targets={str(MAIN): 1})
|
||||
rows = {int(row["id"]): row for row in build_view(engine, "ranch", self.config(engine))["rows"]}
|
||||
self.assertEqual(rows[MAIN]["cultivation_role_key"], "primary")
|
||||
self.assertEqual(rows[MAIN]["cultivation_role"], "主培养")
|
||||
self.assertEqual(rows[MAIN]["primary_id"], MAIN)
|
||||
self.assertFalse(rows[MAIN]["automatic_eligible"])
|
||||
self.assertIn("正在探险", rows[MAIN]["automatic_reason"])
|
||||
self.assertEqual(rows[BACKUP]["cultivation_role_key"], "backup")
|
||||
for prefix in ("feed", "gift", "breakthrough"):
|
||||
self.assertTrue(rows[MAIN][prefix + "_selected"])
|
||||
self.assertTrue(rows[MAIN]["edits"][prefix + "_selected"]["disabled"])
|
||||
self.assertEqual(client.calls, [])
|
||||
|
||||
def test_web_existing_extras_report_protection_and_dispatch_off_without_managed_history(self):
|
||||
engine, client = self.engine()
|
||||
client.raw["monsters"] += [monster(self.catalog, 903, lock=1), monster(self.catalog, 904, equip1=123),
|
||||
monster(self.catalog, 905, typeId=1030010)]
|
||||
engine.snapshot = client.snapshot()
|
||||
self.assertEqual(engine.planner.managed, set())
|
||||
rows = {int(row["id"]): row for row in build_view(engine, "ranch", self.config(engine))["rows"]}
|
||||
self.assertIn("自动派遣", rows[EXTRA]["scope"])
|
||||
self.assertIn("关闭", rows[EXTRA]["scope"])
|
||||
self.assertNotIn("已有:不自动处理", rows[EXTRA]["scope"])
|
||||
self.assertIn("已锁定", rows[903]["scope"])
|
||||
self.assertIn("携带装备", rows[904]["scope"])
|
||||
self.assertIn("规则未启用", rows[905]["scope"])
|
||||
self.assertEqual(client.calls, [])
|
||||
|
||||
def test_web_uses_the_retention_planners_reserve_when_replacement_is_still_incubating(self):
|
||||
engine, client = self.engine()
|
||||
client.raw["monsters"][1] = monster(self.catalog, BACKUP, quality=.5)
|
||||
client.raw["monsters"].append(monster(self.catalog, 903, quality=1, process=2))
|
||||
engine.snapshot = client.snapshot()
|
||||
rows = {int(row["id"]): row for row in build_view(engine, "ranch", self.config(engine))["rows"]}
|
||||
self.assertEqual(rows[BACKUP]["cultivation_role_key"], "duplicate")
|
||||
self.assertEqual(rows[903]["cultivation_role_key"], "backup")
|
||||
self.assertIn("待收取", rows[903]["cultivation_role"])
|
||||
self.assertFalse(rows[903]["automatic_eligible"])
|
||||
self.assertTrue(rows[903]["edits"]["feed_selected"]["disabled"])
|
||||
self.assertEqual(client.calls, [])
|
||||
|
||||
def test_same_name_variants_have_independent_primary_admission_and_web_roles(self):
|
||||
engine, client = self.engine()
|
||||
for mid, species in enumerate((1030010, 1030012, 1030013, 1030014), 1000):
|
||||
client.raw["monsters"].append(monster(self.catalog, mid, typeId=species, level=1))
|
||||
engine.snapshot = client.snapshot()
|
||||
rows = {int(row["id"]): row for row in build_view(engine, "ranch", self.config(engine))["rows"]}
|
||||
for mid in range(1000, 1004):
|
||||
self.assertEqual(rows[mid]["cultivation_role_key"], "primary")
|
||||
self.assertTrue(rows[mid]["automatic_eligible"])
|
||||
self.assertEqual(client.calls, [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,6 +1,8 @@
|
||||
import copy
|
||||
import json
|
||||
import time
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from ranch_assistant.breakthrough import POTENTIAL_PATH
|
||||
from ranch_assistant.engine import Engine
|
||||
@@ -20,6 +22,17 @@ def raw(catalog):
|
||||
return value
|
||||
|
||||
|
||||
def species_monster(catalog, mid, grades, *, level=10, species=1030010, **values):
|
||||
row = catalog.monster(species)
|
||||
mon = {"id": mid, "typeId": species, "process": 3, "mode": 2, "level": level,
|
||||
"exp": 0, "potentialLevel": 2, "tpLevel": 4, "tpExp": 9999,
|
||||
"feel": 0, "giftTime": 0, "entangleLevel": 0, "lock": 0, "roomId": 1}
|
||||
for stat, grade in zip(("atk", "def", "hp", "dex"), grades):
|
||||
low, high = row[stat + "_grow_min"], row[stat + "_grow_max"]
|
||||
mon["g" + stat.capitalize()] = low + (high - low) * {"C": .1, "B": .375, "A": .625, "S": .9}[grade]
|
||||
return mon | values
|
||||
|
||||
|
||||
class FakeClient:
|
||||
def __init__(self, value):
|
||||
self.value, self.calls = value, []
|
||||
@@ -35,18 +48,170 @@ class FakeClient:
|
||||
return copy.deepcopy(self.response)
|
||||
|
||||
|
||||
class StatefulRanchClient(FakeClient):
|
||||
def call(self, path, payload):
|
||||
super().call(path, copy.deepcopy(payload))
|
||||
monsters = {int(mon["id"]): mon for mon in self.value["monsters"]}
|
||||
removed = []
|
||||
if path == "monsterService/monsterSell":
|
||||
removed = payload["monsterIds"]
|
||||
elif path == "stackService/stackTransferMonster":
|
||||
for data in payload["datas"]:
|
||||
for mid in data["monsterId"]:
|
||||
monsters[mid].update(process=3, roomId=data["roomId"])
|
||||
for stack in self.value["stacks"]:
|
||||
if stack.get("monsterId") == mid:
|
||||
stack["monsterId"] = 0
|
||||
elif path == "monsterService/monsterIntensify":
|
||||
removed = payload["foods"]
|
||||
elif path == "monsterService/monsterSendGift":
|
||||
mon = monsters[payload["monsterId"]]
|
||||
mon.update(feel=int(mon.get("feel") or 0) + 1, giftTime=int(time.time() * 1000))
|
||||
return {"feel": mon["feel"], "giftDate": mon["giftTime"]}
|
||||
elif path == POTENTIAL_PATH:
|
||||
mon = monsters[payload["monId"]]
|
||||
stat = "p" + payload["monsterAttr"].capitalize()
|
||||
mon[stat] += 1
|
||||
else:
|
||||
raise AssertionError(f"Unexpected offline ranch operation: {path}")
|
||||
self.value["monsters"] = [mon for mon in self.value["monsters"] if mon["id"] not in removed]
|
||||
for stack in self.value["stacks"]:
|
||||
if stack.get("monsterId") in removed:
|
||||
stack["monsterId"] = 0
|
||||
return {"resCode": 0}
|
||||
|
||||
|
||||
class RanchAutomationIntegrationTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.catalog = Catalog()
|
||||
|
||||
def engine(self, folder, value=None):
|
||||
client = FakeClient(value or raw(self.catalog))
|
||||
def engine(self, folder, value=None, client_type=FakeClient):
|
||||
client = client_type(value or raw(self.catalog))
|
||||
engine = Engine(self.catalog, client, folder / "budget.json")
|
||||
engine.master_sync.settle = lambda *args: None
|
||||
engine.settle_pending_growth = lambda *args, **kwargs: False
|
||||
return engine, client
|
||||
|
||||
def test_screenshot_lv20_sass_primary_never_spends_on_four_lesser_duplicates(self):
|
||||
primary = species_monster(self.catalog, 900, "SASS", level=20,
|
||||
pAtk=44, pDef=10, pHp=180, pDex=9)
|
||||
primary["feel"] = self.catalog.max_feel(primary)
|
||||
duplicates = [species_monster(self.catalog, 901 + index, grades, level=9 + index % 2,
|
||||
tpLevel=0, tpExp=0, pAtk=1, pDef=1, pHp=1, pDex=1)
|
||||
for index, grades in enumerate(("SAAA", "ASAS", "AASS", "AAAS"))]
|
||||
duplicate_ids = {mon["id"] for mon in duplicates}
|
||||
cases = [({}, False, {}), ({"900": 1, "901": 2, "902": 3, "903": 4, "904": 5}, False, {}),
|
||||
({}, True, {}), ({}, False, {"901": 1})]
|
||||
for feed_targets, manual_gifts, potential_targets in cases:
|
||||
with self.subTest(feed_targets=feed_targets, manual_gifts=manual_gifts, potential_targets=potential_targets):
|
||||
with workspace_temp() as folder:
|
||||
value = raw(self.catalog)
|
||||
value.update(monsters=copy.deepcopy([primary, *duplicates]),
|
||||
items=[{"id": 600, "typeId": 30058, "num": 100},
|
||||
{"id": 601, "typeId": 30005, "num": 10}])
|
||||
engine, client = self.engine(folder, value, StatefulRanchClient)
|
||||
engine.policy = Policy(enabled=True, dispatch=True, feed=True, manual_eggs=True,
|
||||
fill=False, protect_star=4, protect_quality=5, keep_better_quality=False,
|
||||
egg_rules={"1030010": {"enabled": True, "action": "feed", "keep_count": 1}},
|
||||
feed_targets=feed_targets, breakthrough_targets=potential_targets,
|
||||
gift_enabled=manual_gifts, gift_auto_representative=not manual_gifts,
|
||||
gift_targets={str(mid): mid for mid in duplicate_ids | {900}},
|
||||
gift_liked_only=False, gift_items={"30005": {"enabled": True}})
|
||||
engine.planner.managed.update(duplicate_ids | {900})
|
||||
engine.auto = True
|
||||
_, plans, _ = engine.poll()
|
||||
for path, payload in client.calls:
|
||||
target = payload.get("targetId", payload.get("monsterId", payload.get("monId")))
|
||||
self.assertNotIn(target, duplicate_ids, (path, payload))
|
||||
self.assertNotIn(900, payload.get("foods", []) + payload.get("monsterIds", []))
|
||||
for action in plans:
|
||||
if action.kind in ("feed", "gift", "potential", "breakthrough"):
|
||||
target = action.payload.get("targetId", action.payload.get("monsterId", action.payload.get("monId")))
|
||||
self.assertNotIn(target, duplicate_ids, action)
|
||||
self.assertIn(900, engine.snapshot.monsters)
|
||||
|
||||
def test_existing_enabled_duplicates_cleanup_without_managed_and_preserve_constraints(self):
|
||||
for constraint in (None, "lock", "sysLock", "equip1", "team", "entangle", "inExploreTeam", "inBuild", "unknown_quality", "active_exploration_team", "active_exploration_team_csv", "stale_targets_high_rarity"):
|
||||
with self.subTest(constraint=constraint):
|
||||
with workspace_temp() as folder:
|
||||
value = raw(self.catalog)
|
||||
stale_targets = constraint == "stale_targets_high_rarity"
|
||||
species = next(int(key) for key, row in self.catalog.monsters.items()
|
||||
if row.get("star") == 5 and not row.get("npc")
|
||||
and all(row.get(stat + "_grow_min") is not None for stat in ("atk", "def", "hp", "dex"))) if stale_targets else 1030010
|
||||
rows = [species_monster(self.catalog, 900, "SASS", level=20, species=species)]
|
||||
rows += [species_monster(self.catalog, mid, "CCCC", species=species) for mid in range(901, 905)]
|
||||
rows += [species_monster(self.catalog, 950 + index, "CCCC", species=species)
|
||||
for index, species in enumerate((1030012, 1030013, 1030014))]
|
||||
value.update(monsters=rows, teams=[])
|
||||
if constraint == "team":
|
||||
value["teams"] = [{"monsters": [901]}]
|
||||
elif constraint in ("active_exploration_team", "active_exploration_team_csv"):
|
||||
value["exploreTeams"][0].update(status=1,
|
||||
monsters="901" if constraint.endswith("_csv") else [901], endTime=9999999999999)
|
||||
elif constraint == "unknown_quality":
|
||||
rows[1]["gAtk"] = None
|
||||
elif constraint and not stale_targets:
|
||||
rows[1][constraint] = 1
|
||||
engine, client = self.engine(folder, value, StatefulRanchClient)
|
||||
engine.policy = Policy(manual_eggs=True, fill=False, protect_star=4, protect_quality=5,
|
||||
keep_better_quality=False, gift_auto_representative=False,
|
||||
egg_rules={str(species): {"enabled": True, "action": "sell", "keep_count": 0}},
|
||||
feed_targets={str(mid): mid for mid in range(900, 905)} if stale_targets else {},
|
||||
gift_targets={str(mid): mid for mid in range(900, 905)} if stale_targets else {},
|
||||
breakthrough_targets={str(mid): mid for mid in range(900, 905)} if stale_targets else {})
|
||||
self.assertEqual(engine.planner.managed, set())
|
||||
engine.auto = True
|
||||
for _ in range(5):
|
||||
engine.poll()
|
||||
expected = {900, 950, 951, 952} | ({901} if constraint and not stale_targets else set())
|
||||
self.assertEqual(set(engine.snapshot.monsters), expected)
|
||||
self.assertTrue(client.calls)
|
||||
self.assertTrue(all(path == "monsterService/monsterSell" for path, _ in client.calls))
|
||||
if constraint and not stale_targets:
|
||||
self.assertTrue(engine.planner.statuses.get(901))
|
||||
if constraint == "lock":
|
||||
self.assertEqual(engine.snapshot.monsters[901]["lock"], 1)
|
||||
if constraint in ("active_exploration_team", "active_exploration_team_csv"):
|
||||
client.value["exploreTeams"][0]["status"] = 0
|
||||
engine.poll()
|
||||
self.assertEqual(set(engine.snapshot.monsters), {900, 950, 951, 952})
|
||||
self.assertEqual(client.calls[-1], ("monsterService/monsterSell", {"monsterIds": [901]}))
|
||||
|
||||
def test_successive_quality_backups_replace_before_collect_and_new_mature_ties_dispatch(self):
|
||||
with workspace_temp() as folder:
|
||||
value = raw(self.catalog)
|
||||
room_type = next(key for key, row in self.catalog.data["room_info"].items() if row.get("maxNum", 0) >= 2)
|
||||
value.update(monsters=[species_monster(self.catalog, 900, "SASS", level=20, lock=1),
|
||||
species_monster(self.catalog, 901, "SSSA"),
|
||||
species_monster(self.catalog, 902, "SSSS", level=1, process=2, roomId=None)],
|
||||
rooms=[{"id": 1, "typeId": int(room_type)}],
|
||||
stacks=[{"id": 1, "position": 0, "monsterId": 902}])
|
||||
row = self.catalog.monster(1030010)
|
||||
for stat, scale in zip(("atk", "def", "hp", "dex"), (.95, .95, .95, .7)):
|
||||
value["monsters"][1]["g" + stat.capitalize()] = row[stat + "_grow_min"] + scale * (row[stat + "_grow_max"] - row[stat + "_grow_min"])
|
||||
engine, client = self.engine(folder, value, StatefulRanchClient)
|
||||
engine.policy = Policy(manual_eggs=True, fill=False, protect_star=4, protect_quality=5,
|
||||
keep_better_quality=False, gift_auto_representative=False,
|
||||
egg_rules={"1030010": {"enabled": True, "action": "sell", "keep_count": 4}})
|
||||
engine.auto = True
|
||||
with patch.dict(self.catalog.data["room_info"][room_type], {"maxNum": 2}):
|
||||
engine.poll()
|
||||
self.assertEqual(client.calls, [("monsterService/monsterSell", {"monsterIds": [901]})])
|
||||
engine.poll()
|
||||
self.assertEqual(client.calls[-1], ("stackService/stackTransferMonster",
|
||||
{"datas": [{"monsterId": [902], "roomId": 1}]}))
|
||||
self.assertEqual(set(engine.snapshot.monsters), {900, 902})
|
||||
client.value["monsters"].insert(0,
|
||||
species_monster(self.catalog, 903, "SSSS", level=1, process=2, roomId=None))
|
||||
client.value["stacks"][0]["monsterId"] = 903
|
||||
engine.poll()
|
||||
self.assertEqual(client.calls[-1], ("monsterService/monsterSell", {"monsterIds": [903]}))
|
||||
self.assertEqual(set(engine.snapshot.monsters), {900, 902})
|
||||
engine.poll()
|
||||
self.assertEqual(len(client.calls), 3)
|
||||
|
||||
def test_breakthrough_targets_execute_and_require_new_snapshot_before_repeat(self):
|
||||
with workspace_temp() as folder:
|
||||
engine, client = self.engine(folder)
|
||||
|
||||
@@ -27,47 +27,49 @@ class RanchRetentionTests(unittest.TestCase):
|
||||
|
||||
def policy(self, action="sell", count=1, **values):
|
||||
values.setdefault("protect_star", 6)
|
||||
return Policy(manual_eggs=True, fill=False, protect_quality=6, keep_better_quality=True,
|
||||
values.setdefault("protect_quality", 5)
|
||||
values.setdefault("keep_better_quality", False)
|
||||
return Policy(manual_eggs=True, fill=False,
|
||||
egg_rules={"1001010": asdict(EggRule(enabled=True, action=action, keep_count=count))}, **values)
|
||||
|
||||
def plan(self, rows, policy=None, managed=None):
|
||||
self.snapshot.raw["monsters"] = rows
|
||||
self.planner.managed.update(managed if managed is not None else [row["id"] for row in rows])
|
||||
self.planner.cultivation.choices["1001010"] = 1
|
||||
self.planner.cultivation.signature = None
|
||||
return self.planner.plan(self.snapshot, policy or self.policy())
|
||||
|
||||
def test_quality_uses_s_then_a_then_b_before_normalized_growth(self):
|
||||
def test_quality_uses_s_count_then_equal_weight_normalized_growth(self):
|
||||
aasa, ssas = graded_monster(self.catalog, 1, "AASA", level=50), graded_monster(self.catalog, 2, "SSAS")
|
||||
self.assertLess(quality_rank(self.catalog, aasa), quality_rank(self.catalog, ssas))
|
||||
self.assertGreater(quality_rank(self.catalog, graded_monster(self.catalog, 3, "AAAC")),
|
||||
self.assertLess(quality_rank(self.catalog, graded_monster(self.catalog, 3, "AAAC")),
|
||||
quality_rank(self.catalog, graded_monster(self.catalog, 4, "BBAA")))
|
||||
self.assertFalse(any(a.kind == "sell" for a in self.plan([aasa, ssas])))
|
||||
reason = self.planner.protection_reason(ssas, self.snapshot, self.policy())
|
||||
self.assertIn("SSAS", reason)
|
||||
self.assertIn("S项3", reason)
|
||||
|
||||
def test_quota_zero_one_two_apply_to_every_enabled_action(self):
|
||||
def test_legacy_quota_zero_one_two_always_reserves_one_primary(self):
|
||||
for action in ("sell", "feed", "keep"):
|
||||
for quota, disposed in ((0, 3), (1, 2), (2, 1)):
|
||||
for quota in (0, 1, 2):
|
||||
with self.subTest(action=action, quota=quota):
|
||||
disposed = 2
|
||||
rows = [graded_monster(self.catalog, mid, "CCCC", tpLevel=4) for mid in (1, 2, 3)]
|
||||
if action == "feed":
|
||||
target = graded_monster(self.catalog, 99, "SSSS", species=1002010,
|
||||
level=1, exp=0, potentialLevel=2, tpLevel=4, tpExp=33)
|
||||
rows.append(target)
|
||||
elif action == "keep":
|
||||
disposed = 0
|
||||
policy = self.policy(action=action, count=quota,
|
||||
feed_targets={"99": 1} if action == "feed" else {})
|
||||
actions = self.plan(rows, policy)
|
||||
self.assertIn(1, self.planner.retained)
|
||||
self.assertNotIn(2, self.planner.retained)
|
||||
self.assertNotIn(3, self.planner.retained)
|
||||
sold = [mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]]
|
||||
fed = [mid for a in actions if a.kind == "feed" for mid in a.payload["foods"] if mid != 99]
|
||||
self.assertEqual(len(sold + fed), disposed)
|
||||
for target in (a.payload["targetId"] for a in actions if a.kind == "feed"):
|
||||
self.assertNotIn(target, fed)
|
||||
|
||||
def test_same_batch_and_locked_ranch_monsters_share_one_quota(self):
|
||||
def test_locked_ranch_duplicates_stay_locked_and_equal_mature_extras_dispatch(self):
|
||||
rows = [graded_monster(self.catalog, mid, "CCCC", roomId=mid) for mid in (1, 2)]
|
||||
rows += [graded_monster(self.catalog, mid, "CCCC", process=2, roomId=None) for mid in (3, 4)]
|
||||
for row in rows[:2]:
|
||||
@@ -75,48 +77,67 @@ class RanchRetentionTests(unittest.TestCase):
|
||||
actions = self.plan(rows, self.policy(count=2))
|
||||
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [3, 4])
|
||||
|
||||
def test_incubator_batch_fills_quota_and_keeps_same_ids_after_collection(self):
|
||||
for quota in (2, 3):
|
||||
def test_incubator_batch_keeps_one_primary_and_same_id_after_collection(self):
|
||||
for quota in (0, 2, 3):
|
||||
with self.subTest(quota=quota):
|
||||
self.setUp()
|
||||
rows = [graded_monster(self.catalog, mid, "CCCC", process=2, roomId=None) for mid in (1, 2, 3)]
|
||||
self.snapshot.raw["stacks"] = [{"id": mid, "position": mid - 1, "monsterId": mid} for mid in (1, 2, 3)]
|
||||
actions = self.plan(rows, self.policy(count=quota))
|
||||
collected = {mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]}
|
||||
self.assertEqual(collected, set(range(1, quota + 1)))
|
||||
self.assertEqual(self.planner.retained, collected)
|
||||
for row in rows:
|
||||
row.update(process=3, roomId=1)
|
||||
actions = self.plan(rows, self.policy(count=quota))
|
||||
self.assertEqual(self.planner.retained, collected)
|
||||
self.assertFalse(any(a.kind == "collect" for a in actions))
|
||||
sold = {mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]}
|
||||
self.assertEqual(sold, set(range(1, 4)) - collected)
|
||||
self.assertEqual(sold, {2, 3})
|
||||
self.assertEqual(self.planner.retained, {1})
|
||||
rows = rows[:1]
|
||||
self.snapshot.raw["stacks"] = self.snapshot.raw["stacks"][:1]
|
||||
actions = self.plan(rows, self.policy(count=quota))
|
||||
collected = {mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]}
|
||||
self.assertEqual(collected, {1})
|
||||
rows[0].update(process=3, roomId=1)
|
||||
self.snapshot.raw["stacks"][0]["monsterId"] = 0
|
||||
actions = self.plan(rows, self.policy(count=quota))
|
||||
self.assertEqual(self.planner.retained, collected)
|
||||
self.assertFalse(actions)
|
||||
self.assertTrue(all(mid not in collected for a in actions for mid in a.payload.get("foods", [])))
|
||||
|
||||
def test_ranch_and_incubator_share_quota_before_and_after_collection(self):
|
||||
def test_ranch_primary_rejects_equal_incubator_extras_before_and_after_collection(self):
|
||||
ranch = graded_monster(self.catalog, 1, "CCCC")
|
||||
rows = [ranch] + [graded_monster(self.catalog, mid, "CCCC", process=2, roomId=None) for mid in (2, 3, 4)]
|
||||
self.snapshot.raw["stacks"] = [{"id": mid, "position": mid - 1, "monsterId": mid} for mid in (2, 3, 4)]
|
||||
actions = self.plan(rows, self.policy(count=2))
|
||||
collected = {mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]}
|
||||
self.assertEqual(collected, {2})
|
||||
self.assertEqual(self.planner.retained, {1, 2})
|
||||
self.assertEqual(collected, set())
|
||||
self.assertEqual(self.planner.retained, {1})
|
||||
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [2, 3, 4])
|
||||
for row in rows[1:]:
|
||||
row.update(process=3, roomId=1)
|
||||
actions = self.plan(rows, self.policy(count=2))
|
||||
self.assertEqual(self.planner.retained, {1, 2})
|
||||
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [3, 4])
|
||||
self.assertEqual(self.planner.retained, {1})
|
||||
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [2, 3, 4])
|
||||
|
||||
def test_initial_incubator_quota_prefers_best_quality_last_in_raw(self):
|
||||
def test_initial_incubator_keeps_first_primary_and_best_quality_backup_last_in_raw(self):
|
||||
rows = [graded_monster(self.catalog, mid, "CCCC", process=2, roomId=None) for mid in (1, 2)]
|
||||
rows.append(graded_monster(self.catalog, 3, "SSAS", process=2, roomId=None))
|
||||
self.snapshot.raw["stacks"] = [{"id": mid, "position": mid - 1, "monsterId": mid} for mid in (1, 2, 3)]
|
||||
actions = self.plan(rows, self.policy(count=2))
|
||||
collected = {mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]}
|
||||
self.assertEqual(collected, {1, 3})
|
||||
self.assertEqual(collected, set())
|
||||
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [2])
|
||||
self.assertEqual(self.planner.retained, {1, 3})
|
||||
rows = [rows[0], rows[2]]
|
||||
self.snapshot.raw["stacks"] = [self.snapshot.raw["stacks"][0], self.snapshot.raw["stacks"][2]]
|
||||
actions = self.plan(rows, self.policy(count=2))
|
||||
self.assertEqual([mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]], [1])
|
||||
rows[0].update(process=3, roomId=1)
|
||||
self.snapshot.raw["stacks"][0]["monsterId"] = 0
|
||||
actions = self.plan(rows, self.policy(count=2))
|
||||
self.assertEqual([mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]], [3])
|
||||
rows[1].update(process=3, roomId=1)
|
||||
self.snapshot.raw["stacks"][1]["monsterId"] = 0
|
||||
actions = self.plan(rows, self.policy(count=2))
|
||||
self.assertEqual(self.planner.representatives["1001010"]["id"], 1)
|
||||
self.assertEqual(self.planner.retained, {1, 3})
|
||||
self.assertFalse(actions)
|
||||
|
||||
def test_incubator_quota_quality_prevents_equal_quality_extra_retention(self):
|
||||
rows = [graded_monster(self.catalog, 1, "AASA")]
|
||||
@@ -125,8 +146,16 @@ class RanchRetentionTests(unittest.TestCase):
|
||||
actions = self.plan(rows, self.policy(count=2))
|
||||
self.assertEqual(self.planner.retained, {1, 2})
|
||||
collected = [mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]]
|
||||
self.assertEqual(collected, [2])
|
||||
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [])
|
||||
self.assertEqual(collected, [])
|
||||
self.assertEqual([mid for a in actions if a.kind == "sell" for mid in a.payload["monsterIds"]], [3])
|
||||
rows = rows[:2]
|
||||
self.snapshot.raw["stacks"] = self.snapshot.raw["stacks"][:1]
|
||||
actions = self.plan(rows, self.policy(count=2))
|
||||
self.assertEqual([mid for a in actions if a.kind == "collect" for data in a.payload["datas"] for mid in data["monsterId"]], [2])
|
||||
rows[1].update(process=3, roomId=1)
|
||||
self.snapshot.raw["stacks"][0]["monsterId"] = 0
|
||||
actions = self.plan(rows, self.policy(count=2))
|
||||
self.assertFalse(actions)
|
||||
|
||||
def test_zero_quota_still_protects_better_incubator_above_locked_ranch(self):
|
||||
locked = graded_monster(self.catalog, 1, "AASA", lock=1)
|
||||
@@ -159,7 +188,7 @@ class RanchRetentionTests(unittest.TestCase):
|
||||
rows = [target, graded_monster(self.catalog, 2, "CCCC"), graded_monster(self.catalog, 3, "CCCC")]
|
||||
self.assertEqual(self.plan(rows, self.policy(action="feed"))[0].payload, {"targetId": 1, "foods": [2, 3]})
|
||||
target.update(tpLevel=4, tpExp=self.catalog.data["game_setting"]["tpExp"]["1"]["4"])
|
||||
self.assertFalse(any(a.kind == "feed" and 1 in a.payload["foods"] for a in self.plan(rows, self.policy(action="feed"))))
|
||||
self.assertFalse(any(a.kind == "feed" for a in self.plan(rows, self.policy(action="feed"))))
|
||||
|
||||
def test_normal_cap_still_allows_tp_food_until_cumulative_exp_is_full(self):
|
||||
target = graded_monster(self.catalog, 1, "SCCC", level=10, tpLevel=2, tpExp=6,
|
||||
@@ -171,9 +200,9 @@ class RanchRetentionTests(unittest.TestCase):
|
||||
target["tpExp"] = self.catalog.data["game_setting"]["tpExp"]["1"]["4"]
|
||||
self.assertFalse(any(a.kind == "feed" for a in self.plan([target, food], self.policy(action="feed"))))
|
||||
|
||||
def test_unmanaged_protected_and_other_feed_targets_are_not_materials(self):
|
||||
def test_unmanaged_other_species_primary_and_locked_monsters_are_not_materials(self):
|
||||
target = graded_monster(self.catalog, 1, "SSSS", tpLevel=0, tpExp=0)
|
||||
other = graded_monster(self.catalog, 2, "SSSA", tpLevel=0, tpExp=0)
|
||||
other = graded_monster(self.catalog, 2, "SSSA", species=1002010, tpLevel=0, tpExp=0)
|
||||
food = graded_monster(self.catalog, 3, "SSSB")
|
||||
action = self.plan([target, other, food], self.policy(action="feed", count=0), managed=[3])[0]
|
||||
self.assertEqual(action.payload, {"targetId": 1, "foods": [3]})
|
||||
@@ -199,9 +228,9 @@ class RanchRetentionTests(unittest.TestCase):
|
||||
def test_missing_tp_fields_pause_special_feed_but_not_legacy_experience(self):
|
||||
target = graded_monster(self.catalog, 1, "SCCC", level=10,
|
||||
potentialLevel=1, exp=self.catalog.data["monster_level"]["10"])
|
||||
food = graded_monster(self.catalog, 2, "CCCC")
|
||||
food = graded_monster(self.catalog, 2, "CCCC", level=1)
|
||||
self.assertFalse(any(a.kind == "feed" for a in self.plan([target, food], self.policy(action="feed"))))
|
||||
target.update(tpLevel=0, tpExp=0, level=1, exp=0)
|
||||
target.update(tpLevel=0, tpExp=0, level=2, exp=0)
|
||||
policy = Policy(strategy="experience", feed_target=1, fill=False, protect_star=6, protect_quality=6)
|
||||
self.assertEqual(self.plan([target, food], policy)[0].payload, {"targetId": 1, "foods": [2]})
|
||||
|
||||
|
||||
@@ -41,7 +41,10 @@ class ManualRuleTests(unittest.TestCase):
|
||||
self.planner.managed.add(food["id"])
|
||||
primary = self.snapshot.monsters[900]
|
||||
primary.update(potentialLevel=2, level=20)
|
||||
secondary = dict(primary, id=901, level=9, potentialLevel=1)
|
||||
row = self.catalog.monster(primary["typeId"])
|
||||
for stat in ("atk", "def", "hp", "dex"):
|
||||
primary["g" + stat.capitalize()] = row[stat + "_grow_min"] + .6 * (row[stat + "_grow_max"] - row[stat + "_grow_min"])
|
||||
secondary = dict(primary, id=901, typeId=1002010, level=9, potentialLevel=1)
|
||||
self.snapshot.raw["monsters"].append(secondary)
|
||||
policy = Policy(manual_eggs=True, strategy="gold", fill=False, protect_star=6, protect_quality=5,
|
||||
egg_rules={str(food["typeId"]): self.rule(action="feed", keep_count=0)}, feed_targets={"900": 1, "901": 2})
|
||||
|
||||
@@ -0,0 +1,479 @@
|
||||
"""Offline regressions for primary-only cultivation and bounded species retention."""
|
||||
import copy
|
||||
from dataclasses import asdict
|
||||
import unittest
|
||||
|
||||
from ranch_assistant.cultivation import quality_rank
|
||||
from ranch_assistant.model import Action, Catalog, EggRule, Planner, Policy, Snapshot
|
||||
|
||||
|
||||
SPECIES = 1030010
|
||||
|
||||
|
||||
class SpeciesRetentionLimitsTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.catalog = Catalog()
|
||||
room_type = next(iter(self.catalog.data["room_info"]))
|
||||
self.catalog.data["room_info"][room_type]["maxNum"] = 20
|
||||
self.snapshot = Snapshot({"master": {"id": 1}, "monsters": [], "teams": [],
|
||||
"stacks": [], "items": [], "rooms": [{"id": 1, "typeId": int(room_type)},
|
||||
{"id": 2, "typeId": int(room_type)}]})
|
||||
self.planner = Planner(self.catalog)
|
||||
|
||||
def mon(self, mid, grades="CCCC", *, species=SPECIES, **values):
|
||||
info = self.catalog.monster(species)
|
||||
mon = {"id": mid, "typeId": species, "process": 3, "mode": 2,
|
||||
"level": 10, "feel": 0, "roomId": 1, "potentialLevel": 3,
|
||||
"exp": 451, "tpLevel": 0, "tpExp": 0, "lock": 0}
|
||||
for stat, grade in zip(("atk", "def", "hp", "dex"), grades):
|
||||
low, high = info[stat + "_grow_min"], info[stat + "_grow_max"]
|
||||
mon["g" + stat.capitalize()] = low + (high - low) * {
|
||||
"C": .1, "B": .375, "A": .625, "S": .9}[grade]
|
||||
return mon | values
|
||||
|
||||
def policy(self, *, action="sell", count=1, **values):
|
||||
return Policy(**({"manual_eggs": True, "fill": False, "buy": False,
|
||||
"protect_star": 6, "protect_quality": 5, "keep_better_quality": False,
|
||||
"gift_auto_representative": True, "egg_rules": {str(SPECIES):
|
||||
asdict(EggRule(enabled=True, action=action, keep_count=count))}} | values))
|
||||
|
||||
def plan(self, rows, policy=None, *, managed=()):
|
||||
self.snapshot.raw["monsters"] = rows
|
||||
self.planner.managed.update(managed)
|
||||
return self.planner.plan(self.snapshot, policy or self.policy())
|
||||
|
||||
@staticmethod
|
||||
def sold(actions):
|
||||
return {mid for action in actions if action.kind == "sell"
|
||||
for mid in action.payload["monsterIds"]}
|
||||
|
||||
@staticmethod
|
||||
def collected(actions):
|
||||
return {mid for action in actions if action.kind == "collect"
|
||||
for data in action.payload["datas"] for mid in data["monsterId"]}
|
||||
|
||||
def screenshot(self):
|
||||
return [self.mon(910001, "SASS", level=20, potentialLevel=2,
|
||||
tpLevel=4, tpExp=999, exp=self.catalog.data["monster_level"]["20"], lock=1),
|
||||
self.mon(910002, "SASA"), self.mon(910003, "AASS"),
|
||||
self.mon(910004, "SASA"), self.mon(910005, "ASAS", level=9)]
|
||||
|
||||
def test_screenshot_unmanaged_extras_are_trimmed_only_for_enabled_species(self):
|
||||
rows = self.screenshot()
|
||||
unrelated = self.mon(999, "SSSS", species=1030012)
|
||||
actions = self.plan(rows + [unrelated])
|
||||
self.assertEqual(self.sold(actions), {row["id"] for row in rows[1:]})
|
||||
self.assertEqual(self.planner.retained, {910001})
|
||||
self.assertFalse(any(action.kind == "feed" for action in actions))
|
||||
self.assertFalse(self.planner.managed, "Planning must not invent recorded ownership")
|
||||
|
||||
def test_screenshot_tp_and_ordinary_caps_never_fall_back_to_duplicate(self):
|
||||
rows = self.screenshot()
|
||||
self.snapshot.raw["monsters"] = rows
|
||||
self.planner.managed.update(row["id"] for row in rows[1:])
|
||||
target, _ = self.planner.same_species_feeding_target(rows[-1], self.snapshot,
|
||||
self.policy(action="feed"))
|
||||
self.assertIsNone(target)
|
||||
self.assertFalse(any(action.kind == "feed" for action in
|
||||
self.plan(rows, self.policy(action="feed"))))
|
||||
|
||||
def test_old_keep_flags_and_counts_do_not_expand_or_disable_fixed_slots(self):
|
||||
for count in (0, 1, 2, 1000):
|
||||
for keep_better in (False, True):
|
||||
with self.subTest(count=count, keep_better=keep_better):
|
||||
self.setUp()
|
||||
rows = [self.mon(1, "AASA", level=30), self.mon(2, "SSAS"),
|
||||
self.mon(3, "SSAS", roomId=2), self.mon(4, "AASA")]
|
||||
policy = self.policy(count=count, keep_better_quality=keep_better)
|
||||
before = copy.deepcopy(asdict(policy))
|
||||
actions = self.plan(rows, policy)
|
||||
self.assertEqual(self.planner.retained, {1, 2})
|
||||
self.assertEqual(self.sold(actions), {3, 4})
|
||||
self.assertEqual(asdict(policy), before)
|
||||
|
||||
def test_quality_protection_does_not_keep_unlimited_managed_four_s(self):
|
||||
for threshold in (3, 6):
|
||||
with self.subTest(threshold=threshold):
|
||||
self.setUp()
|
||||
rows = [self.mon(1, "SSSS", level=30)] + [
|
||||
self.mon(mid, "SSSS") for mid in (2, 3, 4)]
|
||||
actions = self.plan(rows, self.policy(count=1000, protect_quality=threshold),
|
||||
managed=(1, 2, 3, 4))
|
||||
self.assertEqual(self.planner.retained, {1})
|
||||
self.assertEqual(self.sold(actions), {2, 3, 4})
|
||||
|
||||
def test_backup_requires_strict_improvement_over_primary(self):
|
||||
rows = [self.mon(1, "SSAS", level=30), self.mon(2, "SSAS"), self.mon(3, "AASA")]
|
||||
self.assertEqual(self.sold(self.plan(rows)), {2, 3})
|
||||
self.assertEqual(self.planner.retained, {1})
|
||||
|
||||
def test_equal_four_s_newcomer_dispatches_instead_of_becoming_tp_food(self):
|
||||
primary = self.mon(1, "SSSS", level=30, tpLevel=0, tpExp=0)
|
||||
newcomer = self.mon(2, "SSSS", process=2, roomId=None)
|
||||
self.snapshot.raw["stacks"] = [{"id": 1, "position": 0, "monsterId": 2}]
|
||||
policy = self.policy(action="feed")
|
||||
actions = self.plan([primary, newcomer], policy)
|
||||
self.assertEqual(self.sold(actions), {2})
|
||||
self.assertEqual(self.collected(actions), set())
|
||||
newcomer.update(process=3, roomId=1)
|
||||
actions = self.plan([primary, newcomer], policy)
|
||||
self.assertEqual(self.sold(actions), {2})
|
||||
self.assertFalse(any(a.kind == "feed" for a in actions))
|
||||
|
||||
def test_rejected_better_quality_candidate_dispatches_and_hard_locks_still_win(self):
|
||||
for protected in (False, True):
|
||||
with self.subTest(protected=protected):
|
||||
self.setUp()
|
||||
rows = [self.mon(1, "AASA", level=30), self.mon(2, "SSSS"),
|
||||
self.mon(3, "SSAS", lock=int(protected))]
|
||||
policy = self.policy(action="feed")
|
||||
actions = self.plan(rows, policy, managed=(2, 3))
|
||||
self.assertEqual(self.sold(actions), set() if protected else {3})
|
||||
self.assertEqual(self.planner.disposition(rows[2], self.snapshot, policy),
|
||||
"keep" if protected else "sell")
|
||||
self.assertFalse(any(a.kind == "feed" for a in actions))
|
||||
|
||||
def test_backup_ranks_s_count_before_equal_weight_normalized_growth(self):
|
||||
rows = [self.mon(1, "CCCC", level=30), self.mon(2, "AAAC"),
|
||||
self.mon(3, "BBAA"), self.mon(4, "SSAS"), self.mon(5, "AASA")]
|
||||
self.assertGreater(quality_rank(self.catalog, rows[3]), quality_rank(self.catalog, rows[4]))
|
||||
self.assertEqual(self.sold(self.plan(rows)), {2, 3, 5})
|
||||
self.assertEqual(self.planner.retained, {1, 4})
|
||||
|
||||
def test_backup_breaks_grade_ties_by_equal_weight_normalized_growth(self):
|
||||
primary = self.mon(1, level=30)
|
||||
better_atk, better_hp = self.mon(2, "AAAA"), self.mon(3, "AAAA")
|
||||
info = self.catalog.monster(SPECIES)
|
||||
better_atk["gAtk"] += .05 * (info["atk_grow_max"] - info["atk_grow_min"])
|
||||
better_hp["gHp"] += .10 * (info["hp_grow_max"] - info["hp_grow_min"])
|
||||
self.assertEqual(self.sold(self.plan([primary, better_atk, better_hp])), {2})
|
||||
self.assertEqual(self.planner.retained, {1, 3})
|
||||
|
||||
def test_equal_s_count_uses_growth_without_extra_a_or_b_count_priority(self):
|
||||
rows = [self.mon(1, level=30), self.mon(2, "SACC"), self.mon(3, "SBBB")]
|
||||
self.assertLess(quality_rank(self.catalog, rows[1]), quality_rank(self.catalog, rows[2]))
|
||||
self.assertEqual(self.sold(self.plan(rows)), {2})
|
||||
self.assertEqual(self.planner.retained, {1, 3})
|
||||
|
||||
def test_quality_tie_prefers_existing_ranch_backup_over_new_incubator(self):
|
||||
primary, backup = self.mon(1, level=30), self.mon(20, "SSAS")
|
||||
self.plan([primary, backup])
|
||||
new = self.mon(10, "SSAS", process=2, roomId=None)
|
||||
self.snapshot.raw["stacks"] = [{"id": 1, "position": 0, "monsterId": 10}]
|
||||
actions = self.plan([new, backup, primary])
|
||||
self.assertEqual(self.planner.retained, {1, 20})
|
||||
self.assertEqual(self.sold(actions), {10})
|
||||
self.assertEqual(self.collected(actions), set())
|
||||
|
||||
def test_equal_ranch_backups_use_oldest_id_independent_of_row_order(self):
|
||||
for order in ((30, 20, 10), (10, 30, 20)):
|
||||
with self.subTest(order=order):
|
||||
self.setUp()
|
||||
rows = [self.mon(1, level=30)] + [self.mon(mid, "SSAS") for mid in order]
|
||||
self.assertEqual(self.sold(self.plan(rows)), {20, 30})
|
||||
self.assertEqual(self.planner.retained, {1, 10})
|
||||
|
||||
def test_better_incubator_dispatches_obsolete_backup_before_collection(self):
|
||||
primary, old = self.mon(1, level=30), self.mon(2, "SSAS")
|
||||
self.plan([primary, old])
|
||||
new = self.mon(3, "SSSS", process=2, roomId=None)
|
||||
self.snapshot.raw["stacks"] = [{"id": 1, "position": 0, "monsterId": 3}]
|
||||
policy = self.policy(action="feed")
|
||||
actions = self.plan([primary, old, new], policy, managed=(2, 3))
|
||||
self.assertEqual(self.sold(actions), {2})
|
||||
self.assertEqual(self.collected(actions), set())
|
||||
self.assertFalse(any(action.kind == "feed" for action in actions))
|
||||
actions = self.plan([primary, new], policy)
|
||||
self.assertEqual(self.collected(actions), {3})
|
||||
self.assertEqual(self.sold(actions), set())
|
||||
|
||||
def test_obsolete_backup_replacement_waits_when_dispatch_is_off(self):
|
||||
rows = [self.mon(1, level=30), self.mon(2, "SSAS"),
|
||||
self.mon(3, "SSSS", process=2, roomId=None)]
|
||||
actions = self.plan(rows, self.policy(dispatch=False), managed=(2, 3))
|
||||
self.assertEqual(actions, [])
|
||||
self.assertIn("派遣", self.planner.statuses[2])
|
||||
self.assertIn("关闭", self.planner.statuses[2])
|
||||
|
||||
def test_first_mature_incubator_is_collected_before_any_feeding(self):
|
||||
rows = [self.mon(2, "SSSS", process=2, roomId=None),
|
||||
self.mon(1, process=2, roomId=None)]
|
||||
self.snapshot.raw["stacks"] = [{"id": mid, "position": mid - 1,
|
||||
"monsterId": mid} for mid in (1, 2)]
|
||||
actions = self.plan(rows, self.policy(action="feed"))
|
||||
self.assertEqual(self.collected(actions), {1})
|
||||
self.assertFalse(any(action.kind == "feed" for action in actions))
|
||||
self.assertIn(1, self.planner.retained)
|
||||
|
||||
def test_primary_can_consume_only_nonprotected_lower_quality_excess(self):
|
||||
rows = [self.mon(1, "AAAA", level=30, lock=1), self.mon(2, "SSSS"), self.mon(3)]
|
||||
actions = self.plan(rows, self.policy(action="feed"), managed=(2, 3))
|
||||
self.assertEqual([a.payload for a in actions if a.kind == "feed"],
|
||||
[{"targetId": 1, "foods": [3]}])
|
||||
self.assertEqual(self.planner.retained, {1, 2})
|
||||
|
||||
def test_legacy_same_species_feed_does_not_require_target_quality_above_fodder(self):
|
||||
rows = [self.mon(1, level=30, lock=1), self.mon(2, "SSAS")]
|
||||
policy = Policy(strategy="experience", fill=False, protect_star=6, protect_quality=5)
|
||||
actions = self.plan(rows, policy, managed=(2,))
|
||||
self.assertEqual([a.payload for a in actions if a.kind == "feed"],
|
||||
[{"targetId": 1, "foods": [2]}])
|
||||
|
||||
def test_backup_is_food_protected_but_never_a_target(self):
|
||||
primary = self.mon(1, level=30, tpLevel=4, tpExp=999)
|
||||
backup, food = self.mon(2, "SSSS"), self.mon(3, "SSAS")
|
||||
self.snapshot.raw["monsters"] = [primary, backup, food]
|
||||
self.planner.managed.update((2, 3))
|
||||
policy = self.policy(action="feed")
|
||||
self.assertTrue(self.planner.protected(backup, self.snapshot, policy))
|
||||
target, reason = self.planner.same_species_feeding_target(food, self.snapshot, policy)
|
||||
self.assertIsNone(target, reason)
|
||||
self.assertNotIn(2, self.planner.tp_feed_targets)
|
||||
|
||||
def test_same_species_selection_uses_only_primary_even_if_priority_favors_backup(self):
|
||||
primary, backup, food = self.mon(1, level=30), self.mon(2, "SSSS"), self.mon(3, "SSAS")
|
||||
self.snapshot.raw["monsters"] = [primary, backup, food]
|
||||
self.planner.managed.update((2, 3))
|
||||
policy = self.policy(action="feed", breakthrough_targets={"2": 1})
|
||||
target, _ = self.planner.same_species_feeding_target(food, self.snapshot, policy)
|
||||
self.assertIs(target, primary)
|
||||
|
||||
def test_unavailable_primary_does_not_fall_back_to_available_duplicate(self):
|
||||
for unavailable in ({"inExploreTeam": True}, {"inBuild": True}):
|
||||
with self.subTest(unavailable=unavailable):
|
||||
self.setUp()
|
||||
rows = [self.mon(1, level=30, **unavailable), self.mon(2, "SSSS"), self.mon(3, "SSAS")]
|
||||
self.snapshot.raw["monsters"] = rows
|
||||
self.planner.managed.update((2, 3))
|
||||
policy = self.policy(action="feed", feed_targets={"1": 1, "2": 2})
|
||||
self.assertIsNone(self.planner.feeding_target(self.snapshot, policy)[0])
|
||||
self.assertIsNone(self.planner.same_species_feeding_target(rows[-1], self.snapshot, policy)[0])
|
||||
|
||||
def test_manual_backup_only_is_skipped_without_changing_selection(self):
|
||||
rows = [self.mon(1, level=30), self.mon(2, "SSSS"), self.mon(3, "SSAS")]
|
||||
for values in ({"feed_targets": {"2": 1}}, {"feed_target": 2}):
|
||||
with self.subTest(values=values):
|
||||
self.snapshot.raw["monsters"] = rows
|
||||
policy = self.policy(action="feed", **values)
|
||||
before = copy.deepcopy(asdict(policy))
|
||||
target, reason = self.planner.feeding_target(self.snapshot, policy)
|
||||
self.assertIsNone(target)
|
||||
self.assertIn("主培养", reason)
|
||||
self.assertIn("#1", reason)
|
||||
self.assertFalse(any(action.kind == "feed" for action in
|
||||
self.plan(rows, policy, managed=(2, 3))))
|
||||
self.assertEqual(asdict(policy), before)
|
||||
|
||||
def test_manual_capped_primary_skips_duplicate_and_may_use_other_species_primary(self):
|
||||
rows = [self.mon(1, level=30), self.mon(2, "SSSS"), self.mon(3, species=1002010)]
|
||||
self.snapshot.raw["monsters"] = rows
|
||||
policy = self.policy(feed_targets={"1": 1, "2": 2, "3": 3})
|
||||
self.assertIs(self.planner.feeding_target(self.snapshot, policy)[0], rows[2])
|
||||
del policy.feed_targets["3"]
|
||||
self.assertIsNone(self.planner.feeding_target(self.snapshot, policy)[0])
|
||||
|
||||
def test_all_hard_protections_survive_species_limit(self):
|
||||
flags = ({"lock": 1}, {"sysLock": 1}, {"equip1": 7}, {"entangle": 1},
|
||||
{"inExploreTeam": 1}, {"inBuild": 1}, {"gAtk": None})
|
||||
rows = [self.mon(1, level=30)] + [self.mon(mid, "SSAS", **values)
|
||||
for mid, values in enumerate(flags, 2)]
|
||||
rows += [self.mon(20, "SSAS"), self.mon(21, "CCCC")]
|
||||
self.snapshot.raw["teams"] = [{"id": 1, "monsters": [20]}]
|
||||
before = copy.deepcopy(rows)
|
||||
actions = self.plan(rows, managed=range(1, 22))
|
||||
self.assertEqual(self.sold(actions), {21})
|
||||
self.assertEqual(rows, before)
|
||||
for row in rows[1:-1]:
|
||||
self.assertIn("保护", self.planner.statuses[row["id"]])
|
||||
|
||||
def test_reserved_species_never_sells_or_feeds_extras(self):
|
||||
rows = [self.mon(1, level=30), self.mon(2, "SSAS"), self.mon(3)]
|
||||
actions = self.plan(rows, self.policy(reserved_types=[SPECIES]), managed=(2, 3))
|
||||
self.assertFalse(any(a.kind in ("sell", "feed") for a in actions))
|
||||
self.assertIn("委托", self.planner.statuses[3])
|
||||
|
||||
def test_active_exploration_roster_protects_extras_without_individual_flags(self):
|
||||
for members in ("910002", [910002], (910002,)):
|
||||
with self.subTest(members=members):
|
||||
self.setUp()
|
||||
rows = self.screenshot()
|
||||
# Status remains occupied until exploration rewards are claimed,
|
||||
# including when its end time has already passed.
|
||||
self.snapshot.raw["exploreTeams"] = [{"id": 7, "status": 1,
|
||||
"monsters": members, "endTime": 1}]
|
||||
actions = self.plan(rows, self.policy(action="feed"),
|
||||
managed=tuple(row["id"] for row in rows))
|
||||
self.assertEqual(self.sold(actions), {910003, 910004, 910005})
|
||||
self.assertEqual(self.planner.retained, {910001, 910002})
|
||||
self.assertIn("保护", self.planner.statuses[910002])
|
||||
self.assertFalse(any(a.kind == "feed" for a in actions))
|
||||
|
||||
def test_exploring_primary_without_individual_flag_is_never_feed_target(self):
|
||||
rows = self.screenshot()
|
||||
rows[0].update(level=19, exp=451, tpLevel=0, tpExp=0)
|
||||
self.snapshot.raw["monsters"] = rows
|
||||
self.snapshot.raw["exploreTeams"] = [{"id": 7, "status": "1",
|
||||
"monsters": "910001"}]
|
||||
self.planner.managed.update(row["id"] for row in rows[1:])
|
||||
policy = self.policy(action="feed", feed_targets={"910001": 1})
|
||||
self.assertIsNone(self.planner.feeding_target(self.snapshot, policy)[0])
|
||||
self.assertIsNone(self.planner.same_species_feeding_target(rows[1], self.snapshot, policy)[0])
|
||||
action = Action("feed", "busy primary", "monsterService/monsterIntensify",
|
||||
{"targetId": 910001, "foods": [910002]})
|
||||
self.assertEqual(self.planner.batch_actions([action], self.snapshot, policy), [])
|
||||
|
||||
def test_exploration_only_changes_invalidate_retention_cache(self):
|
||||
rows = self.screenshot()
|
||||
self.snapshot.raw["monsters"] = rows
|
||||
policy = self.policy()
|
||||
self.assertFalse(self.planner.protected(rows[1], self.snapshot, policy))
|
||||
self.snapshot.raw["exploreTeams"] = [{"id": 7, "status": 1,
|
||||
"monsters": [910002]}]
|
||||
self.assertTrue(self.planner.protected(rows[1], self.snapshot, policy))
|
||||
self.assertIn(910002, self.planner.retained)
|
||||
self.snapshot.raw["exploreTeams"][0]["status"] = 0
|
||||
self.assertFalse(self.planner.protected(rows[1], self.snapshot, policy))
|
||||
self.assertNotIn(910002, self.planner.retained)
|
||||
|
||||
def test_dispatch_off_reports_unmanaged_extras_without_expanding_ownership(self):
|
||||
rows = self.screenshot()
|
||||
self.assertEqual(self.plan(rows, self.policy(dispatch=False)), [])
|
||||
self.assertIn("关闭", self.planner.statuses[910002])
|
||||
self.assertFalse(self.planner.managed)
|
||||
|
||||
def test_disabled_rules_and_disabled_automation_never_adopt_old_inventory(self):
|
||||
rows = self.screenshot()
|
||||
for policy in (self.policy(enabled=False), self.policy(egg_rules={str(SPECIES):
|
||||
asdict(EggRule(enabled=False))})):
|
||||
with self.subTest(policy=policy):
|
||||
self.assertEqual(self.plan(rows, policy), [])
|
||||
self.assertFalse(self.planner.managed)
|
||||
|
||||
def test_stale_nonprimary_targets_do_not_override_species_slots(self):
|
||||
rows = [self.mon(1, level=30), self.mon(2, "SSSS"), self.mon(3, "SSAS"), self.mon(4)]
|
||||
policy = self.policy(action="feed", feed_targets={"3": 1}, breakthrough_targets={"4": 1})
|
||||
actions = self.plan(rows, policy, managed=(2, 3, 4))
|
||||
self.assertEqual(self.sold(actions), {3, 4})
|
||||
self.assertFalse(any(a.kind == "feed" for a in actions))
|
||||
self.assertFalse(self.planner.protected(rows[2], self.snapshot, policy))
|
||||
self.assertFalse(self.planner.protected(rows[3], self.snapshot, policy))
|
||||
|
||||
def test_all_old_targets_and_star_threshold_are_soft_for_enabled_species(self):
|
||||
rows = self.screenshot()
|
||||
rows[2]["lock"] = 1
|
||||
selected = {str(row["id"]): i for i, row in enumerate(rows, 1)}
|
||||
policy = self.policy(action="feed", protect_star=1, feed_targets=selected.copy(),
|
||||
gift_targets=selected.copy(), breakthrough_targets=selected.copy())
|
||||
before = copy.deepcopy(asdict(policy))
|
||||
actions = self.plan(rows, policy, managed=tuple(row["id"] for row in rows))
|
||||
self.assertEqual(self.sold(actions), {910002, 910004, 910005})
|
||||
self.assertEqual(self.planner.retained, {910001, 910003})
|
||||
self.assertIn("保护", self.planner.statuses[910003])
|
||||
self.assertEqual(asdict(policy), before)
|
||||
self.assertFalse(any(a.kind == "feed" for a in actions))
|
||||
|
||||
def test_batch_revalidates_primary_instead_of_trusting_supplied_feed_action(self):
|
||||
rows = [self.mon(1, level=30), self.mon(2, "SSSS"), self.mon(3, "SSAS")]
|
||||
self.snapshot.raw["monsters"] = rows
|
||||
self.planner.managed.update((2, 3))
|
||||
action = Action("feed", "stale duplicate target", "monsterService/monsterIntensify",
|
||||
{"targetId": 2, "foods": [3]})
|
||||
self.assertEqual(self.planner.batch_actions([action], self.snapshot,
|
||||
self.policy(action="feed", feed_targets={"2": 1})), [])
|
||||
|
||||
def test_batch_never_consumes_primary_backup_unmanaged_or_locked_food(self):
|
||||
rows = [self.mon(1, "AAAA", level=29), self.mon(2, "SSSS"), self.mon(3),
|
||||
self.mon(4, lock=1), self.mon(5, species=1002010)]
|
||||
self.snapshot.raw["monsters"] = rows
|
||||
self.planner.managed.update((2, 3, 4))
|
||||
policy = self.policy(action="feed", feed_targets={"1": 1})
|
||||
actions = [Action("feed", "candidate", "monsterService/monsterIntensify",
|
||||
{"targetId": 1, "foods": [mid]}) for mid in (1, 2, 3, 4, 5)]
|
||||
self.assertEqual([a.payload for a in self.planner.batch_actions(actions, self.snapshot, policy)],
|
||||
[{"targetId": 1, "foods": [3]}])
|
||||
|
||||
def test_normal_experience_cap_still_allows_same_species_tp_on_primary(self):
|
||||
rows = [self.mon(1, "AAAA", level=30, tpLevel=2, tpExp=3), self.mon(2, "SSSS"), self.mon(3)]
|
||||
actions = self.plan(rows, self.policy(action="feed"), managed=(2, 3))
|
||||
self.assertEqual([a.payload for a in actions if a.kind == "feed"], [{"targetId": 1, "foods": [3]}])
|
||||
|
||||
def test_keep_action_cannot_bypass_the_two_species_slots(self):
|
||||
rows = [self.mon(1, level=30), self.mon(2, "SSSS"), self.mon(3, "SSAS"), self.mon(4)]
|
||||
actions = self.plan(rows, self.policy(action="keep", count=1000))
|
||||
self.assertEqual(self.sold(actions), {3, 4})
|
||||
self.assertEqual(self.planner.retained, {1, 2})
|
||||
|
||||
def test_transient_food_collection_reserves_only_one_species_slot(self):
|
||||
rows = [self.mon(1, "SSAS", level=30)] + [
|
||||
self.mon(mid, process=2, roomId=None) for mid in (2, 3, 4, 5)]
|
||||
self.snapshot.raw["stacks"] = [{"id": mid, "position": mid - 2,
|
||||
"monsterId": mid} for mid in (2, 3, 4, 5)]
|
||||
actions = self.plan(rows, self.policy(action="feed"))
|
||||
self.assertEqual(self.sold(actions), {3, 4, 5})
|
||||
self.assertEqual(self.collected(actions), set())
|
||||
rows = rows[:2]
|
||||
self.snapshot.raw["stacks"] = self.snapshot.raw["stacks"][:1]
|
||||
actions = self.plan(rows, self.policy(action="feed"))
|
||||
self.assertEqual(len(self.collected(actions)), 1)
|
||||
self.assertEqual(self.collected(actions), {2})
|
||||
self.assertTrue(all(action.kind != "feed" for action in actions))
|
||||
# A refreshed snapshot sees one transient food, never four admitted at once.
|
||||
rows[1].update(process=3, roomId=1)
|
||||
self.snapshot.raw["stacks"][0]["monsterId"] = 0
|
||||
actions = self.plan(rows, self.policy(action="feed"))
|
||||
self.assertEqual(self.collected(actions), set())
|
||||
self.assertTrue(any(action.kind == "feed" and action.payload["targetId"] == 1 for action in actions))
|
||||
|
||||
def test_primary_and_backup_block_extra_food_collection(self):
|
||||
rows = [self.mon(1, "AAAA", level=30), self.mon(2, "SSSS"),
|
||||
self.mon(3, process=2, roomId=None)]
|
||||
self.snapshot.raw["stacks"] = [{"id": 1, "position": 0, "monsterId": 3}]
|
||||
actions = self.plan(rows, self.policy(action="feed"))
|
||||
self.assertEqual(self.collected(actions), set())
|
||||
self.assertEqual(self.sold(actions), {3})
|
||||
|
||||
def test_hard_protected_old_backup_blocks_replacement_at_two_ranch_members(self):
|
||||
rows = [self.mon(1, level=30), self.mon(2, "SSAS", lock=1),
|
||||
self.mon(3, "SSSS", process=2, roomId=None)]
|
||||
actions = self.plan(rows, managed=(2, 3))
|
||||
self.assertEqual(actions, [])
|
||||
self.assertIn("保护", self.planner.statuses[2])
|
||||
self.assertIn("两只", self.planner.statuses[3])
|
||||
|
||||
def test_unknown_primary_quality_pauses_cleanup_until_synchronized(self):
|
||||
rows = [self.mon(1, level=30, gAtk=None), self.mon(2, "SSSS"), self.mon(3, "SSAS")]
|
||||
actions = self.plan(rows, managed=(1, 2, 3))
|
||||
self.assertFalse(any(a.kind in ("sell", "feed") for a in actions))
|
||||
self.assertIn("同步", self.planner.statuses[3])
|
||||
|
||||
def test_saved_nonranch_primary_is_held_instead_of_promoting_backup(self):
|
||||
primary, backup = self.mon(30, level=30), self.mon(10, "SSSS")
|
||||
self.plan([primary, backup])
|
||||
primary.update(process=2, mode=1, roomId=None)
|
||||
actions = self.plan([backup, primary], self.policy(action="feed"), managed=(10, 30))
|
||||
self.assertEqual(self.planner.cultivation.select(self.snapshot), {})
|
||||
self.assertIs(self.planner.representatives[str(SPECIES)], primary)
|
||||
self.assertIn(30, self.planner.retained)
|
||||
self.assertFalse(any(a.kind in ("feed", "sell", "collect") for a in actions))
|
||||
self.assertIn("主培养", self.planner.statuses[10])
|
||||
|
||||
def test_confirmed_removed_primary_allows_selector_to_choose_new_primary(self):
|
||||
primary, backup = self.mon(30, level=30), self.mon(10, "SSSS")
|
||||
self.plan([primary, backup])
|
||||
self.assertEqual(self.plan([backup], self.policy(action="feed"), managed=(10,)), [])
|
||||
self.assertIs(self.planner.representatives[str(SPECIES)], backup)
|
||||
self.assertEqual(self.planner.retained, {10})
|
||||
|
||||
def test_ordinary_cross_species_feed_farming_and_priorities_still_work(self):
|
||||
first = self.mon(1, "SSSS", level=30, species=1002010)
|
||||
second = self.mon(2, "SSSS", level=20, potentialLevel=3, species=1003010)
|
||||
foods = [self.mon(mid, species=1001010, level=1, exp=0) for mid in (3, 4, 5)]
|
||||
policy = Policy(strategy="experience", protect_star=6, protect_quality=5,
|
||||
fill=False, feed_targets={"1": 1, "2": 2})
|
||||
actions = self.plan([first, second] + foods, policy, managed=(3, 4, 5))
|
||||
self.assertEqual([a.payload for a in actions if a.kind == "feed"],
|
||||
[{"targetId": 2, "foods": [3, 4, 5]}])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user