refactor: replace rule.ts with a command runner based solution
This commit is contained in:
+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) {
|
||||
|
||||
Reference in New Issue
Block a user