import { BattlePhase } from 'db://assets/mx/module/battle'; import { createMechanismContext, type IBattleMechanism, type MechanismContext } from './IBattleMechanism'; import { createMechanismsForPlayIds, resolveMechanismConfig } from './MechanismRegistry'; import type { BattleRuntime } from '../runtime/BattleRuntime'; /** 战斗机制宿主:解析 new_play、驱动各 IBattleMechanism 生命周期 */ export class BattleMechanismHost { private _runtime: BattleRuntime | null = null; private _ctx: MechanismContext | null = null; private _mechanisms: IBattleMechanism[] = []; private _started = false; bind(runtime: BattleRuntime): void { this.unbind(); this._runtime = runtime; this._ctx = createMechanismContext(runtime); gg.data.project.initChapterNewPlayInfo(runtime); const playIds = gg.data.project.newPlayIdArr ?? []; this._mechanisms = createMechanismsForPlayIds(playIds); for (const m of this._mechanisms) { const cfg = resolveMechanismConfig(m.typeId); if (cfg != null) { m.init(this._ctx, cfg); } else { console.error('[BattleMechanismHost] 机制配表缺失,未初始化', m.typeId); } } } tryStart(): void { if (this._started || !this._runtime?.Map) return; this._started = true; } tick(dt: number): void { if (!this._runtime?.Map) return; this.tryStart(); if (!this._started || !this._ctx?.canTick()) return; const scaledDt = dt * this._ctx.timeScale; for (const m of this._mechanisms) { m.tick(scaledDt); } } onPhaseChanged(phase: BattlePhase): void { for (const m of this._mechanisms) { m.onPhaseChanged?.(phase); } } destroy(): void { for (const m of this._mechanisms) { m.destroy(); } this._mechanisms = []; this._ctx = null; this._runtime = null; this._started = false; } unbind(): void { this.destroy(); } }