Files
windroost/tools/fullgame/effects.py
T
wushenghua 16d3cbe911 feat: effect-primitive engine foundation (stage A of gameplay-depth goal)
Continued PRODUCTION/51. Built the ADR-008 effect-primitive system that turns
skills from damage numbers into real distinct combat effects:
- tools/fullgame/effects.py + GDScript effects.gd mirror: 16 primitives
  (damage/heal/shield/buff/debuff/stun/slow/poison/taunt/summon/cleanse/
  execute/chain/lifesteal/energy/reflect) with real battle semantics.
- test_effects.py PASS 9 checks (each primitive distinct + identity).
- check_effects_parity.py PASS 17 cases (python==gd).
- skill_runtime.py bridge: folds skill effects into per-tick battle state;
  test_skill_runtime.py PASS 7 checks proving >=4 skills give distinct outcomes.
- Identity invariant: absent skills -> zero change (all 64 gates green).

Next: wire skill_runtime into both battle sims (with parity + identity guard).
P2_CHECKS_PASS. prototype/ untracked.
2026-11-19 13:07:43 +08:00

195 lines
8.0 KiB
Python

#!/usr/bin/env python3
"""Authoritative effect-primitive engine (ADR-008 / FINAL_GAME_DESIGN 6.2/7).
A skill is NOT just a damage number: it is a list of *effect primitives* with
parameters. This module defines each primitive's real combat semantics and a
small state machine that both paper sims (Python + GDScript mirror) apply on
each tick. Identity invariant: with no skill_effects, nothing changes.
Primitives (16 from FINAL_GAME_DESIGN:375 + FANTASY_SKILL_SCALING):
damage, heal, shield, buff, debuff, stun, slow, poison, taunt, summon,
cleanse, execute, chain, lifesteal, energy, reflect
Each primitive is a pure function over a battle-state dict, so behaviour is
reviewable and parity-tested between engines. Effects produce OBSERVABLE,
DISTINCT outcomes (a stun skips enemy actions, poison ticks damage, execute
kills low-HP targets, chain hits multiple enemies, shield absorbs, etc.).
"""
from __future__ import annotations
from typing import Any, Dict, List
PRIMITIVES = (
"damage", "heal", "shield", "buff", "debuff", "stun", "slow", "poison",
"taunt", "summon", "cleanse", "execute", "chain", "lifesteal", "energy", "reflect",
)
def new_skill_state() -> Dict[str, Any]:
"""Per-battle mutable state for effect primitives. Empty = no effects active."""
return {
"ally_shield": 0.0, # absorb pool for the company
"ally_buff_atk": 0.0, # additive attack multiplier from buff
"ally_buff_def": 0.0, # damage reduction from buff/taunt
"debuffs": {}, # enemy_id -> {atk: x, slow: x, poison_dps: x, ticks: n}
"stunned": {}, # enemy_id -> remaining seconds
"taunt_target": "", # enemy_id currently taunted
"summons_dps": 0.0, # extra DPS from summoned units
"lifesteal_pct": 0.0, # fraction of damage returned as ally heal/shield
"energy_bonus": 0.0, # storm/ultimate energy gain multiplier bonus
"reflect_pct": 0.0, # fraction of incoming damage reflected
"event_counts": {}, # primitive -> times applied (for tests/telemetry)
}
def _bump(state: Dict[str, Any], prim: str, n: int = 1) -> None:
state["event_counts"][prim] = int(state["event_counts"].get(prim, 0)) + n
def apply_effect(state: Dict[str, Any], effect: Dict[str, Any], ctx: Dict[str, Any]) -> Dict[str, Any]:
"""Apply one primitive. `ctx` carries {enemies, target_id, allies, dps, tick_seconds}.
Returns a dict of observable deltas: {damage, healed, shield_gain, killed_ids,
skipped_enemies, ...}. The caller folds these into the battle state. This
function never mutates enemies directly (caller does via the returned deltas),
keeping it deterministic and easy to mirror.
"""
t = str(effect.get("type", "damage"))
v = float(effect.get("value", 0.0))
dur = float(effect.get("duration", 0.0))
ctx_enemies: List[Dict[str, Any]] = ctx.get("enemies", [])
target_id = str(effect.get("target_id", ctx.get("target_id", "")))
out: Dict[str, Any] = {"primitive": t, "damage": 0.0, "healed": 0.0,
"shield_gain": 0.0, "killed_ids": [], "skipped": [], "meta": {}}
_bump(state, t)
if t == "damage":
out["damage"] = v
elif t == "execute":
# Instantly kill a target below the HP-fraction threshold.
threshold = float(effect.get("threshold", 0.25))
e = _find_enemy(ctx_enemies, target_id)
if e and float(e["hp"]) <= float(e["max_hp"]) * threshold:
out["killed_ids"].append(e["id"])
out["damage"] += float(e["hp"])
out["meta"]["executed"] = True
elif t == "chain":
# Hit up to N additional targets for value damage each.
jumps = int(effect.get("jumps", 2))
alive = [e for e in ctx_enemies if not e.get("dead")]
hit = 0
for e in alive:
if e["id"] == target_id:
continue
out["damage"] += v
out["meta"].setdefault("chain_targets", []).append(e["id"])
hit += 1
if hit >= jumps:
break
elif t == "poison":
e = _find_enemy(ctx_enemies, target_id)
if e:
d = state["debuffs"].setdefault(e["id"], {"atk": 0.0, "slow": 0.0, "poison_dps": 0.0, "ticks": 0})
d["poison_dps"] += v
d["ticks"] = max(d["ticks"], int(dur / ctx.get("tick_seconds", 0.1)))
elif t == "debuff":
e = _find_enemy(ctx_enemies, target_id)
if e:
stat = str(effect.get("stat", "atk"))
d = state["debuffs"].setdefault(e["id"], {"atk": 0.0, "slow": 0.0, "poison_dps": 0.0, "ticks": 0})
d[stat] = d.get(stat, 0.0) + v
d["ticks"] = max(d["ticks"], int(dur / ctx.get("tick_seconds", 0.1)))
elif t == "stun":
e = _find_enemy(ctx_enemies, target_id)
if e:
state["stunned"][e["id"]] = max(float(state["stunned"].get(e["id"], 0.0)), dur)
out["skipped"].append(e["id"])
elif t == "slow":
e = _find_enemy(ctx_enemies, target_id)
if e:
d = state["debuffs"].setdefault(e["id"], {"atk": 0.0, "slow": 0.0, "poison_dps": 0.0, "ticks": 0})
d["slow"] = min(0.9, d.get("slow", 0.0) + v)
d["ticks"] = max(d["ticks"], int(dur / ctx.get("tick_seconds", 0.1)))
elif t == "shield":
out["shield_gain"] = v
elif t == "heal":
out["healed"] = v
elif t == "lifesteal":
state["lifesteal_pct"] = min(1.0, state["lifesteal_pct"] + v)
elif t == "buff":
stat = str(effect.get("stat", "atk"))
if stat == "def":
state["ally_buff_def"] = min(0.8, state["ally_buff_def"] + v)
else:
state["ally_buff_atk"] += v
elif t == "taunt":
e = _find_enemy(ctx_enemies, target_id)
if e:
state["taunt_target"] = e["id"]
state["ally_buff_def"] = min(0.8, state["ally_buff_def"] + v * 0.5)
elif t == "summon":
state["summons_dps"] += v
elif t == "cleanse":
# Remove own negative states (reflect on allies modelled as clearing debuffs).
state["debuffs"].clear()
out["meta"]["cleansed"] = True
elif t == "energy":
state["energy_bonus"] += v
elif t == "reflect":
state["reflect_pct"] = min(1.0, state["reflect_pct"] + v)
else:
raise ValueError(f"unknown primitive: {t}")
return out
def _find_enemy(enemies: List[Dict[str, Any]], target_id: str):
for e in enemies:
if e.get("dead"):
continue
if e["id"] == target_id or e["content_id"] == target_id:
return e
return None
def tick_effects(state: Dict[str, Any], tick_seconds: float) -> Dict[str, Any]:
"""Per-tick passive effect damage (poison) + debuff duration decay.
Returns {poison_damage: {enemy_id: amount}, expired: [enemy_id]}.
"""
poison = {}
expired = []
for eid, d in list(state["debuffs"].items()):
if d.get("poison_dps", 0.0) > 0.0:
poison[eid] = d["poison_dps"] * tick_seconds
if d.get("ticks", 0) > 0:
d["ticks"] -= 1
if d["ticks"] <= 0:
expired.append(eid)
del state["debuffs"][eid]
for eid in list(state["stunned"].keys()):
state["stunned"][eid] = max(0.0, state["stunned"][eid] - tick_seconds)
if state["stunned"][eid] <= 0.0:
del state["stunned"][eid]
return {"poison_damage": poison, "expired": expired}
def ally_damage_mult(state: Dict[str, Any]) -> float:
return 1.0 + state["ally_buff_atk"] + state["energy_bonus"] * 0.25
def ally_incoming_mult(state: Dict[str, Any]) -> float:
return max(0.1, 1.0 - state["ally_buff_def"])
def extra_dps(state: Dict[str, Any]) -> float:
return state["summons_dps"]
def validate_primitives() -> List[str]:
problems = []
for p in PRIMITIVES:
if not p:
problems.append("empty primitive")
if len(PRIMITIVES) != len(set(PRIMITIVES)):
problems.append("duplicate primitive ids")
return problems