feat: add tic-tac-toe with rule invoking rule
This commit is contained in:
+6
-3
@@ -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
@@ -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;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import { GameContextInstance } from '../core/context';
|
||||
import type { GameContextLike, RuleContext } from '../core/rule';
|
||||
import { createRule, type InvokeYield, type RuleYield } from '../core/rule';
|
||||
import type { Command } from '../utils/command';
|
||||
import type { Part } from '../core/part';
|
||||
import type { Region } from '../core/region';
|
||||
import type { Context } from '../core/context';
|
||||
|
||||
export type TicTacToeState = Context & {
|
||||
type: 'tic-tac-toe';
|
||||
currentPlayer: 'X' | 'O';
|
||||
winner: 'X' | 'O' | 'draw' | null;
|
||||
moveCount: number;
|
||||
};
|
||||
|
||||
type TurnResult = {
|
||||
winner: 'X' | 'O' | 'draw' | null;
|
||||
};
|
||||
|
||||
function getBoardRegion(game: GameContextLike) {
|
||||
return game.regions.get('board');
|
||||
}
|
||||
|
||||
function isCellOccupied(game: GameContextLike, row: number, col: number): boolean {
|
||||
const board = getBoardRegion(game);
|
||||
return board.value.children.some(
|
||||
(child: { value: { position: number[] } }) => child.value.position[0] === row && child.value.position[1] === col
|
||||
);
|
||||
}
|
||||
|
||||
function checkWinner(game: GameContextLike): 'X' | 'O' | 'draw' | null {
|
||||
const parts = Object.values(game.parts.collection.value).map((s: { value: Part }) => s.value);
|
||||
|
||||
const xPositions = parts.filter((_: Part, i: number) => i % 2 === 0).map((p: Part) => p.position);
|
||||
const oPositions = parts.filter((_: Part, i: number) => i % 2 === 1).map((p: Part) => p.position);
|
||||
|
||||
if (hasWinningLine(xPositions)) return 'X';
|
||||
if (hasWinningLine(oPositions)) return 'O';
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function hasWinningLine(positions: number[][]): boolean {
|
||||
const lines = [
|
||||
[[0, 0], [0, 1], [0, 2]],
|
||||
[[1, 0], [1, 1], [1, 2]],
|
||||
[[2, 0], [2, 1], [2, 2]],
|
||||
[[0, 0], [1, 0], [2, 0]],
|
||||
[[0, 1], [1, 1], [2, 1]],
|
||||
[[0, 2], [1, 2], [2, 2]],
|
||||
[[0, 0], [1, 1], [2, 2]],
|
||||
[[0, 2], [1, 1], [2, 0]],
|
||||
];
|
||||
|
||||
return lines.some(line =>
|
||||
line.every(([r, c]) =>
|
||||
positions.some(([pr, pc]) => pr === r && pc === c)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function placePiece(game: GameContextLike, row: number, col: number, moveCount: number) {
|
||||
const board = getBoardRegion(game);
|
||||
const piece: Part = {
|
||||
id: `piece-${moveCount}`,
|
||||
sides: 1,
|
||||
side: 0,
|
||||
region: board,
|
||||
position: [row, col],
|
||||
};
|
||||
game.parts.add(piece);
|
||||
board.value.children.push(game.parts.get(piece.id));
|
||||
}
|
||||
|
||||
const playSchema = 'play <player> <row:number> <col:number>';
|
||||
|
||||
export function createSetupRule() {
|
||||
return createRule('start', function*() {
|
||||
this.pushContext({
|
||||
type: 'tic-tac-toe',
|
||||
currentPlayer: 'X',
|
||||
winner: null,
|
||||
moveCount: 0,
|
||||
} as TicTacToeState);
|
||||
|
||||
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;
|
||||
|
||||
while (true) {
|
||||
const yieldValue: InvokeYield = {
|
||||
type: 'invoke',
|
||||
rule: 'turn',
|
||||
command: { name: 'turn', params: [currentPlayer], flags: {}, options: {} } as Command,
|
||||
};
|
||||
const ctx = yield yieldValue as RuleYield;
|
||||
turnResult = (ctx as RuleContext<TurnResult>).resolution;
|
||||
if (turnResult?.winner) break;
|
||||
|
||||
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 };
|
||||
});
|
||||
}
|
||||
|
||||
export function createTurnRule() {
|
||||
return createRule('turn <player>', function*(cmd) {
|
||||
while (true) {
|
||||
const received = yield playSchema;
|
||||
if ('resolution' in received) continue;
|
||||
|
||||
const playCmd = received as Command;
|
||||
if (playCmd.name !== 'play') continue;
|
||||
|
||||
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, row, col)) continue;
|
||||
|
||||
const state = this.latestContext<TicTacToeState>('tic-tac-toe')!;
|
||||
if (state.value.winner) continue;
|
||||
|
||||
placePiece(this, row, col, state.value.moveCount);
|
||||
state.value.moveCount++;
|
||||
|
||||
const winner = checkWinner(this);
|
||||
if (winner) return { winner };
|
||||
|
||||
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 startTicTacToe(game: GameContextInstance) {
|
||||
game.dispatchCommand('start');
|
||||
}
|
||||
Reference in New Issue
Block a user