fix(web): finalize quick battle and commission procurement for 2.0.9

This commit is contained in:
AttilaNet
2026-11-13 11:28:14 +08:00
parent cfce3e0bc5
commit 7845751cf6
21 changed files with 2442 additions and 117 deletions
+117 -64
View File
@@ -45,7 +45,8 @@ import uuid
from .game_data import ProgressionData, load_progression_data
from .model import Planner, seconds
from .quests import commission_priority, commission_selection, indexed, stage_has_level
from .quests import commission_priority, commission_selection, commission_reason_kind, indexed, stage_has_level
from .procurement import ResourceProcurement, resource_kind
CATEGORIES = {1: ("mainline", "主线"), 2: ("sidequest", "支线"),
@@ -180,6 +181,8 @@ class ProgressionPlanner:
self.catalog = catalog
self.data = data if isinstance(data, ProgressionData) else ProgressionData(data) if data is not None else load_progression_data()
self.guard = Planner(catalog)
self.procurement = ResourceProcurement(catalog, self.guard)
self.procurement_daily_left = None
self._namespace = str(account_key) if account_key is not None else ""
self._anonymous = uuid.uuid4().hex
self._accounts = {}
@@ -328,6 +331,18 @@ class ProgressionPlanner:
"bar": "酒馆", "shop": "商店", "wild": "野外", "mine": "矿洞", "pve": "挑战"}
return city_name + (" · " + labels.get(tail, tail) if tail else "")
def city_diagnostic(self, city, snapshot):
info = (self.data.game_setting.get("cityInfo") or {}).get(str(city), {})
name = info.get("name") or f"城市 {city}"
key = str(info.get("openTask") or "")
task = self.data.task(key) or {}
_, account = self._account(snapshot)
unlocked = snapshot.city_unlocked(city) or str(city) in account["city_unlocks"]
condition = f"完成{CATEGORIES.get(task.get('type'), ('', '任务'))[1]}《{task.get('name') or key}》({key})" if key else "等待服务器确认城市解锁"
reason = "" if unlocked else f"{name}(城市{city})城市尚未解锁;解锁条件:{condition}" if info else "城市尚未解锁"
return {"city_name": name, "unlock_task_id": key, "unlock_condition": condition,
"city_unlocked": unlocked, "city_reason": reason}
def _location_gate(self, position, snapshot, account):
if not position or position in ("farm", "stackGround"):
return ""
@@ -341,7 +356,7 @@ class ProgressionPlanner:
if city_info.get("hide") is True:
return "城市已隐藏"
if not (snapshot.city_unlocked(int(city)) or city in account["city_unlocks"]):
return "目标城市尚未解锁"
return self.city_diagnostic(int(city), snapshot)["city_reason"]
if tail is None or tail in {"market", "xiehui", "alchemy", "bar", "shop", "wild", "mine", "pve"}:
if tail == "mine" and (snapshot.raw.get("history") or {}).get("openMine") is not True:
return "矿洞功能尚未开放"
@@ -459,47 +474,9 @@ class ProgressionPlanner:
if money - amount < ranch_policy.keep_money:
return False, None, "提交后低于牧场金币保留量"
return money >= amount, None, f"金币 {money}/{amount}"
if kind == "getItem" or kind == "getMonster" and _integer(value.get("mode"), -2) == 0:
key, count = str(value.get("type", "")), _integer(value.get("num"), -1)
if not key.isdigit() or count < 0:
return False, None, "道具条件缺少有效类型或数量"
remove = value.get("remove") is True
reserve = max(policy.item_reserves.get(key, 0), _integer(ranch_policy.reserved_eggs.get(key)))
gift = ranch_policy.gift_items.get(key, {})
reserve = max(reserve, _integer(gift.get("reserve")))
items = [item for item in snapshot.raw.get("items", []) if str(item.get("typeId")) == key
and not item.get("lock") and not item.get("sysLock") and not item.get("feedLock")
and _integer(item.get("id")) > 0 and _integer(item.get("num")) > 0]
total = sum(_integer(item.get("num")) for item in items)
if total - (reserve if remove else 0) < count:
return False, None, f"道具 {self.catalog.item_name(key)} {total}/{count},需保留 {reserve}"
if remove and count and not policy.allow_items:
return False, None, "提交道具未启用"
ids, used = [], 0
for item in items:
if used >= count:
break
ids.append(_integer(item["id"]))
used += _integer(item["num"])
# AS3 supplies IDs for observation-only getItem as well.
return True, ids, f"道具 {self.catalog.item_name(key)} ×{count}"
if kind == "getMonster":
key, count, mode = str(value.get("type", "")), _integer(value.get("num"), -1), _integer(value.get("mode"), -2)
if not key.isdigit() or count < 0 or mode not in (2, -1):
return False, None, "未支持的魔物条件或形态"
remove = value.get("remove") is True
if remove and count and not policy.allow_monsters:
return False, None, "提交魔物未启用"
candidates = []
for monster in snapshot.raw.get("monsters", []):
if (str(monster.get("typeId")) != key or _integer(monster.get("level"), 1) != 1
or _integer(monster.get("mode"), -2) != 2 or _integer(monster.get("process"), 2) < 2
or monster.get("inteam") or self.guard.protected(monster, snapshot, ranch_policy)):
continue
candidates.append(monster)
candidates.sort(key=lambda monster: (sum(self.catalog.quality(monster)), _integer(monster["id"])))
return (len(candidates) >= count, [_integer(monster["id"]) for monster in candidates[:count]],
f"未保护的1级成熟魔物 {self.catalog.item_name(key)} {len(candidates)}/{count}")
if resource_kind(step):
row = self.procurement.inventory(snapshot, step, policy, ranch_policy)
return row["ready"], row["ids"] if row["ready"] else None, row["reason"]
if kind == "killMonster":
target = task.get("stepValue")
kills = indexed(history.get("numKillMonsters"), value.get("type"))
@@ -600,6 +577,13 @@ class ProgressionPlanner:
reason = self._script_gate(step.get("afterStory"))
if reason or step.get("afterStory") and not policy.auto_dialogue:
return block(reason or "自动后续对话未启用")
if resource_kind(step):
supply = self.remaining_resource_plan(snapshot, info, task, policy, ranch)
if supply.feasible:
action = self._resource_intent(snapshot, supply, effective_task, number, step, policy)
if action is not None:
return action
return block(supply.reason + ";" + supply.next_step)
farming = self.farming_intents(snapshot, step, effective_task, policy, ranch)
if farming:
return farming[0]
@@ -838,6 +822,54 @@ class ProgressionPlanner:
return self._intent(scope, task, number, steps[number - 1], "progression_blocked", reason, policy, block_reason=reason)
return self._next(snapshot, policy, ranch, scope, account, task, info)
def remaining_resource_plan(self, snapshot, info, task, policy, ranch):
"""One remaining-step/coin-reserve calculation for planning and dispatch."""
effective_task = dict(task)
number = 1
if _integer(task.get("id")) > 0:
_, account = self._account(snapshot)
record = self._record(task, account)
number = record["cursor"]
if number != _integer(task.get("curStep")):
effective_task["stepValue"] = record["next_value"]
effective_task["curStep"] = number
steps = (info.get("steps") or [])[max(0, number - 1):]
money = sum(_integer((step.get("statusValue") or {}).get("money")) for step in steps
if step.get("statusType") == "getMoney" and (step.get("statusValue") or {}).get("remove") is True)
return self.resource_plan(snapshot, steps, effective_task, policy,
replace(ranch, keep_money=ranch.keep_money + money))
def resource_plan(self, snapshot, steps, task, policy, ranch):
def sources(trial):
actions = self.farming_intents(snapshot, trial, task, policy, ranch)
check = getattr(self, "battle_capability", None)
supported, reasons = [], []
for action in actions:
ok, reason = (True, "") if action.kind == "sweep" or not callable(check) else check(action)
if ok:
supported.append(action)
elif reason:
reasons.append(reason)
return supported, ";".join(dict.fromkeys(reasons))
return self.procurement.plan(snapshot, steps, policy, ranch,
daily_left=self.procurement_daily_left, farm_sources=sources)
def _resource_intent(self, snapshot, supply, task, number, step, policy):
if supply.sources:
return supply.sources[0]
scope, _ = self._account(snapshot)
if supply.action:
action = supply.action
note = ";先补资源,未提交任务步骤" if _integer(task.get("id")) else ";先补资源,尚未接取委托,未消耗接取次数"
return self._intent(scope, {}, 0, {}, "progression_procure", action.description + note, policy,
path=action.path, payload=deepcopy(action.payload), phase=action.kind,
source_task_id=_integer(task.get("id")), source_task_type_id=str(task.get("typeId", "")),
source_step_number=number)
if not supply.ready:
reason = supply.reason + ";" + supply.next_step
return self._intent(scope, task, number, step, "progression_blocked", reason, policy, block_reason=reason)
return None
def _commission_offer_ready(self, snapshot, quest_policy, policy, ranch, info):
if info.get("closed"):
return False, "委托已关闭"
@@ -847,9 +879,14 @@ class ProgressionPlanner:
# Acceptance spends a daily slot. Keep the old scheduler's conservative
# resource preflight, now allowing verified linear story completion.
money = 0
item_costs = {}
monster_costs = {}
scope, account = self._account(snapshot)
for number, step in enumerate(info.get("steps") or [], 1):
ok, reason = self.condition(step.get("condition"), snapshot)
reason = reason if not ok else self._location_gate(str(step.get("position") or ""), snapshot, account)
if not reason and step.get("passGuide") and indexed((snapshot.raw.get("history") or {}).get("guide_record"), step["passGuide"]) is not True:
reason = "等待引导记录:" + str(step["passGuide"])
if reason:
return False, f"第{number}步:{reason}"
for script in (step.get("story"), step.get("afterStory")):
reason = self._script_gate(script)
if reason or script and not policy.auto_dialogue:
@@ -862,7 +899,7 @@ class ProgressionPlanner:
return False, "委托战斗配置缺失"
if kind == "passStage" and not self.data.stage(value.get("stage")):
return False, "委托关卡配置缺失"
else:
elif not resource_kind(step):
ready, _, reason = self.requirement(snapshot, step, {}, policy, ranch)
if not ready:
preview = {"id": 0, "typeId": str(info.get("id", "")), "curStep": number}
@@ -871,23 +908,12 @@ class ProgressionPlanner:
if value.get("remove") is True:
if kind == "getMoney":
money += _integer(value.get("money"))
elif kind == "getItem" or kind == "getMonster" and _integer(value.get("mode"), -1) == 0:
key = str(value.get("type"))
item_costs[key] = item_costs.get(key, 0) + _integer(value.get("num"))
elif kind == "getMonster":
key = str(value.get("type"))
monster_costs[key] = monster_costs.get(key, 0) + _integer(value.get("num"))
if money and (money > policy.max_money or _integer(snapshot.raw["master"].get("money")) - money < ranch.keep_money):
return False, "整份委托提交金币超过设置或保留量"
for key, count in item_costs.items():
trial = {"statusType": "getItem", "statusValue": {"type": key, "num": count, "remove": True}}
if not self.requirement(snapshot, trial, {}, policy, ranch)[0]:
if not self.farming_intents(snapshot, trial, {"id": 0}, policy, ranch):
return False, "整份委托提交道具不足或受保留保护"
for key, count in monster_costs.items():
trial = {"statusType": "getMonster", "statusValue": {"type": key, "num": count, "mode": 2, "remove": True}}
if not self.requirement(snapshot, trial, {}, policy, ranch)[0]:
return False, "整份委托提交魔物不足或受保留保护"
supply = self.resource_plan(snapshot, info.get("steps") or [], {"id": 0, "typeId": str(info.get("id", ""))},
policy, replace(ranch, keep_money=ranch.keep_money + money))
if not supply.feasible:
return False, supply.reason
return (True, "可接取") if info.get("steps") else (False, "委托没有有效步骤")
def commission_plan(self, snapshot, quest_policy, ranch_policy, *, battle_policy=None, accept_supported=None):
@@ -936,6 +962,16 @@ class ProgressionPlanner:
for candidate in candidates:
city, key = candidate["city"], candidate["task_type_id"]
info = self.data.task(key)
if candidate.get("preparable"):
money = sum(_integer((s.get("statusValue") or {}).get("money")) for s in info.get("steps") or []
if s.get("statusType") == "getMoney" and (s.get("statusValue") or {}).get("remove") is True)
supply = self.resource_plan(snapshot, info.get("steps") or [], {"id": 0, "typeId": key}, policy,
replace(ranch_policy, keep_money=ranch_policy.keep_money + money))
action = self._resource_intent(snapshot, supply, {"id": 0, "typeId": key}, 0, {}, policy)
if action is not None:
if not action.blocked:
self._issued[action.token] = action.to_dict()
return [action]
if not candidate["eligible"]:
rejected.append(candidate)
if candidate["blocked_by_support"]:
@@ -969,11 +1005,13 @@ class ProgressionPlanner:
if info.get("type") != 4:
continue
support_blocked = False
city_info = self.city_diagnostic(city, snapshot)
supply = None
reason = ("城市编号无效" if city <= 0 else
"当日接取次数已用完(剩余0次),等待次日刷新" if remaining <= 0 else
f"策略限定城市 {quest_policy.city}" if quest_policy.city and city != quest_policy.city else
"城市尚未解锁" if not snapshot.city_unlocked(city) else
city_info["city_reason"] if not city_info["city_unlocked"] else
"委托列表已跨日,等待刷新确认" if recorded is not None and recorded != today and account["commissions"]["day"] != today else
"当日接取次数已用完" if remaining <= 0 else
"自动委托未启用" if not quest_policy.enabled else "自动接取未启用" if not quest_policy.accept else
"存在未确认请求,等待核对" if account["pending"] else
"该委托已接取或已完成" if key in active or key in finished else
@@ -988,9 +1026,24 @@ class ProgressionPlanner:
if not supported:
reason = detail or "委托后续战斗或条件当前无法自动完成"
support_blocked = True
if not reason:
money = sum(_integer((s.get("statusValue") or {}).get("money")) for s in info.get("steps") or []
if s.get("statusType") == "getMoney" and (s.get("statusValue") or {}).get("remove") is True)
supply = self.resource_plan(snapshot, info.get("steps") or [], {"id": 0, "typeId": key},
policy, replace(ranch_policy, keep_money=ranch_policy.keep_money + money))
if not supply.ready:
reason = supply.reason + ";" + supply.next_step + ";补齐并核对后再接取,不消耗接取次数"
elif any(resource_kind(s) for s in info.get("steps") or []):
supply = self.resource_plan(snapshot, info.get("steps") or [], {"id": 0, "typeId": key}, policy, ranch_policy)
if supply.feasible:
supply = None # A hard prerequisite failed; procurement cannot bypass it.
rows.append({"task_type_id": key, "name": info.get("name", key), "city": city,
"expected_ke": -commission_priority(info), "eligible": not reason, "reason": reason or "可接取",
"blocked_by_support": support_blocked})
"blocked_by_support": support_blocked, "preparable": bool(supply and supply.feasible and not supply.ready and not support_blocked),
**city_info, "remaining_quota": remaining,
"reason_kind": supply.reason_kind if supply and not supply.ready and not support_blocked else commission_reason_kind(reason),
"resources": supply.resources if supply else [], "progress_plan": supply.progress_plan if supply else [],
"next_step": supply.next_step if supply and not supply.ready else reason or "按奖励优先接取城市委托"})
return rows
def commission_rows(self, snapshot, quest_policy, ranch_policy, *, battle_policy=None):