ttrpg-tools/src/components/md-commander/hooks/useDiceRoller.ts

87 lines
1.8 KiB
TypeScript

import { roll as rollDice } from "./dice-engine";
export interface DiceRollerResult {
formula: string;
result: {
total: number;
detail: string;
plainDetail: string;
pools: Array<{
rolls: number[];
keptRolls: number[];
subtotal: number;
}>;
};
success: boolean;
error?: string;
}
/**
* 骰子引擎 Hook
* 提供高级骰子功能:骰池、修饰符、组合等
*/
/**
* 执行掷骰
* @param formula 骰子公式,支持:
* - 3d6: 标准骰子
* - {d4, d8, 2d6}: 骰池字面量
* - kh2/dl1: 修饰符
* - +: 组合骰池
* - -: 负数组合
* - 5: 固定数字
*/
export function rollFormula(formula: string): DiceRollerResult {
try {
const result = rollDice(formula);
return {
formula,
result: {
total: result.total,
detail: result.detail,
plainDetail: result.plainDetail,
pools: result.pools.map((pool) => ({
rolls: pool.rolls.map((r) => r.value),
keptRolls: pool.keptRolls.map((r) => r.value),
subtotal: pool.subtotal,
})),
},
success: true,
};
} catch (e) {
return {
formula,
result: {
total: 0,
detail: "",
plainDetail: "",
pools: [],
},
success: false,
error: e instanceof Error ? e.message : String(e),
};
}
}
/**
* 简化版掷骰,返回 HTML 格式结果
* 格式:[1] [2] [3] = <strong>6</strong>
*/
export function rollSimple(formula: string): {
text: string;
isHtml?: boolean;
} {
try {
const result = rollDice(formula);
return {
text: result.detail,
isHtml: true, // detail 包含 HTML
};
} catch (e) {
return {
text: `错误:${e instanceof Error ? e.message : String(e)}`,
isHtml: false,
};
}
}