boardgame-core/src/core/game.ts

69 lines
2.3 KiB
TypeScript

import {MutableSignal, mutableSignal} from "@/utils/mutable-signal";
import {
Command,
CommandRegistry,
CommandRunnerContext,
CommandRunnerContextExport,
CommandSchema,
createCommandRegistry,
createCommandRunnerContext,
parseCommandSchema,
registerCommand
} from "@/utils/command";
export interface IGameContext<TState extends Record<string, unknown> = {} > {
state: MutableSignal<TState>;
commands: CommandRunnerContextExport<MutableSignal<TState>>;
}
export function createGameContext<TState extends Record<string, unknown> = {} >(
commandRegistry: CommandRegistry<MutableSignal<TState>>,
initialState?: TState | (() => TState)
): IGameContext<TState> {
const stateValue = typeof initialState === 'function' ? initialState() : initialState ?? {} as TState;
const state = mutableSignal(stateValue);
const commands = createCommandRunnerContext(commandRegistry, state);
return {
state,
commands
};
}
/**
* so that we can do `import * as tictactoe from './tic-tac-toe.ts';\n\n createGameContextFromModule(tictactoe);`
* @param module
*/
export function createGameContextFromModule<TState extends Record<string, unknown> = {} >(
module: {
registry: CommandRegistry<MutableSignal<TState>>,
createInitialState: () => TState
},
): IGameContext<TState> {
return createGameContext(module.registry, module.createInitialState);
}
export function createGameCommandRegistry<TState extends Record<string, unknown> = {} >() {
const registry = createCommandRegistry<MutableSignal<TState>>();
return {
registry,
add<TResult = unknown>(
schema: CommandSchema | string,
run: (this: CommandRunnerContext<MutableSignal<TState>>, command: Command) => Promise<TResult>
){
createGameCommand(registry, schema, run);
return this;
}
}
}
export function createGameCommand<TState extends Record<string, unknown> = {} , TResult = unknown>(
registry: CommandRegistry<MutableSignal<TState>>,
schema: CommandSchema | string,
run: (this: CommandRunnerContext<MutableSignal<TState>>, command: Command) => Promise<TResult>
) {
registerCommand(registry, {
schema: typeof schema === 'string' ? parseCommandSchema(schema) : schema,
run,
});
}