refactor: replace rule.ts with a command runner based solution
This commit is contained in:
+169
-35
@@ -2,20 +2,47 @@ import {createModel, Signal, signal} from '@preact/signals-core';
|
||||
import {createEntityCollection} from "../utils/entity";
|
||||
import {Part} from "./part";
|
||||
import {Region} from "./region";
|
||||
import {RuleDef, RuleRegistry, RuleContext, RuleEngineHost, dispatchCommand as dispatchRuleCommand} from "./rule";
|
||||
import {createCommandRunnerContext, CommandRegistry, createCommandRegistry, type CommandRunnerContextExport} from "../utils/command";
|
||||
import type {Command} from "../utils/command";
|
||||
import {parseCommand} from "../utils/command/command-parse";
|
||||
import {applyCommandSchema} from "../utils/command/command-validate";
|
||||
import {parseCommandSchema} from "../utils/command/schema-parse";
|
||||
import type {CommandRunner} from "../utils/command/command-runner";
|
||||
|
||||
export type Context = {
|
||||
type: string;
|
||||
}
|
||||
|
||||
export type GameQueueState = 'idle' | 'processing' | 'waiting-for-prompt';
|
||||
|
||||
export interface IGameContext {
|
||||
parts: ReturnType<typeof createEntityCollection<Part>>;
|
||||
regions: ReturnType<typeof createEntityCollection<Region>>;
|
||||
commandRegistry: Signal<CommandRegistry<IGameContext>>;
|
||||
contexts: Signal<Signal<Context>[]>;
|
||||
pushContext: (context: Context) => Context;
|
||||
popContext: () => void;
|
||||
latestContext: <T extends Context>(type: T['type']) => Signal<T> | undefined;
|
||||
registerCommand: (name: string, runner: CommandRunner<IGameContext, unknown>) => void;
|
||||
unregisterCommand: (name: string) => void;
|
||||
enqueue: (input: string) => void;
|
||||
enqueueAll: (inputs: string[]) => void;
|
||||
dispatchCommand: (input: string) => void;
|
||||
}
|
||||
|
||||
export const GameContext = createModel((root: Context) => {
|
||||
const parts = createEntityCollection<Part>();
|
||||
const regions = createEntityCollection<Region>();
|
||||
const rules = signal<RuleRegistry>(new Map());
|
||||
const ruleContexts = signal<RuleContext<unknown>[]>([]);
|
||||
const commandRegistry = signal<CommandRegistry<IGameContext>>(createCommandRegistry());
|
||||
const contexts = signal<Signal<Context>[]>([]);
|
||||
contexts.value = [signal(root)];
|
||||
|
||||
const inputQueue: string[] = [];
|
||||
let processing = false;
|
||||
let pendingPromptResolve: ((cmd: Command) => void) | null = null;
|
||||
let pendingPromptReject: ((err: Error) => void) | null = null;
|
||||
let activeRunnerCtx: CommandRunnerContextExport<IGameContext> | null = null;
|
||||
|
||||
function pushContext(context: Context) {
|
||||
const ctxSignal = signal(context);
|
||||
contexts.value = [...contexts.value, ctxSignal];
|
||||
@@ -37,58 +64,165 @@ export const GameContext = createModel((root: Context) => {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function registerRule(name: string, rule: RuleDef<unknown, RuleEngineHost>) {
|
||||
const newRules = new Map(rules.value);
|
||||
newRules.set(name, rule);
|
||||
rules.value = newRules;
|
||||
function registerCommand(name: string, runner: CommandRunner<IGameContext, unknown>) {
|
||||
const newRegistry = new Map(commandRegistry.value);
|
||||
newRegistry.set(name, runner);
|
||||
commandRegistry.value = newRegistry;
|
||||
}
|
||||
|
||||
function unregisterRule(name: string) {
|
||||
const newRules = new Map(rules.value);
|
||||
newRules.delete(name);
|
||||
rules.value = newRules;
|
||||
function unregisterCommand(name: string) {
|
||||
const newRegistry = new Map(commandRegistry.value);
|
||||
newRegistry.delete(name);
|
||||
commandRegistry.value = newRegistry;
|
||||
}
|
||||
|
||||
function addRuleContext(ctx: RuleContext<unknown>) {
|
||||
ruleContexts.value = [...ruleContexts.value, ctx];
|
||||
function makeRunnerCtx(): CommandRunnerContextExport<IGameContext> {
|
||||
const ctx = createCommandRunnerContext(commandRegistry.value, instance as IGameContext);
|
||||
|
||||
ctx.prompt = async (schema) => {
|
||||
const parsedSchema = typeof schema === 'string'
|
||||
? parseCommandSchema(schema)
|
||||
: schema;
|
||||
return new Promise<Command>((resolve, reject) => {
|
||||
pendingPromptResolve = resolve;
|
||||
pendingPromptReject = reject;
|
||||
const event = { schema: parsedSchema, resolve, reject };
|
||||
for (const listener of (ctx as any)._listeners || []) {
|
||||
listener(event);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const origRun = ctx.run.bind(ctx);
|
||||
ctx.run = async (input: string) => {
|
||||
const prevCtx = activeRunnerCtx;
|
||||
activeRunnerCtx = ctx;
|
||||
const result = await runCommand(ctx, input);
|
||||
activeRunnerCtx = prevCtx;
|
||||
return result;
|
||||
};
|
||||
|
||||
return ctx;
|
||||
}
|
||||
|
||||
function removeRuleContext(ctx: RuleContext<unknown>) {
|
||||
ruleContexts.value = ruleContexts.value.filter(c => c !== ctx);
|
||||
async function runCommand(runnerCtx: CommandRunnerContextExport<IGameContext>, input: string): Promise<{ success: true; result: unknown } | { success: false; error: string }> {
|
||||
const command = parseCommand(input);
|
||||
const runner = runnerCtx.registry.get(command.name);
|
||||
if (!runner) {
|
||||
return { success: false, error: `Unknown command: ${command.name}` };
|
||||
}
|
||||
|
||||
const validationResult = applyCommandSchema(command, runner.schema);
|
||||
if (!validationResult.valid) {
|
||||
return { success: false, error: validationResult.errors.join('; ') };
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await runner.run.call(runnerCtx, validationResult.command);
|
||||
return { success: true, result };
|
||||
} catch (e) {
|
||||
const error = e as Error;
|
||||
return { success: false, error: error.message };
|
||||
}
|
||||
}
|
||||
|
||||
function dispatchCommand(this: GameContextInstance, input: string) {
|
||||
return dispatchRuleCommand({
|
||||
rules: rules.value,
|
||||
ruleContexts: ruleContexts.value,
|
||||
addRuleContext,
|
||||
removeRuleContext,
|
||||
pushContext,
|
||||
popContext,
|
||||
latestContext,
|
||||
parts,
|
||||
regions,
|
||||
} as any, input);
|
||||
async function processQueue(): Promise<void> {
|
||||
if (processing) return;
|
||||
processing = true;
|
||||
|
||||
while (inputQueue.length > 0) {
|
||||
if (pendingPromptResolve) {
|
||||
const input = inputQueue.shift()!;
|
||||
try {
|
||||
const command = parseCommand(input);
|
||||
pendingPromptResolve(command);
|
||||
} catch (e) {
|
||||
pendingPromptReject!(new Error(`Invalid input for prompt: ${input}`));
|
||||
}
|
||||
pendingPromptResolve = null;
|
||||
pendingPromptReject = null;
|
||||
continue;
|
||||
}
|
||||
|
||||
const input = inputQueue.shift()!;
|
||||
const runnerCtx = makeRunnerCtx();
|
||||
const prevCtx = activeRunnerCtx;
|
||||
activeRunnerCtx = runnerCtx;
|
||||
|
||||
runCommand(runnerCtx, input).finally(() => {
|
||||
if (activeRunnerCtx === runnerCtx) {
|
||||
activeRunnerCtx = prevCtx;
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.resolve();
|
||||
}
|
||||
|
||||
processing = false;
|
||||
}
|
||||
|
||||
return {
|
||||
function enqueue(input: string) {
|
||||
if (pendingPromptResolve) {
|
||||
try {
|
||||
const command = parseCommand(input);
|
||||
pendingPromptResolve(command);
|
||||
} catch (e) {
|
||||
pendingPromptReject!(new Error(`Invalid input for prompt: ${input}`));
|
||||
}
|
||||
pendingPromptResolve = null;
|
||||
pendingPromptReject = null;
|
||||
} else {
|
||||
inputQueue.push(input);
|
||||
if (!processing) {
|
||||
void processQueue();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function enqueueAll(inputs: string[]) {
|
||||
for (const input of inputs) {
|
||||
if (pendingPromptResolve) {
|
||||
try {
|
||||
const command = parseCommand(input);
|
||||
pendingPromptResolve(command);
|
||||
} catch (e) {
|
||||
pendingPromptReject!(new Error(`Invalid input for prompt: ${input}`));
|
||||
}
|
||||
pendingPromptResolve = null;
|
||||
pendingPromptReject = null;
|
||||
} else {
|
||||
inputQueue.push(input);
|
||||
}
|
||||
}
|
||||
if (!processing) {
|
||||
void processQueue();
|
||||
}
|
||||
}
|
||||
|
||||
function dispatchCommand(input: string) {
|
||||
enqueue(input);
|
||||
}
|
||||
|
||||
const instance: IGameContext = {
|
||||
parts,
|
||||
regions,
|
||||
rules,
|
||||
ruleContexts,
|
||||
commandRegistry,
|
||||
contexts,
|
||||
pushContext,
|
||||
popContext,
|
||||
latestContext,
|
||||
registerRule,
|
||||
unregisterRule,
|
||||
registerCommand,
|
||||
unregisterCommand,
|
||||
enqueue,
|
||||
enqueueAll,
|
||||
dispatchCommand,
|
||||
}
|
||||
};
|
||||
|
||||
return instance;
|
||||
})
|
||||
|
||||
/** 创建游戏上下文实�?*/
|
||||
export function createGameContext(root: Context = { type: 'game' }) {
|
||||
return new GameContext(root);
|
||||
}
|
||||
|
||||
export type GameContextInstance = ReturnType<typeof createGameContext>;
|
||||
export type GameContextInstance = IGameContext;
|
||||
|
||||
@@ -1,233 +0,0 @@
|
||||
import {Command, CommandSchema, parseCommand, parseCommandSchema, applyCommandSchema} from "../utils/command";
|
||||
|
||||
export type RuleState = 'running' | 'yielded' | 'waiting' | 'invoking' | 'done';
|
||||
|
||||
export type SchemaYield = { type: 'schema'; value: string | CommandSchema };
|
||||
export type InvokeYield = { type: 'invoke'; rule: string; command: Command };
|
||||
export type RuleYield = SchemaYield | InvokeYield;
|
||||
|
||||
export type RuleContext<T = unknown> = {
|
||||
type: string;
|
||||
schema?: CommandSchema;
|
||||
generator: Generator<RuleYield, T, Command | RuleContext<unknown>>;
|
||||
parent?: RuleContext<unknown>;
|
||||
children: RuleContext<unknown>[];
|
||||
state: RuleState;
|
||||
resolution?: T;
|
||||
}
|
||||
|
||||
export type RuleDef<T = unknown, H extends RuleEngineHost = RuleEngineHost> = {
|
||||
schema: CommandSchema;
|
||||
create: (this: H, cmd: Command) => Generator<RuleYield, T, Command | RuleContext<unknown>>;
|
||||
};
|
||||
|
||||
export type RuleRegistry = Map<string, RuleDef<unknown, RuleEngineHost>>;
|
||||
|
||||
export type RuleEngineHost = {
|
||||
rules: RuleRegistry;
|
||||
ruleContexts: RuleContext<unknown>[];
|
||||
addRuleContext: (ctx: RuleContext<unknown>) => void;
|
||||
removeRuleContext: (ctx: RuleContext<unknown>) => void;
|
||||
};
|
||||
|
||||
export function createRule<T, H extends RuleEngineHost = RuleEngineHost>(
|
||||
schemaStr: string,
|
||||
fn: (this: H, cmd: Command) => Generator<RuleYield, T, Command | RuleContext<unknown>>
|
||||
): RuleDef<T, H> {
|
||||
return {
|
||||
schema: parseCommandSchema(schemaStr, ''),
|
||||
create: fn as RuleDef<T, H>['create'],
|
||||
};
|
||||
}
|
||||
|
||||
function parseYieldedSchema(value: string | CommandSchema): CommandSchema {
|
||||
if (typeof value === 'string') {
|
||||
return parseCommandSchema(value, '');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function addContextToHost(host: RuleEngineHost, ctx: RuleContext<unknown>) {
|
||||
host.addRuleContext(ctx);
|
||||
}
|
||||
|
||||
function discardChildren(host: RuleEngineHost, parent: RuleContext<unknown>) {
|
||||
for (const child of parent.children) {
|
||||
host.removeRuleContext(child);
|
||||
}
|
||||
parent.children = [];
|
||||
parent.state = 'yielded';
|
||||
}
|
||||
|
||||
function commandMatchesSchema(command: Command, schema: CommandSchema): boolean {
|
||||
const requiredParams = schema.params.filter(p => p.required);
|
||||
const variadicParam = schema.params.find(p => p.variadic);
|
||||
|
||||
if (command.params.length < requiredParams.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!variadicParam && command.params.length > schema.params.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const requiredOptions = Object.values(schema.options).filter(o => o.required);
|
||||
for (const opt of requiredOptions) {
|
||||
const hasOption = opt.name in command.options || (opt.short && opt.short in command.options);
|
||||
if (!hasOption) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
function applySchemaToCommand(command: Command, schema: CommandSchema): Command {
|
||||
return applyCommandSchema(command, schema).command;
|
||||
}
|
||||
|
||||
function findYieldedContext(contexts: RuleContext<unknown>[]): RuleContext<unknown> | undefined {
|
||||
for (let i = contexts.length - 1; i >= 0; i--) {
|
||||
const ctx = contexts[i];
|
||||
if (ctx.state === 'yielded') {
|
||||
return ctx;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function createContext<T>(
|
||||
command: Command,
|
||||
ruleDef: RuleDef<T>,
|
||||
host: RuleEngineHost,
|
||||
parent?: RuleContext<unknown>
|
||||
): RuleContext<T> {
|
||||
return {
|
||||
type: ruleDef.schema.name,
|
||||
schema: undefined,
|
||||
generator: ruleDef.create.call(host, command),
|
||||
parent,
|
||||
children: [],
|
||||
state: 'running',
|
||||
resolution: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function handleGeneratorResult<T>(
|
||||
host: RuleEngineHost,
|
||||
ctx: RuleContext<T>,
|
||||
result: IteratorResult<RuleYield, T>
|
||||
): RuleContext<unknown> | undefined {
|
||||
if (result.done) {
|
||||
ctx.resolution = result.value;
|
||||
ctx.state = 'done';
|
||||
return resumeParentAfterChildComplete(host, ctx as RuleContext<unknown>);
|
||||
}
|
||||
|
||||
const yielded = result.value;
|
||||
if (yielded.type === 'invoke') {
|
||||
const childRuleDef = host.rules.get(yielded.rule);
|
||||
if (childRuleDef) {
|
||||
ctx.state = 'invoking';
|
||||
return invokeChildRule(host, yielded.rule, yielded.command, ctx as RuleContext<unknown>);
|
||||
} else {
|
||||
ctx.schema = parseYieldedSchema({ name: '', params: [], options: {}, flags: {} });
|
||||
ctx.state = 'yielded';
|
||||
}
|
||||
} else {
|
||||
ctx.schema = parseYieldedSchema(yielded.value);
|
||||
ctx.state = 'yielded';
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function stepGenerator<T>(
|
||||
host: RuleEngineHost,
|
||||
ctx: RuleContext<T>
|
||||
): RuleContext<T> {
|
||||
const result = ctx.generator.next();
|
||||
const resumed = handleGeneratorResult(host, ctx, result);
|
||||
if (resumed) return resumed as RuleContext<T>;
|
||||
return ctx;
|
||||
}
|
||||
|
||||
function invokeChildRule<T>(
|
||||
host: RuleEngineHost,
|
||||
ruleName: string,
|
||||
command: Command,
|
||||
parent: RuleContext<unknown>
|
||||
): RuleContext<T> {
|
||||
const ruleDef = host.rules.get(ruleName)!;
|
||||
const ctx = createContext(command, ruleDef, host, parent);
|
||||
|
||||
parent.children.push(ctx as RuleContext<unknown>);
|
||||
addContextToHost(host, ctx as RuleContext<unknown>);
|
||||
|
||||
return stepGenerator(host, ctx) as RuleContext<T>;
|
||||
}
|
||||
|
||||
function resumeParentAfterChildComplete(
|
||||
host: RuleEngineHost,
|
||||
childCtx: RuleContext<unknown>
|
||||
): RuleContext<unknown> | undefined {
|
||||
const parent = childCtx.parent;
|
||||
if (!parent || parent.state !== 'invoking') return undefined;
|
||||
|
||||
parent.children = parent.children.filter(c => c !== childCtx);
|
||||
|
||||
const result = parent.generator.next(childCtx);
|
||||
const resumed = handleGeneratorResult(host, parent, result);
|
||||
if (resumed) return resumed;
|
||||
return parent;
|
||||
}
|
||||
|
||||
function invokeRule<T>(
|
||||
host: RuleEngineHost,
|
||||
command: Command,
|
||||
ruleDef: RuleDef<T>,
|
||||
parent?: RuleContext<unknown>
|
||||
): RuleContext<T> {
|
||||
const ctx = createContext(command, ruleDef, host, parent);
|
||||
|
||||
if (parent) {
|
||||
discardChildren(host, parent);
|
||||
parent.children.push(ctx as RuleContext<unknown>);
|
||||
parent.state = 'waiting';
|
||||
}
|
||||
|
||||
addContextToHost(host, ctx as RuleContext<unknown>);
|
||||
|
||||
return stepGenerator(host, ctx);
|
||||
}
|
||||
|
||||
function feedYieldedContext(
|
||||
host: RuleEngineHost,
|
||||
ctx: RuleContext<unknown>,
|
||||
command: Command
|
||||
): RuleContext<unknown> {
|
||||
const typedCommand = applySchemaToCommand(command, ctx.schema!);
|
||||
const result = ctx.generator.next(typedCommand);
|
||||
const resumed = handleGeneratorResult(host, ctx, result);
|
||||
return resumed ?? ctx;
|
||||
}
|
||||
|
||||
export function dispatchCommand(host: RuleEngineHost, input: string): RuleContext<unknown> | undefined {
|
||||
const command = parseCommand(input);
|
||||
|
||||
const matchedRule = host.rules.get(command.name);
|
||||
if (matchedRule) {
|
||||
const typedCommand = applySchemaToCommand(command, matchedRule.schema);
|
||||
const parent = findYieldedContext(host.ruleContexts);
|
||||
return invokeRule(host, typedCommand, matchedRule, parent);
|
||||
}
|
||||
|
||||
for (let i = host.ruleContexts.length - 1; i >= 0; i--) {
|
||||
const ctx = host.ruleContexts[i];
|
||||
if (ctx.state === 'yielded' && ctx.schema && commandMatchesSchema(command, ctx.schema)) {
|
||||
return feedYieldedContext(host, ctx, command);
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
+3
-6
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
|
||||
// Core types
|
||||
export type { Context } from './core/context';
|
||||
export type { Context, GameContextInstance, GameQueueState } from './core/context';
|
||||
export { GameContext, createGameContext } from './core/context';
|
||||
|
||||
export type { Part } from './core/part';
|
||||
@@ -13,15 +13,12 @@ export { flip, flipTo, roll } from './core/part';
|
||||
export type { Region, RegionAxis } from './core/region';
|
||||
export { applyAlign, shuffle } from './core/region';
|
||||
|
||||
export type { RuleContext, RuleState, RuleDef, RuleRegistry } from './core/rule';
|
||||
export { createRule, dispatchCommand } from './core/rule';
|
||||
|
||||
// Utils
|
||||
export type { Command, CommandSchema, CommandParamSchema, CommandOptionSchema, CommandFlagSchema } from './utils/command';
|
||||
export { parseCommand, parseCommandSchema, validateCommand, parseCommandWithSchema, applyCommandSchema } from './utils/command';
|
||||
|
||||
export type { CommandRunner, CommandRunnerHandler, CommandRegistry, CommandRunnerContext } from './utils/command';
|
||||
export { createCommandRegistry, registerCommand, unregisterCommand, hasCommand, getCommand, runCommand, createCommandRunnerContext } from './utils/command';
|
||||
export type { CommandRunner, CommandRunnerHandler, CommandRunnerContext, PromptEvent, CommandRunnerEvents } from './utils/command';
|
||||
export { createCommandRegistry, registerCommand, unregisterCommand, hasCommand, getCommand, runCommand, runCommandParsed, createCommandRunnerContext, type CommandRegistry, type CommandRunnerContextExport } from './utils/command';
|
||||
|
||||
export type { Entity, EntityAccessor } from './utils/entity';
|
||||
export { createEntityCollection } from './utils/entity';
|
||||
|
||||
+63
-75
@@ -1,10 +1,9 @@
|
||||
import { GameContextInstance } from '../core/context';
|
||||
import type { RuleEngineHost, RuleContext } from '../core/rule';
|
||||
import { createRule, type InvokeYield, type SchemaYield } from '../core/rule';
|
||||
import type { Command } from '../utils/command';
|
||||
import type { Command, CommandRunner, CommandRunnerContext } from '../utils/command';
|
||||
import type { Part } from '../core/part';
|
||||
import type { Region } from '../core/region';
|
||||
import type { Context } from '../core/context';
|
||||
import { parseCommandSchema } from '../utils/command/schema-parse';
|
||||
|
||||
export type TicTacToeState = Context & {
|
||||
type: 'tic-tac-toe';
|
||||
@@ -17,25 +16,18 @@ type TurnResult = {
|
||||
winner: 'X' | 'O' | 'draw' | null;
|
||||
};
|
||||
|
||||
type TicTacToeHost = RuleEngineHost & {
|
||||
pushContext: (context: Context) => any;
|
||||
latestContext: <T>(type: string) => { value: T } | undefined;
|
||||
regions: { add: (...entities: any[]) => void; get: (id: string) => { value: { children: any[] } } };
|
||||
parts: { add: (...entities: any[]) => void; get: (id: string) => any; collection: { value: Record<string, { value: Part }> } };
|
||||
};
|
||||
|
||||
function getBoardRegion(host: TicTacToeHost) {
|
||||
function getBoardRegion(host: GameContextInstance) {
|
||||
return host.regions.get('board');
|
||||
}
|
||||
|
||||
function isCellOccupied(host: TicTacToeHost, row: number, col: number): boolean {
|
||||
function isCellOccupied(host: GameContextInstance, row: number, col: number): boolean {
|
||||
const board = getBoardRegion(host);
|
||||
return board.value.children.some(
|
||||
(child: { value: { position: number[] } }) => child.value.position[0] === row && child.value.position[1] === col
|
||||
);
|
||||
}
|
||||
|
||||
function checkWinner(host: TicTacToeHost): 'X' | 'O' | 'draw' | null {
|
||||
function checkWinner(host: GameContextInstance): 'X' | 'O' | 'draw' | null {
|
||||
const parts = Object.values(host.parts.collection.value).map((s: { value: Part }) => s.value);
|
||||
|
||||
const xPositions = parts.filter((_: Part, i: number) => i % 2 === 0).map((p: Part) => p.position);
|
||||
@@ -66,7 +58,7 @@ function hasWinningLine(positions: number[][]): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
function placePiece(host: TicTacToeHost, row: number, col: number, moveCount: number) {
|
||||
function placePiece(host: GameContextInstance, row: number, col: number, moveCount: number) {
|
||||
const board = getBoardRegion(host);
|
||||
const piece: Part = {
|
||||
id: `piece-${moveCount}`,
|
||||
@@ -79,82 +71,78 @@ function placePiece(host: TicTacToeHost, row: number, col: number, moveCount: nu
|
||||
board.value.children.push(host.parts.get(piece.id));
|
||||
}
|
||||
|
||||
const playSchema: SchemaYield = { type: 'schema', value: 'play <player> <row:number> <col:number>' };
|
||||
export function createSetupCommand(): CommandRunner<GameContextInstance, { winner: 'X' | 'O' | 'draw' | null }> {
|
||||
return {
|
||||
schema: parseCommandSchema('start'),
|
||||
run: async function(this: CommandRunnerContext<GameContextInstance>) {
|
||||
this.context.pushContext({
|
||||
type: 'tic-tac-toe',
|
||||
currentPlayer: 'X',
|
||||
winner: null,
|
||||
moveCount: 0,
|
||||
} as TicTacToeState);
|
||||
|
||||
export function createSetupRule() {
|
||||
return createRule('start', function*(this: TicTacToeHost) {
|
||||
this.pushContext({
|
||||
type: 'tic-tac-toe',
|
||||
currentPlayer: 'X',
|
||||
winner: null,
|
||||
moveCount: 0,
|
||||
} as TicTacToeState);
|
||||
this.context.regions.add({
|
||||
id: 'board',
|
||||
axes: [
|
||||
{ name: 'x', min: 0, max: 2 },
|
||||
{ name: 'y', min: 0, max: 2 },
|
||||
],
|
||||
children: [],
|
||||
} as Region);
|
||||
|
||||
this.regions.add({
|
||||
id: 'board',
|
||||
axes: [
|
||||
{ name: 'x', min: 0, max: 2 },
|
||||
{ name: 'y', min: 0, max: 2 },
|
||||
],
|
||||
children: [],
|
||||
} as Region);
|
||||
let currentPlayer: 'X' | 'O' = 'X';
|
||||
let turnResult: TurnResult | undefined;
|
||||
|
||||
let currentPlayer: 'X' | 'O' = 'X';
|
||||
let turnResult: TurnResult | undefined;
|
||||
while (true) {
|
||||
const turnOutput = await this.run(`turn ${currentPlayer}`);
|
||||
if (!turnOutput.success) throw new Error(turnOutput.error);
|
||||
turnResult = turnOutput.result as TurnResult;
|
||||
if (turnResult?.winner) break;
|
||||
|
||||
while (true) {
|
||||
const yieldValue: InvokeYield = {
|
||||
type: 'invoke',
|
||||
rule: 'turn',
|
||||
command: { name: 'turn', params: [currentPlayer], flags: {}, options: {} } as Command,
|
||||
};
|
||||
const ctx = yield yieldValue;
|
||||
turnResult = (ctx as RuleContext<TurnResult>).resolution;
|
||||
if (turnResult?.winner) break;
|
||||
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
|
||||
const state = this.context.latestContext<TicTacToeState>('tic-tac-toe')!;
|
||||
state.value.currentPlayer = currentPlayer;
|
||||
}
|
||||
|
||||
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
|
||||
const state = this.latestContext<TicTacToeState>('tic-tac-toe')!;
|
||||
state.value.currentPlayer = currentPlayer;
|
||||
}
|
||||
|
||||
const state = this.latestContext<TicTacToeState>('tic-tac-toe')!;
|
||||
state.value.winner = turnResult?.winner ?? null;
|
||||
return { winner: state.value.winner };
|
||||
});
|
||||
const state = this.context.latestContext<TicTacToeState>('tic-tac-toe')!;
|
||||
state.value.winner = turnResult?.winner ?? null;
|
||||
return { winner: state.value.winner };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createTurnRule() {
|
||||
return createRule('turn <player>', function*(this: TicTacToeHost, cmd) {
|
||||
while (true) {
|
||||
const received = yield playSchema;
|
||||
if ('resolution' in received) continue;
|
||||
export function createTurnCommand(): CommandRunner<GameContextInstance, TurnResult> {
|
||||
return {
|
||||
schema: parseCommandSchema('turn <player>'),
|
||||
run: async function(this: CommandRunnerContext<GameContextInstance>, cmd: Command) {
|
||||
while (true) {
|
||||
const playCmd = await this.prompt('play <player> <row:number> <col:number>');
|
||||
|
||||
const playCmd = received as Command;
|
||||
if (playCmd.name !== 'play') continue;
|
||||
const row = Number(playCmd.params[1]);
|
||||
const col = Number(playCmd.params[2]);
|
||||
|
||||
const row = playCmd.params[1] as number;
|
||||
const col = playCmd.params[2] as number;
|
||||
if (isNaN(row) || isNaN(col) || row < 0 || row > 2 || col < 0 || col > 2) continue;
|
||||
if (isCellOccupied(this.context, row, col)) continue;
|
||||
|
||||
if (isNaN(row) || isNaN(col) || row < 0 || row > 2 || col < 0 || col > 2) continue;
|
||||
if (isCellOccupied(this, row, col)) continue;
|
||||
const state = this.context.latestContext<TicTacToeState>('tic-tac-toe')!;
|
||||
if (state.value.winner) continue;
|
||||
|
||||
const state = this.latestContext<TicTacToeState>('tic-tac-toe')!;
|
||||
if (state.value.winner) continue;
|
||||
placePiece(this.context, row, col, state.value.moveCount);
|
||||
state.value.moveCount++;
|
||||
|
||||
placePiece(this, row, col, state.value.moveCount);
|
||||
state.value.moveCount++;
|
||||
const winner = checkWinner(this.context);
|
||||
if (winner) return { winner };
|
||||
|
||||
const winner = checkWinner(this);
|
||||
if (winner) return { winner };
|
||||
|
||||
if (state.value.moveCount >= 9) return { winner: 'draw' as const };
|
||||
}
|
||||
});
|
||||
if (state.value.moveCount >= 9) return { winner: 'draw' as const };
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function registerTicTacToeRules(game: GameContextInstance) {
|
||||
game.registerRule('start', createSetupRule());
|
||||
game.registerRule('turn', createTurnRule());
|
||||
export function registerTicTacToeCommands(game: GameContextInstance) {
|
||||
game.registerCommand('start', createSetupCommand());
|
||||
game.registerCommand('turn', createTurnCommand());
|
||||
}
|
||||
|
||||
export function startTicTacToe(game: GameContextInstance) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Command } from './types.js';
|
||||
import type { Command, CommandSchema } from './types.js';
|
||||
import type { CommandRunner, CommandRunnerContext, PromptEvent } from './command-runner.js';
|
||||
import { parseCommand } from './command-parse.js';
|
||||
import { applyCommandSchema } from './command-apply.js';
|
||||
import { applyCommandSchema } from './command-validate.js';
|
||||
import { parseCommandSchema } from './schema-parse.js';
|
||||
|
||||
export type CommandRegistry<TContext> = Map<string, CommandRunner<TContext, unknown>>;
|
||||
@@ -42,6 +42,10 @@ type Listener = (e: PromptEvent) => void;
|
||||
|
||||
export type CommandRunnerContextExport<TContext> = CommandRunnerContext<TContext> & {
|
||||
registry: CommandRegistry<TContext>;
|
||||
_activePrompt: PromptEvent | null;
|
||||
_resolvePrompt: (command: Command) => void;
|
||||
_rejectPrompt: (error: Error) => void;
|
||||
_pendingInput: string | null;
|
||||
};
|
||||
|
||||
export function createCommandRunnerContext<TContext>(
|
||||
@@ -58,9 +62,26 @@ export function createCommandRunnerContext<TContext>(
|
||||
listeners.delete(listener);
|
||||
};
|
||||
|
||||
let activePrompt: PromptEvent | null = null;
|
||||
|
||||
const resolvePrompt = (command: Command) => {
|
||||
if (activePrompt) {
|
||||
activePrompt.resolve(command);
|
||||
activePrompt = null;
|
||||
}
|
||||
};
|
||||
|
||||
const rejectPrompt = (error: Error) => {
|
||||
if (activePrompt) {
|
||||
activePrompt.reject(error);
|
||||
activePrompt = null;
|
||||
}
|
||||
};
|
||||
|
||||
const prompt = (schema: Parameters<CommandRunnerContext<TContext>['prompt']>[0]): Promise<Command> => {
|
||||
const resolvedSchema = typeof schema === 'string' ? parseCommandSchema(schema) : schema;
|
||||
return new Promise((resolve, reject) => {
|
||||
activePrompt = { schema: resolvedSchema, resolve, reject };
|
||||
const event: PromptEvent = { schema: resolvedSchema, resolve, reject };
|
||||
for (const listener of listeners) {
|
||||
listener(event);
|
||||
@@ -71,13 +92,21 @@ export function createCommandRunnerContext<TContext>(
|
||||
const runnerCtx: CommandRunnerContextExport<TContext> = {
|
||||
registry,
|
||||
context,
|
||||
run: (input: string) => runCommandWithContext(registry, runnerCtx, input),
|
||||
runParsed: (command: Command) => runCommandParsedWithContext(registry, runnerCtx, command),
|
||||
run: (input: string) => runCommandWithContext(runnerCtx, input),
|
||||
runParsed: (command: Command) => runCommandParsedWithContext(runnerCtx, command),
|
||||
prompt,
|
||||
on,
|
||||
off,
|
||||
_activePrompt: null,
|
||||
_resolvePrompt: resolvePrompt,
|
||||
_rejectPrompt: rejectPrompt,
|
||||
_pendingInput: null,
|
||||
};
|
||||
|
||||
Object.defineProperty(runnerCtx, '_activePrompt', {
|
||||
get: () => activePrompt,
|
||||
});
|
||||
|
||||
return runnerCtx;
|
||||
}
|
||||
|
||||
@@ -101,16 +130,15 @@ export async function runCommand<TContext>(
|
||||
input: string
|
||||
): Promise<{ success: true; result: unknown } | { success: false; error: string }> {
|
||||
const runnerCtx = createCommandRunnerContext(registry, context);
|
||||
return await runCommandWithContext(registry, runnerCtx, input);
|
||||
return await runCommandWithContext(runnerCtx, input);
|
||||
}
|
||||
|
||||
async function runCommandWithContext<TContext>(
|
||||
registry: CommandRegistry<TContext>,
|
||||
runnerCtx: CommandRunnerContextExport<TContext>,
|
||||
input: string
|
||||
): Promise<{ success: true; result: unknown } | { success: false; error: string }> {
|
||||
const command = parseCommand(input);
|
||||
return await runCommandParsedWithContext(registry, runnerCtx, command);
|
||||
return await runCommandParsedWithContext(runnerCtx, command);
|
||||
}
|
||||
|
||||
export async function runCommandParsed<TContext>(
|
||||
@@ -119,15 +147,14 @@ export async function runCommandParsed<TContext>(
|
||||
command: Command
|
||||
): Promise<{ success: true; result: unknown } | { success: false; error: string }> {
|
||||
const runnerCtx = createCommandRunnerContext(registry, context);
|
||||
return await runCommandParsedWithContext(registry, runnerCtx, command);
|
||||
return await runCommandParsedWithContext(runnerCtx, command);
|
||||
}
|
||||
|
||||
async function runCommandParsedWithContext<TContext>(
|
||||
registry: CommandRegistry<TContext>,
|
||||
runnerCtx: CommandRunnerContextExport<TContext>,
|
||||
command: Command
|
||||
): Promise<{ success: true; result: unknown } | { success: false; error: string }> {
|
||||
const runner = registry.get(command.name);
|
||||
const runner = runnerCtx.registry.get(command.name);
|
||||
if (!runner) {
|
||||
return { success: false, error: `Unknown command: ${command.name}` };
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user