boardgame-core/src/core/game.ts

65 lines
2.0 KiB
TypeScript

import { MutableSignal, mutableSignal } from "@/utils/mutable-signal";
import { CommandSchema, parseCommandSchema, PromptDef } from "@/utils/command";
import { PromptValidator } from "@/utils/command/command-runner";
import { Mulberry32RNG, ReadonlyRNG, RNG } from "@/utils/rng";
import { PromptContext } from "@/utils/command/command-prompt";
export interface IGameContext<TState extends Record<string, unknown> = {}> {
get value(): TState;
get rng(): ReadonlyRNG;
produce(fn: (draft: TState) => undefined): void;
produceAsync(fn: (draft: TState) => undefined): Promise<void>;
prompt: <TResult, TArgs extends any[] = any[]>(
def: PromptDef<TArgs>,
validator: PromptValidator<TResult, TArgs>,
player?: string,
) => Promise<TResult>;
// test only
_state: MutableSignal<TState>;
_rng: RNG;
}
export type IGameContextExport<TState extends Record<string, unknown> = {}> =
Omit<IGameContext<TState>, "_state" | "_commands" | "_rng">;
export function createGameContext<TState extends Record<string, unknown> = {}>(
promptContext: PromptContext,
initialState?: TState | (() => TState),
): IGameContext<TState> {
const stateValue =
typeof initialState === "function"
? initialState()
: (initialState ?? ({} as TState));
const state = mutableSignal(stateValue);
const { prompt } = promptContext;
const context: IGameContext<TState> = {
get value(): TState {
return state.value;
},
get rng() {
return this._rng;
},
produce(fn: (draft: TState) => undefined) {
return state.produce(fn);
},
produceAsync(fn: (draft: TState) => undefined) {
return state.produceAsync(fn);
},
prompt,
_state: state,
_rng: new Mulberry32RNG(),
};
return context;
}
export function createPromptDef<TArgs extends any[] = any[]>(
schema: CommandSchema | string,
hintText?: string,
): PromptDef<TArgs> {
schema = typeof schema === "string" ? parseCommandSchema(schema) : schema;
return { schema, hintText };
}