refactor: rewrite game & tic tac toe

This commit is contained in:
2026-04-02 11:06:29 +08:00
parent 5042d6ebc7
commit 1cb7fa05ec
5 changed files with 87 additions and 484 deletions
+28 -6
View File
@@ -1,27 +1,49 @@
import {createEntityCollection} from "../utils/entity";
import {Part} from "./part";
import {Region} from "./region";
import {CommandRegistry, CommandRunnerContextExport, createCommandRunnerContext, PromptEvent} from "../utils/command";
import {
Command,
CommandRegistry,
type CommandRunner, CommandRunnerContext,
CommandRunnerContextExport, CommandSchema,
createCommandRunnerContext, parseCommandSchema,
PromptEvent
} from "../utils/command";
import {AsyncQueue} from "../utils/async-queue";
export interface IGameContext {
parts: ReturnType<typeof createEntityCollection<Part>>;
regions: ReturnType<typeof createEntityCollection<Region>>;
commands: CommandRunnerContextExport<IGameContext>;
inputs: AsyncQueue<PromptEvent>;
prompts: AsyncQueue<PromptEvent>;
}
/**
* creates a game context.
* expects a command registry already registered with commands.
* @param commandRegistry
*/
export function createGameContext(commandRegistry: CommandRegistry<IGameContext>) {
const parts = createEntityCollection<Part>();
const regions = createEntityCollection<Region>();
const ctx: IGameContext = {
parts,
regions,
commands: null,
inputs: new AsyncQueue(),
commands: null!,
prompts: new AsyncQueue(),
};
ctx.commands = createCommandRunnerContext(commandRegistry, ctx);
ctx.commands.on('prompt', (prompt: PromptEvent) => ctx.inputs.push(prompt));
ctx.commands.on('prompt', (prompt: PromptEvent) => ctx.prompts.push(prompt));
return ctx;
}
}
export function createGameCommand<TResult>(
schema: CommandSchema | string,
run: (this: CommandRunnerContext<IGameContext>, command: Command) => Promise<TResult>
): CommandRunner<IGameContext, TResult> {
return {
schema: typeof schema === 'string' ? parseCommandSchema(schema) : schema,
run,
};
}