Add automatic mining and ticket resource stages

This commit is contained in:
AttilaNet
2026-11-10 12:54:48 +08:00
parent 0109cc0d1c
commit 5082c2df5c
20 changed files with 1615 additions and 67 deletions
+247 -29
View File
@@ -37,9 +37,9 @@ LIMITATIONS = (
"Original hit callbacks and projectile speed inform delays; visual offsets, easing and rocket paths are omitted.",
"Skills 3, 5, 7, 9, 38 have partial source ports; all other skills are omitted and individually reported.",
"Skill presentation callbacks are replaced with immediate model activation; AI checks use modeled cadence.",
"Knockback, cosmetic equipment animations and special equipment words are omitted.",
"Attack knockback, cosmetic equipment animations and special equipment words are omitted.",
"Python seeded RNG is not the original Random helper or Math.random stream.",
"Only elimination objectives are supported; authored combat controllers, triggers and active field areas are rejected.",
"Mining supports destroy-all/protect-all objectives, fixed hurt, target locks and timed joins; other controllers and triggers are rejected.",
"Original cheat-check execution is incomplete; detected model anomalies are preserved, not a clean-engine verdict.",
)
@@ -186,6 +186,12 @@ class Unit:
effects: Mapping = field(default_factory=dict)
source_id: str = ""
attack_area: str = ""
protect_target: bool = False
destroy_target: bool = False
pow_defense: float = 0
hurt_types: Mapping = field(default_factory=dict)
hurt_elements: Mapping = field(default_factory=dict)
lock_target: str = ""
@dataclass
@@ -211,6 +217,10 @@ class Actor:
poison_damage: int = 0
area_hit: bool = False
combo_hits: int = 0
force_join: bool = False
vx: float = 0
vy: float = 0
locked_target: str = ""
def _skills(species_row, mon, tables, diagnostic, *, player):
@@ -310,6 +320,12 @@ def _enemy(mon, team, tables, key, battle, diagnostic, master):
raise SimulationInputError("Configured enemy movement/range/attack interval is incomplete")
effect_keys = ("atkVim", "atkStun", "defStun", "atkStunTime", "defStunTime", "atkPoi",
"atkPoiDmg", "thorns", "selfCure", "skillCooldown", "sunFire", "moonHeal", "deadBoom")
hurt_types, hurt_elements = {}, {}
for controller in mon.get("controller", ()) or ():
if _get(controller, "type") == "fixHurt":
para = _get(controller, "para", {})
hurt_types = {str(k): _number(v) for k, v in para.get("type", {}).items()}
hurt_elements = {str(k): _number(v) for k, v in para.get("element", {}).items()}
return Unit(key, species, _int(mon.get("team", team["team"])),
Stats(hp, int(stats["atk"] * ability), int(stats["def"] * ability),
int(stats["dex"] * ability), attack, move, distance, _int(row["element"]),
@@ -325,7 +341,41 @@ def _enemy(mon, team, tables, key, battle, diagnostic, master):
ap_recovery=bool(mon.get("apRecovery")), boss_point=_int(mon.get("bossPoint", 0)),
effects=_freeze({k: _number(mon[k], k) * (ability if k in ("deadBoom", "sunFire", "moonHeal", "selfCure") else 1)
for k in effect_keys if k in mon}),
source_id=str(mon.get("mid", "")), attack_area=str(mon.get("attackArea", "")))
source_id=str(mon.get("mid", "")), attack_area=str(mon.get("attackArea", "")),
protect_target=mon.get("protectTarget") is True,
destroy_target=mon.get("destroyTarget") is True,
pow_defense=_number(mon.get("powDefPercent", 0)),
hurt_types=_freeze(hurt_types), hurt_elements=_freeze(hurt_elements),
lock_target=next((str(_get(c, "para", {}).get("mid", ""))
for c in mon.get("controller", ()) or ()
if _get(c, "type") == "lockTarget"), ""))
def _mining_trigger(entry, unit_mids):
"""Return an immutable trigger, or a precise unsupported reason."""
kind = _get(entry, "type", "unknown")
para = _get(entry, "para", {})
if not isinstance(para, Mapping) or not isinstance(_get(entry, "effects"), list):
return None, "Malformed mining battle trigger"
if kind == "monDead":
if _int(para.get("mid", -1)) not in unit_mids:
return None, "Mining monDead trigger references an unknown unit"
if any(_get(effect, "type") != "showFace" for effect in entry["effects"]):
return None, "Only visual showFace effects are supported for mining monDead"
elif kind == "time":
if _int(para.get("time", -1)) <= 0 or para.get("loop") is True:
return None, "Mining time trigger requires a positive non-looping time"
for effect in entry["effects"]:
if _get(effect, "type") == "showFace":
continue
effect_para = _get(effect, "para", {})
if (_get(effect, "type") != "monJoin" or not isinstance(effect_para, Mapping)
or _int(effect_para.get("mid", -1)) not in unit_mids):
return None, "Only showFace and configured monJoin are supported for mining time"
else:
return None, "Unsupported mining battle trigger: " + str(kind)
return _freeze({"id": str(_get(entry, "id", "")), "type": kind,
"para": para, "effects": entry["effects"]}), None
@dataclass
@@ -339,6 +389,9 @@ class Scenario:
trace_limit: int
position: object
roster_ids: tuple
win_types: tuple = (1,)
lose_types: tuple = (1, 2)
triggers: tuple = ()
def _prepare(request, tables):
@@ -361,12 +414,15 @@ def _prepare(request, tables):
battle = _get(original, "battle")
if not isinstance(battle, Mapping) or not battle:
raise SimulationInputError("original_data.battle must contain the full original configuration")
if list(map(_int, battle.get("winType", (1,)))) != [1] or any(
_int(x) not in (1, 2) for x in battle.get("loseType", (1, 2))):
win_types = tuple(map(_int, battle.get("winType", (1,))))
lose_types = tuple(map(_int, battle.get("loseType", (1, 2))))
mining = win_types == (4,)
if not mining and (win_types != (1,) or any(x not in (1, 2) for x in lose_types)):
diagnostic("objective", "Non-elimination win/loss objective is unsupported", blocking=True)
for key in ("controller", "triggers"):
for entry in battle.get(key, ()) or ():
diagnostic(key, f"Unsupported battle {key}: {_get(entry, 'type', 'unknown')}", blocking=True)
if mining and lose_types != (4, 2):
diagnostic("objective", "Mining requires exact winType=[4] and loseType=[4,2]", blocking=True)
for entry in battle.get("controller", ()) or ():
diagnostic("controller", f"Unsupported battle controller: {_get(entry, 'type', 'unknown')}", blocking=True)
raw = _get(request, "roster", _get(request, "snapshot"))
raw = _get(raw, "raw", raw)
if not isinstance(raw, Mapping) or not isinstance(raw.get("master"), Mapping):
@@ -413,6 +469,19 @@ def _prepare(request, tables):
diagnostic("equipment_words", "Equipment/skin numeric bonuses use monsterAttributes; special words and skin attack overrides are omitted", ignored=True)
if battle.get("hideTeamMon"):
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}
triggers = []
for entry in battle.get("triggers", ()) or ():
if mining:
parsed, reason = _mining_trigger(entry, unit_mids)
if reason:
diagnostic("triggers", reason, blocking=True)
else:
triggers.append(parsed)
else:
diagnostic("triggers", f"Unsupported battle triggers: {_get(entry, 'type', 'unknown')}", blocking=True)
for ti, team in enumerate(battle.get("teams", ())):
team_id = _int(team.get("team", 2))
initial_ap = _int(team.get("ap", 0))
@@ -432,14 +501,28 @@ def _prepare(request, tables):
if (kind == "buffMovie" and isinstance(para, Mapping)
and para.get("type") == "none" and not para.get("stopMove", False)):
diagnostic("cosmetic_controller", "Cosmetic monster buffMovie animation is omitted", ignored=True)
elif mining and kind in ("fixHurt", "lockTarget"):
if not isinstance(para, Mapping):
diagnostic("unit_controller", f"Malformed mining controller: {kind}", blocking=True)
elif kind == "lockTarget":
if _int(para.get("mid", -1)) not in unit_mids:
diagnostic("unit_controller", "Mining lockTarget references an unknown unit", blocking=True)
if para.get("interval") is not None and _number(para["interval"]) <= 0:
diagnostic("unit_controller", "Mining lockTarget interval must be positive", blocking=True)
else:
diagnostic("unit_controller", f"Unsupported monster controller: {kind}", blocking=True)
if mon.get("protectTarget") or mon.get("destroyTarget"):
diagnostic("unit_objective", "Protected/destroy objective units are unsupported", blocking=True)
if not mining:
diagnostic("unit_objective", "Protected/destroy objective units are unsupported", blocking=True)
elif mon.get("protectTarget") and mon.get("destroyTarget"):
diagnostic("unit_objective", "Mining target cannot be both protected and destroyed", blocking=True)
unit = _enemy(mon, dict(team, team=team_id), tables, f"configured-{ti + 1}-{mi + 1}", battle, diagnostic, master)
teams.setdefault(unit.team, config.copy())
units.append(unit)
if not any(u.team != 1 and not u.is_object for u in units):
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):
raise SimulationInputError("Elimination battle must contain configured enemies")
for team in teams.values():
if team["capacity"] <= 0 or team["initial"] < 0:
@@ -459,7 +542,7 @@ def _prepare(request, tables):
if "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") != "none":
if area.get("type", "none") not in (("none", "pow") if mining else ("none",)):
diagnostic("field_effect", f"Unsupported active field area: {area.get('type')}", blocking=True)
if field_config.get("mapObjects"):
diagnostic("ground_objects", "Battlefield ground object collision/decoration is omitted", ignored=True)
@@ -495,9 +578,11 @@ def _prepare(request, tables):
report["teams"] = _plain(teams)
report["duration_ms"] = duration * 1000
report["supported"] = not report["reasons"]
report["objective"] = "destroy_all_protect_until_none" if mining else "elimination"
return Scenario(units, teams, points, areas, duration * 1000, seed, trace_limit,
_position(_get(request, "battle_position")),
tuple(_int(mid) for mid in selected) if not battle.get("hideTeamMon") else ()), report
tuple(_int(mid) for mid in selected) if not battle.get("hideTeamMon") else (),
win_types, lose_types, tuple(triggers)), report
except (SimulationInputError, KeyError, TypeError, AttributeError, IndexError) as exc:
message = str(exc) if isinstance(exc, SimulationInputError) else "Malformed original combat input"
diagnostic("input", message, blocking=True)
@@ -510,7 +595,10 @@ def _unit_preview(unit):
"skills": [{"id": s.id, "level": s.level, "cost": s.cost,
"cooldown_ms": s.cooldown_ms, "para": _plain(s.para)} for s in unit.skills],
"wave": unit.wave, "join_time_seconds": unit.join_time, "position": unit.position,
"count_unit": unit.count_unit, "is_object": unit.is_object, "ap_cost": unit.ap_cost}
"count_unit": unit.count_unit, "is_object": unit.is_object, "ap_cost": unit.ap_cost,
"auto_target": unit.auto_target, "source_id": unit.source_id,
"protect_target": unit.protect_target, "destroy_target": unit.destroy_target,
"lock_target": unit.lock_target}
def _snapshot_anomalies(mon, unit, tables):
@@ -571,6 +659,7 @@ class _Battle:
self.ap = {team: dict(initial=v["initial"], current=v["initial"], max=v["max"], spent=0, recovered=0)
for team, v in scenario.teams.items()}
self.wave = {team: 1 for team in scenario.teams}
self.unlocked_waves = {team: {0, 1} for team in scenario.teams}
self.wave_due = {}
self.queue = []
self.sequence = 0
@@ -588,6 +677,10 @@ class _Battle:
self.complete_at = None
self.resource_limited = False
self.skill_used = False
self.pending_triggers = list(scenario.triggers)
self.by_source_id = {a.unit.source_id: a for a in self.actors if a.unit.source_id}
self.next_area = 0
self.area_due = {key: 0 for key in scenario.areas}
def event(self, kind, **fields):
record = {"at_ms": self.now, "type": kind, **fields}
@@ -617,6 +710,24 @@ class _Battle:
return sum(a.unit.team == team and a.state != "dead"
and (team == 1 or a.state == "active" or not a.unit.is_object) for a in self.actors)
def check_objectives(self):
"""BattleGround.checkGameOver's original winner precedence."""
if self.now >= self.s.duration_ms:
return "win" if 2 in self.s.win_types else "loss"
mining = self.s.win_types == (4,)
team_one_alive = sum(a.unit.team == 1 and a.state != "dead" for a in self.actors) if mining else self.terminal_team_size(1)
if not team_one_alive:
return "loss"
if not mining and not any(self.terminal_team_size(team) for team in self.s.teams if team != 1):
return "win"
protected = [a for a in self.actors if a.unit.protect_target]
if 4 in self.s.lose_types and protected and all(a.state == "dead" for a in protected):
return "loss"
destroyed = [a for a in self.actors if a.unit.destroy_target]
if 4 in self.s.win_types and destroyed and all(a.state == "dead" for a in destroyed):
return "win"
return None
def add_ap(self, team, amount, reason):
ap = self.ap[team]
before = ap["current"]
@@ -657,7 +768,8 @@ class _Battle:
def deploy(self):
for actor in self.actors:
u = actor.unit
if actor.state != "waiting" or u.wave > self.wave[u.team] or u.join_time * 1000 > self.now:
if (actor.state != "waiting" or not actor.force_join and u.wave not in self.unlocked_waves[u.team]
or not actor.force_join and u.join_time * 1000 > self.now):
continue
count = sum(a.state == "active" and a.unit.team == u.team and a.unit.count_unit for a in self.actors)
if u.count_unit and count >= self.s.teams[u.team]["capacity"]:
@@ -674,6 +786,8 @@ class _Battle:
self.add_ap(u.team, self.ap[u.team]["max"] * self.game["addApByJoinMon"], "join")
self.event("deploy", actor=u.key, team=u.team, wave=u.wave, x=actor.x, y=actor.y,
count_unit=u.count_unit, ap_charged=0)
if actor.unit.lock_target:
actor.locked_target = actor.unit.lock_target
@staticmethod
def ai_interval(unit):
@@ -683,6 +797,11 @@ class _Battle:
def target(self, actor):
u = actor.unit
if actor.locked_target:
locked = self.by_source_id.get(actor.locked_target)
if locked is not None and locked.state == "active" and locked.hp > 0:
return locked
actor.locked_target = ""
choices = [b for b in self.active() if b.unit.team != u.team]
if u.attack_area:
area = self.s.areas[u.attack_area]
@@ -791,9 +910,35 @@ class _Battle:
if amount:
self.event("heal", actor=actor.unit.key, amount=amount, hp=actor.hp, reason=reason)
def hurt(self, actor, amount, attacker, reason):
def hurt(self, actor, amount, attacker, reason, real_attack=False):
if actor.state != "active":
return 0
# beHurt passes the attack value (its atk argument) to onHurt at line
# 902, despite onHurt naming that parameter damage. For real attacks
# there is no GameMath.damage call before this controller.
element = str(attacker.unit.stats.element) if attacker else ""
if element in actor.unit.hurt_types and element in actor.unit.hurt_elements:
amount = int(amount * actor.unit.hurt_elements[element])
elif attacker and str(attacker.unit.species) in actor.unit.hurt_types:
amount = int(amount * actor.unit.hurt_types[str(attacker.unit.species)])
if real_attack:
amount = max(0, int(amount * (1 - actor.unit.stats.damage_reduction)))
lost = min(actor.hp, amount)
actor.hp -= lost
actor.total_hurt += amount
self.hp_lost[actor.unit.team] += lost
if actor.unit.boss_point == -1:
self.boss_points += lost
if attacker:
attacker.damage_dealt += lost
self.event("damage", actor=attacker.unit.key if attacker else None, target=actor.unit.key,
damage=amount, hp_lost=lost, hp=actor.hp, reason=reason)
if amount > 80000:
self.anomaly("+10overdamage", points=10, damage=amount, hurt_team=actor.unit.team,
actor=attacker.unit.key if attacker else None, target=actor.unit.key)
if actor.hp == 0:
self.finish_death(actor)
return amount
amount = max(0, int(int(amount) * (1 - actor.unit.stats.damage_reduction)))
lost = min(actor.hp, amount)
actor.hp -= lost
@@ -809,6 +954,10 @@ class _Battle:
self.anomaly("+10overdamage", points=10, damage=amount, hurt_team=actor.unit.team,
actor=attacker.unit.key if attacker else None, target=actor.unit.key)
if actor.hp == 0:
self.finish_death(actor)
return amount
def finish_death(self, actor):
actor.state = "dead"
actor.died_ms = self.now
if actor.unit.boss_point > 0:
@@ -822,8 +971,15 @@ class _Battle:
if actor.total_hurt == 0:
self.anomaly("+1k_cheatDead", points=1000, target=actor.unit.key)
self.event("death", actor=actor.unit.key, team=actor.unit.team, summon=bool(actor.summon_of))
remaining = []
for trigger in self.pending_triggers:
if trigger["type"] == "monDead" and _int(trigger["para"]["mid"]) == _int(actor.unit.source_id):
self.event("trigger", trigger_kind="monDead", trigger=trigger["id"],
actor=actor.unit.key, effects="visual_only")
else:
remaining.append(trigger)
self.pending_triggers = remaining
self.complete_at = self.now + 1000 # Original delayed checkGameOver.
return amount
def impact(self, fields):
attacker = self.by_key[fields["attacker"]]
@@ -886,17 +1042,65 @@ class _Battle:
for team in self.s.teams:
if team in self.wave_due:
if self.now >= self.wave_due[team]:
self.wave[team] += 1
current = self.wave[team]
waves = [a.unit.wave for a in self.actors if a.unit.team == team
and a.state != "dead" and not a.unit.is_object and a.unit.wave > current]
self.wave[team] = min(waves) if waves else current + 1
self.unlocked_waves[team].update(range(current + 1, self.wave[team] + 1))
del self.wave_due[team]
self.event("wave", team=team, wave=self.wave[team])
continue
current = self.wave[team]
relevant = [a for a in self.actors if a.unit.team == team and a.state != "dead"]
relevant = [a for a in self.actors if a.unit.team == team and a.state != "dead" and not a.unit.is_object]
if any(a.unit.wave == current for a in relevant):
continue
if any(a.unit.wave == current + 1 for a in relevant):
next_waves = [a.unit.wave for a in relevant if a.unit.wave > current]
if next_waves:
next_wave = min(next_waves)
self.wave_due[team] = self.now + 700
self.event("wave_wait", team=team, next_wave=current + 1, until_ms=self.now + 700)
self.event("wave_wait", team=team, next_wave=next_wave, until_ms=self.now + 700)
def advance_triggers(self):
"""SecondDriver checks elapsed seconds once; trigger removal prevents repeats."""
if self.now % 1000:
return
remaining = []
for trigger in self.pending_triggers:
if trigger["type"] == "time" and _int(trigger["para"]["time"]) * 1000 <= self.now:
for effect in trigger["effects"]:
if effect.get("type") == "monJoin":
target = self.by_source_id.get(str(_int(effect["para"]["mid"])))
if target is not None and target.state != "dead":
target.force_join = True
self.event("trigger", trigger_kind="time", trigger=trigger["id"],
effect="monJoin", actor=target.unit.key)
self.event("trigger", trigger_kind="time", trigger=trigger["id"])
else:
remaining.append(trigger)
self.pending_triggers = remaining
def advance_areas(self):
if self.now < self.next_area:
return
self.next_area = self.now + 125
for key, area in self.s.areas.items():
if area.get("type") != "pow" or self.now < self.area_due[key]:
continue
self.area_due[key] = self.now + _int(area["para"].get("interval", 0))
for actor in self.active():
if not (area["x"] <= actor.x <= area["x"] + area["w"]
and area["y"] <= actor.y <= area["y"] + area["h"]):
continue
if actor.unit.move_immune:
continue # BattleMon.givePow returns before changing velocity.
para = area["para"]
power = _number(para["pow"]) * .8 * (1 - actor.unit.pow_defense)
dx, dy = actor.x - _number(para.get("fromX", actor.x)), actor.y - _number(para.get("fromY", actor.y))
length = math.hypot(dx, dy)
if length:
actor.vx, actor.vy = power * dx / length, power * dy / length
self.event("area_pow", actor=actor.unit.key, area=key,
vx=actor.vx, vy=actor.vy)
def tick(self):
self.skill_used = False
@@ -909,6 +1113,8 @@ class _Battle:
if self.now >= self.next_deploy:
self.deploy()
self.next_deploy = (self.now // 1000 + 1) * 1000
self.advance_triggers()
self.advance_areas()
while self.queue and self.queue[0][0] <= self.now:
_, _, kind, fields = heapq.heappop(self.queue)
if kind == "impact":
@@ -926,6 +1132,15 @@ class _Battle:
self.impact(fields)
for actor in list(self.active()):
u = actor.unit
if not u.move_immune and (actor.vx or actor.vy):
# Engine2D's existing damping is retained as a trajectory
# approximation; movement resumes once inertia has decayed.
actor.x += actor.vx
actor.y += actor.vy
actor.vx *= .91
actor.vy *= .91
if abs(actor.vx) + abs(actor.vy) < .01:
actor.vx = actor.vy = 0
if actor.poison_until >= self.now and actor.poison_at and actor.poison_at <= self.now:
self.hurt(actor, actor.poison_damage, None, "poison")
actor.poison_at += 1000
@@ -951,7 +1166,7 @@ class _Battle:
self.event("attack", actor=u.key, target=target.unit.key, hit_delay_ms=delay)
self.schedule(delay, "launch", attacker=u.key, target=target.unit.key,
atk=u.stats.atk, projectile=profile["projectile"], speed=profile["projectile_speed"])
elif not u.move_immune:
elif not u.move_immune and not (actor.vx or actor.vy):
dx, dy = target.x - actor.x, target.y - actor.y
distance = math.hypot(dx, dy)
# Source Pointer.Point2Point uses spd_mov per frame.
@@ -1027,8 +1242,9 @@ def simulate(request, *, cancel_event=None, timeout=30.0, tables=None):
if time.monotonic() - started >= timeout:
return battle.result("timeout", "wall_clock")
if battle.now >= scenario.duration_ms:
battle.event("complete", outcome="loss", reason="battle_time_limit")
result = battle.result("loss")
outcome = battle.check_objectives()
battle.event("complete", outcome=outcome, reason="battle_time_limit")
result = battle.result(outcome)
result["terminal_reason"] = "battle_time_limit"
return result
try:
@@ -1041,12 +1257,14 @@ def simulate(request, *, cancel_event=None, timeout=30.0, tables=None):
if battle.resource_limited:
return battle.result("timeout", "resource_limit")
if battle.complete_at is not None and battle.now >= battle.complete_at:
if not battle.terminal_team_size(1):
battle.event("complete", outcome="loss")
return battle.result("loss")
if not any(battle.terminal_team_size(team) for team in scenario.teams if team != 1):
battle.event("complete", outcome="win")
return battle.result("win")
outcome = battle.check_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)
result = battle.result(outcome)
result["terminal_reason"] = reason
return result
return battle.result("timeout", "resource_limit")