249 lines
13 KiB
Python
249 lines
13 KiB
Python
from __future__ import annotations
|
||
from dataclasses import dataclass, field
|
||
from datetime import datetime, timedelta, timezone
|
||
|
||
from .model import Action, Planner, seconds
|
||
|
||
CN = timezone(timedelta(hours=8))
|
||
|
||
|
||
def commission_priority(info):
|
||
try:
|
||
reward = int((info.get("reward") or {}).get("ke") or 0)
|
||
except (TypeError, ValueError):
|
||
reward = 0
|
||
return -reward
|
||
|
||
|
||
def commission_selection(info, offers, rejected):
|
||
"""Explain this selection using the offers actually examined, across cities."""
|
||
reward = -commission_priority(info)
|
||
higher = [row for row in rejected if row["expected_ke"] > reward]
|
||
has_twenty = any(row["expected_ke"] == 20 for row in offers)
|
||
if reward >= 20:
|
||
code, reason = "highest_reward", f"按氪金奖励优先,选择当前可处理的 {reward} 氪金委托"
|
||
elif not has_twenty:
|
||
code, reason = "no_20_offered", f"本次候选未提供20氪金委托,按奖励优先选择 {reward} 氪金委托"
|
||
if higher:
|
||
reason += ";" + ";".join(f"{row['name']}({row['expected_ke']}氪金):{row['reason']}" for row in higher)
|
||
else:
|
||
code = "20_ineligible"
|
||
details = ";".join(f"{row['name']}({row['expected_ke']}氪金):{row['reason']}" for row in higher)
|
||
reason = f"较高奖励委托当前不可接取,选择 {reward} 氪金委托" + (";" + details if details else "")
|
||
return {"selection_code": code, "selection_reason": reason, "higher_reward_blockers": higher}
|
||
|
||
|
||
def indexed(value, key, default=None):
|
||
if isinstance(value, dict):
|
||
return value.get(str(key), value.get(key, default))
|
||
if isinstance(value, list) and str(key).isdigit() and int(key) < len(value):
|
||
return value[int(key)]
|
||
return default
|
||
|
||
|
||
def stage_has_level(history, field, stage_id, level):
|
||
"""Wire histories contain difficulty ID lists; AS3 expands them to flags."""
|
||
value = indexed(history.get(field), stage_id)
|
||
if isinstance(value, dict):
|
||
return indexed(value, level, False) is True
|
||
if isinstance(value, list):
|
||
if value and all(isinstance(v, bool) or v is None for v in value):
|
||
return indexed(value, level, False) is True
|
||
return str(level) in {str(v) for v in value}
|
||
return False
|
||
|
||
|
||
def condition_ok(condition, snapshot):
|
||
if not condition:
|
||
return True
|
||
history = snapshot.raw.get("history", {})
|
||
level = int(snapshot.raw["master"].get("level", 0))
|
||
def limit(key, default):
|
||
value = condition.get(key)
|
||
return default if value is None else value
|
||
if condition.get("close") or not limit("minLevel", 0) <= level <= limit("maxLevel", 2147483647):
|
||
return False
|
||
if condition.get("platform", "all") not in (None, "all", "ANDROID") or condition.get("channel", "all") not in (None, "all", "DYD"):
|
||
return False
|
||
if condition.get("lang", "all") not in (None, "all", "CN", "cn", "chs"):
|
||
return False
|
||
for key in condition.get("finishTask") or []:
|
||
if not indexed(history.get("passTask"), key, False):
|
||
return False
|
||
active = {str(t["typeId"]) for t in snapshot.raw.get("currentTasks", [])}
|
||
for key in condition.get("unfinishTask") or []:
|
||
if indexed(history.get("passTask"), key, False) or str(key) in active:
|
||
return False
|
||
for field, source in (("passStage", "passStage"), ("unlockStage", "unlockStage")):
|
||
for key in condition.get(field) or []:
|
||
if not stage_has_level(history, source, key, 1):
|
||
return False
|
||
now = datetime.fromtimestamp(snapshot.now, CN)
|
||
if condition.get("week") is not None and (now.weekday() + 1) % 7 not in condition["week"]:
|
||
return False
|
||
hhmm = now.hour * 100 + now.minute
|
||
return (limit("startTime", 0) <= hhmm <= limit("endTime", 2400)
|
||
and limit("startTimestamp", 0) <= snapshot.now <= limit("endTimestamp", 2147483647))
|
||
|
||
|
||
@dataclass
|
||
class QuestPolicy:
|
||
enabled: bool = False
|
||
accept: bool = True
|
||
city: int = 0
|
||
allow_items: bool = False
|
||
allow_monsters: bool = False
|
||
max_money: int = 0
|
||
battle_tasks: bool = False
|
||
item_reserves: dict[str, int] = field(default_factory=dict)
|
||
|
||
|
||
class TaskPlanner:
|
||
def __init__(self, catalog):
|
||
self.catalog = catalog
|
||
self.guard = Planner(catalog)
|
||
self.commission_selection = {}
|
||
|
||
def current(self, snapshot):
|
||
infos = self.catalog.data.get("task_info", {})
|
||
return [t for t in snapshot.raw.get("currentTasks", []) if str(t.get("typeId")) in infos
|
||
and infos[str(t["typeId"])].get("type", 4) == 4]
|
||
|
||
def requirement(self, snapshot, step, task, policy, ranch):
|
||
if not condition_ok(step.get("condition"), snapshot):
|
||
return False, [], "前置条件未满足"
|
||
kind, value = step.get("statusType", "none"), step.get("statusValue") or {}
|
||
if kind in ("battle", "passStage"):
|
||
return False, [], f"需实际战斗:{value.get('stage', '委托战斗')} / 难度 {value.get('level', 1)}"
|
||
if step.get("afterStory"):
|
||
return False, [], "需在游戏中完成后续剧情"
|
||
history = snapshot.raw.get("history", {})
|
||
remove = bool(value.get("remove"))
|
||
if kind == "none":
|
||
return True, [], "可推进对话步骤"
|
||
if kind == "getMoney":
|
||
amount = max(0, int(value.get("money", 0)))
|
||
if remove and amount > policy.max_money:
|
||
return False, [], "金币提交超过设置上限"
|
||
return int(snapshot.raw["master"].get("money", 0)) >= amount, [], f"需要金币 {amount}"
|
||
if kind == "getItem" or kind == "getMonster" and int(value.get("mode", 2)) == 0:
|
||
type_id, count = str(value.get("type")), max(0, int(value.get("num", 0)))
|
||
reserve = max(int(policy.item_reserves.get(type_id, 0)), int(ranch.reserved_eggs.get(type_id, 0)))
|
||
items = [i for i in snapshot.raw["items"] if str(i.get("typeId")) == type_id and not i.get("lock") and not i.get("feedLock")]
|
||
if sum(int(i.get("num", 0)) for i in items) - (reserve if remove else 0) < count:
|
||
return False, [], f"道具 {type_id} 数量不足(需{count},保留{reserve})"
|
||
if remove and not policy.allow_items:
|
||
return False, [], "需启用委托提交道具"
|
||
ids, total = [], 0
|
||
for item in items:
|
||
ids.append(int(item["id"]))
|
||
total += int(item.get("num", 0))
|
||
if total >= count:
|
||
break
|
||
return True, ids, f"道具 {type_id} × {count}"
|
||
if kind == "getMonster":
|
||
type_id, count = str(value.get("type")), max(0, int(value.get("num", 0)))
|
||
if remove and not policy.allow_monsters:
|
||
return False, [], "需启用委托提交魔物"
|
||
monsters = [m for m in snapshot.raw["monsters"] if str(m.get("typeId")) == type_id and int(m.get("mode", 0)) == 2
|
||
and int(m.get("level", 1)) == 1 and not self.guard.protected(m, snapshot, ranch)]
|
||
monsters.sort(key=lambda m: sum(self.catalog.quality(m)))
|
||
return len(monsters) >= count, [int(m["id"]) for m in monsters[:count]], f"需要未保护的1级成熟魔物 {type_id} × {count}"
|
||
if kind == "killMonster":
|
||
target = task.get("stepValue")
|
||
kills = int(indexed(history.get("numKillMonsters"), str(value.get("type")), 0))
|
||
return target is not None and kills >= int(target), [], f"累计击杀 {kills} / {target if target is not None else '未知'}"
|
||
if kind == "passLevel":
|
||
return int(snapshot.raw["master"].get("level", 0)) >= int(value.get("level", 0)), [], f"需要等级 {value.get('level')}"
|
||
if kind == "unlockMonster":
|
||
return int(value.get("type", 0)) in history.get("monLib", []), [], "需要解锁图鉴"
|
||
if kind == "sysLock":
|
||
return bool(indexed(history.get("guide_record"), value.get("key"), False)), [], "等待游戏条件"
|
||
return False, [], "尚未支持的委托条件"
|
||
|
||
def rows(self, snapshot, policy, ranch):
|
||
rows = []
|
||
for task in self.current(snapshot):
|
||
info = self.catalog.data["task_info"][str(task["typeId"])]
|
||
index = int(task.get("curStep", 1)) - 1
|
||
steps = info.get("steps", [])
|
||
text = "可领取奖励" if index >= len(steps) else self.requirement(snapshot, steps[max(0, index)], task, policy, ranch)[2]
|
||
rows.append((str(task["typeId"]), info.get("name", ""), "已接取", text, task))
|
||
history = snapshot.raw.get("history", {})
|
||
for city, offers in (history.get("loopTask") or {}).items():
|
||
if not isinstance(offers, list):
|
||
continue
|
||
for type_id in offers:
|
||
info = self.catalog.data.get("task_info", {}).get(str(type_id), {})
|
||
if info and info.get("type", 4) == 4:
|
||
rows.append((str(type_id), info.get("name", ""), f"城市 {city} 可接", info.get("des", ""), {"city": int(city)}))
|
||
return rows
|
||
|
||
def plan(self, snapshot, policy, ranch, *, include_active=True, accept_supported=None):
|
||
self.commission_selection = {}
|
||
if not policy.enabled:
|
||
return []
|
||
history = snapshot.raw.get("history", {})
|
||
if "loopTaskTime" in history:
|
||
old_day = int((seconds(history["loopTaskTime"]) + 8 * 3600) // 86400)
|
||
current_day = int((snapshot.now - 10 + 8 * 3600) // 86400)
|
||
if old_day < current_day:
|
||
return [Action("quest_reset", "刷新跨日委托", "taskService/taskLoopFlush", {})]
|
||
current_tasks = sorted(self.current(snapshot), key=lambda task: commission_priority(
|
||
self.catalog.data["task_info"][str(task["typeId"])])) if include_active else []
|
||
for task in current_tasks:
|
||
info = self.catalog.data["task_info"][str(task["typeId"])]
|
||
index, steps = int(task.get("curStep", 1)) - 1, info.get("steps", [])
|
||
payload = {"taskId": int(task["id"]), "taskTypeId": str(task["typeId"])}
|
||
if steps and index >= len(steps):
|
||
return [Action("quest_complete", f"领取委托奖励:{info['name']}(预计{-commission_priority(info)}氪金)", "taskService/taskComplete", payload)]
|
||
if 0 <= index < len(steps):
|
||
ready, ids, _ = self.requirement(snapshot, steps[index], task, policy, ranch)
|
||
if ready:
|
||
return [Action("quest_step", f"推进委托:{info['name']}(预计{-commission_priority(info)}氪金)", "taskService/taskCompleteStep", payload | {"removeIds": ids or None})]
|
||
if current_tasks or not policy.accept or int(history.get("loopTaskNum", 0)) <= 0:
|
||
return []
|
||
current = {str(t["typeId"]) for t in self.current(snapshot)}
|
||
offers = sorted(self.rows(snapshot, policy, ranch), key=lambda row: commission_priority(
|
||
self.catalog.data["task_info"][row[0]]))
|
||
candidates, rejected = [], []
|
||
for type_id, name, state, _, meta in offers:
|
||
if "city" not in meta or type_id in current:
|
||
continue
|
||
city = meta["city"]
|
||
info = self.catalog.data["task_info"][type_id]
|
||
candidate = {"task_type_id": type_id, "name": name, "city": city, "expected_ke": -commission_priority(info)}
|
||
candidates.append(candidate)
|
||
reason = (f"策略限定城市 {policy.city}" if policy.city and city != policy.city else
|
||
"城市尚未解锁" if not snapshot.city_unlocked(city) else "委托已关闭" if info.get("closed") else
|
||
"接取前置条件未满足" if not condition_ok((info.get("startStep") or {}).get("condition"), snapshot) else "")
|
||
if reason:
|
||
rejected.append(candidate | {"reason": reason})
|
||
continue
|
||
steps = info.get("steps", [])
|
||
supported = accept_supported(type_id) if accept_supported else all(
|
||
(s.get("statusType") in ("passStage", "battle") and policy.battle_tasks)
|
||
or self.requirement(snapshot, s, {}, policy, ranch)[0] for s in steps)
|
||
if supported:
|
||
self.commission_selection = {"task_type_id": type_id, "city": city,
|
||
**commission_selection(info, candidates, rejected)}
|
||
return [Action("quest_accept", f"接取委托:{name}(预计{-commission_priority(info)}氪金);" + self.commission_selection["selection_reason"],
|
||
"taskService/taskLoopReceive", {"taskTypeId": type_id, "city": city})]
|
||
reason = next((self.requirement(snapshot, step, {}, policy, ranch)[2] for step in steps
|
||
if not self.requirement(snapshot, step, {}, policy, ranch)[0]), "委托后续步骤当前无法自动完成")
|
||
rejected.append(candidate | {"reason": reason})
|
||
return []
|
||
|
||
def reservations(self, snapshot):
|
||
types, eggs = set(), {}
|
||
for task in self.current(snapshot):
|
||
info = self.catalog.data["task_info"][str(task["typeId"])]
|
||
for step in info.get("steps", [])[max(0, int(task.get("curStep", 1)) - 1):]:
|
||
value = step.get("statusValue") or {}
|
||
key = str(value.get("type", ""))
|
||
if step.get("statusType") == "getMonster" and int(value.get("mode", 2)) != 0 and key.isdigit():
|
||
types.add(int(key))
|
||
elif step.get("statusType") in ("getItem", "getMonster") and key in self.catalog.monsters:
|
||
eggs[key] = eggs.get(key, 0) + max(0, int(value.get("num", 0)))
|
||
return types, eggs
|