Files
myrzx_bot/ranch_assistant/engine.py
T

426 lines
23 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 replace
import json
from pathlib import Path
import time
from .model import Action, Catalog, Planner, Policy, Snapshot, seconds
from .daily import DailyLedger, DailyPolicy, selected_entries
from .sweeping import SweepPolicy, SweepRunner
from .quests import QuestPolicy, TaskPlanner
from .market import PurchaseBudget
from .management import expansion_quote, manual_monster_actions
from .gifts import GiftPlanner
class Engine:
def __init__(self, catalog, client=None, budget_path=None):
self.catalog, self.client = catalog, client
self.planner = Planner(catalog)
self.gift_planner = GiftPlanner(catalog)
self.policy = Policy()
self.quest_policy = QuestPolicy()
self.tasks = TaskPlanner(catalog)
self.snapshot = None
self.demo = client is None
self.auto = False
self.last_heartbeat = 0
self.heartbeat_enabled = True
self.purchase_budget = PurchaseBudget(budget_path)
self.last_draw = ""
self.growth_cache = {}
self.growth_attempts = {}
self.last_executed = False
folder = Path(budget_path).parent if budget_path else None
self.daily_policy = DailyPolicy()
self.daily_ledger = DailyLedger(folder / "daily_claims.json" if folder else None)
self.sweep_policy = SweepPolicy()
self.sweeper = SweepRunner(catalog, folder / "sweep_runs.json" if folder else None)
def read_snapshot(self):
self.snapshot = self.client.snapshot()
present = self.snapshot.monsters
self.growth_cache = {mid: entry for mid, entry in self.growth_cache.items() if mid in present}
self.growth_attempts = {key: stamp for key, stamp in self.growth_attempts.items() if key[0] in present}
rows = []
fields = ("gAtk", "gDef", "gHp", "gDex")
for mon in self.snapshot.raw["monsters"]:
mid = int(mon["id"])
entry = self.growth_cache.get(mid)
if entry:
start = seconds(mon.get("timeStart"))
if str(mon.get("typeId")) != entry["type"] or start > 0 and entry["start"] > 0 and start != entry["start"]:
self.growth_cache.pop(mid, None)
else:
confirmed = int(mon.get("mode") or 0) >= entry.get("mode", 0)
if entry.get("mode") == 2:
confirmed = confirmed and all(q is not None for q in self.catalog.quality(mon))
for field in fields:
if field in entry and mon.get(field) != entry[field]:
confirmed = False
if confirmed:
self.growth_cache.pop(mid, None)
else:
mon = dict(mon)
mon["mode"] = max(int(mon.get("mode") or 0), entry.get("mode", 0))
mon.update({field: entry[field] for field in fields if field in entry})
rows.append(mon)
self.snapshot.raw["monsters"] = rows
return self.snapshot
def remember_growth(self, response):
# MonsterCenter.checkGrowUpHandler treats these two arrays as the
# authoritative stage and growth values, including after a stale read.
if not isinstance(response, dict):
return
current = self.snapshot.monsters
for key in ("datas", "stackMonsterInfos"):
for row in response.get(key) or []:
if not isinstance(row, dict) or row.get("monsterId") is None:
continue
mid = int(row["monsterId"])
mon = current.get(mid)
if mon is None:
continue
entry = self.growth_cache.setdefault(mid, {"type": str(mon.get("typeId")), "start": seconds(mon.get("timeStart"))})
if key == "datas" and row.get("mode") in (0, 1, 2):
entry["mode"] = max(entry.get("mode", 0), int(row["mode"]))
else:
entry.update({field: row[field] for field in ("gAtk", "gDef", "gHp", "gDex") if row.get(field) is not None})
def settle_pending_growth(self, force=False):
pending = self.snapshot.growth_pending(self.catalog)
now = time.monotonic()
if not pending or not force and all(now - self.growth_attempts.get(key, -1e12) < 60 for key in pending):
return False
for key in pending:
self.growth_attempts[key] = now
response = self.client.settle_growth()
self.remember_growth(response)
self.read_snapshot()
return True
def sync_growth(self):
self.auto = False
if self.demo:
if self.snapshot is None:
self.snapshot = demo_snapshot(self.catalog)
for mon in self.snapshot.raw["monsters"]:
if mon.get("process") == 2:
mon["mode"] = self.snapshot.expected_growth_mode(mon, self.catalog)
else:
self.read_snapshot()
self.settle_pending_growth(force=True)
pending = self.snapshot.growth_pending(self.catalog)
message = "已同步孵化 / 成长状态;本次不执行派遣或喂养"
if pending:
message += f";仍有 {len(pending)} 只等待服务器确认阶段或资质"
return self.snapshot, self.plans(), message
def keep_alive(self):
if self.demo:
return "离线演示无需心跳"
self.last_heartbeat = time.monotonic()
self.client.call("heartBeatService/keepAlive")
return "会话心跳已更新"
def poll(self):
self.last_executed = False
settled = False
if self.demo:
if self.snapshot is None:
self.snapshot = demo_snapshot(self.catalog)
if self.auto and self.policy.enabled:
for mon in self.snapshot.raw["monsters"]:
if mon.get("process") == 2:
mon["mode"] = self.snapshot.expected_growth_mode(mon, self.catalog)
else:
self.read_snapshot()
if self.auto and self.policy.enabled:
settled = self.settle_pending_growth()
message = "状态已刷新" + (";已请求孵化 / 成长结算" if settled else "")
if not self.auto and self.snapshot.growth_pending(self.catalog):
message += ";仅监控:有待结算的孵化 / 成长;请开始执行,或点击“同步孵化 / 成长”"
try:
plans = self.plans()
except (ValueError, TypeError, KeyError, AttributeError) as error:
self.auto = False
return self.snapshot, [], "状态已读取;策略暂不可用:" + str(error)
if self.auto and plans:
action = plans[0]
self.last_executed = True
if action.kind == "daily":
entry = next(row for row in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger) if row.action == action)
self.claim_daily_entry(entry)
return self.snapshot, self.plans(), ("[演示] " if self.demo else "") + action.description
if action.kind == "sweep":
stage = self.sweeper.next(self.snapshot, self.sweep_policy)
if self.demo:
return self.snapshot, plans, "扫荡需要登录真实账号;演示不会提交战斗"
self.sweeper.run(self.client, self.snapshot, stage, self.sweep_policy)
self.read_snapshot()
return self.snapshot, self.plans(), f"扫荡完成:{stage.number} {stage.name} / 难度{stage.level}"
if action.kind == "buy":
price = int(self.catalog.data["markets"][action.payload["id"]]["money"])
self.purchase_budget.record(self.snapshot.now, price * action.payload["num"], self.policy.daily_buy_money)
if self.demo:
self.apply_demo(action)
else:
response = self.client.call(action.path, action.payload)
if action.kind == "buy":
self.record_draw(response.get("eggs") or [])
self.read_snapshot()
if action.kind == "feed" and any(mid in self.snapshot.monsters for mid in action.payload["foods"]):
self.auto = False
raise ValueError("喂养已返回,但素材状态尚未同步;已停止,请刷新核对后再继续")
message = ("[演示] " if self.demo else "") + action.description
if action.kind == "buy" and self.last_draw:
message += ";" + self.last_draw
try:
plans = self.plans()
except (ValueError, TypeError, KeyError, AttributeError) as error:
self.auto = False
plans = []
message += ";状态已读取,策略暂不可用:" + str(error)
if not plans and self.planner.notes:
message += ";" + ";".join(dict.fromkeys(self.planner.notes))
return self.snapshot, plans, message
def plans(self):
quests = self.tasks.plan(self.snapshot, self.quest_policy, self.policy)
types, eggs = self.tasks.reservations(self.snapshot)
reserved = dict(self.policy.reserved_eggs)
for key, count in eggs.items():
reserved[key] = max(reserved.get(key, 0), count)
policy = replace(self.policy, reserved_types=list(set(self.policy.reserved_types) | types), reserved_eggs=reserved)
left = self.purchase_budget.remaining(self.snapshot.now, policy.daily_buy_money)
daily = [row.action for row in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger)] if self.daily_policy.enabled else []
sweep = self.sweeper.next(self.snapshot, self.sweep_policy) if self.sweep_policy.enabled and not self.demo else None
sweep_actions = [Action(kind="sweep", path="", payload={}, description=f"扫荡 {sweep.number} {sweep.name} / 难度{sweep.level}")] if sweep else []
return daily + quests + self.gift_planner.plan(self.snapshot, policy, self.quest_policy) + self.planner.plan(self.snapshot, policy, left) + sweep_actions
def claim_daily_entry(self, entry):
self.daily_ledger.record(self.snapshot, entry.key)
if not self.demo:
self.client.call(entry.action.path, entry.action.payload)
self.read_snapshot()
def claim_daily(self):
self.auto = False
if not self.demo:
self.read_snapshot()
# Fresh status after every claim, bounded by the initially available IDs.
keys = [row.key for row in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger)]
done = 0
for key in keys:
row = next((r for r in selected_entries(self.catalog, self.snapshot, self.daily_policy, self.daily_ledger) if r.key == key), None)
if row:
self.claim_daily_entry(row)
done += 1
return self.snapshot, self.plans(), ("[演示] " if self.demo else "") + f"已处理 {done} 项勾选奖励;自动执行已暂停"
def record_draw(self, eggs):
totals = {}
for egg in eggs:
if isinstance(egg, dict) and egg.get("typeId") is not None:
key = str(egg["typeId"])
totals[key] = totals.get(key, 0) + int(egg.get("num") or 0)
parts = [f"{self.catalog.monster(key).get('name', key)} ×{count}" for key, count in totals.items()]
self.last_draw = f"抽蛋完成,共 {sum(totals.values())} 枚:" + "、".join(parts[:8]) + ("…" if len(parts) > 8 else "")
def set_monster_lock(self, monster_ids, locked):
self.auto = False
ids = list(dict.fromkeys(int(mid) for mid in monster_ids))
if not ids or any(mid <= 0 for mid in ids):
raise ValueError("请先选择需要锁定 / 解锁的魔物")
if not self.demo:
self.read_snapshot()
monsters = self.snapshot.monsters
if any(mid not in monsters for mid in ids):
raise ValueError("选中的魔物已不存在,请刷新后重新选择")
if not locked and any(monsters[mid].get("sysLock") for mid in ids):
raise ValueError("选中包含系统锁定魔物,普通解锁不能解除系统锁,请重新选择")
changed = 0
for mid in ids:
if bool(monsters[mid].get("lock")) == bool(locked):
continue
if self.demo:
monsters[mid]["lock"] = int(locked)
else:
self.client.call("monsterService/monsterLock", {"monsterId": mid, "lock": int(locked)})
self.read_snapshot()
if bool(self.snapshot.monsters.get(mid, {}).get("lock")) != bool(locked):
raise ValueError("服务器返回的锁定状态未更新,已停止后续操作")
changed += 1
message = ("[演示] " if self.demo else "") + f"已{'锁定' if locked else '解锁'} {changed} 只魔物;自动执行已暂停"
return self.snapshot, self.plans(), message
def manage_monsters(self, kind, monster_ids, target_id=0):
self.auto = False
if not self.demo:
self.read_snapshot()
actions = manual_monster_actions(self.catalog, self.snapshot, kind, monster_ids, target_id)
for action in actions:
if self.demo:
field = "foods" if kind == "feed" else "monsterId" if "monsterId" in action.payload else "monsterIds"
for mid in action.payload[field]:
self.apply_demo(replace(action, payload=action.payload | {field: [mid]}))
else:
self.client.call(action.path, action.payload)
self.read_snapshot()
consumed = action.payload.get("foods") or action.payload.get("monsterId") or action.payload.get("monsterIds") or []
if any(int(mid) in self.snapshot.monsters for mid in consumed):
raise ValueError("操作已返回,但魔物记录尚未更新;请刷新核对,不会重复提交")
return self.snapshot, self.plans(), ("[演示] " if self.demo else "") + ";".join(a.description for a in actions) + ";自动执行已暂停"
def expand(self, quote):
self.auto = False
if not self.demo:
self.read_snapshot()
fresh = expansion_quote(self.catalog, self.snapshot, quote.kind, quote.currency, quote.position)
if fresh != quote:
raise ValueError("扩建费用或次数已变化,请刷新后重新确认")
old_rooms = {int(r["id"]) for r in self.snapshot.raw["rooms"]}
if self.demo:
raw = self.snapshot.raw
raw["master"][quote.currency] -= quote.cost
counter = ("numAdd" if quote.currency == "money" else "numKeAdd") + ("Stack" if quote.kind == "stack" else "Room")
raw["history"][counter] += 1
if quote.kind == "stack":
raw["stacks"].append({"id": max([int(s["id"]) for s in raw["stacks"]] + [0]) + 1,
"position": quote.position, "monsterId": -1, "openType": quote.payload["openType"]})
else:
type_id = 1000 if "1000" in self.catalog.data["room_info"] else int(raw["rooms"][0]["typeId"])
raw["rooms"].append({"id": max(old_rooms or {0}) + 1, "typeId": type_id, "openType": 1 if quote.currency == "money" else 2})
else:
self.client.call(quote.path, quote.payload)
self.read_snapshot()
verified = (any(int(s.get("position", -1)) == quote.position for s in self.snapshot.raw["stacks"]) if quote.kind == "stack"
else bool({int(r["id"]) for r in self.snapshot.raw["rooms"]} - old_rooms))
if not verified:
raise ValueError("扩建请求已返回,但尚未读取到新增记录;请刷新核对,不会自动重复提交")
return self.snapshot, self.plans(), ("[演示] " if self.demo else "") + quote.description + ",已完成"
def apply_demo(self, action):
if action.kind == "collect" and sum(len(d["monsterId"]) for d in action.payload["datas"]) > 1:
for data in action.payload["datas"]:
for mid in data["monsterId"]:
self.apply_demo(replace(action, payload={"datas": [{"monsterId": [mid], "roomId": data["roomId"]}]}))
return
if action.kind == "feed" and len(action.payload["foods"]) > 1:
for mid in action.payload["foods"]:
self.apply_demo(replace(action, payload=action.payload | {"foods": [mid]}))
return
raw = self.snapshot.raw
if action.kind.startswith("quest_"):
self.apply_demo_quest(action)
return
if action.kind == "buy":
market = self.catalog.data["markets"][action.payload["id"]]
count = action.payload["num"]
gift_every = int(market.get("freegift") or 0)
received = count + (count // gift_every if gift_every > 0 else 0)
# Deterministic offline example, not a prediction of the server draw.
type_id = int(next(iter(market["eggs"].values()))[0])
item = next((i for i in raw["items"] if int(i["typeId"]) == type_id), None)
if item:
item["num"] += received
else:
raw["items"].append({"id": max([int(i["id"]) for i in raw["items"]] + [500]) + 1, "typeId": type_id, "num": received})
raw["master"]["money"] -= int(market["money"]) * count
self.record_draw([{"typeId": type_id, "num": received}])
return
if action.kind == "collect":
data = action.payload["datas"][0]
mid = data["monsterId"][0]
self.snapshot.monsters[mid].update(process=3, roomId=data["roomId"])
elif action.kind in ("sell", "feed"):
mid = (action.payload.get("monsterId") or action.payload.get("monsterIds") or action.payload.get("foods"))[0]
mon = self.snapshot.monsters[mid]
if action.kind == "sell":
raw["master"]["money"] += self.catalog.monster(mon["typeId"])["sell_money"]
else:
target = self.snapshot.monsters[action.payload["targetId"]]
target["exp"] = target.get("exp", 0) + self.catalog.feed_exp(mon)
raw["monsters"] = [m for m in raw["monsters"] if m["id"] != mid]
elif action.kind == "gift":
target = self.snapshot.monsters[action.payload["monsterId"]]
item = next(i for i in raw["items"] if int(i["typeId"]) == action.payload["itemId"])
gain = int(self.catalog.monster(target.get("typeId")).get("like", {}).get(str(item["typeId"]), 0))
target["feel"] = max(0, min(self.catalog.max_feel(target), int(target.get("feel") or 0) + gain))
target["giftTime"] = int(time.time())
item["num"] -= 1
return
else:
egg = action.payload["eggs"][0]
item = next(i for i in raw["items"] if i["id"] == egg["itemId"])
item["num"] -= 1
mid = max([m["id"] for m in raw["monsters"]] + [100]) + 1
row = self.catalog.monster(item["typeId"])
mon = {"id": mid, "typeId": item["typeId"], "process": 2, "mode": 0, "level": 1, "exp": 0, "timeStart": int(time.time() * 1000), "roomId": 0}
mon.update({"g" + s.capitalize(): row[s + "_grow_min"] for s in ("atk", "def", "hp", "dex")})
raw["monsters"].append(mon)
next(s for s in raw["stacks"] if s["id"] == egg["stackId"])["monsterId"] = mid
return
for slot in raw["stacks"]:
if slot.get("monsterId") == mid:
slot["monsterId"] = 0
def apply_demo_quest(self, action):
raw = self.snapshot.raw
history = raw.setdefault("history", {})
tasks = raw.setdefault("currentTasks", [])
if action.kind == "quest_reset":
history["loopTaskTime"] = int(time.time())
history["loopTaskNum"] = self.catalog.data["game_setting"].get("loopTaskMaxNum", 6)
elif action.kind == "quest_accept":
type_id = action.payload["taskTypeId"]
tasks.append({"id": max([t["id"] for t in tasks] + [1000]) + 1, "typeId": type_id, "curStep": 1, "stepValue": 0})
history["loopTaskNum"] -= 1
offers = history["loopTask"][str(action.payload["city"])]
offers[:] = [t for t in offers if str(t) != type_id]
else:
task = next(t for t in tasks if int(t["id"]) == action.payload["taskId"])
info = self.catalog.data["task_info"][str(task["typeId"])]
if action.kind == "quest_complete":
raw["master"]["money"] += int(info.get("reward", {}).get("money", 0))
raw["master"]["ke"] = raw["master"].get("ke", 0) + int(info.get("reward", {}).get("ke", 0))
tasks.remove(task)
else:
step = info["steps"][task["curStep"] - 1]
value = step.get("statusValue") or {}
if value.get("remove"):
ids = action.payload.get("removeIds") or []
if step["statusType"] == "getMoney":
raw["master"]["money"] -= int(value["money"])
elif step["statusType"] == "getItem" or int(value.get("mode", 2)) == 0:
left = int(value["num"])
for item in raw["items"]:
if int(item["id"]) in ids:
used = min(left, int(item["num"]))
item["num"] -= used
left -= used
else:
raw["monsters"] = [m for m in raw["monsters"] if int(m["id"]) not in ids]
for slot in raw["stacks"]:
if slot.get("monsterId") in ids:
slot["monsterId"] = 0
task["curStep"] += 1
def demo_snapshot(catalog):
types = [int(k) for k, row in catalog.monsters.items() if row.get("star") == 1 and not row.get("npc")][:4]
monsters = []
for i, type_id in enumerate(types):
row = catalog.monster(type_id)
mon = {"id": 101 + i, "typeId": type_id, "level": 1, "exp": 0, "process": 2, "mode": 2 if i < 2 else 0,
"timeStart": int((time.time() - catalog.total_time(type_id) + (0 if i < 2 else 200)) * 1000), "roomId": 0, "lock": 0}
mon.update({"g" + s.capitalize(): row[s + "_grow_min"] for s in ("atk", "def", "hp", "dex")})
monsters.append(mon)
target = dict(monsters[0]) | {"id": 900, "process": 3, "mode": 2, "level": 20, "potentialLevel": 7, "roomId": 1, "lock": 1}
room_type = next(k for k, row in catalog.data["room_info"].items() if row.get("maxNum", 0) >= 10)
return Snapshot({"master": {"id": 1, "roleName": "离线演示", "level": 62, "exp": 456789, "money": 12345, "ke": 2000, "ti": 100},
"stacks": [{"id": i + 1, "position": i, "monsterId": 101 + i if i < 4 else 0, "openType": 3} for i in range(6)],
"monsters": monsters + [target], "items": [{"id": 501 + i, "typeId": t, "num": 8} for i, t in enumerate(types)] + [{"id": 600, "typeId": 20047, "num": 3}],
"rooms": [{"id": 1, "typeId": int(room_type), "openType": 3, "name": "主牧场"}], "teams": [{"monsters": [900]}], "activityHistory": {},
"history": {"unlockCity": {"1": True}, "openFarmBuild": True, "numAddStack": 0, "numKeAddStack": 0, "numAddRoom": 0, "numKeAddRoom": 0}})