import {createEntityCollection, entity, Entity, EntityCollection} from "../utils/entity"; import {Part} from "./part"; import {Region} from "./region"; import { Command, CommandRegistry, CommandRunnerContext, CommandRunnerContextExport, CommandSchema, createCommandRegistry, createCommandRunnerContext, parseCommandSchema, PromptEvent, registerCommand } from "../utils/command"; import {AsyncQueue} from "../utils/async-queue"; export interface IGameContext = {} > { parts: EntityCollection; regions: EntityCollection; state: Entity; commands: CommandRunnerContextExport>; prompts: AsyncQueue; } export function createGameContext = {} >( commandRegistry: CommandRegistry>, initialState?: TState | (() => TState) ): IGameContext { const parts = createEntityCollection(); const regions = createEntityCollection(); const prompts = new AsyncQueue(); const state = typeof initialState === 'function' ? initialState() : initialState ?? {} as TState; const ctx = { parts, regions, prompts, commands: null!, state: entity('gameState', state), } as IGameContext ctx.commands = createCommandRunnerContext(commandRegistry, ctx); ctx.commands.on('prompt', (prompt: PromptEvent) => ctx.prompts.push(prompt)); return ctx; } /** * so that we can do `import * as tictactoe from './tic-tac-toe.ts';\n\n createGameContextFromModule(tictactoe);` * @param module */ export function createGameContextFromModule = {} >( module: { registry: CommandRegistry>, createInitialState: () => TState }, ): IGameContext { return createGameContext(module.registry, module.createInitialState); } export function createGameCommandRegistry = {} >(): CommandRegistry> { return createCommandRegistry>(); } export function createGameCommand = {} , TResult = unknown>( registry: CommandRegistry>, schema: CommandSchema | string, run: (this: CommandRunnerContext>, command: Command) => Promise ) { registerCommand(registry, { schema: typeof schema === 'string' ? parseCommandSchema(schema) : schema, run, }); }