121 lines
6.3 KiB
Python
121 lines
6.3 KiB
Python
"""Conservative item gifting, using the original client's caps and cooldown."""
|
||
import math
|
||
from .model import Action, seconds
|
||
from .cultivation import CultivationSelector
|
||
from .team_availability import _exploring_ids
|
||
|
||
|
||
def item_reserve(item_type, ranch, quests):
|
||
return max(int(ranch.reserved_eggs.get(item_type, 0)), int(quests.item_reserves.get(item_type, 0)))
|
||
|
||
|
||
class GiftPlanner:
|
||
def __init__(self, catalog, cultivation=None):
|
||
self.catalog = catalog
|
||
self.cultivation = cultivation or CultivationSelector(catalog)
|
||
self.notes = []
|
||
self.next_ready_at = None
|
||
self.confirmed = {}
|
||
|
||
def remember_success(self, snapshot, action, response):
|
||
try:
|
||
feel = float(response["feel"])
|
||
gifted_at = seconds(response["giftDate"])
|
||
if not math.isfinite(feel) or feel < 0 or not math.isfinite(gifted_at) or gifted_at <= 0:
|
||
raise ValueError("Invalid gift state")
|
||
except (KeyError, TypeError, ValueError, OverflowError) as error:
|
||
raise ValueError("赠礼已返回,但缺少有效的 feel / giftDate;已关闭策略,请刷新核对") from error
|
||
mid = action.payload["monsterId"]
|
||
self.confirmed[mid] = {"owner": str(snapshot.raw["master"]["id"]),
|
||
"type": str(snapshot.monsters[mid]["typeId"]), "feel": int(feel), "giftTime": gifted_at}
|
||
|
||
def apply_confirmed(self, snapshot):
|
||
current = snapshot.monsters
|
||
for mid, entry in list(self.confirmed.items()):
|
||
mon = current.get(mid)
|
||
if (str(snapshot.raw["master"]["id"]) != entry["owner"] or mon is None
|
||
or str(mon.get("typeId")) != entry["type"] or mon.get("process") != 3
|
||
or seconds(mon.get("giftTime")) >= entry["giftTime"]):
|
||
del self.confirmed[mid]
|
||
else:
|
||
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(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):
|
||
limit = self.catalog.max_feel(mon)
|
||
if int(mon.get("feel") or 0) < limit:
|
||
return mon, limit
|
||
return None, 0
|
||
|
||
def plan(self, snapshot, policy, quest_policy=None):
|
||
self.notes = []
|
||
self.next_ready_at = None
|
||
if not policy.gift_enabled:
|
||
return []
|
||
if not any(rule.get("enabled") for rule in policy.gift_items.values()):
|
||
self.notes.append("自动赠礼:请先在“背包”勾选允许使用的物品")
|
||
return []
|
||
totals, blocked = {}, set()
|
||
for item in snapshot.raw["items"]:
|
||
key = str(item.get("typeId"))
|
||
totals[key] = totals.get(key, 0) + int(item.get("num") or 0)
|
||
if item.get("lock") or item.get("feedLock"):
|
||
blocked.add(key)
|
||
stocks = {}
|
||
instances = {}
|
||
for key, rule in policy.gift_items.items():
|
||
if not rule.get("enabled") or totals.get(key, 0) <= 0:
|
||
continue
|
||
if self.catalog.item_type(key) in (5, 6) or key in blocked:
|
||
continue
|
||
if not self.catalog.item(key).get("sellable"):
|
||
continue
|
||
reserve = item_reserve(key, policy, quest_policy) if quest_policy else int(rule.get("reserve", 0))
|
||
available = max(0, totals[key] - max(int(rule.get("reserve", 0)), reserve))
|
||
item = next((item for item in snapshot.raw["items"] if str(item.get("typeId")) == key
|
||
and int(item.get("num") or 0) > 0 and int(item.get("id") or 0) > 0), None)
|
||
if available and item is not None:
|
||
stocks[key] = available
|
||
instances[key] = int(item["id"])
|
||
if not stocks:
|
||
self.notes.append("自动赠礼:背包中没有符合开关和保留数量的物品")
|
||
return []
|
||
cooldown = int(self.catalog.data["game_setting"].get("monGiftTime", 7200))
|
||
actions = []
|
||
for target in self.candidates(snapshot, policy):
|
||
limit = self.catalog.max_feel(target)
|
||
if int(target.get("feel") or 0) >= limit:
|
||
continue
|
||
likes = self.catalog.monster(target.get("typeId")).get("like") or {}
|
||
usable = [key for key in stocks if not policy.gift_liked_only or int(likes.get(key, 0)) > 0]
|
||
if not usable:
|
||
continue
|
||
ready_at = max(snapshot.now, seconds(target.get("giftTime")) + cooldown)
|
||
self.next_ready_at = ready_at if self.next_ready_at is None else min(self.next_ready_at, ready_at)
|
||
if ready_at > snapshot.now:
|
||
if len(self.notes) < 6:
|
||
self.notes.append(f"自动赠礼:{self.catalog.monster_label(target)} 还需等待 {math.ceil(ready_at - snapshot.now)} 秒")
|
||
continue
|
||
key = max(usable, key=lambda k: (int(likes.get(k, 0)), stocks[k], -int(k)))
|
||
gain = int(likes.get(key, 0))
|
||
name = self.catalog.item_name(key)
|
||
actions.append(Action("gift", f"赠礼 {self.catalog.monster_label(target)} ← {name}(好感 {target.get('feel', 0)}/{limit},预计 {gain:+d})",
|
||
"monsterService/monsterSendGift", {"monsterId": int(target["id"]), "itemId": instances[key]}))
|
||
if actions:
|
||
return actions
|
||
self.notes.append("自动赠礼:培养代表已达好感上限、处于冷却或缺少允许的礼物" if policy.gift_auto_representative
|
||
else "自动赠礼:未选择目标、目标已达当前好感上限或没有符合偏好的礼物")
|
||
return []
|