refactor: replace rule.ts with a command runner based solution
This commit is contained in:
+167
-319
@@ -1,396 +1,244 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createRule, type RuleContext, type RuleEngineHost } from '../../src/core/rule';
|
||||
import { createGameContext } from '../../src/core/context';
|
||||
import type { Command } from '../../src/utils/command';
|
||||
import type { Command, CommandRunner, CommandRunnerContext } from '../../src/utils/command';
|
||||
import { parseCommandSchema } from '../../src/utils/command/schema-parse';
|
||||
|
||||
function isCommand(value: Command | RuleContext<unknown>): value is Command {
|
||||
return 'name' in value;
|
||||
}
|
||||
|
||||
function schema(value: string | { name: string; params: any[]; options: any[]; flags: any[] }) {
|
||||
return { type: 'schema' as const, value };
|
||||
}
|
||||
|
||||
describe('Rule System', () => {
|
||||
describe('Command System', () => {
|
||||
function createTestGame() {
|
||||
const game = createGameContext();
|
||||
return game;
|
||||
}
|
||||
|
||||
describe('createRule', () => {
|
||||
it('should create a rule definition with parsed schema', () => {
|
||||
const rule = createRule('<from> <to> [--force]', function*(cmd) {
|
||||
return { from: cmd.params[0], to: cmd.params[1] };
|
||||
});
|
||||
function createRunner<T = unknown>(
|
||||
schemaStr: string,
|
||||
fn: (this: CommandRunnerContext<any>, cmd: Command) => Promise<T>
|
||||
): CommandRunner<any, T> {
|
||||
return {
|
||||
schema: parseCommandSchema(schemaStr),
|
||||
run: fn,
|
||||
};
|
||||
}
|
||||
|
||||
expect(rule.schema.params).toHaveLength(2);
|
||||
expect(rule.schema.params[0].name).toBe('from');
|
||||
expect(rule.schema.params[0].required).toBe(true);
|
||||
expect(rule.schema.params[1].name).toBe('to');
|
||||
expect(rule.schema.params[1].required).toBe(true);
|
||||
expect(Object.keys(rule.schema.flags)).toHaveLength(1);
|
||||
expect(rule.schema.flags.force.name).toBe('force');
|
||||
});
|
||||
|
||||
it('should create a generator when called', () => {
|
||||
const game = createTestGame();
|
||||
const rule = createRule('<target>', function*(cmd) {
|
||||
return cmd.params[0];
|
||||
});
|
||||
|
||||
const gen = rule.create.call(game as unknown as RuleEngineHost, { name: 'test', params: ['card1'], flags: {}, options: {} });
|
||||
const result = gen.next();
|
||||
expect(result.done).toBe(true);
|
||||
expect(result.value).toBe('card1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('dispatchCommand - rule invocation', () => {
|
||||
it('should invoke a registered rule and yield schema', () => {
|
||||
describe('registerCommand', () => {
|
||||
it('should register and execute a command', async () => {
|
||||
const game = createTestGame();
|
||||
|
||||
game.registerRule('move', createRule('<from> <to>', function*(cmd) {
|
||||
yield schema({ name: '', params: [], options: [], flags: [] });
|
||||
return { moved: cmd.params[0] };
|
||||
}));
|
||||
|
||||
const ctx = game.dispatchCommand('move card1 hand');
|
||||
|
||||
expect(ctx).toBeDefined();
|
||||
expect(ctx!.state).toBe('yielded');
|
||||
expect(ctx!.schema).toBeDefined();
|
||||
expect(ctx!.resolution).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should complete a rule when final command matches yielded schema', () => {
|
||||
const game = createTestGame();
|
||||
|
||||
game.registerRule('move', createRule('<from> <to>', function*(cmd) {
|
||||
const confirm = yield schema({ name: '', params: [], options: [], flags: [] });
|
||||
const confirmCmd = isCommand(confirm) ? confirm : undefined;
|
||||
return { moved: cmd.params[0], confirmed: confirmCmd?.name === 'confirm' };
|
||||
}));
|
||||
|
||||
game.dispatchCommand('move card1 hand');
|
||||
const ctx = game.dispatchCommand('confirm');
|
||||
|
||||
expect(ctx).toBeDefined();
|
||||
expect(ctx!.state).toBe('done');
|
||||
expect(ctx!.resolution).toEqual({ moved: 'card1', confirmed: true });
|
||||
});
|
||||
|
||||
it('should return undefined when command matches no rule and no yielded context', () => {
|
||||
const game = createTestGame();
|
||||
|
||||
const result = game.dispatchCommand('unknown command');
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should pass the initial command to the generator', () => {
|
||||
const game = createTestGame();
|
||||
|
||||
game.registerRule('attack', createRule('<target> [--power: number]', function*(cmd) {
|
||||
return { target: cmd.params[0], power: cmd.options.power || '1' };
|
||||
}));
|
||||
|
||||
const ctx = game.dispatchCommand('attack goblin --power 5');
|
||||
|
||||
expect(ctx!.state).toBe('done');
|
||||
expect(ctx!.resolution).toEqual({ target: 'goblin', power: 5 });
|
||||
});
|
||||
|
||||
it('should complete immediately if generator does not yield', () => {
|
||||
const game = createTestGame();
|
||||
|
||||
game.registerRule('look', createRule('[--at]', function*() {
|
||||
game.registerCommand('look', createRunner('[--at]', async () => {
|
||||
return 'looked';
|
||||
}));
|
||||
|
||||
const ctx = game.dispatchCommand('look');
|
||||
game.enqueue('look');
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
|
||||
expect(ctx!.state).toBe('done');
|
||||
expect(ctx!.resolution).toBe('looked');
|
||||
expect(game.commandRegistry.value.has('look')).toBe(true);
|
||||
});
|
||||
|
||||
it('should return error for unknown command', async () => {
|
||||
const game = createTestGame();
|
||||
|
||||
game.enqueue('unknown command');
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
});
|
||||
});
|
||||
|
||||
describe('dispatchCommand - rule priority', () => {
|
||||
it('should prioritize new rule invocation over feeding yielded context', () => {
|
||||
describe('prompt and queue resolution', () => {
|
||||
it('should resolve prompt from queue input', async () => {
|
||||
const game = createTestGame();
|
||||
let promptReceived: Command | null = null;
|
||||
|
||||
game.registerRule('move', createRule('<from> <to>', function*(cmd) {
|
||||
yield schema({ name: '', params: [], options: [], flags: [] });
|
||||
return { moved: cmd.params[0] };
|
||||
game.registerCommand('move', createRunner('<from> <to>', async function(this: CommandRunnerContext<any>, cmd) {
|
||||
const confirm = await this.prompt('confirm');
|
||||
promptReceived = confirm;
|
||||
return { moved: cmd.params[0], confirmed: confirm.name };
|
||||
}));
|
||||
|
||||
game.registerRule('confirm', createRule('', function*() {
|
||||
return 'new confirm rule';
|
||||
game.enqueueAll([
|
||||
'move card1 hand',
|
||||
'confirm',
|
||||
]);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
expect(promptReceived).not.toBeNull();
|
||||
expect(promptReceived!.name).toBe('confirm');
|
||||
});
|
||||
|
||||
it('should handle multiple prompts in sequence', async () => {
|
||||
const game = createTestGame();
|
||||
const prompts: Command[] = [];
|
||||
|
||||
game.registerCommand('multi', createRunner('<start>', async function() {
|
||||
const a = await this.prompt('<value>');
|
||||
prompts.push(a);
|
||||
const b = await this.prompt('<value>');
|
||||
prompts.push(b);
|
||||
return { a: a.params[0], b: b.params[0] };
|
||||
}));
|
||||
|
||||
game.dispatchCommand('move card1 hand');
|
||||
game.enqueueAll([
|
||||
'multi init',
|
||||
'first',
|
||||
'second',
|
||||
]);
|
||||
|
||||
const ctx = game.dispatchCommand('confirm');
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
expect(ctx!.state).toBe('done');
|
||||
expect(ctx!.resolution).toBe('new confirm rule');
|
||||
expect(ctx!.type).toBe('');
|
||||
expect(prompts).toHaveLength(2);
|
||||
expect(prompts[0].params[0]).toBe('first');
|
||||
expect(prompts[1].params[0]).toBe('second');
|
||||
});
|
||||
|
||||
it('should handle command that completes without prompting', async () => {
|
||||
const game = createTestGame();
|
||||
let executed = false;
|
||||
|
||||
game.registerCommand('attack', createRunner('<target> [--power: number]', async function(cmd) {
|
||||
executed = true;
|
||||
return { target: cmd.params[0], power: cmd.options.power || '1' };
|
||||
}));
|
||||
|
||||
game.enqueue('attack goblin --power 5');
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
|
||||
expect(executed).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('dispatchCommand - fallback to yielded context', () => {
|
||||
it('should feed a yielded context when command does not match any rule', () => {
|
||||
describe('nested command execution', () => {
|
||||
it('should allow a command to run another command', async () => {
|
||||
const game = createTestGame();
|
||||
let childResult: unknown;
|
||||
|
||||
game.registerRule('move', createRule('<from> <to>', function*(cmd) {
|
||||
const response = yield schema({ name: '', params: [], options: [], flags: [] });
|
||||
const rcmd = isCommand(response) ? response : undefined;
|
||||
return { moved: cmd.params[0], response: rcmd?.name };
|
||||
game.registerCommand('child', createRunner('<arg>', async (cmd) => {
|
||||
return `child:${cmd.params[0]}`;
|
||||
}));
|
||||
|
||||
game.dispatchCommand('move card1 hand');
|
||||
const ctx = game.dispatchCommand('yes');
|
||||
game.registerCommand('parent', createRunner('<action>', async function() {
|
||||
const output = await this.run('child test_arg');
|
||||
if (!output.success) throw new Error(output.error);
|
||||
childResult = output.result;
|
||||
return `parent:${output.result}`;
|
||||
}));
|
||||
|
||||
expect(ctx!.state).toBe('done');
|
||||
expect(ctx!.resolution).toEqual({ moved: 'card1', response: 'yes' });
|
||||
game.enqueue('parent start');
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
expect(childResult).toBe('child:test_arg');
|
||||
});
|
||||
|
||||
it('should skip non-matching commands for yielded context', () => {
|
||||
it('should handle nested commands with prompts', async () => {
|
||||
const game = createTestGame();
|
||||
let childPromptResult: Command | null = null;
|
||||
|
||||
game.registerRule('move', createRule('<from> <to>', function*(cmd) {
|
||||
const response = yield schema('<item>');
|
||||
const rcmd = isCommand(response) ? response : undefined;
|
||||
return { response: rcmd?.params[0] };
|
||||
game.registerCommand('child', createRunner('<target>', async function() {
|
||||
const confirm = await this.prompt('yes | no');
|
||||
childPromptResult = confirm;
|
||||
return `child:${confirm.name}`;
|
||||
}));
|
||||
|
||||
game.dispatchCommand('move card1 hand');
|
||||
|
||||
const ctx = game.dispatchCommand('goblin');
|
||||
|
||||
expect(ctx).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should validate command against yielded schema', () => {
|
||||
const game = createTestGame();
|
||||
|
||||
game.registerRule('trade', createRule('<from> <to>', function*(cmd) {
|
||||
const response = yield schema('<item> [amount: number]');
|
||||
const rcmd = isCommand(response) ? response : undefined;
|
||||
return { traded: rcmd?.params[0] };
|
||||
game.registerCommand('parent', createRunner('<action>', async function() {
|
||||
const output = await this.run('child target1');
|
||||
if (!output.success) throw new Error(output.error);
|
||||
return `parent:${output.result}`;
|
||||
}));
|
||||
|
||||
game.dispatchCommand('trade player1 player2');
|
||||
const ctx = game.dispatchCommand('offer gold 5');
|
||||
game.enqueueAll([
|
||||
'parent start',
|
||||
'yes',
|
||||
]);
|
||||
|
||||
expect(ctx!.state).toBe('done');
|
||||
expect(ctx!.resolution).toEqual({ traded: 'gold' });
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
expect(childPromptResult).not.toBeNull();
|
||||
expect(childPromptResult!.name).toBe('yes');
|
||||
});
|
||||
});
|
||||
|
||||
describe('dispatchCommand - deepest context first', () => {
|
||||
it('should feed the deepest yielded context', () => {
|
||||
describe('enqueueAll for action log replay', () => {
|
||||
it('should process all inputs in order', async () => {
|
||||
const game = createTestGame();
|
||||
const results: string[] = [];
|
||||
|
||||
game.registerRule('parent', createRule('<action>', function*() {
|
||||
yield schema({ name: '', params: [], options: [], flags: [] });
|
||||
return 'parent done';
|
||||
game.registerCommand('step', createRunner('<value>', async (cmd) => {
|
||||
results.push(cmd.params[0] as string);
|
||||
return cmd.params[0];
|
||||
}));
|
||||
|
||||
game.registerRule('child', createRule('<target>', function*() {
|
||||
yield schema({ name: '', params: [], options: [], flags: [] });
|
||||
return 'child done';
|
||||
game.enqueueAll([
|
||||
'step one',
|
||||
'step two',
|
||||
'step three',
|
||||
]);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
expect(results).toEqual(['one', 'two', 'three']);
|
||||
});
|
||||
|
||||
it('should buffer inputs and resolve prompts automatically', async () => {
|
||||
const game = createTestGame();
|
||||
let prompted: Command | null = null;
|
||||
|
||||
game.registerCommand('interactive', createRunner('<start>', async function() {
|
||||
const response = await this.prompt('<reply>');
|
||||
prompted = response;
|
||||
return { start: 'start', reply: response.params[0] };
|
||||
}));
|
||||
|
||||
game.dispatchCommand('parent start');
|
||||
game.dispatchCommand('child target1');
|
||||
game.enqueueAll([
|
||||
'interactive begin',
|
||||
'hello',
|
||||
]);
|
||||
|
||||
const ctx = game.dispatchCommand('grandchild_cmd');
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
expect(ctx!.state).toBe('done');
|
||||
expect(ctx!.resolution).toBe('child done');
|
||||
expect(prompted).not.toBeNull();
|
||||
expect(prompted!.params[0]).toBe('hello');
|
||||
});
|
||||
});
|
||||
|
||||
describe('nested rule invocations', () => {
|
||||
it('should link child to parent', () => {
|
||||
describe('command schema validation', () => {
|
||||
it('should reject commands that do not match schema', async () => {
|
||||
const game = createTestGame();
|
||||
let errors: string[] = [];
|
||||
|
||||
game.registerRule('parent', createRule('<action>', function*() {
|
||||
yield schema('child_cmd');
|
||||
return 'parent done';
|
||||
game.registerCommand('strict', createRunner('<required>', async () => {
|
||||
return 'ok';
|
||||
}));
|
||||
|
||||
game.registerRule('child_cmd', createRule('<target>', function*() {
|
||||
return 'child done';
|
||||
}));
|
||||
|
||||
game.dispatchCommand('parent start');
|
||||
const parentCtx = game.ruleContexts.value[0];
|
||||
|
||||
game.dispatchCommand('child_cmd target1');
|
||||
|
||||
expect(parentCtx.state).toBe('waiting');
|
||||
|
||||
const childCtx = game.ruleContexts.value[1];
|
||||
expect(childCtx.parent).toBe(parentCtx);
|
||||
expect(parentCtx.children).toContain(childCtx);
|
||||
});
|
||||
|
||||
it('should discard previous children when a new child is invoked', () => {
|
||||
const game = createTestGame();
|
||||
|
||||
game.registerRule('parent', createRule('<action>', function*() {
|
||||
yield schema('child_a | child_b');
|
||||
return 'parent done';
|
||||
}));
|
||||
|
||||
game.registerRule('child_a', createRule('<target>', function*() {
|
||||
return 'child_a done';
|
||||
}));
|
||||
|
||||
game.registerRule('child_b', createRule('<target>', function*() {
|
||||
return 'child_b done';
|
||||
}));
|
||||
|
||||
game.dispatchCommand('parent start');
|
||||
game.dispatchCommand('child_a target1');
|
||||
|
||||
expect(game.ruleContexts.value.length).toBe(2);
|
||||
|
||||
const oldParent = game.ruleContexts.value[0];
|
||||
expect(oldParent.children).toHaveLength(1);
|
||||
|
||||
game.dispatchCommand('parent start');
|
||||
game.dispatchCommand('child_b target2');
|
||||
|
||||
const newParent = game.ruleContexts.value[2];
|
||||
expect(newParent.children).toHaveLength(1);
|
||||
expect(newParent.children[0].resolution).toBe('child_b done');
|
||||
});
|
||||
});
|
||||
|
||||
describe('context tracking', () => {
|
||||
it('should track rule contexts in ruleContexts signal', () => {
|
||||
const game = createTestGame();
|
||||
|
||||
game.registerRule('test', createRule('<arg>', function*() {
|
||||
yield schema({ name: '', params: [], options: [], flags: [] });
|
||||
return 'done';
|
||||
}));
|
||||
|
||||
expect(game.ruleContexts.value.length).toBe(0);
|
||||
|
||||
game.dispatchCommand('test arg1');
|
||||
|
||||
expect(game.ruleContexts.value.length).toBe(1);
|
||||
expect(game.ruleContexts.value[0].state).toBe('yielded');
|
||||
});
|
||||
});
|
||||
|
||||
describe('error handling', () => {
|
||||
it('should leave context in place when generator throws', () => {
|
||||
const game = createTestGame();
|
||||
|
||||
game.registerRule('failing', createRule('<arg>', function*() {
|
||||
throw new Error('rule error');
|
||||
}));
|
||||
|
||||
expect(() => game.dispatchCommand('failing arg1')).toThrow('rule error');
|
||||
|
||||
expect(game.ruleContexts.value.length).toBe(1);
|
||||
});
|
||||
|
||||
it('should leave children in place when child generator throws', () => {
|
||||
const game = createTestGame();
|
||||
|
||||
game.registerRule('parent', createRule('<action>', function*() {
|
||||
yield schema('child');
|
||||
return 'parent done';
|
||||
}));
|
||||
|
||||
game.registerRule('child', createRule('<target>', function*() {
|
||||
throw new Error('child error');
|
||||
}));
|
||||
|
||||
game.dispatchCommand('parent start');
|
||||
expect(() => game.dispatchCommand('child target1')).toThrow('child error');
|
||||
|
||||
expect(game.ruleContexts.value.length).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('schema yielding', () => {
|
||||
it('should accept a CommandSchema object as yield value', () => {
|
||||
const game = createTestGame();
|
||||
|
||||
const customSchema = {
|
||||
name: 'custom',
|
||||
params: [{ name: 'x', required: true, variadic: false }],
|
||||
options: [],
|
||||
flags: [],
|
||||
const originalError = console.error;
|
||||
console.error = (...args: unknown[]) => {
|
||||
errors.push(String(args[0]));
|
||||
};
|
||||
|
||||
game.registerRule('test', createRule('<arg>', function*() {
|
||||
const cmd = yield schema(customSchema);
|
||||
const rcmd = isCommand(cmd) ? cmd : undefined;
|
||||
return { received: rcmd?.params[0] };
|
||||
}));
|
||||
game.enqueue('strict');
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
|
||||
game.dispatchCommand('test val1');
|
||||
const ctx = game.dispatchCommand('custom hello');
|
||||
console.error = originalError;
|
||||
|
||||
expect(ctx!.state).toBe('done');
|
||||
expect(ctx!.resolution).toEqual({ received: 'hello' });
|
||||
});
|
||||
|
||||
it('should parse string schema on each yield', () => {
|
||||
const game = createTestGame();
|
||||
|
||||
game.registerRule('multi', createRule('<start>', function*() {
|
||||
const a = yield schema('<value>');
|
||||
const b = yield schema('<value>');
|
||||
const acmd = isCommand(a) ? a : undefined;
|
||||
const bcmd = isCommand(b) ? b : undefined;
|
||||
return { a: acmd?.params[0], b: bcmd?.params[0] };
|
||||
}));
|
||||
|
||||
game.dispatchCommand('multi init');
|
||||
game.dispatchCommand('cmd first');
|
||||
const ctx = game.dispatchCommand('cmd second');
|
||||
|
||||
expect(ctx!.state).toBe('done');
|
||||
expect(ctx!.resolution).toEqual({ a: 'first', b: 'second' });
|
||||
expect(errors.some(e => e.includes('Unknown') || e.includes('error'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('complex flow', () => {
|
||||
it('should handle a multi-step game flow', () => {
|
||||
describe('context management', () => {
|
||||
it('should push and pop contexts', () => {
|
||||
const game = createTestGame();
|
||||
|
||||
game.registerRule('start', createRule('<player>', function*(cmd) {
|
||||
const player = cmd.params[0];
|
||||
const action = yield schema({ name: '', params: [], options: [], flags: [] });
|
||||
game.pushContext({ type: 'sub-game' });
|
||||
expect(game.contexts.value.length).toBe(2);
|
||||
|
||||
if (isCommand(action)) {
|
||||
if (action.name === 'move') {
|
||||
yield schema('<target>');
|
||||
} else if (action.name === 'attack') {
|
||||
yield schema('<target> [--power: number]');
|
||||
}
|
||||
}
|
||||
game.popContext();
|
||||
expect(game.contexts.value.length).toBe(1);
|
||||
});
|
||||
|
||||
return { player, action: isCommand(action) ? action.name : '' };
|
||||
}));
|
||||
it('should find latest context by type', () => {
|
||||
const game = createTestGame();
|
||||
|
||||
const ctx1 = game.dispatchCommand('start alice');
|
||||
expect(ctx1!.state).toBe('yielded');
|
||||
game.pushContext({ type: 'sub-game' });
|
||||
const found = game.latestContext('sub-game');
|
||||
|
||||
const ctx2 = game.dispatchCommand('attack');
|
||||
expect(ctx2!.state).toBe('yielded');
|
||||
|
||||
const ctx3 = game.dispatchCommand('attack goblin --power 3');
|
||||
expect(ctx3!.state).toBe('done');
|
||||
expect(ctx3!.resolution).toEqual({ player: 'alice', action: 'attack' });
|
||||
expect(found).toBeDefined();
|
||||
expect(found!.value.type).toBe('sub-game');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createGameContext } from '../../src/core/context';
|
||||
import { registerTicTacToeRules, startTicTacToe, type TicTacToeState } from '../../src/samples/tic-tac-toe';
|
||||
import { registerTicTacToeCommands, startTicTacToe, type TicTacToeState } from '../../src/samples/tic-tac-toe';
|
||||
|
||||
describe('Tic-Tac-Toe', () => {
|
||||
function createGame() {
|
||||
const game = createGameContext();
|
||||
registerTicTacToeRules(game);
|
||||
registerTicTacToeCommands(game);
|
||||
return game;
|
||||
}
|
||||
|
||||
@@ -13,9 +13,10 @@ describe('Tic-Tac-Toe', () => {
|
||||
return game.latestContext<TicTacToeState>('tic-tac-toe')!.value;
|
||||
}
|
||||
|
||||
it('should initialize the board and start the game', () => {
|
||||
it('should initialize the board and start the game', async () => {
|
||||
const game = createGame();
|
||||
startTicTacToe(game);
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
const state = getBoardState(game);
|
||||
expect(state.currentPlayer).toBe('X');
|
||||
@@ -28,95 +29,117 @@ describe('Tic-Tac-Toe', () => {
|
||||
expect(board.value.axes[1].name).toBe('y');
|
||||
});
|
||||
|
||||
it('should play moves and determine a winner', () => {
|
||||
it('should play moves and determine a winner', async () => {
|
||||
const game = createGame();
|
||||
startTicTacToe(game);
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
// X wins with column 0
|
||||
game.dispatchCommand('play X 0 0');
|
||||
game.dispatchCommand('play O 0 1');
|
||||
game.dispatchCommand('play X 1 0');
|
||||
game.dispatchCommand('play O 1 1');
|
||||
game.dispatchCommand('play X 2 0');
|
||||
game.enqueueAll([
|
||||
'play X 0 0',
|
||||
'play O 0 1',
|
||||
'play X 1 0',
|
||||
'play O 1 1',
|
||||
'play X 2 0',
|
||||
]);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
|
||||
const state = getBoardState(game);
|
||||
expect(state.winner).toBe('X');
|
||||
expect(state.moveCount).toBe(5);
|
||||
});
|
||||
|
||||
it('should reject out-of-bounds moves', () => {
|
||||
it('should reject out-of-bounds moves', async () => {
|
||||
const game = createGame();
|
||||
startTicTacToe(game);
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
const beforeCount = getBoardState(game).moveCount;
|
||||
|
||||
game.dispatchCommand('play X 5 5');
|
||||
game.dispatchCommand('play X -1 0');
|
||||
game.dispatchCommand('play X 3 3');
|
||||
game.enqueueAll([
|
||||
'play X 5 5',
|
||||
'play X -1 0',
|
||||
'play X 3 3',
|
||||
]);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
|
||||
expect(getBoardState(game).moveCount).toBe(beforeCount);
|
||||
});
|
||||
|
||||
it('should reject moves on occupied cells', () => {
|
||||
it('should reject moves on occupied cells', async () => {
|
||||
const game = createGame();
|
||||
startTicTacToe(game);
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
game.dispatchCommand('play X 1 1');
|
||||
game.enqueue('play X 1 1');
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
expect(getBoardState(game).moveCount).toBe(1);
|
||||
|
||||
// Try to play on the same cell
|
||||
game.dispatchCommand('play O 1 1');
|
||||
game.enqueue('play O 1 1');
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
expect(getBoardState(game).moveCount).toBe(1);
|
||||
});
|
||||
|
||||
it('should ignore moves after game is over', () => {
|
||||
it('should ignore moves after game is over', async () => {
|
||||
const game = createGame();
|
||||
startTicTacToe(game);
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
// X wins
|
||||
game.dispatchCommand('play X 0 0');
|
||||
game.dispatchCommand('play O 0 1');
|
||||
game.dispatchCommand('play X 1 0');
|
||||
game.dispatchCommand('play O 1 1');
|
||||
game.dispatchCommand('play X 2 0');
|
||||
game.enqueueAll([
|
||||
'play X 0 0',
|
||||
'play O 0 1',
|
||||
'play X 1 0',
|
||||
'play O 1 1',
|
||||
'play X 2 0',
|
||||
]);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
|
||||
expect(getBoardState(game).winner).toBe('X');
|
||||
const moveCountAfterWin = getBoardState(game).moveCount;
|
||||
|
||||
// Try to play more
|
||||
game.dispatchCommand('play X 2 1');
|
||||
game.dispatchCommand('play O 2 2');
|
||||
game.enqueueAll([
|
||||
'play X 2 1',
|
||||
'play O 2 2',
|
||||
]);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
|
||||
expect(getBoardState(game).moveCount).toBe(moveCountAfterWin);
|
||||
});
|
||||
|
||||
it('should detect a draw', () => {
|
||||
it('should detect a draw', async () => {
|
||||
const game = createGame();
|
||||
startTicTacToe(game);
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
// Fill board with no winner (cat's game)
|
||||
// X: (1,1), (0,2), (2,2), (1,0), (2,1)
|
||||
// O: (0,0), (2,0), (0,1), (1,2)
|
||||
game.dispatchCommand('play X 1 1'); // X
|
||||
game.dispatchCommand('play O 0 0'); // O
|
||||
game.dispatchCommand('play X 0 2'); // X
|
||||
game.dispatchCommand('play O 2 0'); // O
|
||||
game.dispatchCommand('play X 2 2'); // X
|
||||
game.dispatchCommand('play O 0 1'); // O
|
||||
game.dispatchCommand('play X 1 0'); // X
|
||||
game.dispatchCommand('play O 1 2'); // O
|
||||
game.dispatchCommand('play X 2 1'); // X (last move, draw)
|
||||
game.enqueueAll([
|
||||
'play X 1 1',
|
||||
'play O 0 0',
|
||||
'play X 0 2',
|
||||
'play O 2 0',
|
||||
'play X 2 2',
|
||||
'play O 0 1',
|
||||
'play X 1 0',
|
||||
'play O 1 2',
|
||||
'play X 2 1',
|
||||
]);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, 300));
|
||||
|
||||
const state = getBoardState(game);
|
||||
expect(state.winner).toBe('draw');
|
||||
expect(state.moveCount).toBe(9);
|
||||
});
|
||||
|
||||
it('should place parts on the board region at correct positions', () => {
|
||||
it('should place parts on the board region at correct positions', async () => {
|
||||
const game = createGame();
|
||||
startTicTacToe(game);
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
game.dispatchCommand('play X 1 2');
|
||||
game.enqueue('play X 1 2');
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
const board = game.regions.get('board');
|
||||
expect(board.value.children).toHaveLength(1);
|
||||
|
||||
Reference in New Issue
Block a user