feat: rng & commands impl & tests

This commit is contained in:
hyper
2026-04-01 17:34:21 +08:00
parent ea337acacb
commit df9698b67b
10 changed files with 835 additions and 221 deletions
+7 -2
View File
@@ -26,7 +26,7 @@ export const GameContext = createModel((root: Context) => {
}
}
}
return {
parts,
regions,
@@ -35,4 +35,9 @@ export const GameContext = createModel((root: Context) => {
popContext,
latestContext,
}
})
})
/** 创建游戏上下文实例 */
export function createGameContext(root: Context = { type: 'game' }) {
return new GameContext(root);
}
+58 -4
View File
@@ -5,7 +5,7 @@ import {RNG} from "../utils/rng";
export type Region = Entity & {
// aligning axes of the region
axes: RegionAxis[];
// current children; expect no overlapped positions
children: EntityAccessor<Part>[];
}
@@ -27,7 +27,49 @@ export type RegionAxis = {
*/
export function applyAlign(region: Region){
for (const axis of region.axes) {
// TODO implement this
if (region.children.length === 0) continue;
// 获取当前轴向上的所有位置
const positions = region.children.map(accessor => accessor.value.position);
// 根据当前轴的位置排序 children
region.children.sort((a, b) => {
const posA = a.value.position[0] ?? 0;
const posB = b.value.position[0] ?? 0;
return posA - posB;
});
if (axis.align === 'start' && axis.min !== undefined) {
// 从 min 开始紧凑排列
region.children.forEach((accessor, index) => {
const currentPos = accessor.value.position.slice();
currentPos[0] = axis.min! + index;
accessor.value.position = currentPos;
});
} else if (axis.align === 'end' && axis.max !== undefined) {
// 从 max 开始向前紧凑排列
const count = region.children.length;
region.children.forEach((accessor, index) => {
const currentPos = accessor.value.position.slice();
currentPos[0] = axis.max! - (count - 1 - index);
accessor.value.position = currentPos;
});
} else if (axis.align === 'center') {
// 居中排列
const count = region.children.length;
const min = axis.min ?? 0;
const max = axis.max ?? count - 1;
const range = max - min;
const center = min + range / 2;
region.children.forEach((accessor, index) => {
const currentPos = accessor.value.position.slice();
// 计算相对于中心的偏移
const offset = index - (count - 1) / 2;
currentPos[0] = center + offset;
accessor.value.position = currentPos;
});
}
}
}
@@ -37,5 +79,17 @@ export function applyAlign(region: Region){
* @param rng
*/
export function shuffle(region: Region, rng: RNG){
// TODO implement this
}
if (region.children.length <= 1) return;
// Fisher-Yates 洗牌算法
const children = [...region.children];
for (let i = children.length - 1; i > 0; i--) {
const j = rng.nextInt(i + 1);
// 交换位置
const posI = children[i].value.position.slice();
const posJ = children[j].value.position.slice();
children[i].value.position = posJ;
children[j].value.position = posI;
}
}
+63 -7
View File
@@ -9,24 +9,80 @@ export type RuleContext<T> = Context & {
resolution?: T;
}
function invokeRuleContext<T>(pushContext: (context: Context) => void, type: string, rule: Generator<string, T, Command>){
/**
* 调用规则生成器并管理其上下文
* @param pushContext - 用于推送上下文到上下文栈的函数
* @param type - 规则类型
* @param rule - 规则生成器函数
* @returns 规则执行结果
*/
export function invokeRuleContext<T>(
pushContext: (context: Context) => void,
type: string,
rule: Generator<string, T, Command>
): RuleContext<T> {
const ctx: RuleContext<T> = {
type,
actions: [],
handledActions: 0,
invocations: [],
resolution: undefined,
}
};
// 执行生成器直到完成或需要等待动作
const executeRule = () => {
try {
const result = rule.next();
if (result.done) {
// 规则执行完成,设置结果
ctx.resolution = result.value;
return;
}
// 如果生成器 yield 了一个动作类型,等待处理
// 这里可以扩展为实际的动作处理逻辑
const actionType = result.value;
// 继续执行直到有动作需要处理或规则完成
if (!result.done) {
executeRule();
}
} catch (error) {
// 规则执行出错,抛出错误
throw error;
}
};
// 使用 effect 来跟踪响应式依赖
const dispose = effect(() => {
if(ctx.resolution) {
if (ctx.resolution !== undefined) {
dispose();
return;
}
executeRule();
});
pushContext(rule);
// 将规则上下文推入栈中
pushContext(ctx);
return ctx;
}
function* rule(){
const play: Command = yield 'play';
}
/**
* 创建一个规则生成器辅助函数
* @param type - 规则类型
* @param fn - 规则逻辑函数
*/
export function createRule<T>(
type: string,
fn: (ctx: RuleContext<T>) => Generator<string, T, Command>
): Generator<string, T, Command> {
return fn({
type,
actions: [],
handledActions: 0,
invocations: [],
resolution: undefined,
});
}
+15 -201
View File
@@ -3,211 +3,25 @@
* 基于 Preact Signals 的桌游状态管理库
*/
// Rules engine
export type {
Rule,
RuleContext,
RuleResult,
ValidationRule,
EffectRule,
TriggerRule,
RuleLogEntry,
} from './rules/Rule';
export {
isValidationRule,
isEffectRule,
isTriggerRule,
createValidationRule,
createEffectRule,
createTriggerRule,
} from './rules/Rule';
export { RuleEngine, createRuleEngine } from './rules/RuleEngine';
export type { RuleEngineOptions, RuleEngineExecutionResult } from './rules/RuleEngine';
export { RuleRegistry, createRuleRegistry } from './rules/RuleRegistry';
export type { RuleGroup } from './rules/RuleRegistry';
// Tic Tac Toe game
export type {
Player,
CellState,
TicTacToeMetadata,
MoveRecord,
WinningLine,
TicTacToeBoardConfig,
} from './games/tictactoe/TicTacToeState';
export {
DEFAULT_BOARD_CONFIG,
getCellId,
parseCellId,
isValidCellId,
getAllCellIds,
getWinningCombinations,
} from './games/tictactoe/TicTacToeState';
export {
validateTurnRule,
validateCellEmptyRule,
validateGameNotEndedRule,
switchTurnRule,
recordMoveHistoryRule,
checkWinConditionRule,
checkDrawConditionRule,
ticTacToeRules,
getTicTacToeValidationRules,
getTicTacToeEffectRules,
getTicTacToeTriggerRules,
createTicTacToeGame,
} from './games/tictactoe';
export {
startGameCommand,
markCellCommand,
resetGameCommand,
setPlayersCommand,
getCellCommand,
ticTacToeCommands,
createMarkCellCommand,
createSetPlayersCommand,
} from './games/tictactoe';
// Core types
export { PartType } from './core/Part';
export type {
Part,
PartBase,
MeeplePart,
CardPart,
TilePart,
PartSignal,
} from './core/Part';
export type { Context } from './core/context';
export { GameContext, createGameContext } from './core/context';
export { RegionType } from './core/Region';
export type { Region, RegionProperties, Slot } from './core/Region';
export type { Part } from './core/part';
export { flip, flipTo, roll } from './core/part';
export type { Placement, PlacementProperties, Position, PlacementSignal } from './core/Placement';
export type { Region, RegionAxis } from './core/region';
export { applyAlign, shuffle } from './core/region';
export type { GameStateData } from './core/GameState';
export type { RuleContext } from './core/rule';
export { invokeRuleContext, createRule } from './core/rule';
// Core classes and functions
export {
createPart,
createMeeple,
createCard,
createTile,
} from './core/Part';
// Utils
export type { Command } from './utils/command';
export { parseCommand } from './utils/command';
export { createRegion, createRegion as createRegionCore } from './core/Region';
export type { Region as RegionClass } from './core/Region';
export type { Entity, EntityAccessor } from './utils/entity';
export { createEntityCollection } from './utils/entity';
export { createPlacement } from './core/Placement';
export { GameState, createGameState } from './core/GameState';
// Part actions
export {
createPartAction,
createMeepleAction,
createCardAction,
createTileAction,
updatePartAction,
removePartAction,
getPartAction,
} from './actions/part.actions';
// Region actions
export {
createRegionAction,
getRegionAction,
removeRegionAction,
addPlacementToRegionAction,
removePlacementFromRegionAction,
setSlotAction,
getSlotAction,
clearRegionAction,
getRegionPlacementCountAction,
isRegionEmptyAction,
isRegionFullAction,
} from './actions/region.actions';
// Placement actions
export {
createPlacementAction,
getPlacementAction,
removePlacementAction,
movePlacementAction,
updatePlacementPositionAction,
updatePlacementRotationAction,
flipPlacementAction,
updatePlacementPartAction,
swapPlacementsAction,
setPlacementFaceAction,
getPlacementsInRegionAction,
getPlacementsOfPartAction,
} from './actions/placement.actions';
// Commands
export {
CommandActionType,
type Command,
type CommandStep,
type CommandExecutionResult,
type CommandLogEntry,
type StepResult,
type CommandStatus,
type QueuedCommand,
} from './commands/Command';
export { CommandExecutor } from './commands/CommandExecutor';
export { CommandLog, createCommandLog } from './commands/CommandLog';
export {
setupGameCommand,
placeMeepleCommand,
moveMeepleCommand,
drawCardCommand,
playCardCommand,
placeTileCommand,
flipTileCommand,
swapPlacementsCommand,
setPhaseCommand,
clearRegionCommand,
defaultCommands,
getDefaultCommand,
} from './commands/default.commands';
// CLI Commands
export {
type CliCommand,
type CliCommandArgs,
type CliCommandResult,
type CliCommandStep,
type ParsedCliCommand,
} from './commands/CliCommand';
export { CommandParser, createCommandParser, CommandParseError } from './commands/CommandParser';
export { CommandRegistry, createCommandRegistry } from './commands/CommandRegistry';
export {
moveCommand,
placeCommand,
flipCommand,
createCommand,
regionCommand,
drawCommand,
shuffleCommand,
discardCommand,
swapCommand,
rotateCommand,
positionCommand,
phaseCommand,
clearCommand,
removeCommand,
helpCommand,
cliCommands,
} from './commands/cli.commands';
export type { RNG } from './utils/rng';
export { createRNG, Mulberry32RNG } from './utils/rng';
+60 -2
View File
@@ -5,6 +5,64 @@
params: string[];
}
// TODO implement this
export function parseCommand(input: string): Command {
/**
* 解析命令行输入字符串为 Command 对象
* 支持格式:commandName [params...] [--flags...] [-o value...]
*
* @example
* parseCommand("move meeple1 region1 --force -x 10")
* // returns { name: "move", params: ["meeple1", "region1"], flags: { force: true }, options: { x: "10" } }
*/
export function parseCommand(input: string): Command {
const tokens = input.trim().split(/\s+/).filter(Boolean);
if (tokens.length === 0) {
return { name: '', flags: {}, options: {}, params: [] };
}
const name = tokens[0];
const params: string[] = [];
const flags: Record<string, true> = {};
const options: Record<string, string> = {};
let i = 1;
while (i < tokens.length) {
const token = tokens[i];
if (token.startsWith('--') && !/^-?\d+$/.test(token)) {
// 长格式标志或选项:--flag 或 --option value
const key = token.slice(2);
const nextToken = tokens[i + 1];
// 如果下一个 token 存在且不以 - 开头(或者是负数),则是选项值
if (nextToken && (!nextToken.startsWith('-') || /^-\d+$/.test(nextToken))) {
options[key] = nextToken;
i += 2;
} else {
// 否则是布尔标志
flags[key] = true;
i++;
}
} else if (token.startsWith('-') && token.length > 1 && !/^-?\d+$/.test(token)) {
// 短格式标志或选项:-f 或 -o value(但不匹配负数)
const key = token.slice(1);
const nextToken = tokens[i + 1];
// 如果下一个 token 存在且不以 - 开头(或者是负数),则是选项值
if (nextToken && (!nextToken.startsWith('-') || /^-\d+$/.test(nextToken))) {
options[key] = nextToken;
i += 2;
} else {
// 否则是布尔标志
flags[key] = true;
i++;
}
} else {
// 普通参数(包括负数)
params.push(token);
i++;
}
}
return { name, flags, options, params };
}
+77 -5
View File
@@ -1,12 +1,84 @@
export interface RNG {
/** 设置随机数种子 */
(seed: number): void;
/** 获取一个[0,1)随机数 */
/** 获取一个 [0,1) 随机数 */
next(max?: number): number;
/** 获取一个[0,max)随机整数 */
/** 获取一个 [0,max) 随机整数 */
nextInt(max: number): number;
}
// TODO: create a RNG implementation with the alea library
/**
* 使用 mulberry32 算法实现的伪随机数生成器
* 这是一个快速、高质量的 32 位 PRNG
*/
export function createRNG(seed?: number): RNG {
let currentSeed: number = seed ?? 1;
function rng(seed: number): void {
currentSeed = seed;
}
rng.next = function(max?: number): number {
let t = (currentSeed += 0x6d2b79f5);
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
const result = ((t ^ (t >>> 14)) >>> 0) / 4294967296;
return max !== undefined ? result * max : result;
};
rng.nextInt = function(max: number): number {
return Math.floor(rng.next(max));
};
(rng as any).setSeed = function(seed: number): void {
currentSeed = seed;
};
(rng as any).getSeed = function(): number {
return currentSeed;
};
return rng;
}
/** Mulberry32RNG 类实现(用于类型兼容) */
export class Mulberry32RNG {
private seed: number = 1;
constructor(seed?: number) {
if (seed !== undefined) {
this.seed = seed;
}
}
/** 设置随机数种子 */
call(seed: number): void {
this.seed = seed;
}
/** 获取一个 [0,1) 随机数 */
next(max?: number): number {
let t = (this.seed += 0x6d2b79f5);
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
const result = ((t ^ (t >>> 14)) >>> 0) / 4294967296;
return max !== undefined ? result * max : result;
}
/** 获取一个 [0,max) 随机整数 */
nextInt(max: number): number {
return Math.floor(this.next(max));
}
/** 重新设置种子 */
setSeed(seed: number): void {
this.seed = seed;
}
/** 获取当前种子 */
getSeed(): number {
return this.seed;
}
}