/** * Misiones dirigidas por datos (ver defs.ts). Asigna `game.quests` (QuestService). * * - Flags: `quest.` = 'active' | 'done'; escenas vistas: `quest.scene.`. * - Se re-evalúa al cambiar cualquier flag/estado: arranque y cierre automáticos, recompensas, * banners ("Nueva misión" / "¡Misión cumplida!") y `ui.setObjective` con el objetivo más importante. * - Diálogos y banners pasan por una cola: nunca se pisan con otro diálogo, la pausa, la carga de * zona ni con los banners del héroe (`hero:grant`) o de un NPC (`npc:talk`). * - `state.save()` en cada hito. */ import type { Game } from '../core/game'; import type { DialogLine, QuestService } from '../core/types'; import { HINTS, QUESTS, SCENES, type QuestDef } from './defs'; export { QUESTS, HINTS, SCENES } from './defs'; const BANNER_GAP = 2.9; interface Job { kind: "dialog" | "banner"; run: () => Promise | void } class QuestManager implements QuestService { private readonly defs = new Map(); private queue: Job[] = []; private busy = false; private gap = 0; private dirty = true; private current: string | null = null; constructor(private game: Game) { for (const d of QUESTS) this.defs.set(d.id, d); const ev = game.events; ev.on('flag', ({ key }) => { if (!key.startsWith('map.')) this.dirty = true; }); ev.on('state:changed', () => (this.dirty = true)); ev.on('zone:loaded', () => (this.dirty = true)); ev.on('hero:grant', () => (this.gap = Math.max(this.gap, BANNER_GAP))); ev.on('npc:talk', () => (this.gap = Math.max(this.gap, 0.6))); for (const s of SCENES) { if (!s.event) continue; ev.on(s.event, (p) => { if (s.bossId && p.id !== s.bossId) return; this.playScene(s.id, s.lines); }); } // Oleadas siguientes a la primera: aviso breve. ev.on('flag', ({ key, value, prev }) => { if (key === 'horde.wave' && typeof value === 'number' && value > 1 && value !== prev && !game.state.has('horde.cleared')) { game.ui.toast(`¡Oleada ${value}!`, '🌙'); } }); } // ───────── QuestService ───────── get objective(): string | null { return this.current; } isActive(id: string): boolean { return this.game.state.get(`quest.${id}`) === 'active'; } isDone(id: string): boolean { return this.game.state.get(`quest.${id}`) === 'done'; } start(id: string): void { const def = this.defs.get(id); if (!def || this.isActive(id) || this.isDone(id)) return; const st = this.game.state; st.set(`quest.${id}`, 'active'); if (def.startDialog) this.say(def.startDialog); if (def.startBanner !== false) { this.enqueue('banner', () => { this.game.audio.sfx('quest'); this.game.ui.banner('¡Nueva misión!', def.title, def.emoji); this.gap = BANNER_GAP; }); } st.save(); this.dirty = true; } complete(id: string): void { const def = this.defs.get(id); if (!def || this.isDone(id)) return; const g = this.game; const st = g.state; st.set(`quest.${id}`, 'done'); if (def.completeDialog) this.say(def.completeDialog); const r = def.reward; if (r?.coins) st.addCoins(r.coins); if (r?.diamonds) st.addDiamonds(r.diamonds); this.enqueue('banner', () => { g.audio.sfx('victory'); const extra = r?.coins ? `+${r.coins} 🪙` : undefined; g.ui.banner('¡Misión cumplida!', extra ? `${def.title} · ${extra}` : def.title, def.emoji); const h = g.hero; if (h) { g.vfx.burst('confetti', h.x, h.y + 0.8, { count: 26 }); if (r?.coins) g.vfx.floatText(`+${r.coins} 🪙`, h.x, h.y + 1.4, '#ffe066'); } st.save(); this.gap = BANNER_GAP; }); st.save(); this.dirty = true; } // ───────── Cola de diálogos/banners ───────── private enqueue(kind: Job['kind'], run: Job['run']): void { this.queue.push({ kind, run }); } /** Encola un diálogo que no depende de ningún NPC. */ say(lines: DialogLine[]): void { this.enqueue('dialog', async () => { const h = this.game.hero; if (h) h.inputLocked = true; try { await this.game.ui.dialog(lines); } finally { if (h) h.inputLocked = false; } }); } private playScene(id: string, lines: DialogLine[]): void { const key = `quest.scene.${id}`; const st = this.game.state; if (st.has(key)) return; st.set(key, true); this.say(lines); } // ───────── Evaluación ───────── private evaluate(): void { const g = this.game; for (const s of SCENES) if (s.when && s.when(g)) this.playScene(s.id, s.lines); for (const def of QUESTS) { if (!this.isActive(def.id) && !this.isDone(def.id) && def.autoStart?.(g)) this.start(def.id); if (this.isActive(def.id) && def.autoComplete !== false && def.steps.every((s) => s.done(g))) this.complete(def.id); } // Objetivo vigente más importante. let best: { p: number; text: string } | null = null; for (const h of HINTS) if (h.when(g) && (!best || h.priority > best.p)) best = { p: h.priority, text: h.text }; for (const def of QUESTS) { if (!this.isActive(def.id)) continue; const step = def.steps.find((s) => !s.done(g)); if (step && (!best || def.priority > best.p)) best = { p: def.priority, text: step.text(g) }; } this.current = best?.text ?? null; g.ui.setObjective(this.current); } update(dt: number): void { const g = this.game; // Evaluar varias veces si una evaluación provoca cambios encadenados. for (let i = 0; i < 4 && this.dirty; i++) { this.dirty = false; this.evaluate(); } const blocked = g.ui.modalOpen || g.loading || g.paused; if (!blocked && this.gap > 0) this.gap -= dt; // Los diálogos pasan delante de los banners pendientes y no esperan el hueco entre banners. if (this.busy || blocked || !this.queue.length) return; let i = this.queue.findIndex((j) => j.kind === 'dialog'); if (i < 0) { if (this.gap > 0) return; i = 0; } const job = this.queue.splice(i, 1)[0].run; this.busy = true; Promise.resolve() .then(job) .catch((err) => console.error('[quests] error en la cola', err)) .finally(() => (this.busy = false)); } } export function install(game: Game): void { const q = new QuestManager(game); game.quests = q; game.addSystem({ always: true, update: (dt) => q.update(dt) }); }