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

87 lines
1.9 KiB
TypeScript
Raw Normal View History

2026-02-28 16:49:02 +08:00
import { roll as rollDice } from "./dice-engine";
export interface DiceRollerResult {
formula: string;
result: {
total: number;
detail: string;
pools: Array<{
rolls: number[];
keptRolls: number[];
subtotal: number;
}>;
};
success: boolean;
error?: string;
}
/**
* Hook
*
*/
export function useDiceRoller() {
/**
*
* @param formula
* - 3d6: 标准骰子
* - {d4, d8, 2d6}:
* - kh2/dl1: 修饰符
* - +:
* - -:
* - 5: 固定数字
*/
function roll(formula: string): DiceRollerResult {
try {
const result = rollDice(formula);
return {
formula,
result: {
total: result.total,
detail: result.detail,
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: "",
pools: [],
},
success: false,
error: e instanceof Error ? e.message : String(e),
};
}
}
/**
* HTML
*/
function rollSimple(formula: string): { text: string; isHtml?: boolean } {
try {
const result = rollDice(formula);
return {
text: `${result.formula} = ${result.total} (${result.detail})`,
isHtml: true, // detail 包含 HTML
};
} catch (e) {
return {
text: `错误:${e instanceof Error ? e.message : String(e)}`,
isHtml: false,
};
}
}
return {
roll,
rollSimple,
};
}