307 lines
19 KiB
Python
307 lines
19 KiB
Python
"""Offline resource accounting and bounded gold-only task procurement.
|
||
|
||
Task reservations belong to the scheduler. Only explicit user reserves enter
|
||
this accounting, so a task never reserves its own eggs away from itself.
|
||
"""
|
||
from collections import Counter
|
||
from dataclasses import dataclass, field, replace
|
||
|
||
from .model import Planner, seconds
|
||
|
||
|
||
def integer(value, default=0):
|
||
try:
|
||
return int(value)
|
||
except (TypeError, ValueError, OverflowError):
|
||
return default
|
||
|
||
|
||
def resource_kind(step):
|
||
kind, value = step.get("statusType"), step.get("statusValue") or {}
|
||
if kind == "getItem" or kind == "getMonster" and integer(value.get("mode"), -1) == 0:
|
||
return "items"
|
||
return "monsters" if kind == "getMonster" else ""
|
||
|
||
|
||
@dataclass
|
||
class ResourcePlan:
|
||
feasible: bool = True
|
||
ready: bool = True
|
||
reason_kind: str = "ready"
|
||
reason: str = "资源已齐备"
|
||
resources: list = field(default_factory=list)
|
||
progress_plan: list = field(default_factory=list)
|
||
next_step: str = "提交已满足的任务条件"
|
||
action: object = None
|
||
farm_step: dict = field(default_factory=dict)
|
||
purchase_cost: int = 0
|
||
sources: list = field(default_factory=list)
|
||
|
||
def diagnostic(self):
|
||
return {key: getattr(self, key) for key in
|
||
("reason_kind", "resources", "progress_plan", "next_step")}
|
||
|
||
|
||
class ResourceProcurement:
|
||
def __init__(self, catalog, guard=None):
|
||
self.catalog = catalog
|
||
self.guard = guard or Planner(catalog)
|
||
|
||
def reserve(self, key, policy, ranch):
|
||
return max(0, integer(policy.item_reserves.get(key)), integer(ranch.reserved_eggs.get(key)),
|
||
integer(ranch.gift_items.get(key, {}).get("reserve")))
|
||
|
||
def inventory(self, snapshot, step, policy, ranch):
|
||
"""The same exact counts/IDs drive submission, preflight and the UI."""
|
||
kind, value = resource_kind(step), step.get("statusValue") or {}
|
||
key, needed = str(value.get("type", "")), integer(value.get("num"), -1)
|
||
remove = value.get("remove") is True
|
||
row = {"kind": kind, "type_id": key, "name": self.catalog.item_name(key), "needed": needed,
|
||
"available": 0, "total": 0, "reserved": 0, "protected": 0, "protections": {}, "ids": []}
|
||
if not key.isdigit() or needed < 0:
|
||
return row | {"ready": False, "reason": "资源条件缺少有效类型或数量"}
|
||
if kind == "items":
|
||
items = [i for i in snapshot.raw.get("items", []) if str(i.get("typeId")) == key
|
||
and integer(i.get("id")) > 0 and integer(i.get("num")) > 0]
|
||
free = [i for i in items if not any(i.get(f) for f in ("lock", "sysLock", "feedLock"))]
|
||
row["total"] = sum(integer(i.get("num")) for i in items)
|
||
unlocked = sum(integer(i.get("num")) for i in free)
|
||
row["reserved"] = self.reserve(key, policy, ranch) if remove else 0
|
||
row["protected"] = row["total"] - unlocked
|
||
row["available"] = max(0, unlocked - row["reserved"])
|
||
used = 0
|
||
for item in free:
|
||
if used >= needed:
|
||
break
|
||
row["ids"].append(integer(item["id"]))
|
||
used += integer(item["num"])
|
||
allowed = not remove or not needed or policy.allow_items
|
||
row["reason"] = (f"{row['name']}:需{needed},可用{row['available']},背包{row['total']},"
|
||
f"锁定{row['protected']},保留{row['reserved']}")
|
||
if not allowed:
|
||
row["reason"] += ";提交道具未启用"
|
||
elif kind == "monsters":
|
||
if integer(value.get("mode"), -2) not in (2, -1):
|
||
return row | {"ready": False, "reason": "未支持的魔物条件或形态"}
|
||
monsters = [m for m in snapshot.raw.get("monsters", []) if str(m.get("typeId")) == key]
|
||
protections, free = Counter(), []
|
||
for monster in monsters:
|
||
reason = self.monster_protection(monster, snapshot, ranch)
|
||
mature = (integer(monster.get("mode"), -1) == 2 and integer(monster.get("process")) >= 2
|
||
and integer(monster.get("level"), 1) == 1)
|
||
if reason:
|
||
protections[reason] += 1
|
||
elif mature:
|
||
free.append(monster)
|
||
elif integer(monster.get("level"), 1) != 1:
|
||
protections["等级不是1级"] += 1
|
||
free.sort(key=lambda m: (sum(self.catalog.quality(m)), integer(m["id"])))
|
||
row.update(total=len(monsters), available=len(free), protected=sum(protections.values()),
|
||
protections=dict(protections), ids=[integer(m["id"]) for m in free[:needed]])
|
||
allowed = not remove or not needed or policy.allow_monsters
|
||
row["reason"] = f"{row['name']}:需{needed}只1级成熟魔物,可提交{len(free)},同种共{len(monsters)},保护{row['protected']}"
|
||
if protections:
|
||
row["reason"] += "(" + "、".join(f"{r} {n}只" for r, n in protections.items()) + ")"
|
||
if not allowed:
|
||
row["reason"] += ";提交魔物未启用"
|
||
else:
|
||
return row | {"ready": False, "reason": "未支持的资源条件"}
|
||
row["ready"] = allowed and row["available"] >= needed
|
||
return row
|
||
|
||
def monster_protection(self, monster, snapshot, ranch):
|
||
# Cultivation targets stay protected even when a species rule is enabled.
|
||
mid = str(monster.get("id"))
|
||
if monster.get("inteam") or integer(monster.get("id")) in snapshot.team_ids:
|
||
return "在队魔物"
|
||
if integer(monster.get("id")) == ranch.feed_target or any(mid in targets for targets in
|
||
(ranch.feed_targets, ranch.gift_targets, ranch.breakthrough_targets)):
|
||
return "主培养或已选培养目标"
|
||
return self.guard.protection_reason(monster, snapshot, ranch) or ""
|
||
|
||
@staticmethod
|
||
def demands(steps):
|
||
"""Sum removals and retain observation peaks; shared eggs are counted once."""
|
||
spent, needed, templates = Counter(), Counter(), {}
|
||
for step in steps:
|
||
kind, value = resource_kind(step), step.get("statusValue") or {}
|
||
if not kind:
|
||
continue
|
||
key = (kind, str(value.get("type", "")))
|
||
count = max(0, integer(value.get("num")))
|
||
needed[key] = max(needed[key], spent[key] + count)
|
||
templates[key] = step
|
||
if value.get("remove") is True:
|
||
spent[key] += count
|
||
return needed, templates
|
||
|
||
def plan(self, snapshot, steps, policy, ranch, *, daily_left=None, farm_sources=None):
|
||
for step in steps:
|
||
if resource_kind(step):
|
||
value = step.get("statusValue") or {}
|
||
if (not str(value.get("type", "")).isdigit() or integer(value.get("num"), -1) < 0
|
||
or resource_kind(step) == "monsters" and integer(value.get("mode"), -2) not in (2, -1)):
|
||
return ResourcePlan(feasible=False, ready=False, reason_kind="model_unsupported",
|
||
reason="资源条件的类型、数量或魔物形态未验证", next_step="等待有效任务配置")
|
||
needed, templates = self.demands(steps)
|
||
plan = ResourcePlan()
|
||
item_demands = {key: count for (kind, key), count in needed.items() if kind == "items"}
|
||
evaluations = []
|
||
for (kind, key), count in needed.items():
|
||
template = templates[kind, key]
|
||
# Any consuming step must retain permission/reserve checks, even if
|
||
# a later observation uses the same resource without remove=True.
|
||
remove = any(resource_kind(s) == kind and str((s.get("statusValue") or {}).get("type")) == key
|
||
and (s.get("statusValue") or {}).get("remove") is True for s in steps)
|
||
trial = dict(template, statusValue=dict(template.get("statusValue") or {}, num=count, remove=remove))
|
||
row = self.inventory(snapshot, trial, policy, ranch)
|
||
plan.resources.append({k: v for k, v in row.items() if k not in ("ids", "ready", "reason")})
|
||
if not row["ready"]:
|
||
result = self._missing(snapshot, trial, row, policy, ranch, item_demands, daily_left)
|
||
if result.feasible and result.farm_step and callable(farm_sources):
|
||
result.sources, reason = farm_sources(result.farm_step)
|
||
if not result.sources:
|
||
result.feasible = False
|
||
result.reason_kind = "model_unsupported" if reason else "temp_resource"
|
||
result.reason += ";" + (reason or "没有满足解锁、资源保护与批次规则的已验证收集来源")
|
||
result.next_step = result.reason
|
||
evaluations.append(result)
|
||
if not evaluations:
|
||
return plan
|
||
plan.ready = False
|
||
plan.feasible = all(result.feasible for result in evaluations)
|
||
selected = next((r for r in evaluations if not r.feasible), None)
|
||
selected = selected or next((r for r in evaluations if r.action or r.farm_step), evaluations[0])
|
||
plan.reason_kind, plan.next_step = selected.reason_kind, selected.next_step
|
||
plan.reason = ";".join(r.reason for r in evaluations)
|
||
plan.progress_plan = [text for result in evaluations for text in result.progress_plan]
|
||
if plan.feasible:
|
||
plan.action, plan.farm_step = selected.action, selected.farm_step
|
||
plan.sources = selected.sources
|
||
plan.purchase_cost = selected.purchase_cost
|
||
total_cost = sum(r.purchase_cost for r in evaluations)
|
||
budget = ranch.daily_buy_money if daily_left is None else min(daily_left, ranch.daily_buy_money)
|
||
if total_cost > min(budget, max(0, integer(snapshot.raw["master"].get("money")) - ranch.keep_money)):
|
||
plan.feasible = False
|
||
plan.reason += f";整份任务当前采购至少{total_cost}金币,超过保留金币或今日剩余额度{budget}"
|
||
plan.next_step = "等待金币或次日预算恢复,再核对整份任务采购成本"
|
||
plan.action, plan.sources = None, []
|
||
return plan
|
||
|
||
def _missing(self, snapshot, step, row, policy, ranch, item_demands, daily_left):
|
||
key, deficit = row["type_id"], row["needed"] - row["available"]
|
||
plan = ResourcePlan(ready=False, reason_kind="temp_resource", reason=row["reason"])
|
||
fail = lambda text, kind="protection": replace(plan, feasible=False, reason_kind=kind,
|
||
reason=plan.reason + ";" + text, next_step=text)
|
||
if (step.get("statusValue") or {}).get("remove") is True and not getattr(policy, "allow_" + row["kind"]):
|
||
return fail("按现有提交权限等待处理", "policy")
|
||
if row["kind"] == "monsters":
|
||
species = self.catalog.monster(key)
|
||
rule = self.guard.species_rule({"typeId": key}, ranch)
|
||
if (integer(key) in ranch.reserved_types or not species or
|
||
not rule and (integer(species.get("star"), 99) >= ranch.protect_star or ranch.protect_quality <= 1)):
|
||
return fail("该种新孵魔物也受保留种类、星级或资质保护,无法自动取得可提交副本")
|
||
if not policy.auto_farm or not ranch.enabled or not ranch.fill:
|
||
return fail("自动补齐需要已启用牧场与装填孵化", "policy")
|
||
growing = [m for m in snapshot.raw.get("monsters", []) if str(m.get("typeId")) == key
|
||
and integer(m.get("process")) == 2 and integer(m.get("level"), 1) == 1
|
||
and (integer(m.get("mode"), -1) in (0, 1) or integer(m.get("mode"), -1) == 2
|
||
and any(q is None for q in self.catalog.quality(m)))
|
||
and not (m.get("inteam") or integer(m.get("id")) in snapshot.team_ids
|
||
or integer(m.get("id")) == ranch.feed_target
|
||
or any(str(m.get("id")) in targets for targets in (ranch.feed_targets, ranch.gift_targets, ranch.breakthrough_targets))
|
||
or any(m.get(f) for f in ("lock", "sysLock", "entangle", "inExploreTeam", "inBuild")))]
|
||
eggs = self.inventory(snapshot, {"statusType": "getItem", "statusValue":
|
||
{"type": key, "num": 0, "remove": True}}, replace(policy, allow_items=True), ranch)
|
||
egg_available = max(0, eggs["available"] - item_demands.get(key, 0))
|
||
plan.reason += f";孵化中{len(growing)},可孵蛋{egg_available}(另留提交蛋{item_demands.get(key, 0)}、用户保留{eggs['reserved']})"
|
||
outstanding = max(0, deficit - len(growing))
|
||
if outstanding and egg_available:
|
||
# Reuse the normal hatch API, but select only this task's type.
|
||
hatch_policy = replace(ranch, manual_eggs=False, reserved_eggs={key: eggs["reserved"] + item_demands.get(key, 0)},
|
||
hatch_max_star=99, min_gold_per_hour=0, min_exp_per_hour=0)
|
||
from .model import Snapshot
|
||
remaining = outstanding + eggs["reserved"] + item_demands.get(key, 0)
|
||
hatch_items = []
|
||
for item in snapshot.raw["items"]:
|
||
if (str(item.get("typeId")) != key or any(item.get(f) for f in ("lock", "sysLock", "feedLock"))
|
||
or integer(item.get("id")) <= 0 or remaining <= 0):
|
||
continue
|
||
count = min(remaining, max(0, integer(item.get("num"))))
|
||
hatch_items.append(dict(item, num=count))
|
||
remaining -= count
|
||
scoped = Snapshot(dict(snapshot.raw, items=hatch_items),
|
||
received_at=snapshot.received_at, server_offset=snapshot.server_offset)
|
||
actions = self.guard.hatch_actions(scoped, hatch_policy)
|
||
if actions:
|
||
plan.action = actions[0]
|
||
plan.next_step = f"先装填已有{row['name']}蛋,等待服务器确认成熟后再提交"
|
||
plan.progress_plan = [plan.next_step]
|
||
return plan
|
||
# Mature protected incubator occupants can be collected safely.
|
||
slots = {integer(s.get("monsterId")) for s in snapshot.raw.get("stacks", [])}
|
||
for mon in snapshot.raw.get("monsters", []):
|
||
if (integer(mon.get("id")) in slots and integer(mon.get("mode"), -1) == 2
|
||
and integer(mon.get("process")) == 2
|
||
and all(q is not None for q in self.catalog.quality(mon))):
|
||
room = snapshot.room_available(self.catalog, ranch.room_id)
|
||
if room is not None and ranch.collect:
|
||
from .model import Action
|
||
plan.action = Action("collect", "收取成熟魔物以空出委托孵化位", "stackService/stackTransferMonster",
|
||
{"datas": [{"monsterId": [integer(mon['id'])], "roomId": room}]})
|
||
plan.next_step = "先收取成熟魔物到空闲牧场,再装填委托蛋"
|
||
plan.progress_plan = [plan.next_step]
|
||
return plan
|
||
plan.reason_kind = "busy"
|
||
plan.next_step = "孵化位已占用;等待成长或可收取牧场空位,不再购蛋"
|
||
plan.progress_plan = [plan.next_step]
|
||
return plan
|
||
if outstanding <= 0:
|
||
waits = [snapshot.remaining(m, self.catalog) for m in growing]
|
||
wait = max((w for w in waits if w is not None), default=None)
|
||
plan.reason_kind = "cooldown"
|
||
plan.next_step = "已有足量同种魔物孵化/成长中,等待" + (f"约{int(wait) + 1}秒并同步成熟" if wait is not None else "服务器同步成熟") + ";不重复购蛋"
|
||
plan.progress_plan = [plan.next_step, "成熟后重新核对资质及保护,只提交未保护副本"]
|
||
return plan
|
||
deficit = max(0, outstanding - egg_available)
|
||
plan.progress_plan.append("保留受保护副本,补孵缺少的1级成熟魔物,成熟后重新核对保护")
|
||
elif not policy.auto_farm:
|
||
return fail("自动补资源未启用", "policy")
|
||
if key not in self.catalog.monsters:
|
||
plan.farm_step = step
|
||
plan.next_step = "从已解锁且通过实战能力核对的普通关卡收集缺少材料"
|
||
plan.progress_plan.append(plan.next_step)
|
||
return plan
|
||
# Prefer verified farming when buying is unavailable. The caller checks
|
||
# map unlocks, team, costs, model support and actual drops separately.
|
||
trial = {"statusType": "getItem", "statusValue": {"type": key,
|
||
"num": (row["needed"] if row["kind"] == "items" else deficit + eggs["available"] + eggs["reserved"]),
|
||
"remove": row["kind"] == "items"}}
|
||
plan.farm_step = trial
|
||
if not ranch.enabled or not ranch.buy:
|
||
plan.next_step = "购蛋开关未启用;检查已验证地图掉蛋来源"
|
||
return plan
|
||
markets = self.catalog.data.get("markets", {})
|
||
candidates = [mid for mid in self.catalog.markets_for(key) if mid.startswith("sc_city")
|
||
and integer(markets[mid].get("ke"), -1) == 0 and integer(markets[mid].get("money")) > 0
|
||
and snapshot.city_unlocked(markets[mid].get("city"))]
|
||
candidates.sort(key=lambda mid: (mid != ranch.egg_rules.get(key, {}).get("market_id"),
|
||
mid != ranch.market_id, integer(markets[mid]["money"]), mid))
|
||
failures = []
|
||
for mid in candidates:
|
||
buying = replace(ranch, manual_eggs=False, market_id=mid, egg_stock=deficit)
|
||
self.guard.notes = []
|
||
actions = self.guard.purchase(snapshot, buying, daily_left, stock=0)
|
||
if actions:
|
||
plan.action = actions[0]
|
||
plan.action.description = f"为任务补齐{row['name']}(缺{deficit}):" + plan.action.description
|
||
plan.purchase_cost = integer(markets[mid]["money"]) * integer(plan.action.payload["num"])
|
||
plan.farm_step = {}
|
||
plan.next_step = f"在{markets[mid]['name']}金币市场补抽,单次最多{deficit}枚;蛋池随机,每次按实际回包重算缺口"
|
||
plan.progress_plan.append(plan.next_step)
|
||
return plan
|
||
failures.extend(self.guard.notes)
|
||
plan.next_step = ";".join(dict.fromkeys(failures)) or "没有已解锁且包含目标蛋的金币市场,检查地图掉蛋来源"
|
||
plan.reason += ";" + plan.next_step
|
||
return plan
|