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

87 lines
1.8 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;
plainDetail: string;
2026-02-28 16:49:02 +08:00
pools: Array<{
rolls: number[];
keptRolls: number[];
subtotal: number;
}>;
};
success: boolean;
error?: string;
}
/**
* Hook
*
*/
2026-02-28 17:44:38 +08:00
/**
*
* @param formula
* - 3d6: 标准骰子
* - {d4, d8, 2d6}:
* - kh2/dl1: 修饰符
* - +:
* - -:
* - 5: 固定数字
*/
export function rollFormula(formula: string): DiceRollerResult {
try {
const result = rollDice(formula);
2026-02-28 16:49:02 +08:00
2026-02-28 17:44:38 +08:00
return {
formula,
result: {
total: result.total,
detail: result.detail,
plainDetail: result.plainDetail,
2026-02-28 17:44:38 +08:00
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: "",
2026-02-28 17:44:38 +08:00
pools: [],
},
success: false,
error: e instanceof Error ? e.message : String(e),
};
2026-02-28 16:49:02 +08:00
}
2026-02-28 17:44:38 +08:00
}
2026-02-28 16:49:02 +08:00
2026-02-28 17:44:38 +08:00
/**
* HTML
* [1] [2] [3] = <strong>6</strong>
*/
export function rollSimple(formula: string): {
text: string;
isHtml?: boolean;
} {
2026-02-28 17:44:38 +08:00
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,
};
2026-02-28 16:49:02 +08:00
}
}