boardgame-core/src/core/game.ts

69 lines
2.2 KiB
TypeScript
Raw Normal View History

2026-04-02 15:59:27 +08:00
import {entity, Entity} from "@/utils/entity";
2026-04-02 10:48:20 +08:00
import {
Command,
CommandRegistry,
2026-04-02 14:11:35 +08:00
CommandRunnerContext,
2026-04-02 14:39:30 +08:00
CommandRunnerContextExport,
CommandSchema,
createCommandRegistry,
createCommandRunnerContext,
parseCommandSchema,
registerCommand
2026-04-02 15:59:27 +08:00
} from "@/utils/command";
2026-04-02 10:26:42 +08:00
2026-04-02 12:53:49 +08:00
export interface IGameContext<TState extends Record<string, unknown> = {} > {
state: Entity<TState>;
2026-04-02 14:39:30 +08:00
commands: CommandRunnerContextExport<Entity<TState>>;
2026-04-02 10:26:42 +08:00
}
2026-04-02 12:53:49 +08:00
export function createGameContext<TState extends Record<string, unknown> = {} >(
2026-04-02 14:39:30 +08:00
commandRegistry: CommandRegistry<Entity<TState>>,
2026-04-02 12:48:29 +08:00
initialState?: TState | (() => TState)
): IGameContext<TState> {
2026-04-02 14:39:30 +08:00
const stateValue = typeof initialState === 'function' ? initialState() : initialState ?? {} as TState;
const state = entity('state', stateValue);
const commands = createCommandRunnerContext(commandRegistry, state);
2026-04-02 12:48:29 +08:00
2026-04-02 14:39:30 +08:00
return {
state,
commands
};
2026-04-02 10:48:20 +08:00
}
2026-04-02 12:48:29 +08:00
/**
* so that we can do `import * as tictactoe from './tic-tac-toe.ts';\n\n createGameContextFromModule(tictactoe);`
* @param module
*/
2026-04-02 12:53:49 +08:00
export function createGameContextFromModule<TState extends Record<string, unknown> = {} >(
2026-04-02 12:48:29 +08:00
module: {
2026-04-02 14:39:30 +08:00
registry: CommandRegistry<Entity<TState>>,
2026-04-02 12:48:29 +08:00
createInitialState: () => TState
},
): IGameContext<TState> {
return createGameContext(module.registry, module.createInitialState);
}
2026-04-02 14:39:30 +08:00
export function createGameCommandRegistry<TState extends Record<string, unknown> = {} >() {
const registry = createCommandRegistry<Entity<TState>>();
return {
registry,
add<TResult = unknown>(
schema: CommandSchema | string,
run: (this: CommandRunnerContext<Entity<TState>>, command: Command) => Promise<TResult>
){
createGameCommand(registry, schema, run);
return this;
}
}
}
2026-04-02 12:53:49 +08:00
export function createGameCommand<TState extends Record<string, unknown> = {} , TResult = unknown>(
2026-04-02 14:39:30 +08:00
registry: CommandRegistry<Entity<TState>>,
2026-04-02 10:48:20 +08:00
schema: CommandSchema | string,
2026-04-02 14:39:30 +08:00
run: (this: CommandRunnerContext<Entity<TState>>, command: Command) => Promise<TResult>
2026-04-02 14:11:35 +08:00
) {
registerCommand(registry, {
2026-04-02 10:48:20 +08:00
schema: typeof schema === 'string' ? parseCommandSchema(schema) : schema,
run,
2026-04-02 14:11:35 +08:00
});
}