Files
myrzx_bot/ranch_assistant/quests.py
T

203 lines
10 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 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)
def current(self, snapshot):
return [t for t in snapshot.raw.get("currentTasks", []) if str(t.get("typeId")) in self.catalog.data.get("task_info", {})]
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:
rows.append((str(type_id), info.get("name", ""), f"城市 {city} 可接", info.get("des", ""), {"city": int(city)}))
return rows
def plan(self, snapshot, policy, ranch):
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", {})]
for task in self.current(snapshot):
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']}", "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']}", "taskService/taskCompleteStep", payload | {"removeIds": ids or None})]
if not policy.accept or int(history.get("loopTaskNum", 0)) <= 0:
return []
current = {str(t["typeId"]) for t in self.current(snapshot)}
for type_id, name, state, _, meta in self.rows(snapshot, policy, ranch):
if "city" not in meta or type_id in current:
continue
city = meta["city"]
if policy.city and city != policy.city or not snapshot.city_unlocked(city):
continue
info = self.catalog.data["task_info"][type_id]
if info.get("closed") or not condition_ok((info.get("startStep") or {}).get("condition"), snapshot):
continue
steps = info.get("steps", [])
supported = 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:
return [Action("quest_accept", f"接取委托:{name}", "taskService/taskLoopReceive", {"taskTypeId": type_id, "city": city})]
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