actions reactored. multi-tick action support
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
import type { ScriptContext, ScriptCoroutineContext, ScriptGameEventHandler } from "../types";
|
||||
import type { ScriptCoroutines } from "./coroutines";
|
||||
|
||||
export type ScriptCoroutineGameEventHandler = {
|
||||
handler: ScriptGameEventHandler;
|
||||
coroutine: ScriptCoroutineContext;
|
||||
}
|
||||
|
||||
export class ScriptGameEventBus {
|
||||
private coroutines: ScriptCoroutines;
|
||||
private handlers: Record<string, ScriptCoroutineGameEventHandler[]> = {};
|
||||
|
||||
constructor(coroutines: ScriptCoroutines) {
|
||||
this.coroutines = coroutines;
|
||||
}
|
||||
|
||||
on(event: string, handler: ScriptGameEventHandler, coroutine: ScriptCoroutineContext): void {
|
||||
console.log('subscribing to ' + event, handler, coroutine);
|
||||
let set = this.handlers[event];
|
||||
if (!set) {
|
||||
set = [];
|
||||
this.handlers[event] = set;
|
||||
}
|
||||
|
||||
if (!set.some((h) => h.handler === handler))
|
||||
set.push({ handler, coroutine });
|
||||
}
|
||||
|
||||
off(event: string, handler: ScriptGameEventHandler): void {
|
||||
console.log('unubscribing from ' + event, handler);
|
||||
const handlers = this.handlers[event];
|
||||
if (!handlers)
|
||||
return;
|
||||
|
||||
this.handlers[event] = handlers.filter((h) => h.handler !== handler);
|
||||
}
|
||||
|
||||
emit(event: string, context: Omit<ScriptContext, keyof ScriptCoroutineContext>): void {
|
||||
console.log('emitting ' + event);
|
||||
|
||||
const coroutines = this.handlers[event]
|
||||
?.map((h) => {
|
||||
console.log(`passing ${event} to ${h.handler}(${JSON.stringify(context)}, ${JSON.stringify(h.coroutine)})`);
|
||||
return h.handler({ ...context, ...h.coroutine });
|
||||
});
|
||||
|
||||
console.log(coroutines);
|
||||
|
||||
if (coroutines)
|
||||
this.coroutines.push(coroutines);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user