refactor: rewrite game & tic tac toe
This commit is contained in:
+28
-6
@@ -1,27 +1,49 @@
|
||||
import {createEntityCollection} from "../utils/entity";
|
||||
import {Part} from "./part";
|
||||
import {Region} from "./region";
|
||||
import {CommandRegistry, CommandRunnerContextExport, createCommandRunnerContext, PromptEvent} from "../utils/command";
|
||||
import {
|
||||
Command,
|
||||
CommandRegistry,
|
||||
type CommandRunner, CommandRunnerContext,
|
||||
CommandRunnerContextExport, CommandSchema,
|
||||
createCommandRunnerContext, parseCommandSchema,
|
||||
PromptEvent
|
||||
} from "../utils/command";
|
||||
import {AsyncQueue} from "../utils/async-queue";
|
||||
|
||||
export interface IGameContext {
|
||||
parts: ReturnType<typeof createEntityCollection<Part>>;
|
||||
regions: ReturnType<typeof createEntityCollection<Region>>;
|
||||
commands: CommandRunnerContextExport<IGameContext>;
|
||||
inputs: AsyncQueue<PromptEvent>;
|
||||
prompts: AsyncQueue<PromptEvent>;
|
||||
}
|
||||
|
||||
/**
|
||||
* creates a game context.
|
||||
* expects a command registry already registered with commands.
|
||||
* @param commandRegistry
|
||||
*/
|
||||
export function createGameContext(commandRegistry: CommandRegistry<IGameContext>) {
|
||||
const parts = createEntityCollection<Part>();
|
||||
const regions = createEntityCollection<Region>();
|
||||
const ctx: IGameContext = {
|
||||
parts,
|
||||
regions,
|
||||
commands: null,
|
||||
inputs: new AsyncQueue(),
|
||||
commands: null!,
|
||||
prompts: new AsyncQueue(),
|
||||
};
|
||||
ctx.commands = createCommandRunnerContext(commandRegistry, ctx);
|
||||
ctx.commands.on('prompt', (prompt: PromptEvent) => ctx.inputs.push(prompt));
|
||||
ctx.commands.on('prompt', (prompt: PromptEvent) => ctx.prompts.push(prompt));
|
||||
|
||||
return ctx;
|
||||
}
|
||||
}
|
||||
|
||||
export function createGameCommand<TResult>(
|
||||
schema: CommandSchema | string,
|
||||
run: (this: CommandRunnerContext<IGameContext>, command: Command) => Promise<TResult>
|
||||
): CommandRunner<IGameContext, TResult> {
|
||||
return {
|
||||
schema: typeof schema === 'string' ? parseCommandSchema(schema) : schema,
|
||||
run,
|
||||
};
|
||||
}
|
||||
|
||||
+2
-2
@@ -4,8 +4,8 @@
|
||||
*/
|
||||
|
||||
// Core types
|
||||
export type { Context, GameContextInstance, GameQueueState } from './core/context';
|
||||
export { GameContext, createGameContext } from './core/context';
|
||||
export type { IGameContext } from './core/game';
|
||||
export { createGameContext } from './core/game';
|
||||
|
||||
export type { Part } from './core/part';
|
||||
export { flip, flipTo, roll } from './core/part';
|
||||
|
||||
+57
-82
@@ -1,12 +1,9 @@
|
||||
import { GameContextInstance } from '../core/context';
|
||||
import type { Command, CommandRunner, CommandRunnerContext } from '../utils/command';
|
||||
import { IGameContext } from '../core/game';
|
||||
import {CommandRegistry, CommandRunner, registerCommand} 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';
|
||||
import {createGameCommand} from "../core/game";
|
||||
|
||||
export type TicTacToeState = Context & {
|
||||
type: 'tic-tac-toe';
|
||||
export type TicTacToeState = {
|
||||
currentPlayer: 'X' | 'O';
|
||||
winner: 'X' | 'O' | 'draw' | null;
|
||||
moveCount: number;
|
||||
@@ -16,18 +13,18 @@ type TurnResult = {
|
||||
winner: 'X' | 'O' | 'draw' | null;
|
||||
};
|
||||
|
||||
function getBoardRegion(host: GameContextInstance) {
|
||||
function getBoardRegion(host: IGameContext) {
|
||||
return host.regions.get('board');
|
||||
}
|
||||
|
||||
function isCellOccupied(host: GameContextInstance, row: number, col: number): boolean {
|
||||
function isCellOccupied(host: IGameContext, 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: GameContextInstance): 'X' | 'O' | 'draw' | null {
|
||||
function checkWinner(host: IGameContext): '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);
|
||||
@@ -58,7 +55,7 @@ function hasWinningLine(positions: number[][]): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
function placePiece(host: GameContextInstance, row: number, col: number, moveCount: number) {
|
||||
function placePiece(host: IGameContext, row: number, col: number, moveCount: number) {
|
||||
const board = getBoardRegion(host);
|
||||
const piece: Part = {
|
||||
id: `piece-${moveCount}`,
|
||||
@@ -71,80 +68,58 @@ function placePiece(host: GameContextInstance, row: number, col: number, moveCou
|
||||
board.value.children.push(host.parts.get(piece.id));
|
||||
}
|
||||
|
||||
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);
|
||||
const setup = createGameCommand(
|
||||
'setup',
|
||||
async function() {
|
||||
this.context.regions.add({
|
||||
id: 'board',
|
||||
axes: [
|
||||
{ name: 'x', min: 0, max: 2 },
|
||||
{ name: 'y', min: 0, max: 2 },
|
||||
],
|
||||
children: [],
|
||||
});
|
||||
|
||||
this.context.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 turn = 1;
|
||||
|
||||
let currentPlayer: 'X' | 'O' = 'X';
|
||||
let turnResult: TurnResult | undefined;
|
||||
while (true) {
|
||||
const turnOutput = await this.run<TurnResult>(`turn ${currentPlayer} ${turn++}`);
|
||||
if (!turnOutput.success) throw new Error(turnOutput.error);
|
||||
turnResult = turnOutput?.result.winner;
|
||||
if (turnResult) break;
|
||||
|
||||
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;
|
||||
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
|
||||
}
|
||||
|
||||
currentPlayer = currentPlayer === 'X' ? 'O' : 'X';
|
||||
const state = this.context.latestContext<TicTacToeState>('tic-tac-toe')!;
|
||||
state.value.currentPlayer = currentPlayer;
|
||||
}
|
||||
return { winner: turnResult };
|
||||
}
|
||||
)
|
||||
|
||||
const state = this.context.latestContext<TicTacToeState>('tic-tac-toe')!;
|
||||
state.value.winner = turnResult?.winner ?? null;
|
||||
return { winner: state.value.winner };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
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 row = Number(playCmd.params[1]);
|
||||
const col = Number(playCmd.params[2]);
|
||||
|
||||
if (isNaN(row) || isNaN(col) || row < 0 || row > 2 || col < 0 || col > 2) continue;
|
||||
if (isCellOccupied(this.context, row, col)) continue;
|
||||
|
||||
const state = this.context.latestContext<TicTacToeState>('tic-tac-toe')!;
|
||||
if (state.value.winner) continue;
|
||||
|
||||
placePiece(this.context, row, col, state.value.moveCount);
|
||||
state.value.moveCount++;
|
||||
|
||||
const winner = checkWinner(this.context);
|
||||
if (winner) return { winner };
|
||||
|
||||
if (state.value.moveCount >= 9) return { winner: 'draw' as const };
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function registerTicTacToeCommands(game: GameContextInstance) {
|
||||
game.registerCommand('start', createSetupCommand());
|
||||
game.registerCommand('turn', createTurnCommand());
|
||||
}
|
||||
|
||||
export function startTicTacToe(game: GameContextInstance) {
|
||||
game.dispatchCommand('start');
|
||||
const turn = createGameCommand(
|
||||
'turn <player> <turn:number>',
|
||||
async function(cmd) {
|
||||
const [turnPlayer, turnNumber] = cmd.params as [string, number];
|
||||
while (true) {
|
||||
const playCmd = await this.prompt('play <player> <row:number> <col:number>');
|
||||
const [player, row, col] = playCmd.params as [string, number, number];
|
||||
if(turnPlayer !== player) continue;
|
||||
|
||||
if (isNaN(row) || isNaN(col) || row < 0 || row > 2 || col < 0 || col > 2) continue;
|
||||
if (isCellOccupied(this.context, row, col)) continue;
|
||||
|
||||
placePiece(this.context, row, col, turnNumber);
|
||||
|
||||
const winner = checkWinner(this.context);
|
||||
if (winner) return { winner };
|
||||
|
||||
if (turnNumber >= 9) return { winner: 'draw' as const };
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export function registerTicTacToeCommands(registry: CommandRegistry<IGameContext>) {
|
||||
registerCommand(registry, setup);
|
||||
registerCommand(registry, turn);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user