106 lines
4.9 KiB
Python
106 lines
4.9 KiB
Python
"""Choose a stable cultivation primary per species, independently of eligibility."""
|
|
import json
|
|
from pathlib import Path
|
|
import threading
|
|
|
|
|
|
def growth_values(catalog, mon):
|
|
if any(value is None for value in catalog.quality(mon)):
|
|
return None
|
|
row = catalog.monster(mon.get("typeId"))
|
|
return tuple(round(min(1, max(0, (float(f"{float(mon['g' + stat.capitalize()]):.3f}")
|
|
- row[stat + "_grow_min"]) / (row[stat + "_grow_max"] - row[stat + "_grow_min"]))), 9)
|
|
for stat in ("atk", "def", "hp", "dex"))
|
|
|
|
|
|
def growth_score(catalog, mon):
|
|
values = growth_values(catalog, mon)
|
|
return round(sum(values) / 4, 9) if values is not None else None
|
|
|
|
|
|
def quality_rank(catalog, mon):
|
|
"""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
|
|
return (sum(value == 4 for value in qualities), growth_score(catalog, mon))
|
|
|
|
|
|
def quality_summary(catalog, mon):
|
|
qualities = catalog.quality(mon)
|
|
names = {1: "C", 2: "B", 3: "A", 4: "S"}
|
|
return "".join(names.get(value, "?") for value in qualities)
|
|
|
|
|
|
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
|
|
self.owner = None
|
|
self.choices = {}
|
|
self.selected = {}
|
|
self.signature = None
|
|
self.lock = threading.RLock()
|
|
|
|
def rank(self, mon):
|
|
"""Comparable (level, feel, S count, equal-weight normalized growth)."""
|
|
return (int(mon.get("level") or 1), int(mon.get("feel") or 0),
|
|
*(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"])
|
|
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()}
|
|
return self.selected
|
|
if self.owner != owner:
|
|
self.choices = {}
|
|
if self.path and self.path.exists():
|
|
try:
|
|
value = json.loads(self.path.read_text(encoding="utf-8"))
|
|
if value.get("owner") == owner and isinstance(value.get("choices"), dict):
|
|
self.choices = {str(key): int(mid) for key, mid in value["choices"].items()}
|
|
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():
|
|
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)
|
|
temporary = self.path.with_suffix(".tmp")
|
|
temporary.write_text(json.dumps({"owner": owner, "choices": choices}, ensure_ascii=False), encoding="utf-8")
|
|
temporary.replace(self.path)
|
|
self.choices = choices
|
|
self.signature, self.selected = signature, selected
|
|
return selected
|