feat: add tic-tac-toe with rule invoking rule

This commit is contained in:
2026-04-01 23:58:07 +08:00
parent dbd2a25185
commit b33c901c11
5 changed files with 464 additions and 32 deletions
+6 -3
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, dispatchCommand as dispatchRuleCommand} from "./rule";
import {RuleDef, RuleRegistry, RuleContext, GameContextLike, dispatchCommand as dispatchRuleCommand} from "./rule";
export type Context = {
type: string;
@@ -57,8 +57,9 @@ export const GameContext = createModel((root: Context) => {
ruleContexts.value = ruleContexts.value.filter(c => c !== ctx);
}
function dispatchCommand(input: string) {
function dispatchCommand(this: GameContextLike, input: string) {
return dispatchRuleCommand({
...this,
rules: rules.value,
ruleContexts: ruleContexts.value,
contexts,
@@ -82,7 +83,9 @@ export const GameContext = createModel((root: Context) => {
}
})
/** 创建游戏上下文实例 */
/** 创建游æˆä¸Šä¸‹æ–‡å®žä¾?*/
export function createGameContext(root: Context = { type: 'game' }) {
return new GameContext(root);
}
export type GameContextInstance = ReturnType<typeof createGameContext>;
+148 -16
View File
@@ -1,11 +1,20 @@
import {Command, CommandSchema, parseCommand, parseCommandSchema} from "../utils/command";
import { defineSchema, type ParseError } from 'inline-schema';
export type RuleState = 'running' | 'yielded' | 'waiting' | 'done';
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 RuleContext<T = unknown> = {
type: string;
schema?: CommandSchema;
generator: Generator<string | CommandSchema, T, Command>;
generator: Generator<RuleYield, T, Command | RuleContext<unknown>>;
parent?: RuleContext<unknown>;
children: RuleContext<unknown>[];
state: RuleState;
@@ -14,14 +23,14 @@ export type RuleContext<T = unknown> = {
export type RuleDef<T = unknown> = {
schema: CommandSchema;
create: (cmd: Command) => Generator<string | CommandSchema, T, Command>;
create: (this: GameContextLike, cmd: Command) => Generator<RuleYield, T, Command | RuleContext<unknown>>;
};
export type RuleRegistry = Map<string, RuleDef<unknown>>;
export function createRule<T>(
schemaStr: string,
fn: (cmd: Command) => Generator<string | CommandSchema, T, Command>
fn: (this: GameContextLike, cmd: Command) => Generator<RuleYield, T, Command | RuleContext<unknown>>
): RuleDef<T> {
return {
schema: parseCommandSchema(schemaStr, ''),
@@ -29,6 +38,10 @@ export function createRule<T>(
};
}
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, '');
@@ -36,6 +49,34 @@ function parseYieldedSchema(value: string | CommandSchema): CommandSchema {
return value;
}
function parseCommandWithSchema(command: Command, schema: CommandSchema): Command {
const parsedParams: unknown[] = [...command.params];
for (let i = 0; i < command.params.length; i++) {
const paramSchema = schema.params[i]?.schema;
if (paramSchema && typeof command.params[i] === 'string') {
try {
parsedParams[i] = paramSchema.parse(command.params[i] as string);
} catch {
// keep original value
}
}
}
const parsedOptions: Record<string, unknown> = { ...command.options };
for (const [key, value] of Object.entries(command.options)) {
const optSchema = schema.options.find(o => o.name === key || o.short === key);
if (optSchema?.schema && typeof value === 'string') {
try {
parsedOptions[key] = optSchema.schema.parse(value);
} catch {
// keep original value
}
}
}
return { ...command, params: parsedParams, options: parsedOptions };
}
function pushContextToGame(game: GameContextLike, ctx: RuleContext<unknown>) {
game.contexts.value = [...game.contexts.value, { value: ctx } as any];
game.addRuleContext(ctx);
@@ -79,6 +120,85 @@ function validateYieldedSchema(command: Command, schema: CommandSchema): boolean
return true;
}
function invokeChildRule(
game: GameContextLike,
ruleName: string,
command: Command,
parent: RuleContext<unknown>
): RuleContext<unknown> {
const ruleDef = game.rules.get(ruleName)!;
const ctx: RuleContext<unknown> = {
type: ruleDef.schema.name,
schema: undefined,
generator: ruleDef.create.call(game, command),
parent,
children: [],
state: 'running',
resolution: undefined,
};
parent.children.push(ctx);
pushContextToGame(game, ctx);
return stepGenerator(game, ctx);
}
function resumeInvokingParent(
game: GameContextLike,
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);
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';
}
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,
command: Command,
@@ -88,7 +208,7 @@ function invokeRule<T>(
const ctx: RuleContext<T> = {
type: ruleDef.schema.name,
schema: undefined,
generator: ruleDef.create(command),
generator: ruleDef.create.call(game, command),
parent,
children: [],
state: 'running',
@@ -103,16 +223,7 @@ function invokeRule<T>(
pushContextToGame(game, ctx as RuleContext<unknown>);
const result = ctx.generator.next();
if (result.done) {
ctx.resolution = result.value;
ctx.state = 'done';
} else {
ctx.schema = parseYieldedSchema(result.value);
ctx.state = 'yielded';
}
return ctx;
return stepGenerator(game, ctx);
}
export function dispatchCommand(game: GameContextLike, input: string): RuleContext<unknown> | undefined {
@@ -134,6 +245,12 @@ export function dispatchCommand(game: GameContextLike, input: string): RuleConte
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';
@@ -156,10 +273,25 @@ function findYieldedParent(game: GameContextLike): RuleContext<unknown> | undefi
return undefined;
}
type GameContextLike = {
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;
};