fix(web): finalize quick battle and commission procurement for 2.0.9
This commit is contained in:
@@ -0,0 +1,370 @@
|
||||
"""Fast, approximate HP/DPS budgets; no movement, animation or skill replay.
|
||||
|
||||
Inputs and the experimental result/settlement contract come from the existing
|
||||
simulator. One-second simultaneous damage budgets are not original-engine hits.
|
||||
"""
|
||||
from collections import Counter
|
||||
from dataclasses import replace
|
||||
import math
|
||||
import time
|
||||
|
||||
from . import battle_simulator as sim
|
||||
|
||||
|
||||
ASSUMPTIONS = (
|
||||
"Aggregate model: one-second simultaneous HP/DPS budgets, without movement or animation.",
|
||||
"Expected damage uses original attack, defense, dexterity, element and critical-hit formulas.",
|
||||
"Damage is shared equally among eligible opposing targets; explicit target locks take precedence.",
|
||||
"Team capacity, ordered waves, join times and death/time reinforcement gates use coarse numeric steps.",
|
||||
"Makers generate original-stat units at an averaged rate, bounded by 128 generated units per battle.",
|
||||
"Skills use bounded expected damage/healing contributions; other skill effects are omitted.",
|
||||
"HP controllers use averaged healing/damage rates; other control, movement and buff effects are omitted.",
|
||||
"This approximate model has not been validated against original AIR battle outcomes.",
|
||||
)
|
||||
MAX_GENERATED = 128
|
||||
MAX_STEPS = 7200
|
||||
|
||||
|
||||
class _MeanRoll:
|
||||
@staticmethod
|
||||
def uniform(low, high):
|
||||
return (low + high) / 2
|
||||
|
||||
|
||||
def prepare(request, tables=None):
|
||||
tables = tables if tables is not None else sim.combat_tables()
|
||||
scenario, report = sim._prepare(request, tables, quick=True)
|
||||
report.update(model="quick-v1-hp-dps", approximate=True, faithful=False,
|
||||
simulation_method="aggregate_hp_dps", implemented_skills=[],
|
||||
assumptions=list(ASSUMPTIONS), ignored_mechanics=list(ASSUMPTIONS))
|
||||
for d in report["diagnostics"]:
|
||||
if d["code"] == "unsupported_skill":
|
||||
d["code"] = "aggregate_skill"
|
||||
d["message"] = d["message"].replace("is omitted", "uses a bounded aggregate expectation where numeric parameters exist")
|
||||
elif d["code"] == "aggregate_approximation":
|
||||
d["message"] = d["message"].replace("unsupported", "approximated").replace("Unsupported", "Approximated")
|
||||
if scenario is not None:
|
||||
battle = sim._get(sim._get(request, "original_data", {}), "battle", {})
|
||||
kinds = sorted({str(c.get("type", "unknown")) for c in battle.get("controller", ()) or ()}
|
||||
| {str(c.get("type", "unknown")) for t in battle.get("teams", ()) for m in t.get("mons", ()) if m
|
||||
for c in m.get("controller", ()) or ()})
|
||||
report["aggregate_controllers"] = kinds
|
||||
report["assumptions"].append("Configured controllers: " + (", ".join(kinds) or "none") + "; only makers, HP rates and numeric target gates affect this model.")
|
||||
report["objective"] = {1: "elimination", 2: "survive_until_time", 3: "destroy_any", 4: "destroy_all"}.get(
|
||||
scenario.win_types[0] if scenario.win_types else 1, "elimination_approximation")
|
||||
for c in list(battle.get("controller", ()) or ()) + [c for t in battle.get("teams", ())
|
||||
for m in t.get("mons", ()) if m for c in m.get("controller", ()) or ()]:
|
||||
if c.get("type") == "monMaker":
|
||||
p = c.get("para", {})
|
||||
try:
|
||||
if str(sim._int(p.get("monType", 0))) not in tables["monster_info"]:
|
||||
raise sim.SimulationInputError("Generated monster species has no original attributes")
|
||||
if sim._int(p.get("team", 2)) not in scenario.teams:
|
||||
# Standalone controllers can be the only source of enemies.
|
||||
scenario.teams[sim._int(p.get("team", 2))] = {"capacity": 4, "initial": 0, "max": 0}
|
||||
for name in ("interval", "hp", "hpMax", "atk", "level"):
|
||||
if p.get(name) is not None:
|
||||
sim._number(p[name])
|
||||
except sim.SimulationInputError as exc:
|
||||
report["reasons"].append(str(exc))
|
||||
report["supported"] = False
|
||||
report["teams"] = sim._plain(scenario.teams)
|
||||
return scenario, report
|
||||
|
||||
|
||||
class _QuickBattle(sim._Battle):
|
||||
def __init__(self, scenario, report, tables, request):
|
||||
super().__init__(scenario, report, tables)
|
||||
self.pending_triggers = [] # Triggers below affect budgets, never a detailed replay.
|
||||
self.raw = sim._get(sim._get(request, "original_data", {}), "battle", {})
|
||||
self.raw_mons = {f"configured-{ti + 1}-{mi + 1}": m for ti, t in enumerate(self.raw.get("teams", ()))
|
||||
for mi, m in enumerate(t.get("mons", ())) if m}
|
||||
roster = sim._get(request, "roster", sim._get(request, "snapshot", {}))
|
||||
roster = sim._get(roster, "raw", roster)
|
||||
players = {str(m["id"]): m for m in roster.get("monsters", ())}
|
||||
self.raw_mons.update({a.unit.key: players[a.unit.source_id] for a in self.actors
|
||||
if a.unit.key.startswith("player-")})
|
||||
self.triggers = list(self.raw.get("triggers", ()) or ())
|
||||
self.gated = set()
|
||||
self.join_gates = set()
|
||||
for t in self.triggers:
|
||||
for e in t.get("effects", ()):
|
||||
p = e.get("para", {})
|
||||
if e.get("type") == "unlockWave":
|
||||
self.gated.add((sim._int(p.get("team", 2)), sim._int(p.get("wave", 1))))
|
||||
if e.get("type") == "monJoin":
|
||||
self.join_gates.add(str(p.get("mid", "")))
|
||||
self.next_wave = {}
|
||||
self.generated = 0
|
||||
self.damage_checks = set()
|
||||
self.peak_dps = Counter()
|
||||
self.expectations = {}
|
||||
self.hp_rates = {}
|
||||
self.makers = []
|
||||
for a in self.actors:
|
||||
self.configure(a, self.raw_mons.get(a.unit.key, {}))
|
||||
for c in self.raw.get("controller", ()) or ():
|
||||
if c.get("type") == "monMaker":
|
||||
self.makers.append({"vo": c, "owner": None, "credit": 0.,
|
||||
"active": c.get("para", {}).get("activited", True) is not False})
|
||||
|
||||
def configure(self, actor, mon):
|
||||
u, row = actor.unit, self.tables["monster_info"][str(actor.unit.species)]
|
||||
damage, healing = 1., 0.
|
||||
player = u.key.startswith("player-")
|
||||
for slot in (1, 2):
|
||||
sid = sim._int(mon.get(f"skill_{slot}", -1)) if not player else -1
|
||||
sid = sim._int(row.get(f"skill_{slot}", 0)) if sid == -1 else sid
|
||||
if player and sim._int(mon.get("upStar", 0)) > 0:
|
||||
sid = sim._int(self.tables["upstar_info"].get(str(u.species), {}).get("skill", {}).get(str(slot), sid))
|
||||
tp = min(4, sim._int(mon.get("tpLevel", 0)))
|
||||
level = sim._int(mon.get(f"skill_{slot}_lv", -1))
|
||||
level = max(1, tp + 1 if slot == 1 and not sim._int(row.get("skill_2", 0)) else 1) if level < 1 else level
|
||||
skill = self.tables["monster_skill"].get(str(sid), {}).get(f"lv{level}", {})
|
||||
p = skill.get("para", {})
|
||||
cooldown = max(1., sim._number(skill.get("cd", 10000)) / 1000)
|
||||
# At most 25% total expected damage gain, never a stat multiplier.
|
||||
extra = max(0., sim._number(p.get("damage", p.get("hurt", 1))) - 1)
|
||||
damage += min(.125, extra / cooldown)
|
||||
healing += max(0., sim._number(p.get("cure", 0)) + u.stats.atk * sim._number(p.get("cureAtkAdd", 0))) / cooldown
|
||||
self.expectations[u.key] = (min(1.25, damage), healing)
|
||||
rates = []
|
||||
for c in mon.get("controller", ()) or ():
|
||||
kind, p = c.get("type"), c.get("para", {})
|
||||
if kind == "monMaker":
|
||||
self.makers.append({"vo": c, "owner": u.key, "credit": 0., "active": True})
|
||||
if kind in ("hp", "hpArea"):
|
||||
rates.append((kind, sim._number(p.get("hp", 0)) / max(1., sim._number(p.get("interval", 1000)) / 1000),
|
||||
str(p.get("mid", -1))))
|
||||
for name, kind in (("selfCure", "hp"), ("sunFire", "enemy"), ("moonHeal", "hpArea")):
|
||||
amount = u.effects.get(name, 0)
|
||||
if amount:
|
||||
rates.append((kind, (-amount if name == "sunFire" else amount) / 5, "-1"))
|
||||
self.hp_rates[u.key] = rates
|
||||
|
||||
def gates(self):
|
||||
for trigger in list(self.triggers):
|
||||
p, kind = trigger.get("para", {}), trigger.get("type")
|
||||
source = self.by_source_id.get(str(p.get("mid", "")))
|
||||
ready = kind == "time" and self.now >= sim._number(p.get("time", 0)) * 1000
|
||||
ready |= kind == "monDead" and source is not None and source.state == "dead"
|
||||
ready |= kind == "waveStart" and self.wave.get(sim._int(p.get("team", 2)), 1) >= sim._int(p.get("wave", 1))
|
||||
if not ready:
|
||||
continue
|
||||
self.triggers.remove(trigger)
|
||||
self.event("aggregate_trigger", trigger_kind=kind)
|
||||
for effect in trigger.get("effects", ()):
|
||||
ep, ek = effect.get("para", {}), effect.get("type")
|
||||
if ek == "unlockWave":
|
||||
self.unlocked_waves[sim._int(ep.get("team", 2))].add(sim._int(ep.get("wave", 1)))
|
||||
elif ek == "monJoin":
|
||||
a = self.by_source_id.get(str(ep.get("mid", "")))
|
||||
if a:
|
||||
a.force_join = True
|
||||
elif ek in ("startController", "stopController"):
|
||||
for maker in self.makers:
|
||||
if str(maker["vo"].get("id", "")) == str(ep.get("id", "")):
|
||||
maker["active"] = ek == "startController"
|
||||
|
||||
def recruit(self):
|
||||
self.gates()
|
||||
for team in self.s.teams:
|
||||
waiting = [a for a in self.actors if a.unit.team == team and a.state == "waiting"]
|
||||
active = [a for a in self.actors if a.unit.team == team and a.state == "active" and not a.unit.is_object]
|
||||
if waiting and not active:
|
||||
wave = min(a.unit.wave for a in waiting)
|
||||
if (team, wave) not in self.gated:
|
||||
due = self.next_wave.setdefault((team, wave), self.now + (0 if wave <= 1 else 700))
|
||||
if self.now >= due:
|
||||
self.unlocked_waves[team].add(wave)
|
||||
self.wave[team] = wave
|
||||
counts = Counter(a.unit.team for a in self.active() if a.unit.count_unit)
|
||||
for a in self.actors:
|
||||
u = a.unit
|
||||
if a.state != "waiting" or (not a.force_join and (
|
||||
u.wave not in self.unlocked_waves[u.team] or self.now < max(0, u.join_time) * 1000
|
||||
or u.source_id in self.join_gates)):
|
||||
continue
|
||||
if u.count_unit and counts[u.team] >= self.s.teams[u.team]["capacity"]:
|
||||
continue
|
||||
a.state, a.joined_ms = "active", self.now
|
||||
counts[u.team] += int(u.count_unit)
|
||||
self.event("deploy", actor=u.key, team=u.team, wave=u.wave, count_unit=u.count_unit, ap_charged=0)
|
||||
|
||||
def generate(self, seconds):
|
||||
for maker in self.makers:
|
||||
p = maker["vo"].get("para", {})
|
||||
parent = self.by_key.get(maker["owner"])
|
||||
if not maker["active"] or parent is not None and parent.state != "active":
|
||||
continue
|
||||
after = sim._number(p.get("afterTime", 0))
|
||||
before = sim._number(p.get("beforeTime", 0))
|
||||
after = after * 1000 if after < 1000 else after
|
||||
before = before * 1000 if before < 1000 else before
|
||||
if self.now < after or before > 0 and self.now > before:
|
||||
continue
|
||||
maker["credit"] += seconds / max(1., sim._number(p.get("interval", 1000)) / 1000)
|
||||
count = min(int(maker["credit"]), MAX_GENERATED - self.generated)
|
||||
maker["credit"] -= count
|
||||
for _ in range(count):
|
||||
if len(self.actors) >= sim.MAX_UNITS:
|
||||
self.resource_limited = True
|
||||
return
|
||||
spec = {"type": p.get("monType"), "autoValue": True, "level": p.get("level", 1),
|
||||
"team": p.get("team", parent.unit.team if parent else 2), "mode": p.get("mode", 2),
|
||||
"skill_1": 0, "skill_2": 0, "countUnit": False}
|
||||
unit = sim._enemy(spec, {"team": spec["team"]}, self.tables, f"generated-{self.generated + 1}",
|
||||
{}, lambda *a, **k: None, {})
|
||||
hp = sim._int(p.get("hpMax") if p.get("hpMax") is not None else p.get("hp") if p.get("hp") is not None else unit.stats.hp)
|
||||
unit = replace(unit, stats=replace(unit.stats, hp=hp, atk=sim._int(p.get("atk") if p.get("atk") is not None else unit.stats.atk)),
|
||||
is_object=p.get("isObject", False) is True, source_id=f"-{self.generated + 1}")
|
||||
if hp <= 0 or unit.stats.atk < 0 or unit.team not in self.s.teams:
|
||||
raise sim.SimulationInputError("Generated monster attributes/team are invalid")
|
||||
a = sim.Actor(unit, min(hp, sim._int(p.get("hp") if p.get("hp") is not None else hp)), state="active", joined_ms=self.now)
|
||||
self.actors.append(a)
|
||||
self.by_key[unit.key], self.by_source_id[unit.source_id] = a, a
|
||||
self.expectations[unit.key], self.hp_rates[unit.key] = (1., 0.), []
|
||||
self.generated += 1
|
||||
self.event("aggregate_spawn", actor=unit.key, team=unit.team, hp=a.hp)
|
||||
|
||||
def budgets(self, seconds):
|
||||
active = self.active()
|
||||
damage, healing, dealt = Counter(), Counter(), Counter()
|
||||
team_rates = Counter()
|
||||
for a in active:
|
||||
u = a.unit
|
||||
locked = self.by_source_id.get(u.lock_target)
|
||||
targets = [locked] if locked and locked.state == "active" else [b for b in active if b.unit.team != u.team]
|
||||
if not locked:
|
||||
targets = [b for b in targets if b.unit.auto_target] or targets
|
||||
if not u.is_object and targets and u.ai_search != 0:
|
||||
for b in targets:
|
||||
attack = u.stats.atk
|
||||
counter = self.tables["monster_setting"]["element"].get(str(u.stats.element), {}).get("counter")
|
||||
if counter == b.unit.stats.element:
|
||||
attack = int(attack * self.game["counterAdd"])
|
||||
hit = sim.damage_roll(attack, u.stats.dex, b.unit.stats, self.game, _MeanRoll())
|
||||
quarter = int((u.stats.dex - b.unit.stats.dex) / 4)
|
||||
crit = min(1., .02 + u.stats.crit / 100 + (quarter / (quarter + 120) if quarter >= 0 else 0))
|
||||
hit *= 1 + crit * (self.game["critAdd"] - 1)
|
||||
element = str(u.stats.element)
|
||||
if element in b.unit.hurt_types and element in b.unit.hurt_elements:
|
||||
hit *= b.unit.hurt_elements[element]
|
||||
elif str(u.species) in b.unit.hurt_types:
|
||||
hit *= b.unit.hurt_types[str(u.species)]
|
||||
hit = max(0, int(hit * (1 - b.unit.stats.damage_reduction) * self.expectations[u.key][0]))
|
||||
hit = self.final_damage(hit, a, b)
|
||||
# Apply the desktop cap per expected hit, before summing DPS.
|
||||
amount = hit * 1000 / u.stats.attack_ms * seconds / len(targets)
|
||||
damage[b.unit.key] += amount
|
||||
dealt[u.key] += amount
|
||||
team_rates[u.team] += amount / seconds
|
||||
if hit > 80000 and (u.key, b.unit.key) not in self.damage_checks:
|
||||
self.damage_checks.add((u.key, b.unit.key))
|
||||
self.anomaly("+10overdamage", points=10, damage=hit, hurt_team=b.unit.team,
|
||||
actor=u.key, target=b.unit.key, approximate=True)
|
||||
healing[u.key] += self.expectations[u.key][1] * seconds
|
||||
for kind, rate, mid in self.hp_rates[u.key]:
|
||||
if kind == "hp":
|
||||
target = a if mid == "-1" else self.by_source_id.get(mid)
|
||||
targets = [target] if target and target.state == "active" else []
|
||||
else:
|
||||
targets = [b for b in active if (b.unit.team == u.team) == (rate >= 0)]
|
||||
for b in targets:
|
||||
(healing if rate >= 0 else damage)[b.unit.key] += abs(rate) * seconds
|
||||
for team, rate in team_rates.items():
|
||||
self.peak_dps[team] = max(self.peak_dps[team], rate)
|
||||
self.now += int(seconds * 1000)
|
||||
for a in active:
|
||||
key = a.unit.key
|
||||
lost = min(a.hp, damage[key])
|
||||
a.hp -= lost
|
||||
a.total_hurt += damage[key]
|
||||
self.hp_lost[a.unit.team] += lost
|
||||
a.damage_dealt += dealt[key]
|
||||
if a.unit.boss_point == -1:
|
||||
self.boss_points += int(lost)
|
||||
if lost:
|
||||
self.event("damage", actor=None, target=key, damage=round(damage[key], 3),
|
||||
hp_lost=round(lost, 3), hp=round(a.hp, 3), reason="aggregate_dps")
|
||||
# Healing is a simultaneous sustain budget; it cannot resurrect.
|
||||
if a.hp > 0:
|
||||
gained = min(a.unit.stats.hp - a.hp, healing[key])
|
||||
a.hp += gained
|
||||
a.healed += gained
|
||||
if gained:
|
||||
self.event("heal", actor=key, amount=round(gained, 3), hp=round(a.hp, 3), reason="aggregate_sustain")
|
||||
else:
|
||||
a.hp = 0
|
||||
self.finish_death(a)
|
||||
|
||||
def objectives(self):
|
||||
if self.now >= self.s.duration_ms:
|
||||
return "win" if 2 in self.s.win_types else "loss"
|
||||
if not any(a.unit.team == 1 and a.state != "dead" for a in self.actors):
|
||||
return "loss"
|
||||
# A still-running generator represents a future enemy HP/DPS budget,
|
||||
# including when its effective population bound has been reached.
|
||||
future = any(m["active"] and (m["owner"] is None or self.by_key[m["owner"]].state != "dead")
|
||||
and sim._int(m["vo"].get("para", {}).get("team", 2)) != 1
|
||||
and (not sim._number(m["vo"].get("para", {}).get("beforeTime", 0)) or
|
||||
self.now < (sim._number(m["vo"]["para"]["beforeTime"]) *
|
||||
(1000 if sim._number(m["vo"]["para"]["beforeTime"]) < 1000 else 1)))
|
||||
for m in self.makers)
|
||||
if 1 in self.s.win_types and not future and not any(a.unit.team != 1 and a.state != "dead"
|
||||
and (a.state == "active" or not a.unit.is_object) for a in self.actors):
|
||||
return "win"
|
||||
protected = [a for a in self.actors if a.unit.protect_target]
|
||||
destroyed = [a for a in self.actors if a.unit.destroy_target]
|
||||
if protected and (3 in self.s.lose_types and any(a.state == "dead" for a in protected)
|
||||
or 4 in self.s.lose_types and all(a.state == "dead" for a in protected)):
|
||||
return "loss"
|
||||
if destroyed and (3 in self.s.win_types and any(a.state == "dead" for a in destroyed)
|
||||
or 4 in self.s.win_types and all(a.state == "dead" for a in destroyed)):
|
||||
return "win"
|
||||
return None
|
||||
|
||||
def result(self, outcome, timeout_kind=None):
|
||||
result = super().result(outcome, timeout_kind)
|
||||
result["team_budgets"] = {str(team): {
|
||||
"initial_hp": sum(u.stats.hp for u in self.s.units if u.team == team),
|
||||
"remaining_hp": round(sum(a.hp for a in self.actors if a.unit.team == team), 3),
|
||||
"peak_expected_dps": round(self.peak_dps[team], 3)} for team in self.s.teams}
|
||||
result["generated_units"] = self.generated
|
||||
result["spawn_bound_reached"] = self.generated >= MAX_GENERATED
|
||||
return result
|
||||
|
||||
|
||||
def simulate_quick(request, *, cancel_event=None, timeout=30., tables=None):
|
||||
started = time.monotonic()
|
||||
timeout = sim._number(timeout, "timeout")
|
||||
if timeout < 0:
|
||||
raise sim.SimulationInputError("timeout must be nonnegative")
|
||||
tables = tables if tables is not None else sim.combat_tables()
|
||||
scenario, report = prepare(request, tables)
|
||||
if not report["supported"]:
|
||||
return dict(report, outcome="unsupported", execution_status="unsupported", terminal=False,
|
||||
terminal_reason="unsupported_scenario", elapsed_ms=0, elapsed_seconds=0, events=[])
|
||||
try:
|
||||
battle = _QuickBattle(scenario, report, tables, request)
|
||||
for step in range(min(MAX_STEPS, scenario.duration_ms // 1000 + 1)):
|
||||
if cancel_event is not None and cancel_event.is_set():
|
||||
return battle.result("cancelled")
|
||||
if time.monotonic() - started >= timeout:
|
||||
return battle.result("timeout", "wall_clock")
|
||||
battle.recruit()
|
||||
battle.generate(min(1., (scenario.duration_ms - battle.now) / 1000))
|
||||
outcome = battle.objectives()
|
||||
if outcome:
|
||||
reason = "battle_time_limit" if battle.now >= scenario.duration_ms else "elimination" if 1 in scenario.win_types else "objective"
|
||||
battle.event("complete", outcome=outcome, reason=reason)
|
||||
return dict(battle.result(outcome), terminal_reason=reason)
|
||||
if battle.resource_limited:
|
||||
return battle.result("timeout", "resource_limit")
|
||||
battle.budgets(min(1., (scenario.duration_ms - battle.now) / 1000))
|
||||
return battle.result("timeout", "resource_limit")
|
||||
except (sim.SimulationInputError, KeyError, TypeError, ValueError, ZeroDivisionError):
|
||||
# Do not include account material or arbitrary parameter values in errors.
|
||||
return dict(report, supported=False, outcome="unsupported", execution_status="unsupported", terminal=False,
|
||||
terminal_reason="invalid_numeric_battle_data", elapsed_ms=0, elapsed_seconds=0, events=[],
|
||||
reasons=list(report["reasons"]) + ["Missing or invalid original numeric combat/controller data"])
|
||||
@@ -419,11 +419,17 @@ class Scenario:
|
||||
triggers: tuple = ()
|
||||
|
||||
|
||||
def _prepare(request, tables):
|
||||
def _prepare(request, tables, *, quick=False):
|
||||
report = _envelope()
|
||||
report.update(supported=False, reasons=[], implemented_skills=sorted(KNOWN_SKILLS))
|
||||
|
||||
def diagnostic(code, message, *, ignored=False, blocking=False):
|
||||
if quick and code in ("objective", "controller", "triggers", "unit_controller",
|
||||
"unit_objective", "field_effect", "cosmetic_controller"):
|
||||
record = {"code": "aggregate_approximation", "mechanic": code, "message": message}
|
||||
if record not in report["diagnostics"]:
|
||||
report["diagnostics"].append(record)
|
||||
return
|
||||
record = {"code": code, "message": message}
|
||||
if record not in report["diagnostics"]:
|
||||
report["diagnostics"].append(record)
|
||||
@@ -498,7 +504,9 @@ def _prepare(request, tables):
|
||||
units = [] # BattleCenter empties the master team before adding authored allies.
|
||||
configured_mons = [(team, mon) for team in battle.get("teams", ())
|
||||
for mon in team.get("mons", ()) if mon is not None]
|
||||
unit_mids = {_int(mon.get("mid", -1)) for _, mon in configured_mons}
|
||||
# AS3 int('') is zero for an authored default mid; keep stat parsing strict.
|
||||
unit_mids = {_int(0 if mon.get("mid") == "" else mon.get("mid", -1))
|
||||
for _, mon in configured_mons}
|
||||
triggers = []
|
||||
for entry in battle.get("triggers", ()) or ():
|
||||
if mining:
|
||||
@@ -549,24 +557,26 @@ def _prepare(request, tables):
|
||||
if mining:
|
||||
if not any(u.destroy_target for u in units) or not any(u.protect_target for u in units):
|
||||
diagnostic("unit_objective", "Mining requires actual destroy and protect target units", blocking=True)
|
||||
elif not any(u.team != 1 and not u.is_object for u in units):
|
||||
elif not quick and not any(u.team != 1 and not u.is_object for u in units):
|
||||
raise SimulationInputError("Elimination battle must contain configured enemies")
|
||||
for team in teams.values():
|
||||
if team["capacity"] <= 0 or team["initial"] < 0:
|
||||
if (team["capacity"] < 0 if quick else team["capacity"] <= 0) or team["initial"] < 0:
|
||||
raise SimulationInputError("Original team capacity/AP is invalid")
|
||||
field_config = battle.get("battleField")
|
||||
if quick and not isinstance(field_config, Mapping):
|
||||
field_config = {}
|
||||
if not isinstance(field_config, Mapping):
|
||||
raise SimulationInputError("Full original battleField configuration is required")
|
||||
if field_config.get("fieldMode"):
|
||||
name = field_config.get("fieldName", "default")
|
||||
original_field = tables["setting"]["defaultField"].get(name)
|
||||
if original_field is None:
|
||||
if original_field is None and not quick:
|
||||
raise SimulationInputError("Unknown original default battlefield")
|
||||
field_config = dict(original_field, mapObjects=field_config.get("mapObjects", ()),
|
||||
mapAreas=tuple(original_field.get("mapAreas", ())) + tuple(field_config.get("mapAreas", ())))
|
||||
field_config = dict(original_field or {}, mapObjects=field_config.get("mapObjects", ()),
|
||||
mapAreas=tuple((original_field or {}).get("mapAreas", ())) + tuple(field_config.get("mapAreas", ())))
|
||||
points = {p["id"]: p for p in field_config.get("mapPoints", ())}
|
||||
areas = {a["id"]: a for a in field_config.get("mapAreas", ())}
|
||||
if "area_battlefield" not in areas or not points:
|
||||
if not quick and ("area_battlefield" not in areas or not points):
|
||||
raise SimulationInputError("Battlefield needs original points and area_battlefield")
|
||||
for area in areas.values():
|
||||
if area.get("type", "none") not in (("none", "pow") if mining else ("none",)):
|
||||
@@ -582,11 +592,11 @@ def _prepare(request, tables):
|
||||
diagnostic("attack_profile", f"Attack {u.attack_type} has no bundled source profile; original default AttackType1 is approximated", ignored=True)
|
||||
if u.effects.get("sunFire") or u.effects.get("moonHeal") or u.effects.get("deadBoom"):
|
||||
diagnostic("unimplemented_effect", "sunFire, moonHeal and deadBoom effects are omitted where present", ignored=True)
|
||||
if u.attack_area and u.attack_area not in areas:
|
||||
if not quick and u.attack_area and u.attack_area not in areas:
|
||||
raise SimulationInputError("Configured attackArea is absent from original battlefield")
|
||||
if u.join_point and not u.join_point.startswith("mon_") and u.join_point not in points:
|
||||
if not quick and u.join_point and not u.join_point.startswith("mon_") and u.join_point not in points:
|
||||
raise SimulationInputError("Configured joinPoint is absent from original battlefield")
|
||||
if not u.join_point:
|
||||
if not quick and not u.join_point:
|
||||
default_point = f"point_team{u.team}_{'fore' if u.position < 3 else 'back'}{u.position + 1 if u.position < 3 else u.position - 2}"
|
||||
if (u.position >= 6 or default_point not in points) and not any(
|
||||
p.startswith(f"point_team{u.team}_wait") for p in points):
|
||||
@@ -629,7 +639,7 @@ def _unit_preview(unit):
|
||||
|
||||
|
||||
def _snapshot_anomalies(mon, unit, tables):
|
||||
"""Port the observable input checks from BattlePanel.cheatCheck.
|
||||
"""Check source input bounds, using the cultivation potential cap.
|
||||
|
||||
These are a subset of the final original checks, not a claim to have run
|
||||
them all. Keep raw input values; never repair them to make checks pass.
|
||||
@@ -644,7 +654,6 @@ def _snapshot_anomalies(mon, unit, tables):
|
||||
|
||||
row = tables["monster_info"][str(unit.species)]
|
||||
potential_level = _int(mon.get("potentialLevel", 1))
|
||||
tp = min(4, _int(mon.get("tpLevel", 0)))
|
||||
if _number(mon.get("feel", 0)) > 200:
|
||||
add("+15overfeel", 50, feel=mon["feel"])
|
||||
potential = tables["potential_info"]["potential"].get(str(row["job"]), {}).get(str(row["star"]), {})
|
||||
@@ -653,7 +662,9 @@ def _snapshot_anomalies(mon, unit, tables):
|
||||
maximum = row[stat] + row[stat + "_grow_max"] * (_int(mon["level"]) + potential_level) * 4
|
||||
if value > maximum:
|
||||
add("+15overgrow", 25, stat=stat, value=value, source_maximum=maximum)
|
||||
max_potential = potential.get(stat, 0) + potential.get(stat + "TpAdd", 0) * tp
|
||||
# PotentialPanel.as:102,245 uses cultivation, not TP level. The old
|
||||
# BattlePanel.cheatCheck bound can reject normally cultivated values.
|
||||
max_potential = potential.get(stat, 0) + potential.get(stat + "TpAdd", 0) * (potential_level - 1)
|
||||
value_potential = _number(mon.get("p" + stat.capitalize(), 0))
|
||||
if potential and value_potential > max_potential * 1.5:
|
||||
add("+15overpoten", 30, stat=stat, value=value_potential, source_maximum=max_potential * 1.5)
|
||||
@@ -1335,7 +1346,7 @@ def _execution_failure(outcome, reason, *, supported=True):
|
||||
|
||||
|
||||
class ExperimentalBattleRuntime:
|
||||
"""Offline experimental adapter. run always executes a fixed worker module.
|
||||
"""Fast aggregate adapter. run always executes a fixed offline worker module.
|
||||
|
||||
supported means this approximate model is runnable, not server settlement
|
||||
eligibility. Calls do not mutate the request, cache, or input snapshot.
|
||||
@@ -1343,7 +1354,8 @@ class ExperimentalBattleRuntime:
|
||||
|
||||
def inspect(self, request):
|
||||
try:
|
||||
_, report = _prepare(request, combat_tables())
|
||||
from .battle_quick import prepare
|
||||
_, report = prepare(request, combat_tables())
|
||||
return report
|
||||
except SimulationInputError as exc:
|
||||
result = _envelope()
|
||||
@@ -1418,7 +1430,8 @@ def _worker():
|
||||
if len(wire) > MAX_WIRE_BYTES:
|
||||
raise SimulationInputError("Worker input exceeds limit")
|
||||
payload = json.loads(wire)
|
||||
result = simulate(payload["request"], timeout=payload.get("timeout", 30.0))
|
||||
from .battle_quick import simulate_quick
|
||||
result = simulate_quick(payload["request"], timeout=payload.get("timeout", 30.0))
|
||||
if result.get("outcome") == "unsupported":
|
||||
result.update(execution_status="unsupported", terminal=False, terminal_reason="unsupported_scenario")
|
||||
encoded = json.dumps(result, ensure_ascii=True, allow_nan=False,
|
||||
|
||||
@@ -427,6 +427,7 @@ class BattleOrchestrator:
|
||||
"requires_realtime_wait", "wall_time_ms", "trace_path", "resource_identity", "terminal_reason", "settlement_eligible",
|
||||
"experimental_settlement_eligible", "execution_mode", "execution_status", "terminal", "diagnostics",
|
||||
"ignored_mechanics", "anomalies", "assumptions", "experimental_eligibility_reasons", "omitted_events",
|
||||
"model", "simulation_method", "team_budgets", "generated_units", "spawn_bound_reached",
|
||||
"damage_profile", "damage_multiplier", "damage_cap", "damage_profile_digest", "damage_profile_scope")}}
|
||||
trace = value(result, "trace")
|
||||
if trace is None:
|
||||
|
||||
+158
-6
@@ -12,7 +12,8 @@ from types import SimpleNamespace
|
||||
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, commission_priority
|
||||
from .quests import QuestPolicy, TaskPlanner, commission_priority, commission_reason_kind
|
||||
from .procurement import resource_kind
|
||||
from .commission_history import CommissionHistory
|
||||
from .market import PurchaseBudget
|
||||
from .management import expansion_quote, manual_monster_actions
|
||||
@@ -389,6 +390,8 @@ class Engine:
|
||||
self.game_data = load_progression_data()
|
||||
if self.progression_planner is None:
|
||||
self.progression_planner = ProgressionPlanner(self.catalog, self.game_data, account_key=self._progression_namespace)
|
||||
self.progression_planner.guard.cultivation = self.cultivation
|
||||
self.progression_planner.procurement_daily_left = self.purchase_budget.remaining(self.snapshot.now, self.policy.daily_buy_money) if self.snapshot else 0
|
||||
# This is a read-only preflight; the same check must precede navigation
|
||||
# and dialogue, not just the battle action they lead to.
|
||||
self.progression_planner.battle_capability = self._battle_capability
|
||||
@@ -531,6 +534,7 @@ class Engine:
|
||||
|
||||
def _recover_confirmed_progression(self):
|
||||
"""Replay only local acknowledgement of a durably received success."""
|
||||
self._reconcile_procurement()
|
||||
record = self.battle_journal.pending(self.snapshot)
|
||||
if (not record or str(record.get("role_id")) != str(self.snapshot.raw["master"].get("id"))
|
||||
or not str(record.get("kind", "")).startswith("progression_")):
|
||||
@@ -657,7 +661,8 @@ class Engine:
|
||||
source_supported = row.get("supported") is not False
|
||||
check = self._commission_offer_checks.get(str(row.get("task_type_id")))
|
||||
if row.get("category") == "commission" and row.get("state") == "offered" and check is not None:
|
||||
row.update(block_reason=check[1], next_action="接取城市委托" if check[0] else "暂不接取:" + check[1])
|
||||
if not check[0]:
|
||||
row.update(block_reason=check[1], next_action="暂不接取:" + check[1])
|
||||
commission = commissions.get(str(row.get("task_type_id")))
|
||||
if commission is not None:
|
||||
row.update(next_action=value(commission, "description"), block_reason=value(commission, "block_reason", ""))
|
||||
@@ -675,6 +680,7 @@ class Engine:
|
||||
else:
|
||||
row["supported"] = bool(source_supported and not reason)
|
||||
row["block_reason"] = row["blocked_reason"] = reason
|
||||
row["reason_kind"] = commission_reason_kind(reason)
|
||||
return rows, adjusted
|
||||
|
||||
def _battle_request(self, snapshot, intent, policy, request):
|
||||
@@ -754,7 +760,9 @@ class Engine:
|
||||
|
||||
def _ensure_commission_diagnostics(self):
|
||||
key = (id(self.snapshot), digest({"quest": vars(self.quest_policy), "ranch": vars(self.policy),
|
||||
"progression": vars(self.progression_policy), "checks": self._commission_offer_checks}))
|
||||
"progression": vars(self.progression_policy), "checks": self._commission_offer_checks,
|
||||
"budget": self.purchase_budget.remaining(self.snapshot.now, self.policy.daily_buy_money),
|
||||
"state": self.progression_planner.state_signature(self.snapshot) if self.progression_planner else ""}))
|
||||
if key == self._commission_diagnostics_key:
|
||||
return
|
||||
if self.progression_planner is None:
|
||||
@@ -872,6 +880,13 @@ class Engine:
|
||||
policy = self._intent_policy({"task_type_id": str(type_id)})
|
||||
ready, _, requirement_reason = self.progression_planner.requirement(self.snapshot, step, {}, policy, self.policy)
|
||||
if not ready:
|
||||
if resource_kind(step) and isinstance(self.progression_planner, ProgressionPlanner):
|
||||
supply = self.progression_planner.resource_plan(self.snapshot, info.get("steps") or [],
|
||||
{"id": 0, "typeId": str(type_id), "curStep": number}, policy, self.policy)
|
||||
if supply.feasible:
|
||||
continue
|
||||
self._commission_offer_reason = supply.reason
|
||||
return False
|
||||
sources = self.progression_planner.farming_intents(self.snapshot, step,
|
||||
{"id": 0, "typeId": str(type_id), "curStep": number}, policy, self.policy)
|
||||
source_reasons = []
|
||||
@@ -904,6 +919,7 @@ class Engine:
|
||||
"snapshot": self._battle_snapshot_digest, "runtime": id(self.battles.runtime)})
|
||||
key = digest({"snapshot": self._battle_snapshot_digest, "policy": vars(self.progression_policy),
|
||||
"quests": vars(self.quest_policy), "ranch": vars(self.policy), "local_state": self.progression_planner.state_signature(self.snapshot),
|
||||
"purchase_left": self.progression_planner.procurement_daily_left,
|
||||
"pending": self._progression_pending(), "runtime": id(self.battles.runtime),
|
||||
"day": ProgressionPlanner._loop_day(self.snapshot, self.snapshot.now - 10)})
|
||||
if force or key != self._progression_cache_key:
|
||||
@@ -919,9 +935,18 @@ class Engine:
|
||||
self._commission_offer_diagnostics = deepcopy(self.progression_planner.commission_offer_rows)
|
||||
intents.sort(key=lambda intent: not self._is_commission(intent))
|
||||
self._progression_rows, self._progression_intents = self._overlay_battle_capabilities(rows, intents)
|
||||
for row in self._progression_rows:
|
||||
if row.get("category") == "commission" and row.get("state") == "offered":
|
||||
offer = next((r for r in self._commission_offer_diagnostics if r["task_type_id"] == row["task_type_id"]), None)
|
||||
if offer:
|
||||
row.update(reason_kind=offer["reason_kind"], resources=offer["resources"],
|
||||
progress_plan=offer["progress_plan"], next_action=offer["next_step"],
|
||||
block_reason="" if offer["eligible"] else offer["reason"],
|
||||
blocked_reason="" if offer["eligible"] else offer["reason"], supported=offer["eligible"])
|
||||
self._persist_progression()
|
||||
self._progression_cache_key = digest({"snapshot": self._battle_snapshot_digest, "policy": vars(self.progression_policy),
|
||||
"quests": vars(self.quest_policy), "ranch": vars(self.policy), "local_state": self.progression_planner.state_signature(self.snapshot),
|
||||
"purchase_left": self.progression_planner.procurement_daily_left,
|
||||
"pending": self._progression_pending(), "runtime": id(self.battles.runtime),
|
||||
"day": ProgressionPlanner._loop_day(self.snapshot, self.snapshot.now - 10)})
|
||||
self._progression_error = ""
|
||||
@@ -986,6 +1011,8 @@ class Engine:
|
||||
if record["attempt_id"] not in previous_attempts]
|
||||
if records:
|
||||
message = self._commission_message(records[-1], message)
|
||||
elif kind == "progression_procure":
|
||||
message = self._execute_procurement(intent)
|
||||
else:
|
||||
message = self._execute_task_intent(intent)
|
||||
if self.battle_journal.pending(self.snapshot) and kind == "progression_battle":
|
||||
@@ -998,7 +1025,7 @@ class Engine:
|
||||
self.read_snapshot(sync_master=False)
|
||||
return self.snapshot, self.plans(), message
|
||||
except Exception:
|
||||
if self.battle_journal.pending(self.snapshot) and not self._is_farm(intent) and value(intent, "kind", "").startswith("progression_"):
|
||||
if self.battle_journal.pending(self.snapshot) and not self._is_farm(intent) and value(intent, "kind") != "progression_procure" and value(intent, "kind", "").startswith("progression_"):
|
||||
self.progression_planner.mark_uncertain(self.snapshot, intent, "任务 / 战斗结果待核对,禁止重放")
|
||||
self._persist_progression()
|
||||
raise
|
||||
@@ -1006,6 +1033,117 @@ class Engine:
|
||||
self._sync_commission_history()
|
||||
self._refresh_progression_cache(force=True)
|
||||
|
||||
def _execute_procurement(self, intent):
|
||||
"""Journal resource writes separately; never advance a task cursor."""
|
||||
if self._progression_cancel.is_set() or self._progression_pending():
|
||||
return "补资源已取消或有待核对请求;未发送"
|
||||
planner = self.progression_planner
|
||||
planner.mark_started(self.snapshot, intent) # validates account and issued payload only
|
||||
key = str(value(intent, "source_task_type_id"))
|
||||
policy = self._intent_policy(intent)
|
||||
source_id = int(value(intent, "source_task_id", 0) or 0)
|
||||
info = self._commission_info(key)
|
||||
if source_id:
|
||||
source = next((t for t in self.snapshot.raw.get("currentTasks", [])
|
||||
if int(t.get("id", 0)) == source_id and str(t.get("typeId")) == key), None)
|
||||
if source is None:
|
||||
return "资源来源任务已变化,等待重新规划;未发送"
|
||||
else:
|
||||
offers = planner.commission_offers(self.snapshot, self.quest_policy, self.policy,
|
||||
battle_policy=self.progression_policy, accept_supported=self._commission_offer_eligibility)
|
||||
if not any(row["task_type_id"] == key and row.get("preparable") for row in offers):
|
||||
return "委托额度、城市或资源条件已变化,未采购、未消耗接取次数"
|
||||
source = {"id": 0, "typeId": key}
|
||||
planner.procurement_daily_left = self.purchase_budget.remaining(self.snapshot.now, self.policy.daily_buy_money)
|
||||
supply = planner.remaining_resource_plan(self.snapshot, info, source, policy, self.policy)
|
||||
action = supply.action
|
||||
if not supply.feasible or action is None or action.path != value(intent, "path") or action.payload != value(intent, "payload"):
|
||||
return "资源缺口或保护状态已变化,等待重新规划;未发送"
|
||||
allowed = {"gachaService/gachaGetEggs": {"id", "num", "voucherNum", "traceInfo"},
|
||||
"stackService/stackAddMonster": {"eggs"}, "stackService/stackTransferMonster": {"datas"}}
|
||||
if action.path not in allowed or set(action.payload) != allowed[action.path]:
|
||||
return "补资源请求未验证,未发送"
|
||||
def admission_signature():
|
||||
return digest({"snapshot": self.snapshot.raw, "quest": vars(self.quest_policy), "ranch": vars(self.policy),
|
||||
"progression": vars(self.progression_policy), "task": self._commission_info(key),
|
||||
"day": planner._loop_day(self.snapshot, self.snapshot.now - 10)})
|
||||
admitted = admission_signature()
|
||||
self._sync_commission_history()
|
||||
record = self.battle_journal.begin(self.snapshot, intent)
|
||||
self._journal_commission(record, intent)
|
||||
baseline = {str(i["typeId"]): 0 for i in self.snapshot.raw["items"]}
|
||||
for item in self.snapshot.raw["items"]:
|
||||
baseline[str(item["typeId"])] += max(0, int(item.get("num", 0)))
|
||||
self.battle_journal.update(record, "prepared", procurement_baseline=baseline)
|
||||
dispatched = False
|
||||
try:
|
||||
if self._progression_cancel.is_set() or admission_signature() != admitted:
|
||||
raise CancelledBeforeDispatch()
|
||||
if action.kind == "buy":
|
||||
self.purchase_budget.record(self.snapshot.now, supply.purchase_cost, self.policy.daily_buy_money)
|
||||
self.battle_journal.update(record, "request_pending")
|
||||
if admission_signature() != admitted:
|
||||
raise CancelledBeforeDispatch()
|
||||
dispatched = True
|
||||
response = self.battles._call(self.client, action.path, deepcopy(action.payload), cancel=self._progression_cancel)
|
||||
receipt = gameplay_response(response)
|
||||
if action.kind == "buy" and isinstance(response.get("eggs"), list):
|
||||
receipt["eggs"] = [{k: egg[k] for k in ("typeId", "num") if k in egg}
|
||||
for egg in response["eggs"] if isinstance(egg, dict)]
|
||||
self.battle_journal.update(record, "acknowledged", response=receipt, response_confirmed=True,
|
||||
message="补资源请求已返回,等待权威背包/孵化位核对;不重复发送")
|
||||
if action.kind == "buy":
|
||||
self.record_draw(response.get("eggs") or [])
|
||||
return record["message"]
|
||||
except CancelledBeforeDispatch:
|
||||
self.battle_journal.finish(self.snapshot, record, "cancelled", "补资源请求尚未发送,已取消")
|
||||
return record["message"]
|
||||
except Exception as error:
|
||||
if dispatched:
|
||||
self.battle_journal.update(record, "unknown", message="补资源请求结果未知,禁止重购或重复装填", error_type=type(error).__name__)
|
||||
else:
|
||||
self.battle_journal.finish(self.snapshot, record, "cancelled", "补资源准备未完成,未发送")
|
||||
raise
|
||||
finally:
|
||||
self._sync_commission_history()
|
||||
|
||||
def _reconcile_procurement(self):
|
||||
if self.snapshot is None:
|
||||
return
|
||||
record = self.battle_journal.pending(self.snapshot)
|
||||
if not record or record.get("kind") != "progression_procure" or record.get("response_confirmed") is not True:
|
||||
return
|
||||
payload, response = record.get("payload") or {}, record.get("response") or {}
|
||||
if str(record.get("role_id")) != str(self.snapshot.raw["master"].get("id")) or response.get("resCode", 0) not in (0, "0"):
|
||||
return
|
||||
path, confirmed = record.get("path"), False
|
||||
if path == "gachaService/gachaGetEggs":
|
||||
eggs, expected = response.get("eggs"), {}
|
||||
if isinstance(eggs, list):
|
||||
for egg in eggs:
|
||||
if isinstance(egg, dict) and str(egg.get("typeId")) in self.catalog.monsters and int(egg.get("num", 0)) > 0:
|
||||
key = str(egg["typeId"])
|
||||
expected[key] = expected.get(key, 0) + int(egg["num"])
|
||||
totals = {}
|
||||
for item in self.snapshot.raw["items"]:
|
||||
key = str(item.get("typeId"))
|
||||
totals[key] = totals.get(key, 0) + int(item.get("num", 0))
|
||||
baseline = record.get("procurement_baseline") or {}
|
||||
confirmed = bool(expected) and sum(expected.values()) >= int(payload.get("num", 0)) and all(
|
||||
totals.get(k, 0) >= baseline.get(k, 0) + n for k, n in expected.items())
|
||||
elif path == "stackService/stackAddMonster":
|
||||
confirmed = bool(payload.get("eggs")) and all(any(int(s["id"]) == int(egg["stackId"])
|
||||
and int(s.get("monsterId") or 0) in self.snapshot.monsters for s in self.snapshot.raw["stacks"])
|
||||
for egg in payload["eggs"])
|
||||
elif path == "stackService/stackTransferMonster":
|
||||
confirmed = bool(payload.get("datas")) and all(
|
||||
(self.snapshot.monsters.get(int(mid)) or {}).get("process") == 3
|
||||
and int((self.snapshot.monsters.get(int(mid)) or {}).get("roomId") or 0) == int(data["roomId"])
|
||||
for data in payload["datas"] for mid in data["monsterId"])
|
||||
if confirmed:
|
||||
self.battle_journal.finish(self.snapshot, record, "task", "已按服务器背包/孵化位确认补资源;任务步骤仍需独立核对提交")
|
||||
self._sync_commission_history()
|
||||
|
||||
def _execute_task_intent(self, intent):
|
||||
path, kind = value(intent, "path", "") or "", value(intent, "kind")
|
||||
payload = deepcopy(value(intent, "payload", {}) or {})
|
||||
@@ -1058,6 +1196,7 @@ class Engine:
|
||||
if self._progression_pending():
|
||||
self.last_pending_check = time.monotonic()
|
||||
self.snapshot = self.client.snapshot()
|
||||
self._reconcile_procurement()
|
||||
pending = self.battle_journal.pending(self.snapshot)
|
||||
pending_id = pending.get("attempt_id") if pending else None
|
||||
if self.battle_journal.reconcile(self.snapshot, trusted=True) and pending_id:
|
||||
@@ -1512,10 +1651,23 @@ class Engine:
|
||||
# One owner for commission writes; never accept the same offer through
|
||||
# both the legacy planner and the full progression planner.
|
||||
quests = [] if self._commission_planner_available else self.tasks.plan(self.snapshot, self.quest_policy, self.policy)
|
||||
types, eggs = self.tasks.reservations(self.snapshot)
|
||||
preparing = []
|
||||
for intent in self._progression_intents:
|
||||
key = str(value(intent, "source_task_type_id") or value(intent, "task_type_id") or "")
|
||||
if self._is_commission(intent) and key and not value(intent, "source_task_id") and not value(intent, "task_id"):
|
||||
info = self._commission_info(key)
|
||||
if any(r.get("task_type_id") == key and r.get("preparable") for r in self._commission_offer_diagnostics):
|
||||
preparing.append({"typeId": key, "curStep": 1, "info": info})
|
||||
types, eggs = self.tasks.reservations(self.snapshot, extra_tasks=preparing)
|
||||
reserved = dict(self.policy.reserved_eggs)
|
||||
for key, count in eggs.items():
|
||||
reserved[key] = max(reserved.get(key, 0), count)
|
||||
# The task supply planner owns these eggs, including when it is waiting
|
||||
# for one already growing. Generic hatch/refill must not overproduce.
|
||||
for type_id in types:
|
||||
key = str(type_id)
|
||||
reserved[key] = max(reserved.get(key, 0), sum(int(i.get("num", 0)) for i in self.snapshot.raw["items"]
|
||||
if str(i.get("typeId")) == key))
|
||||
policy = replace(self.policy, reserved_types=list(set(self.policy.reserved_types) | types), reserved_eggs=reserved)
|
||||
self.hatch_planner.notes = []
|
||||
self.pending_hatches = self.hatch_planner.hatch_actions(self.snapshot, policy)
|
||||
@@ -1524,7 +1676,7 @@ class Engine:
|
||||
map_action = self._next_map_action()
|
||||
sweep_actions = [map_action] if map_action else []
|
||||
gifts = self.gift_planner.plan(self.snapshot, policy, self.quest_policy)
|
||||
ranch = self.planner.plan(self.snapshot, policy, left)
|
||||
ranch = self.planner.plan(self.snapshot, replace(policy, buy=False) if types or eggs else policy, left)
|
||||
explore = self.explore_planner.plan(self.snapshot, self.explore_policy, policy)
|
||||
breakthrough_policy = SimpleNamespace(**(asdict(policy) | {"item_reserves": dict(self.quest_policy.item_reserves)}))
|
||||
self.breakthrough_planner.notes = []
|
||||
|
||||
@@ -0,0 +1,306 @@
|
||||
"""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
|
||||
+117
-64
@@ -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):
|
||||
|
||||
@@ -7,6 +7,26 @@ from .model import Action, Planner, seconds
|
||||
CN = timezone(timedelta(hours=8))
|
||||
|
||||
|
||||
def commission_reason_kind(reason):
|
||||
text = str(reason or "")
|
||||
for kind, words in (
|
||||
("quota", ("次数已用完", "次数已耗尽", "额度已用完")),
|
||||
("city_locked", ("城市尚未解锁", "城市未解锁", "城市仍未解锁", "城市还未解锁")),
|
||||
("offline", ("离线", "未登录", "登录失效", "offline")),
|
||||
("uncertain_write", ("未确认请求", "待核对", "结果不明", "禁止重发")),
|
||||
("cooldown", ("冷却", "孵化/成长中", "开放时段", "开放日期", "开放星期", "跨日")),
|
||||
("busy", ("已有委托", "正在探索", "占用", "忙碌", "busy")),
|
||||
("protection", ("保护", "保留种类", "锁定")),
|
||||
("temp_resource", ("不足", "金币", "体力", "可提交", "可用", "缺口")),
|
||||
("prerequisite", ("前置", "前提", "引导", "图鉴", "角色等级", "关卡尚未", "入口关卡")),
|
||||
("policy", ("未启用", "策略限定", "未开启", "限定城市")),
|
||||
("model_unsupported", ("未支持", "尚不支持", "未验证", "尚未验证", "Unsupported", "运行时", "模拟器", "配置缺失")),
|
||||
):
|
||||
if any(word in text for word in words):
|
||||
return kind
|
||||
return "ready" if not text or text in ("可接取", "资源已齐备") else "prerequisite"
|
||||
|
||||
|
||||
def commission_priority(info):
|
||||
try:
|
||||
reward = int((info.get("reward") or {}).get("ke") or 0)
|
||||
@@ -234,10 +254,10 @@ class TaskPlanner:
|
||||
rejected.append(candidate | {"reason": reason})
|
||||
return []
|
||||
|
||||
def reservations(self, snapshot):
|
||||
def reservations(self, snapshot, *, extra_tasks=()):
|
||||
types, eggs = set(), {}
|
||||
for task in self.current(snapshot):
|
||||
info = self.catalog.data["task_info"][str(task["typeId"])]
|
||||
for task in [*self.current(snapshot), *extra_tasks]:
|
||||
info = task.get("info") or 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", ""))
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
"""Aggregate contract tests; synthetic rosters and public original task data."""
|
||||
from copy import deepcopy
|
||||
import threading
|
||||
import unittest
|
||||
|
||||
from ranch_assistant.battle_quick import MAX_GENERATED, prepare, simulate_quick
|
||||
from ranch_assistant.battle_simulator import (
|
||||
DESKTOP_DAMAGE_PROFILE, ExperimentalBattleRuntime, _prepare, combat_tables, simulate,
|
||||
)
|
||||
from ranch_assistant.battles import BattleOrchestrator
|
||||
from ranch_assistant.game_data import ProgressionData
|
||||
from ranch_assistant.tests.test_battle_simulator import battle_of, enemy, monster, request
|
||||
|
||||
|
||||
class QuickBattleTests(unittest.TestCase):
|
||||
def test_default_worker_matches_aggregate_and_preserves_detailed_entrypoint(self):
|
||||
req = request()
|
||||
result = ExperimentalBattleRuntime().run(req)
|
||||
self.assertEqual(result, simulate_quick(req))
|
||||
self.assertEqual(result["simulation_method"], "aggregate_hp_dps")
|
||||
self.assertNotEqual(result["model"], simulate(req)["model"])
|
||||
self.assertTrue(result["approximate"])
|
||||
self.assertFalse(result["faithful"])
|
||||
self.assertFalse(result["settlement_eligible"])
|
||||
|
||||
def test_original_player_and_authored_enemy_stats_are_preserved(self):
|
||||
req = request(enemies=[enemy(atk=31, hp=101, dex=7)])
|
||||
battle_of(req).update(scaleAbility=1.2, scaleHp=1.5)
|
||||
detailed, _ = _prepare(req, combat_tables())
|
||||
quick, report = prepare(req)
|
||||
self.assertEqual([u.stats for u in quick.units], [u.stats for u in detailed.units])
|
||||
self.assertEqual(report["units"][1]["stats"]["hp"], 151)
|
||||
|
||||
def test_unknown_controllers_skills_and_path_data_are_warnings(self):
|
||||
req = request(players=[monster(species=1001020)], enemies=[enemy(controller=[
|
||||
{"type": "unmodeled", "para": {}}, {"type": "monSteps", "para": {"points": ["absent"]}}])])
|
||||
battle_of(req)["controller"] = [{"type": "other_effect", "para": {}}]
|
||||
battle_of(req).pop("battleField")
|
||||
report = ExperimentalBattleRuntime().inspect(req)
|
||||
self.assertTrue(report["supported"], report["reasons"])
|
||||
self.assertTrue(report["assumptions"])
|
||||
self.assertIn("unmodeled", report["aggregate_controllers"])
|
||||
self.assertTrue(any(d["code"] == "aggregate_skill" for d in report["diagnostics"]))
|
||||
self.assertEqual(simulate_quick(req)["execution_status"], "completed")
|
||||
|
||||
def test_missing_growth_or_original_species_still_refuses(self):
|
||||
req = request()
|
||||
req["roster"]["monsters"][0].pop("gAtk")
|
||||
self.assertFalse(ExperimentalBattleRuntime().inspect(req)["supported"])
|
||||
req = request(enemies=[enemy(type="unknown")])
|
||||
self.assertFalse(ExperimentalBattleRuntime().inspect(req)["supported"])
|
||||
|
||||
def test_empty_survival_battle_runs_until_original_clock(self):
|
||||
req = request(seconds=3, enemies=[])
|
||||
battle_of(req)["winType"] = ["2"]
|
||||
result = simulate_quick(req)
|
||||
self.assertEqual(result["outcome"], "win")
|
||||
self.assertEqual(result["elapsed_ms"], 3000)
|
||||
self.assertEqual(result["battle_data"]["leftTime"], 0)
|
||||
self.assertEqual(result["terminal_reason"], "battle_time_limit")
|
||||
|
||||
def test_standalone_maker_has_a_bounded_real_numeric_enemy_budget(self):
|
||||
req = request(seconds=140, enemies=[])
|
||||
battle_of(req)["winType"] = ["2"]
|
||||
battle_of(req)["controller"] = [{"type": "monMaker", "para": {
|
||||
"monType": 1001010, "team": 2, "hp": 1, "atk": 0, "interval": 1}}]
|
||||
result = simulate_quick(req)
|
||||
self.assertEqual(result["outcome"], "win")
|
||||
self.assertEqual(result["generated_units"], MAX_GENERATED)
|
||||
self.assertTrue(result["spawn_bound_reached"])
|
||||
self.assertGreater(result["damage_hp_lost"]["2"], 0)
|
||||
self.assertEqual(result["elapsed_ms"], 140000)
|
||||
|
||||
def test_unknown_generated_species_is_missing_numeric_data(self):
|
||||
req = request(enemies=[])
|
||||
battle_of(req)["controller"] = [{"type": "monMaker", "para": {"monType": 999999999}}]
|
||||
self.assertFalse(ExperimentalBattleRuntime().inspect(req)["supported"])
|
||||
|
||||
def test_zero_capacity_team_can_deploy_uncounted_authored_enemies(self):
|
||||
req = request(enemies=[enemy(countUnit=False)])
|
||||
battle_of(req)["teams"][0]["numMax"] = 0
|
||||
result = simulate_quick(req)
|
||||
self.assertTrue(result["supported"], result["reasons"])
|
||||
self.assertIsNotNone(result["units"][1]["joined_ms"])
|
||||
self.assertEqual(result["execution_status"], "completed")
|
||||
|
||||
def test_weak_team_loses_without_assigned_victory(self):
|
||||
result = simulate_quick(request(players=[monster(level=1)], enemies=[enemy(hp=10000, atk=10000)]))
|
||||
self.assertEqual(result["outcome"], "loss")
|
||||
self.assertEqual(result["alive_num"], 0)
|
||||
self.assertFalse(result["battle_data"]["win"])
|
||||
|
||||
def test_protect_any_and_protect_all_use_actual_remaining_hp(self):
|
||||
req = request(seconds=3, players=[monster(level=1)], enemies=[
|
||||
enemy(mid=11, team=1, protectTarget=True, hp=1, atk=0),
|
||||
enemy(mid=12, team=1, protectTarget=True, hp=10000, atk=0),
|
||||
enemy(mid=13, hp=100000, atk=20)])
|
||||
battle_of(req).update(winType=["2"], loseType=["3", "2"])
|
||||
result = simulate_quick(req)
|
||||
self.assertEqual(result["outcome"], "loss")
|
||||
self.assertLess(result["elapsed_ms"], 3000)
|
||||
battle_of(req)["loseType"] = ["4", "2"]
|
||||
result = simulate_quick(req)
|
||||
self.assertEqual(result["outcome"], "win")
|
||||
self.assertEqual(result["elapsed_ms"], 3000)
|
||||
protected = [u for u in result["units"] if u["protect_target"]]
|
||||
self.assertEqual(sum(u["hp"] > 0 for u in protected), 1)
|
||||
|
||||
def test_destroy_any_and_destroy_all_are_distinct(self):
|
||||
req = request(seconds=3, enemies=[enemy(mid=11, destroyTarget=True, hp=1, atk=0),
|
||||
enemy(mid=12, destroyTarget=True, hp=100000, atk=0)])
|
||||
battle_of(req)["winType"] = ["3"]
|
||||
self.assertEqual(simulate_quick(req)["outcome"], "win")
|
||||
battle_of(req)["winType"] = ["4"]
|
||||
result = simulate_quick(req)
|
||||
self.assertEqual(result["outcome"], "loss")
|
||||
self.assertGreater(next(u for u in result["units"] if u["source_id"] == "12")["hp"], 0)
|
||||
|
||||
def test_task_1002013_public_configuration_runs_without_changing_inputs(self):
|
||||
req = request(context="task_pass_stage", damage_profile=DESKTOP_DAMAGE_PROFILE,
|
||||
players=[monster(level=20), monster(102, level=20), monster(103, level=20)])
|
||||
req["original_data"]["battle"] = ProgressionData().task_battle("1002013", 1)
|
||||
before = deepcopy(req)
|
||||
result = simulate_quick(req)
|
||||
self.assertTrue(result["supported"], result["reasons"])
|
||||
self.assertIn(result["outcome"], ("win", "loss"))
|
||||
self.assertEqual(req, before)
|
||||
boss = next(u for u in result["units"] if u["species"] == 3012010)
|
||||
nest = next(u for u in result["units"] if u["species"] == 9998002)
|
||||
if boss["joined_ms"] is not None:
|
||||
self.assertIsNotNone(nest["died_ms"])
|
||||
self.assertGreaterEqual(boss["joined_ms"], nest["died_ms"])
|
||||
|
||||
def test_task_1001001_blank_default_mids_preserve_original_stats(self):
|
||||
req = request(context="task_battle")
|
||||
req["original_data"]["battle"] = ProgressionData().task_battle("1001001", 1)
|
||||
self.assertTrue(any(m.get("mid") == "" for t in battle_of(req)["teams"] for m in t["mons"] if m))
|
||||
before = deepcopy(req)
|
||||
detailed, _ = _prepare(req, combat_tables())
|
||||
quick, report = prepare(req)
|
||||
self.assertTrue(report["supported"], report["reasons"])
|
||||
self.assertEqual([u.stats for u in quick.units], [u.stats for u in detailed.units])
|
||||
result = simulate_quick(req)
|
||||
self.assertEqual(result["execution_status"], "completed")
|
||||
self.assertIn(result["outcome"], ("win", "loss"))
|
||||
self.assertEqual(req, before)
|
||||
|
||||
def test_cap_applies_per_hit_after_expected_skill_gain(self):
|
||||
req = request(players=[monster(pAtk=10000)], enemies=[enemy(hp=1000000, atk=0)],
|
||||
seconds=1, damage_profile=DESKTOP_DAMAGE_PROFILE)
|
||||
result = simulate_quick(req)
|
||||
attack_ms = result["units"][0]["stats"]["attack_ms"]
|
||||
self.assertLessEqual(result["team_budgets"]["1"]["peak_expected_dps"], round(50000 * 1000 / attack_ms, 3))
|
||||
self.assertEqual(result["damage_multiplier"], 10)
|
||||
self.assertEqual(result["damage_cap"], 50000)
|
||||
|
||||
def test_anomaly_records_and_trace_bounds_are_preserved(self):
|
||||
req = request(players=[monster(mid=100001, feel=201)], trace_limit=0)
|
||||
report = ExperimentalBattleRuntime().inspect(req)
|
||||
result = simulate_quick(req)
|
||||
for anomaly in report["anomalies"]:
|
||||
self.assertIn(anomaly, result["anomalies"])
|
||||
self.assertEqual(result["battle_data"]["cheatRecords"], result["anomalies"])
|
||||
self.assertFalse(result["experimental_settlement_eligible"])
|
||||
self.assertEqual(result["events"], [])
|
||||
|
||||
def test_cancel_and_technical_timeout_have_no_settlement_data(self):
|
||||
event = threading.Event()
|
||||
event.set()
|
||||
for result in (simulate_quick(request(), cancel_event=event), simulate_quick(request(), timeout=0)):
|
||||
self.assertIn(result["outcome"], ("cancelled", "timeout"))
|
||||
self.assertFalse(result["terminal"])
|
||||
self.assertIsNone(result["battle_data"])
|
||||
|
||||
def test_local_runtime_evidence_retains_model_and_hp_dps(self):
|
||||
result = simulate_quick(request())
|
||||
evidence = BattleOrchestrator.runtime_evidence(result, "experimental")
|
||||
for name in ("model", "simulation_method", "team_budgets", "generated_units", "spawn_bound_reached"):
|
||||
self.assertEqual(evidence[name], result[name])
|
||||
self.assertNotIn(name, result["battle_data"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -415,8 +415,9 @@ class SimulatorTests(unittest.TestCase):
|
||||
req = request(players=[monster(species=1001020)]) # actual skill 10
|
||||
report = ExperimentalBattleRuntime().inspect(req)
|
||||
self.assertTrue(report["supported"])
|
||||
self.assertTrue(any(d["code"] == "unsupported_skill" and "10" in d["message"] for d in report["diagnostics"]))
|
||||
self.assertTrue(any("Skill 10" in x for x in report["ignored_mechanics"]))
|
||||
self.assertTrue(any(d["code"] == "aggregate_skill" and "10" in d["message"] for d in report["diagnostics"]))
|
||||
self.assertTrue(any("bounded expected" in x for x in report["assumptions"]))
|
||||
self.assertTrue(any(d["code"] == "unsupported_skill" for d in simulate(req)["diagnostics"]))
|
||||
|
||||
def test_controllers_triggers_and_non_elimination_are_rejected(self):
|
||||
for key, value in (("controller", [{"type": "monMaker"}]),
|
||||
@@ -476,11 +477,13 @@ class WorkerTests(unittest.TestCase):
|
||||
self.assertEqual(result["outcome"], "win")
|
||||
self.assertEqual(result["battle_data"]["battlePosition"], req["battle_position"])
|
||||
|
||||
def test_fixed_module_subprocess_equals_direct_model(self):
|
||||
def test_fixed_module_subprocess_uses_quick_model_by_default(self):
|
||||
from ranch_assistant.battle_quick import simulate_quick
|
||||
req = request()
|
||||
with patch("socket.socket", side_effect=AssertionError("No network")):
|
||||
result = ExperimentalBattleRuntime().run(req)
|
||||
self.assertEqual(result, simulate(req))
|
||||
self.assertEqual(result, simulate_quick(req))
|
||||
self.assertEqual(result["simulation_method"], "aggregate_hp_dps")
|
||||
|
||||
def test_worker_entrypoint_does_not_import_gui_or_production_engine(self):
|
||||
completed = subprocess.run([sys.executable, "-c",
|
||||
|
||||
@@ -0,0 +1,393 @@
|
||||
"""Offline task procurement replay: all writes go to the fake below."""
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from ranch_assistant.engine import Engine
|
||||
from ranch_assistant.game_data import ProgressionData
|
||||
from ranch_assistant.model import Catalog, Policy, Snapshot
|
||||
from ranch_assistant.progression import ProgressionPlanner, ProgressionPolicy
|
||||
from ranch_assistant.quests import QuestPolicy
|
||||
from ranch_assistant.tests.test_progression import config, snapshot, step, task
|
||||
|
||||
|
||||
EGG = "1030010"
|
||||
|
||||
|
||||
def requirement(kind="getMonster", count=1, key=EGG):
|
||||
return step(kind, statusValue={"type": key, "num": count, "mode": 2 if kind == "getMonster" else 0, "remove": True})
|
||||
|
||||
|
||||
def monster(catalog, mid, **changes):
|
||||
row = catalog.monster(EGG)
|
||||
return {"id": mid, "typeId": int(EGG), "mode": 2, "process": 3, "level": 1, "roomId": 1,
|
||||
**{"g" + stat.capitalize(): row[stat + "_grow_min"] for stat in ("atk", "def", "hp", "dex")}, **changes}
|
||||
|
||||
|
||||
class OfflineProcurementClient:
|
||||
def __init__(self, raw, catalog):
|
||||
self.raw, self.catalog, self.writes = deepcopy(raw), catalog, []
|
||||
self.timeout = False
|
||||
|
||||
def snapshot(self):
|
||||
return Snapshot(deepcopy(self.raw))
|
||||
|
||||
def call(self, path, payload):
|
||||
self.writes.append((path, deepcopy(payload)))
|
||||
if self.timeout:
|
||||
raise TimeoutError("offline fake lost reply")
|
||||
if path == "gachaService/gachaGetEggs":
|
||||
count = payload["num"]
|
||||
self.raw["master"]["money"] -= self.catalog.data["markets"][payload["id"]]["money"] * count
|
||||
existing = next((i for i in self.raw["items"] if str(i["typeId"]) == EGG), None)
|
||||
if existing:
|
||||
existing["num"] += count
|
||||
else:
|
||||
self.raw["items"].append({"id": 500, "typeId": int(EGG), "num": count})
|
||||
return {"resCode": 0, "eggs": [{"typeId": int(EGG), "num": count}]}
|
||||
if path == "stackService/stackAddMonster":
|
||||
for egg in payload["eggs"]:
|
||||
item = next(i for i in self.raw["items"] if i["id"] == egg["itemId"])
|
||||
item["num"] -= 1
|
||||
mid = max([m["id"] for m in self.raw["monsters"]] + [900]) + 1
|
||||
self.raw["monsters"].append(monster(self.catalog, mid, mode=0, process=2,
|
||||
timeStart=self.snapshot().now * 1000, roomId=0))
|
||||
next(s for s in self.raw["stacks"] if s["id"] == egg["stackId"])["monsterId"] = mid
|
||||
return {"resCode": 0}
|
||||
if path == "stackService/stackTransferMonster":
|
||||
for data in payload["datas"]:
|
||||
for mid in data["monsterId"]:
|
||||
next(m for m in self.raw["monsters"] if m["id"] == mid).update(process=3, roomId=data["roomId"])
|
||||
for stack in self.raw["stacks"]:
|
||||
if stack["monsterId"] == mid:
|
||||
stack["monsterId"] = 0
|
||||
return {"resCode": 0}
|
||||
if path == "taskService/taskLoopReceive":
|
||||
received = {"id": 51, "typeId": payload["taskTypeId"], "curStep": 1}
|
||||
self.raw["currentTasks"].append(received)
|
||||
self.raw["history"]["loopTaskNum"] -= 1
|
||||
return {"resCode": 0, "task": deepcopy(received)}
|
||||
if path == "taskService/taskCompleteStep":
|
||||
for mid in payload.get("removeIds") or []:
|
||||
self.raw["monsters"] = [m for m in self.raw["monsters"] if m["id"] != mid]
|
||||
for stack in self.raw["stacks"]:
|
||||
if stack["monsterId"] == mid:
|
||||
stack["monsterId"] = 0
|
||||
next(t for t in self.raw["currentTasks"] if t["id"] == payload["taskId"])["curStep"] += 1
|
||||
return {"resCode": 0, "taskStepValue": None}
|
||||
if path == "taskService/taskComplete":
|
||||
self.raw["currentTasks"] = [t for t in self.raw["currentTasks"] if t["id"] != payload["taskId"]]
|
||||
return {"resCode": 0, "reward": {"ke": 20}}
|
||||
raise AssertionError("Unexpected fake write: " + path)
|
||||
|
||||
|
||||
class CommissionProcurementTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.catalog = Catalog()
|
||||
# Keep a real gold market and real growth/protection rules; make the
|
||||
# offline draw deterministic without asserting real RNG outcomes.
|
||||
self.catalog.data["markets"]["sc_city1"]["eggs"] = {"2": [int(EGG)]}
|
||||
self.tasks = {"400": task("400", type=4, reward={"ke": 20}, steps=[requirement()]),
|
||||
"401": task("401", type=4, reward={"ke": 15})}
|
||||
self.data = ProgressionData(config(self.tasks))
|
||||
self.raw = snapshot(currentTasks=[]).raw
|
||||
self.raw["master"]["money"] = 10000
|
||||
self.raw["history"].update(loopTaskTime=snapshot().now, loopTaskNum=4, loopTask={"2": ["400"], "1": ["401"]}, unlockCity={"1": True, "2": True})
|
||||
self.raw["stacks"] = [{"id": i + 1, "position": i % 3, "monsterId": 0} for i in range(10)]
|
||||
self.quest = QuestPolicy(enabled=True, allow_monsters=True, allow_items=True)
|
||||
self.ranch = Policy(buy=True, allow_single_draw=True, buy_batch=5)
|
||||
self.folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.folder.cleanup)
|
||||
|
||||
def engine(self, *, raw=None, folder=None):
|
||||
client = OfflineProcurementClient(raw or self.raw, self.catalog)
|
||||
engine = Engine(self.catalog, client, Path(folder or self.folder.name) / "budget.json", game_data=self.data)
|
||||
engine.snapshot = client.snapshot()
|
||||
engine.policy, engine.quest_policy = deepcopy(self.ranch), deepcopy(self.quest)
|
||||
engine._refresh_progression_cache(force=True)
|
||||
self.assertEqual(engine._progression_error, "")
|
||||
return engine, client
|
||||
|
||||
def sync(self, engine, client):
|
||||
engine.snapshot = client.snapshot()
|
||||
engine._refresh_progression_cache(force=True)
|
||||
|
||||
def intent(self, engine):
|
||||
return next(i for i in engine._progression_intents if not i.block_reason)
|
||||
|
||||
def test_cross_city_twenty_buy_hatch_wait_submit_complete_replay(self):
|
||||
engine, client = self.engine()
|
||||
buy = self.intent(engine)
|
||||
self.assertEqual((buy.kind, buy.phase, buy.source_task_type_id), ("progression_procure", "buy", "400"))
|
||||
self.assertEqual(buy.payload["num"], 1)
|
||||
offer = next(r for r in engine.commission_offer_diagnostics() if r["task_type_id"] == "400")
|
||||
self.assertFalse(offer["eligible"])
|
||||
self.assertTrue(offer["preparable"])
|
||||
self.assertEqual(offer["resources"][0]["available"], 0)
|
||||
engine._run_progression_intent(buy)
|
||||
self.assertIsNone(engine.battle_journal.pending(engine.snapshot))
|
||||
hatch = self.intent(engine)
|
||||
self.assertEqual(hatch.phase, "hatch")
|
||||
engine._run_progression_intent(hatch)
|
||||
self.assertEqual(engine.snapshot.raw["history"]["loopTaskNum"], 4)
|
||||
self.assertFalse(any(not i.block_reason for i in engine._progression_intents))
|
||||
for _ in range(3):
|
||||
self.sync(engine, client)
|
||||
self.assertEqual([p for p, _ in client.writes], ["gachaService/gachaGetEggs", "stackService/stackAddMonster"])
|
||||
client.raw["monsters"][0].update(mode=2)
|
||||
self.sync(engine, client)
|
||||
accept = self.intent(engine)
|
||||
self.assertEqual((accept.kind, accept.payload["city"]), ("progression_loop_accept", 2))
|
||||
engine._run_progression_intent(accept)
|
||||
for _ in range(3):
|
||||
engine._run_progression_intent(self.intent(engine))
|
||||
self.assertEqual(engine.commission_history()["summary"]["confirmed_ke"], 20)
|
||||
self.assertEqual(client.raw["history"]["loopTaskNum"], 3)
|
||||
|
||||
def test_one_missing_ten_empty_slots_thousand_eggs_hatches_only_one(self):
|
||||
self.raw["items"] = [{"id": 500, "typeId": int(EGG), "num": 1000}]
|
||||
engine, client = self.engine()
|
||||
intent = self.intent(engine)
|
||||
self.assertEqual(len(intent.payload["eggs"]), 1)
|
||||
engine._run_progression_intent(intent)
|
||||
self.assertEqual(sum(bool(s["monsterId"]) for s in client.raw["stacks"]), 1)
|
||||
self.assertEqual(client.raw["items"][0]["num"], 999)
|
||||
self.assertFalse(any(not i.block_reason for i in engine._progression_intents))
|
||||
self.assertFalse(any(a.kind in ("buy", "hatch") for a in engine.plans()))
|
||||
self.assertEqual(engine.pending_hatches, [])
|
||||
|
||||
def test_quota_zero_never_procures_or_accepts(self):
|
||||
self.raw["history"]["loopTaskNum"] = 0
|
||||
engine, client = self.engine()
|
||||
engine._run_progression_intent()
|
||||
self.assertEqual(client.writes, [])
|
||||
self.assertTrue(all(r["reason_kind"] == "quota" and not r["preparable"] for r in engine.commission_offer_diagnostics()))
|
||||
|
||||
def test_existing_eggs_and_incubator_count_before_buy(self):
|
||||
self.tasks["400"]["steps"] = [requirement(count=3)]
|
||||
self.raw["items"] = [{"id": 500, "typeId": int(EGG), "num": 1}]
|
||||
self.raw["monsters"] = [monster(self.catalog, 901, mode=0, process=2, timeStart=snapshot().now * 1000)]
|
||||
self.raw["stacks"][0]["monsterId"] = 901
|
||||
engine, client = self.engine()
|
||||
engine._run_progression_intent(self.intent(engine)) # reuse the egg
|
||||
buy = self.intent(engine)
|
||||
self.assertEqual(buy.phase, "buy")
|
||||
self.assertEqual(buy.payload["num"], 1)
|
||||
engine._run_progression_intent(buy)
|
||||
self.assertEqual(sum(p == "gachaService/gachaGetEggs" for p, _ in client.writes), 1)
|
||||
|
||||
def test_shared_eggs_user_reserve_and_multistep_demands_are_not_double_counted(self):
|
||||
self.tasks["400"]["steps"] = [requirement("getItem", 1), requirement("getItem", 1), requirement(count=1)]
|
||||
self.raw["items"] = [{"id": 500, "typeId": int(EGG), "num": 5}]
|
||||
self.ranch.reserved_eggs = {EGG: 2}
|
||||
engine, client = self.engine()
|
||||
self.assertEqual(self.intent(engine).phase, "hatch")
|
||||
engine._run_progression_intent(self.intent(engine))
|
||||
self.assertEqual(client.raw["items"][0]["num"], 4) # 2 task eggs + 2 user reserve
|
||||
self.assertFalse(any(not i.block_reason for i in engine._progression_intents))
|
||||
self.assertFalse(any(path == "gachaService/gachaGetEggs" for path, _ in client.writes))
|
||||
|
||||
def test_multistep_adult_removals_cannot_reuse_one_monster(self):
|
||||
self.tasks["400"]["steps"] = [requirement(), requirement()]
|
||||
self.raw["monsters"] = [monster(self.catalog, 901)]
|
||||
engine, _ = self.engine()
|
||||
buy = self.intent(engine)
|
||||
self.assertEqual(buy.payload["num"], 1)
|
||||
self.assertEqual(engine.commission_offer_diagnostics()[0]["resources"][0]["needed"], 2)
|
||||
|
||||
def test_active_same_species_steps_buy_remaining_deficit_and_advance(self):
|
||||
self.tasks["400"]["steps"] = [requirement(), requirement()]
|
||||
for cursor in (1, 2):
|
||||
with self.subTest(cursor=cursor), tempfile.TemporaryDirectory(dir=self.folder.name) as folder:
|
||||
raw = deepcopy(self.raw)
|
||||
raw["currentTasks"] = [{"id": 51, "typeId": "400", "curStep": cursor}]
|
||||
engine, client = self.engine(raw=raw, folder=folder)
|
||||
deficit = 3 - cursor
|
||||
buy = self.intent(engine)
|
||||
self.assertEqual((buy.kind, buy.phase, buy.source_task_id), ("progression_procure", "buy", 51))
|
||||
self.assertEqual(buy.payload["num"], deficit)
|
||||
engine._run_progression_intent(buy)
|
||||
self.assertEqual(client.writes, [("gachaService/gachaGetEggs", buy.payload)])
|
||||
self.assertIsNone(engine.battle_journal.pending(engine.snapshot))
|
||||
for _ in range(deficit):
|
||||
hatch = self.intent(engine)
|
||||
self.assertEqual((hatch.kind, hatch.phase), ("progression_procure", "hatch"))
|
||||
engine._run_progression_intent(hatch)
|
||||
self.assertIsNone(engine.battle_journal.pending(engine.snapshot))
|
||||
for _ in range(3):
|
||||
engine._run_progression_intent()
|
||||
self.assertEqual(len(client.writes), 1 + deficit)
|
||||
self.assertEqual(client.raw["currentTasks"][0]["curStep"], cursor)
|
||||
for growing in client.raw["monsters"]:
|
||||
growing["mode"] = 2
|
||||
self.sync(engine, client)
|
||||
submitted = []
|
||||
for number in range(cursor, 3):
|
||||
submit = self.intent(engine)
|
||||
self.assertEqual((submit.kind, submit.step_number), ("progression_step", number))
|
||||
submitted.extend(submit.payload["removeIds"])
|
||||
engine._run_progression_intent(submit)
|
||||
self.assertEqual(client.raw["currentTasks"][0]["curStep"], number + 1)
|
||||
local = self.intent(engine)
|
||||
self.assertEqual(local.kind, "progression_local_step")
|
||||
engine._run_progression_intent(local)
|
||||
self.assertEqual(len(set(submitted)), deficit)
|
||||
complete = self.intent(engine)
|
||||
self.assertEqual(complete.kind, "progression_complete")
|
||||
engine._run_progression_intent(complete)
|
||||
purchases = [payload["num"] for path, payload in client.writes if path == "gachaService/gachaGetEggs"]
|
||||
self.assertEqual(purchases, [deficit])
|
||||
self.assertEqual(client.raw["currentTasks"], [])
|
||||
self.assertEqual(client.raw["history"]["loopTaskNum"], 4)
|
||||
self.assertEqual(engine.commission_history()["summary"]["confirmed_ke"], 20)
|
||||
|
||||
def test_active_procurement_keeps_future_handin_money_in_both_checks(self):
|
||||
handin = 500
|
||||
self.tasks["400"]["steps"] = [requirement(count=2),
|
||||
step("getMoney", statusValue={"money": handin, "remove": True})]
|
||||
self.raw["currentTasks"] = [{"id": 51, "typeId": "400", "curStep": 1}]
|
||||
self.quest.max_money = handin
|
||||
price = self.catalog.data["markets"]["sc_city1"]["money"]
|
||||
self.raw["master"]["money"] = self.ranch.keep_money + handin + price
|
||||
engine, client = self.engine()
|
||||
buy = self.intent(engine)
|
||||
self.assertEqual((buy.kind, buy.phase, buy.payload["num"]), ("progression_procure", "buy", 1))
|
||||
engine._run_progression_intent(buy)
|
||||
self.assertEqual(client.writes, [("gachaService/gachaGetEggs", buy.payload)])
|
||||
self.assertEqual(client.raw["master"]["money"], self.ranch.keep_money + handin)
|
||||
self.assertIsNone(engine.battle_journal.pending(engine.snapshot))
|
||||
self.assertEqual(client.raw["currentTasks"][0]["curStep"], 1)
|
||||
|
||||
def test_protected_duplicates_are_reported_and_not_submitted(self):
|
||||
self.raw["monsters"] = [monster(self.catalog, 1, lock=True), monster(self.catalog, 2),
|
||||
monster(self.catalog, 3), monster(self.catalog, 4)]
|
||||
self.raw["teams"] = [{"name": "teamA", "monsters": [2]}]
|
||||
self.ranch.feed_targets = {"3": 1}
|
||||
engine, client = self.engine()
|
||||
info = self.data.task("400")
|
||||
ready, ids, reason = engine.progression_planner.requirement(engine.snapshot, info["steps"][0], {},
|
||||
engine._intent_policy({"task_type_id": "400"}), engine.policy)
|
||||
self.assertTrue(ready)
|
||||
self.assertEqual(ids, [4])
|
||||
self.assertIn("保护3", reason)
|
||||
self.assertIn("已锁定", reason)
|
||||
engine._run_progression_intent(self.intent(engine))
|
||||
engine._run_progression_intent(self.intent(engine))
|
||||
self.assertEqual({m["id"] for m in client.raw["monsters"]}, {1, 2, 3})
|
||||
|
||||
def test_protected_star_species_cannot_be_procured_by_unprotecting(self):
|
||||
self.ranch.protect_star = 2
|
||||
engine, client = self.engine()
|
||||
row = engine.commission_offer_diagnostics()[0]
|
||||
self.assertFalse(row["eligible"] or row["preparable"])
|
||||
self.assertIn("新孵魔物也受", row["reason"])
|
||||
self.assertFalse(any(i.kind == "progression_procure" for i in engine._progression_intents))
|
||||
self.assertEqual(client.writes, [])
|
||||
|
||||
def test_coin_reserve_daily_budget_and_ten_draw_rule_remain_enforced(self):
|
||||
for changes in ({"daily_buy_money": 0}, {"keep_money": 10000}, {"allow_single_draw": False}):
|
||||
with self.subTest(changes=changes):
|
||||
self.ranch = Policy(buy=True, allow_single_draw=True, **{k: v for k, v in changes.items() if k != "allow_single_draw"})
|
||||
if "allow_single_draw" in changes:
|
||||
self.ranch.allow_single_draw = False
|
||||
engine, client = self.engine()
|
||||
self.assertFalse(any(i.kind == "progression_procure" for i in engine._progression_intents))
|
||||
self.assertEqual(client.writes, [])
|
||||
|
||||
def test_stop_and_changed_offer_cancel_before_dispatch(self):
|
||||
for change in (lambda e: e.cancel_progression(), lambda e: e.snapshot.raw["history"].update(loopTaskNum=0),
|
||||
lambda e: e.snapshot.raw["history"].update(loopTask={}),
|
||||
lambda e: e.snapshot.raw["currentTasks"].append({"id": 52, "typeId": "401", "curStep": 1})):
|
||||
with self.subTest(change=change):
|
||||
engine, client = self.engine()
|
||||
intent = self.intent(engine)
|
||||
original = engine._journal_commission
|
||||
def change_before_dispatch(record, incoming):
|
||||
original(record, incoming)
|
||||
change(engine)
|
||||
with patch.object(engine, "_journal_commission", side_effect=change_before_dispatch):
|
||||
engine._execute_procurement(intent)
|
||||
self.assertEqual(client.writes, [])
|
||||
self.assertIsNone(engine.battle_journal.pending(engine.snapshot))
|
||||
|
||||
def test_active_task_changed_before_dispatch_is_cancelled(self):
|
||||
self.raw["currentTasks"] = [{"id": 51, "typeId": "400", "curStep": 1}]
|
||||
engine, client = self.engine()
|
||||
intent = self.intent(engine)
|
||||
original = engine._journal_commission
|
||||
def replace_task(record, incoming):
|
||||
original(record, incoming)
|
||||
engine.snapshot.raw["currentTasks"] = [{"id": 52, "typeId": "400", "curStep": 1}]
|
||||
with patch.object(engine, "_journal_commission", side_effect=replace_task):
|
||||
engine._execute_procurement(intent)
|
||||
self.assertEqual(client.writes, [])
|
||||
self.assertIsNone(engine.battle_journal.pending(engine.snapshot))
|
||||
|
||||
def test_hard_prerequisite_is_not_misreported_as_preparable(self):
|
||||
self.tasks["400"]["steps"][0]["condition"] = {"finishTask": ["999"]}
|
||||
engine, client = self.engine()
|
||||
row = engine.commission_offer_diagnostics()[0]
|
||||
self.assertFalse(row["eligible"] or row["preparable"])
|
||||
self.assertEqual(row["reason_kind"], "prerequisite")
|
||||
self.assertFalse(any(i.kind == "progression_procure" for i in engine._progression_intents))
|
||||
self.assertEqual(client.writes, [])
|
||||
|
||||
def test_ten_draw_cost_uses_verified_unit_price_without_fictitious_discount(self):
|
||||
self.tasks["400"]["steps"] = [requirement(count=10)]
|
||||
price = self.catalog.data["markets"]["sc_city1"]["money"]
|
||||
self.ranch.daily_buy_money = price * 10
|
||||
self.raw["master"]["money"] = self.ranch.keep_money + price * 10
|
||||
engine, _ = self.engine()
|
||||
buy = self.intent(engine)
|
||||
self.assertEqual(buy.payload["num"], 10)
|
||||
engine._run_progression_intent(buy)
|
||||
self.assertEqual(engine.purchase_budget.spent(engine.snapshot.now), price * 10)
|
||||
|
||||
def test_unknown_buy_survives_restart_and_account_isolation(self):
|
||||
engine, client = self.engine()
|
||||
client.timeout = True
|
||||
with self.assertRaises(TimeoutError):
|
||||
engine._execute_procurement(self.intent(engine))
|
||||
self.assertEqual(len(client.writes), 1)
|
||||
restored, second = self.engine()
|
||||
restored._run_progression_intent()
|
||||
self.assertEqual(second.writes, [])
|
||||
self.assertIsNotNone(restored.battle_journal.pending(restored.snapshot))
|
||||
other = deepcopy(self.raw)
|
||||
other["master"]["id"] = 2
|
||||
isolated, _ = self.engine(raw=other)
|
||||
self.assertIsNone(isolated.battle_journal.pending(isolated.snapshot))
|
||||
with self.assertRaises(ValueError):
|
||||
isolated._execute_procurement(self.intent(engine))
|
||||
|
||||
def test_mainline_confirmed_unlock_changes_offer_eligibility(self):
|
||||
self.tasks["100"] = task("100", steps=[step()])
|
||||
data = config(self.tasks)
|
||||
data["game_setting"]["cityInfo"]["2"] = {"name": "测试城", "openTask": "100"}
|
||||
planner = ProgressionPlanner(self.catalog, data)
|
||||
raw = deepcopy(self.raw)
|
||||
raw["history"]["unlockCity"]["2"] = False
|
||||
raw["currentTasks"] = [{"id": 11, "typeId": "100", "curStep": 2}]
|
||||
raw["monsters"] = [monster(self.catalog, 901)]
|
||||
snap = Snapshot(raw)
|
||||
before = planner.commission_offers(snap, self.quest, self.ranch)[0]
|
||||
self.assertEqual(before["reason_kind"], "city_locked")
|
||||
self.assertIn("测试城", before["reason"])
|
||||
finish = planner.plan(snap, ProgressionPolicy(enabled=True), self.ranch)[0]
|
||||
planner.acknowledge(snap, finish, {"reward": {}})
|
||||
self.assertTrue(planner.commission_offers(snap, self.quest, self.ranch)[0]["eligible"])
|
||||
|
||||
def test_material_shortage_uses_real_supported_sweep_source(self):
|
||||
self.tasks["400"]["steps"] = [requirement("getItem", 3, "30054")]
|
||||
data = config(self.tasks, farming={"items": {"30054": [{"stage_id": "0101", "difficulty": 1}]}})
|
||||
self.raw["history"]["passStage"] = {"0101": [1, 2, 3]}
|
||||
planner = ProgressionPlanner(self.catalog, data)
|
||||
actions = planner.commission_plan(Snapshot(self.raw), self.quest, self.ranch)
|
||||
self.assertEqual(actions[0].kind, "sweep")
|
||||
self.assertEqual(actions[0].source_task_type_id, "400")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,194 @@
|
||||
"""Offline coverage-tool regressions against the packaged original task data."""
|
||||
from copy import deepcopy
|
||||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import sys
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from ranch_assistant.game_data import load_progression_data
|
||||
from tools import check_progression_support as support
|
||||
|
||||
|
||||
class ProgressionSupportTests(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.data = load_progression_data()
|
||||
cls.cases = support.collect_cases(cls.data)
|
||||
cls.priority = next(case for case in cls.cases if case.task == "1002013")
|
||||
|
||||
def test_every_mainline_and_commission_battle_step_is_resolved(self):
|
||||
expected = {(str(key), number, step["statusType"])
|
||||
for key, task in self.data.tasks.items() if task.get("type") in (1, 4)
|
||||
for number, step in enumerate(task.get("steps") or (), 1)
|
||||
if step.get("statusType") in ("battle", "passStage")}
|
||||
self.assertEqual({(case.task, case.step, case.step_type) for case in self.cases}, expected)
|
||||
self.assertEqual(len(self.cases), len(expected))
|
||||
self.assertEqual({(case.task_type, case.step_type) for case in self.cases},
|
||||
{(1, "battle"), (1, "passStage"), (4, "battle"), (4, "passStage")})
|
||||
self.assertTrue(all(isinstance(case.battle, dict) and case.battle for case in self.cases))
|
||||
|
||||
def test_priority_task_uses_original_0216_level_one_configuration(self):
|
||||
self.assertEqual((self.priority.task_type, self.priority.step, self.priority.step_type), (1, 1, "passStage"))
|
||||
step = self.data.task("1002013")["steps"][0]
|
||||
self.assertEqual(step["statusValue"], {"stage": "0216", "level": "1"})
|
||||
self.assertEqual(self.priority.battle, self.data.stage_battle("0216", "1"))
|
||||
self.assertEqual(self.priority.battle, self.data.task_battle("1002013", 1))
|
||||
features = support.mechanics(self.priority.battle)
|
||||
for reason in ("trigger:monDead", "trigger_effect:unlockWave", "unit_controller:monMaker",
|
||||
"unit_controller:monSteps", "unit_controller:skill"):
|
||||
self.assertGreater(features[reason], 0)
|
||||
|
||||
def test_structural_hotspots_count_configurations_separately_from_occurrences(self):
|
||||
report = support.source_scan(self.cases)
|
||||
self.assertEqual(report["count"], len(self.cases))
|
||||
self.assertEqual(sum(row["count"] for row in report["counts"]), len(self.cases))
|
||||
affected = {row["reason"]: row["count"] for row in report["mechanics"]}
|
||||
occurrences = {row["reason"]: row["count"] for row in report["occurrences"]}
|
||||
self.assertGreater(affected["unit_controller:hpArea"], 0)
|
||||
self.assertGreater(occurrences["unit_controller:hpArea"], affected["unit_controller:hpArea"])
|
||||
# Source mechanics are descriptive; they cannot themselves deny quick input.
|
||||
self.assertNotIn("support", report)
|
||||
|
||||
def test_fixture_and_requests_preserve_original_source_and_roster(self):
|
||||
roster = support.fixture_roster()
|
||||
before = deepcopy((roster, self.priority.battle))
|
||||
request = support.make_request(self.priority, roster)
|
||||
self.assertEqual(request["context"], "task_pass_stage")
|
||||
self.assertEqual(request["battle_position"], {"battleType": "task", "taskTypeId": "1002013", "taskStep": 0})
|
||||
self.assertEqual(request["damage_profile"], "client_v4_x10")
|
||||
self.assertEqual(support.make_request(self.priority, roster, damage_profile="original_1x")["damage_profile"],
|
||||
"original_1x")
|
||||
self.assertEqual(request["trace_limit"], 0)
|
||||
self.assertIs(request["original_data"]["battle"], self.priority.battle)
|
||||
self.assertEqual(roster["monsters"][0]["level"], 20)
|
||||
self.assertEqual((roster, self.priority.battle), before)
|
||||
|
||||
def test_bounded_case_selection_includes_actual_protection_and_commission(self):
|
||||
cases = support.representative_cases(self.cases, support.MAX_RUNS)
|
||||
self.assertEqual(cases[0], self.priority)
|
||||
self.assertEqual(len(cases), len({(case.task, case.step) for case in cases}))
|
||||
self.assertTrue(any("objective:protectTarget" in support.mechanics(case.battle) for case in cases))
|
||||
self.assertTrue(any(case.task_type == 4 and case.step_type == "battle" for case in cases))
|
||||
self.assertTrue(any(case.task_type == 4 and case.step_type == "passStage" for case in cases))
|
||||
self.assertEqual(support.representative_cases(self.cases, 0), [])
|
||||
with self.assertRaises(ValueError):
|
||||
support.representative_cases(self.cases, support.MAX_RUNS + 1)
|
||||
|
||||
def test_snapshot_loader_drops_identity_envelope_and_sanitizes_failures(self):
|
||||
raw = support.fixture_roster()
|
||||
raw.update(token="private-token-canary", account="private-account-canary")
|
||||
raw["master"].update(id=987654321, nickname="private-nickname-canary")
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
path = Path(directory) / "private-path-canary.json"
|
||||
path.write_text(json.dumps({"raw": raw}), encoding="utf-8")
|
||||
loaded = support.load_snapshot(path)
|
||||
self.assertEqual(loaded, support.fixture_roster())
|
||||
path.write_text('{"token":"private-token-canary",broken', encoding="utf-8")
|
||||
with self.assertRaisesRegex(ValueError, "^snapshot_load_failed$"):
|
||||
support.load_snapshot(path)
|
||||
with self.assertRaisesRegex(ValueError, "^snapshot_load_failed$"):
|
||||
support.load_snapshot(path.with_suffix(".missing"))
|
||||
|
||||
def test_reports_keep_anomaly_counts_separate_from_input_support(self):
|
||||
private = "private-result-canary"
|
||||
raw = {"supported": True, "outcome": "loss", "elapsed_ms": 420,
|
||||
"reasons": [], "units": [{"id": private}], "battle_data": {"monsterIds": [private]},
|
||||
"anomalies": [{"code": "+15overpoten", "monsterId": private}] * 4,
|
||||
"token": private, "events": [{"message": private}]}
|
||||
result = support.result_summary(raw)
|
||||
self.assertTrue(result["support"])
|
||||
self.assertEqual(result["outcome"], "loss")
|
||||
self.assertEqual(result["counts"], [{"reason": "anomaly:+15overpoten", "count": 4}])
|
||||
self.assertNotIn(private, json.dumps(result))
|
||||
raw.update(supported=False, reasons=[private], outcome=private)
|
||||
raw["anomalies"] = [{"code": private}]
|
||||
result = support.result_summary(raw)
|
||||
self.assertNotIn(private, json.dumps(result))
|
||||
self.assertEqual(result["reason"], ["input_or_model_failure"])
|
||||
self.assertEqual(result["outcome"], "error")
|
||||
|
||||
def test_inspection_cancellation_and_deadline_do_not_run_the_model(self):
|
||||
runtime = unittest.mock.Mock()
|
||||
stop = threading.Event()
|
||||
stop.set()
|
||||
cancelled = support.inspect_inputs(self.cases, runtime, cancel_event=stop)
|
||||
self.assertEqual(cancelled["reason"], ["cancelled"])
|
||||
expired = support.inspect_inputs(self.cases, runtime, deadline=time.monotonic() - 1)
|
||||
self.assertEqual(expired["reason"], ["budget_exhausted"])
|
||||
runtime.inspect.assert_not_called()
|
||||
runtime.run.assert_not_called()
|
||||
|
||||
def test_private_model_output_and_exceptions_are_not_logged(self):
|
||||
private = "private-runtime-canary"
|
||||
runtime = unittest.mock.Mock()
|
||||
|
||||
def run(request, **kwargs):
|
||||
print(private)
|
||||
print(private, file=sys.stderr)
|
||||
raise ValueError(private)
|
||||
|
||||
runtime.run.side_effect = run
|
||||
stdout, stderr = io.StringIO(), io.StringIO()
|
||||
with patch.object(sys, "stdout", stdout), patch.object(sys, "stderr", stderr):
|
||||
rows = support.replay_cases([self.priority], runtime, support.fixture_roster())
|
||||
self.assertEqual((stdout.getvalue(), stderr.getvalue()), ("", ""))
|
||||
self.assertNotIn(private, json.dumps(rows))
|
||||
self.assertEqual(rows[0]["outcome"], "error")
|
||||
self.assertEqual(rows[0]["reason"], ["model_execution_failed"])
|
||||
|
||||
def test_replay_uses_web_profile_and_wire_step_without_changing_a_loss(self):
|
||||
runtime = unittest.mock.Mock()
|
||||
runtime.run.return_value = {"supported": True, "outcome": "loss", "elapsed_ms": 1000,
|
||||
"reasons": [], "anomalies": []}
|
||||
rows = support.replay_cases([self.priority], runtime, support.fixture_roster())
|
||||
self.assertEqual(rows[0]["outcome"], "loss")
|
||||
request = runtime.run.call_args.args[0]
|
||||
self.assertEqual(request["damage_profile"], "client_v4_x10")
|
||||
self.assertEqual(request["battle_position"]["taskStep"], 0)
|
||||
self.assertLessEqual(runtime.run.call_args.kwargs["timeout"], 1)
|
||||
|
||||
def test_structure_only_cli_never_imports_or_runs_a_model(self):
|
||||
stdout = io.StringIO()
|
||||
with patch.object(support, "collect_cases", return_value=self.cases), \
|
||||
patch.object(sys, "stdout", stdout), \
|
||||
patch.object(support.importlib, "import_module", side_effect=AssertionError("model import")):
|
||||
self.assertEqual(support.main(["--structure-only"]), 0)
|
||||
report = json.loads(stdout.getvalue())
|
||||
self.assertEqual(report["source"]["count"], len(self.cases))
|
||||
self.assertLessEqual(len(report["source"]["mechanics"]), support.TOP)
|
||||
|
||||
def test_quick_input_counts_follow_current_model_over_the_original_corpus(self):
|
||||
from ranch_assistant import battle_simulator
|
||||
runtime = support.quick_runtime()
|
||||
with patch.object(battle_simulator, "simulate", side_effect=AssertionError("detailed model")):
|
||||
report = support.inspect_inputs(self.cases, runtime)
|
||||
self.assertEqual(report["reason"], [])
|
||||
self.assertEqual(report["count"], len(self.cases))
|
||||
self.assertEqual(sum(row["count"] for row in report["counts"]), len(self.cases))
|
||||
self.assertTrue(report["priority"][0]["support"])
|
||||
# Numeric inputs can remain unsupported. Never freeze an all-supported total.
|
||||
blocked = [row for row in report["rows"] if not row["support"]]
|
||||
self.assertTrue(all(row["reason"] for row in blocked))
|
||||
self.assertEqual(len(blocked), sum(row["count"] for row in report["counts"] if not row["support"]))
|
||||
|
||||
def test_original_priority_and_protection_cases_have_fast_natural_results(self):
|
||||
from ranch_assistant import battle_simulator
|
||||
protection = next(case for case in self.cases if case.task == "1002002" and case.step == 2)
|
||||
roster = support.fixture_roster()
|
||||
before = deepcopy((roster, self.priority.battle, protection.battle))
|
||||
with patch.object(battle_simulator, "simulate", side_effect=AssertionError("detailed model")):
|
||||
rows = support.replay_cases([self.priority, protection], support.quick_runtime(), roster)
|
||||
self.assertEqual([row["outcome"] for row in rows], ["loss", "win"])
|
||||
self.assertTrue(all(row["support"] for row in rows))
|
||||
self.assertTrue(all(0 < row["wall_ms"] < 1000 for row in rows))
|
||||
self.assertTrue(all(row["elapsed_ms"] > 0 for row in rows))
|
||||
self.assertEqual((roster, self.priority.battle, protection.battle), before)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Offline cultivation-bound checks using public tables and synthetic monsters."""
|
||||
from copy import deepcopy
|
||||
from types import SimpleNamespace
|
||||
import unittest
|
||||
|
||||
from ranch_assistant.battle_simulator import _snapshot_anomalies, combat_tables
|
||||
|
||||
|
||||
class SnapshotPotentialAnomalyTests(unittest.TestCase):
|
||||
def snapshot(self, *, species=5208010, **changes):
|
||||
tables = combat_tables()
|
||||
row = tables["monster_info"][str(species)]
|
||||
mon = {"id": 100001, "typeId": species, "level": 1, "potentialLevel": 3,
|
||||
"tpLevel": 0, "feel": 0, "upStar": 0,
|
||||
"pAtk": 0, "pDef": 0, "pHp": 0, "pDex": 0}
|
||||
mon.update(changes)
|
||||
unit = SimpleNamespace(key="player-1", species=species,
|
||||
stats=SimpleNamespace(atk=row["atk"], defense=row["def"],
|
||||
hp=row["hp"], dex=row["dex"]))
|
||||
return mon, unit, tables
|
||||
|
||||
def test_cultivated_potential_at_zero_tp_is_valid(self):
|
||||
# PotentialPanel.as:102,245: job=1, star=5, potentialLevel=3
|
||||
# permits atk=64, def=58, hp=510, dex=22, independently of tpLevel.
|
||||
mon, unit, tables = self.snapshot(pAtk=38, pDef=44, pHp=300, pDex=22)
|
||||
before = deepcopy((mon, unit))
|
||||
self.assertEqual(_snapshot_anomalies(mon, unit, tables), [])
|
||||
self.assertEqual((mon, unit), before)
|
||||
|
||||
def test_all_four_excesses_keep_blocking_records(self):
|
||||
# Preserve the existing strict > 1.5 * cultivation-cap check.
|
||||
mon, unit, tables = self.snapshot(pAtk=97, pDef=88, pHp=766, pDex=34)
|
||||
before = deepcopy((mon, unit))
|
||||
records = _snapshot_anomalies(mon, unit, tables)
|
||||
self.assertEqual([r["code"] for r in records], ["+15overpoten"] * 4)
|
||||
self.assertEqual({r["stat"]: (r["value"], r["source_maximum"]) for r in records},
|
||||
{"atk": (97, 96), "def": (88, 87),
|
||||
"hp": (766, 765), "dex": (34, 33)})
|
||||
self.assertTrue(all(r["source_cheat_points"] == 30 for r in records))
|
||||
self.assertEqual((mon, unit), before)
|
||||
|
||||
def test_tp_and_display_star_cannot_hide_uncultivated_excess(self):
|
||||
for tp in (0, 4, 8):
|
||||
with self.subTest(tp=tp):
|
||||
mon, unit, tables = self.snapshot(potentialLevel=1, tpLevel=tp,
|
||||
upStar=2, pAtk=19)
|
||||
records = _snapshot_anomalies(mon, unit, tables)
|
||||
self.assertEqual(len(records), 1)
|
||||
self.assertEqual(records[0]["code"], "+15overpoten")
|
||||
self.assertEqual(records[0]["source_maximum"], 18)
|
||||
|
||||
def test_existing_tolerance_boundary_is_preserved(self):
|
||||
mon, unit, tables = self.snapshot(pAtk=96, pDef=87, pHp=765, pDex=33)
|
||||
self.assertEqual(_snapshot_anomalies(mon, unit, tables), [])
|
||||
mon["pDex"] = 33.25
|
||||
records = _snapshot_anomalies(mon, unit, tables)
|
||||
self.assertEqual(len(records), 1)
|
||||
self.assertEqual(records[0]["value"], 33.25)
|
||||
|
||||
def test_other_source_anomalies_and_temporary_id_exemption_remain(self):
|
||||
mon, unit, tables = self.snapshot(level=31, feel=201, pAtk=1000000)
|
||||
unit.stats.atk = 1000000
|
||||
before = deepcopy((mon, unit))
|
||||
records = _snapshot_anomalies(mon, unit, tables)
|
||||
self.assertEqual({r["code"] for r in records},
|
||||
{"+15overfeel", "+15overgrow", "+15overpoten", "+50overlv"})
|
||||
self.assertEqual((mon, unit), before)
|
||||
mon["id"] = 99998
|
||||
self.assertEqual(_snapshot_anomalies(mon, unit, tables), [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user