/** * CONTRAATAQUE ALIENÍGENA: tras recibir el poder COOL de Emma, la ciudad y la laguna se llenan de * enemigos. Cada área se cierra con barreras al entrar y se abre al eliminar a todos sus enemigos. * Áreas: Calle de las tiendas (ciudad), Cruce de nenúfares (laguna) y Gruta de cristal (cueva). * * Las hordas vuelven en CADA visita: al regresar a la zona (a por monedas o diamantes) el área se cierra * otra vez. Dentro de una misma visita, los enemigos ya derrotados no reaparecen (una caída al agua no * obliga a empezar de cero) y un área despejada se queda abierta. * * Flags: `invasion.` = área liberada al menos una vez (para el objetivo y el banner final). */ import type { Entity } from '../../core/entity'; import type { Game } from '../../core/game'; import { Barrier, spawnWaveLocal, type WaveSpec } from './shared'; export interface InvasionAreaDef { id: string; name: string; x0: number; x1: number; /** Altura del suelo del área (por defecto 0) y altura máxima de los voladores sobre él (por defecto 11). */ floor?: number; top?: number; /** [tipo, x, y]. En murciélagos, `y` es la percha. */ enemies: Array<[string, number, number]>; } export const INVASION_IDS = ['city-shops', 'lagoon-cross', 'cave-grotto']; export const invasionActive = (g: Game): boolean => g.state.has('emma.cool') || g.state.hasPower('cool'); interface AreaRt { def: InvasionAreaDef; walls: [Barrier, Barrier]; killed: Set; locked: boolean; /** Enemigos vivos de la oleada, por índice en `def.enemies`. */ live: Map; wave: { list: Entity[]; pending: () => number } | null; left: number; /** Despejada en esta visita a la zona. */ cleared: boolean; } const gone = (e: Entity): boolean => e.dead || !!(e as Entity & { defeated?: boolean }).defeated; export class Invasion { private areas: AreaRt[]; constructor(game: Game, defs: InvasionAreaDef[]) { const wall = (x: number, floor: number) => game.add(new Barrier(x, floor - 1, { color: 0x5bd23c, emoji: '👾', height: 28, closed: false })); this.areas = defs.map((def) => ({ def, walls: [wall(def.x0, def.floor ?? 0), wall(def.x1, def.floor ?? 0)], killed: new Set(), locked: false, live: new Map(), wave: null, left: -1, cleared: false, })); } private open(a: AreaRt): void { a.locked = false; for (const w of a.walls) w.setClosed(false); } /** Abre el área y retira a los supervivientes (volverán al entrar de nuevo). */ private reset(a: AreaRt): void { if (a.wave) { (a.wave.list as Entity[] & { cancelled?: boolean }).cancelled = true; for (const e of a.wave.list) if (!e.dead) e.kill(); } a.wave = null; a.live.clear(); this.open(a); } private start(game: Game, a: AreaRt): void { a.locked = true; a.left = -1; for (const w of a.walls) w.setClosed(true); game.gfx.cam.shake(0.25, 0.4); game.audio.music('boss'); game.ui.banner( game.state.has(`invasion.${a.def.id}`) ? '¡Han vuelto los invasores!' : '¡Invasión alienígena!', `${a.def.name}: elimina a todos para abrir las barreras`, '👾', ); const todo = a.def.enemies.map((s, i) => ({ s, i })).filter(({ i }) => !a.killed.has(i)); const arena = { x0: a.def.x0, x1: a.def.x1, floor: a.def.floor ?? 0 }; const specs: WaveSpec[] = todo.map(({ s: [type, x, y] }, n) => ({ type, x, y, delay: 0.6 + n * 0.18, props: { arena, anytime: true, aggro: type !== 'enemy.bat', range: type === 'enemy.bat' ? 8 : 16 }, })); a.wave = spawnWaveLocal(game, specs); a.live.clear(); // spawnWaveLocal añade en orden de aparición (los retardos son crecientes) const list = a.wave.list; const push = list.push.bind(list); let k = 0; list.push = (...items: Entity[]) => { for (const e of items) a.live.set(todo[k++].i, e); return push(...items); }; } private tick(game: Game, a: AreaRt): void { const { x0, x1 } = a.def; for (const [i, e] of a.live) { if (gone(e)) { a.killed.add(i); a.live.delete(i); continue; } // los fantasmas y murciélagos atraviesan paredes: no pueden salir del área ni irse fuera de alcance const b = e.body; if (!b) continue; const cx = Math.min(x1 - 1.2, Math.max(x0 + 1.2, b.x)); const fl = a.def.floor ?? 0; const cy = Math.min(fl + (a.def.top ?? 11), Math.max(fl + 0.4, b.y)); if (cx !== b.x) { b.x = e.x = cx; b.vx = 0; } if (cy !== b.y) { b.y = e.y = cy; b.vy = 0; } } // cuentan también los enemigos que ya estaban patrullando dentro del área let others = 0; const mine = new Set(a.live.values()); for (const e of game.entities) { if (e.tags.has('enemy') && !gone(e) && !mine.has(e) && e.x > x0 && e.x < x1) others++; } const left = a.live.size + (a.wave?.pending() ?? 0) + others; if (left !== a.left) { if (a.left >= 0 && left > 0 && left < a.left && game.hero) { game.vfx.floatText(`👾 Quedan ${left}`, game.hero.x, game.hero.y + 1.8, '#b6ff8a'); } a.left = left; } if (left > 0) return; a.wave = null; a.cleared = true; this.open(a); const first = !game.state.has(`invasion.${a.def.id}`); game.state.set(`invasion.${a.def.id}`, true); game.state.save(); game.audio.music(game.zone?.music ?? null); game.audio.sfx('victory', { volume: 0.7 }); const done = INVASION_IDS.filter((id) => game.state.has(`invasion.${id}`)).length; if (!first) { game.ui.banner('¡Área despejada!', `${a.def.name}: vuelven si regresas otro día`, '✅'); } else if (done === INVASION_IDS.length) { game.ui.banner('¡Invasión rechazada!', 'La ciudad, la laguna y la cueva están a salvo', '🏆'); } else { game.ui.banner('¡Área liberada!', `${a.def.name} · ${done}/${INVASION_IDS.length}`, '✅'); } const h = game.hero; if (h) { game.vfx.burst('confetti', h.x, h.y + 1.5, { count: 36 }); if (game.hasType('item.heart')) game.spawn('item.heart', h.x, h.y + 0.6, { pop: true }); } } update(game: Game): void { const h = game.hero; if (!h || !invasionActive(game)) return; for (const a of this.areas) { if (a.cleared) continue; const { x0, x1 } = a.def; if (a.locked) { // game over o reaparición fuera: nunca dejar al héroe encerrado fuera if (!h.alive || h.x < x0 - 0.5 || h.x > x1 + 0.5) { this.reset(a); game.audio.music(game.zone?.music ?? null); } else this.tick(game, a); } else if (h.alive && h.x > x0 + 1.4 && h.x < x1 - 1.4) { this.start(game, a); } } } }