"""Choose a single ranch representative per species, independently of gifts.""" import json from pathlib import Path import random 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 class CultivationSelector: 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): values = growth_values(self.catalog, mon) 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) def select(self, snapshot): 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)) 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 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()} 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