refactor: improve rule handling

This commit is contained in:
2026-04-02 00:44:29 +08:00
parent ff9d9bd9a1
commit e06dc8ecba
4 changed files with 184 additions and 226 deletions
+10 -7
View File
@@ -2,7 +2,7 @@ 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, GameContextLike, dispatchCommand as dispatchRuleCommand} from "./rule";
import {RuleDef, RuleRegistry, RuleContext, RuleEngineHost, dispatchCommand as dispatchRuleCommand} from "./rule";
export type Context = {
type: string;
@@ -37,7 +37,7 @@ export const GameContext = createModel((root: Context) => {
return undefined;
}
function registerRule(name: string, rule: RuleDef<unknown>) {
function registerRule(name: string, rule: RuleDef<unknown, RuleEngineHost>) {
const newRules = new Map(rules.value);
newRules.set(name, rule);
rules.value = newRules;
@@ -57,15 +57,18 @@ export const GameContext = createModel((root: Context) => {
ruleContexts.value = ruleContexts.value.filter(c => c !== ctx);
}
function dispatchCommand(this: GameContextLike, input: string) {
function dispatchCommand(this: GameContextInstance, input: string) {
return dispatchRuleCommand({
...this,
rules: rules.value,
ruleContexts: ruleContexts.value,
contexts,
addRuleContext,
removeRuleContext,
}, input);
pushContext,
popContext,
latestContext,
parts,
regions,
} as any, input);
}
return {
@@ -83,7 +86,7 @@ export const GameContext = createModel((root: Context) => {
}
})
/** 创建游æˆä¸Šä¸‹æ–‡å®žä¾?*/
/** 创建游戏上下文实?*/
export function createGameContext(root: Context = { type: 'game' }) {
return new GameContext(root);
}
+127 -168
View File
@@ -2,13 +2,9 @@ import {Command, CommandSchema, parseCommand, parseCommandSchema, applyCommandSc
export type RuleState = 'running' | 'yielded' | 'waiting' | 'invoking' | 'done';
export type InvokeYield = {
type: 'invoke';
rule: string;
command: Command;
};
export type RuleYield = string | CommandSchema | InvokeYield;
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;
@@ -20,27 +16,30 @@ export type RuleContext<T = unknown> = {
resolution?: T;
}
export type RuleDef<T = unknown> = {
export type RuleDef<T = unknown, H extends RuleEngineHost = RuleEngineHost> = {
schema: CommandSchema;
create: (this: GameContextLike, cmd: Command) => Generator<RuleYield, T, Command | RuleContext<unknown>>;
create: (this: H, cmd: Command) => Generator<RuleYield, T, Command | RuleContext<unknown>>;
};
export type RuleRegistry = Map<string, RuleDef<unknown>>;
export type RuleRegistry = Map<string, RuleDef<unknown, RuleEngineHost>>;
export function createRule<T>(
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: GameContextLike, cmd: Command) => Generator<RuleYield, T, Command | RuleContext<unknown>>
): RuleDef<T> {
fn: (this: H, cmd: Command) => Generator<RuleYield, T, Command | RuleContext<unknown>>
): RuleDef<T, H> {
return {
schema: parseCommandSchema(schemaStr, ''),
create: fn as RuleDef<T>['create'],
create: fn as RuleDef<T, H>['create'],
};
}
function isInvokeYield(value: RuleYield): value is InvokeYield {
return typeof value === 'object' && value !== null && 'type' in value && (value as InvokeYield).type === 'invoke';
}
function parseYieldedSchema(value: string | CommandSchema): CommandSchema {
if (typeof value === 'string') {
return parseCommandSchema(value, '');
@@ -48,31 +47,19 @@ function parseYieldedSchema(value: string | CommandSchema): CommandSchema {
return value;
}
function parseCommandWithSchema(command: Command, schema: CommandSchema): Command {
return applyCommandSchema(command, schema).command;
function addContextToHost(host: RuleEngineHost, ctx: RuleContext<unknown>) {
host.addRuleContext(ctx);
}
function pushContextToGame(game: GameContextLike, ctx: RuleContext<unknown>) {
game.contexts.value = [...game.contexts.value, { value: ctx } as any];
game.addRuleContext(ctx);
}
function discardChildren(game: GameContextLike, parent: RuleContext<unknown>) {
function discardChildren(host: RuleEngineHost, parent: RuleContext<unknown>) {
for (const child of parent.children) {
game.removeRuleContext(child);
const ctxIdx = game.contexts.value.findIndex((c: any) => c.value === child);
if (ctxIdx !== -1) {
const arr = [...game.contexts.value];
arr.splice(ctxIdx, 1);
game.contexts.value = arr;
}
host.removeRuleContext(child);
}
parent.children = [];
parent.state = 'yielded';
}
function validateYieldedSchema(command: Command, schema: CommandSchema): boolean {
function commandMatchesSchema(command: Command, schema: CommandSchema): boolean {
const requiredParams = schema.params.filter(p => p.required);
const variadicParam = schema.params.find(p => p.variadic);
@@ -95,31 +82,93 @@ function validateYieldedSchema(command: Command, schema: CommandSchema): boolean
return true;
}
function invokeChildRule(
game: GameContextLike,
ruleName: string,
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,
parent: RuleContext<unknown>
): RuleContext<unknown> {
const ruleDef = game.rules.get(ruleName)!;
const ctx: RuleContext<unknown> = {
ruleDef: RuleDef<T>,
host: RuleEngineHost,
parent?: RuleContext<unknown>
): RuleContext<T> {
return {
type: ruleDef.schema.name,
schema: undefined,
generator: ruleDef.create.call(game, command),
generator: ruleDef.create.call(host, command),
parent,
children: [],
state: 'running',
resolution: undefined,
};
parent.children.push(ctx);
pushContextToGame(game, ctx);
return stepGenerator(game, ctx);
}
function resumeInvokingParent(
game: GameContextLike,
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;
@@ -128,147 +177,57 @@ function resumeInvokingParent(
parent.children = parent.children.filter(c => c !== childCtx);
const result = parent.generator.next(childCtx);
if (result.done) {
(parent as RuleContext<unknown>).resolution = result.value;
(parent as RuleContext<unknown>).state = 'done';
const resumed = resumeInvokingParent(game, parent);
return resumed ?? parent;
} else if (isInvokeYield(result.value)) {
(parent as RuleContext<unknown>).state = 'invoking';
const childCtx2 = invokeChildRule(game, result.value.rule, result.value.command, parent);
return childCtx2;
} else {
(parent as RuleContext<unknown>).schema = parseYieldedSchema(result.value);
(parent as RuleContext<unknown>).state = 'yielded';
}
const resumed = handleGeneratorResult(host, parent, result);
if (resumed) return resumed;
return parent;
}
function stepGenerator<T>(
game: GameContextLike,
ctx: RuleContext<T>
): RuleContext<T> {
const result = ctx.generator.next();
if (result.done) {
ctx.resolution = result.value;
ctx.state = 'done';
const resumed = resumeInvokingParent(game, ctx as RuleContext<unknown>);
if (resumed) return resumed as RuleContext<T>;
} else if (isInvokeYield(result.value)) {
const childRuleDef = game.rules.get(result.value.rule);
if (childRuleDef) {
ctx.state = 'invoking';
const childCtx = invokeChildRule(game, result.value.rule, result.value.command, ctx as RuleContext<unknown>);
return childCtx as RuleContext<T>;
} else {
ctx.schema = parseYieldedSchema('');
ctx.state = 'yielded';
}
} else {
ctx.schema = parseYieldedSchema(result.value);
ctx.state = 'yielded';
}
return ctx;
}
function invokeRule<T>(
game: GameContextLike,
host: RuleEngineHost,
command: Command,
ruleDef: RuleDef<T>,
parent?: RuleContext<unknown>
): RuleContext<T> {
const ctx: RuleContext<T> = {
type: ruleDef.schema.name,
schema: undefined,
generator: ruleDef.create.call(game, command),
parent,
children: [],
state: 'running',
resolution: undefined,
};
const ctx = createContext(command, ruleDef, host, parent);
if (parent) {
discardChildren(game, parent);
discardChildren(host, parent);
parent.children.push(ctx as RuleContext<unknown>);
parent.state = 'waiting';
}
pushContextToGame(game, ctx as RuleContext<unknown>);
addContextToHost(host, ctx as RuleContext<unknown>);
return stepGenerator(game, ctx);
return stepGenerator(host, ctx);
}
export function dispatchCommand(game: GameContextLike, input: string): RuleContext<unknown> | undefined {
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);
if (game.rules.has(command.name)) {
const ruleDef = game.rules.get(command.name)!;
const typedCommand = parseCommandWithSchema(command, ruleDef.schema);
const parent = findYieldedParent(game);
return invokeRule(game, typedCommand, ruleDef, parent);
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 = game.ruleContexts.length - 1; i >= 0; i--) {
const ctx = game.ruleContexts[i];
if (ctx.state === 'yielded' && ctx.schema) {
if (validateYieldedSchema(command, ctx.schema)) {
const typedCommand = parseCommandWithSchema(command, ctx.schema);
const result = ctx.generator.next(typedCommand);
if (result.done) {
ctx.resolution = result.value;
ctx.state = 'done';
const resumed = resumeInvokingParent(game, ctx);
return resumed ?? ctx;
} else if (isInvokeYield(result.value)) {
ctx.state = 'invoking';
const childCtx = invokeChildRule(game, result.value.rule, result.value.command, ctx);
return childCtx;
} else {
ctx.schema = parseYieldedSchema(result.value);
ctx.state = 'yielded';
}
return ctx;
}
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;
}
function findYieldedParent(game: GameContextLike): RuleContext<unknown> | undefined {
for (let i = game.ruleContexts.length - 1; i >= 0; i--) {
const ctx = game.ruleContexts[i];
if (ctx.state === 'yielded') {
return ctx;
}
}
return undefined;
}
export type GameContextLike = {
rules: RuleRegistry;
ruleContexts: RuleContext<unknown>[];
contexts: { value: any[] };
addRuleContext: (ctx: RuleContext<unknown>) => void;
removeRuleContext: (ctx: RuleContext<unknown>) => void;
parts: {
collection: { value: Record<string, any> };
add: (...entities: any[]) => void;
remove: (...ids: string[]) => void;
get: (id: string) => any;
};
regions: {
collection: { value: Record<string, any> };
add: (...entities: any[]) => void;
remove: (...ids: string[]) => void;
get: (id: string) => any;
};
pushContext: (context: any) => any;
popContext: () => void;
latestContext: <T>(type: string) => any | undefined;
};