Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- export abstract class DiceController {
- abstract throwDice(): IDicePair
- }
- export class RandomDiceController extends DiceController {
- throwDice(): IDicePair {
- return this.throwRandomDice()
- }
- private throwRandomDice(): IDicePair {
- const dicePair = {
- dice1: randomNumberBetween(1, 6),
- dice2: randomNumberBetween(1, 6),
- }
- return dicePair
- }
- }
- /// Includes the values given
- export function randomNumberBetween(minValue: number, maxValue: number): number {
- return Math.floor(Math.random() * (maxValue - minValue + 1)) + minValue
- }
Advertisement
Comments
-
- // you actually made dice rolls worse
- // Types you already implied
- export interface IDicePair { dice1: number; dice2: number }
- // --- Tiny, safe RNG helpers (unbiased + crypto) ---
- function secureRandomIntInclusive(min: number, max: number): number {
- if (!Number.isInteger(min) || !Number.isInteger(max) || max < min) {
- throw new Error("invalid bounds")
- }
- const range = max - min + 1
- // Use 32-bit values and rejection sampling to avoid modulo bias.
- const buf = new Uint32Array(1)
- // globalThis.crypto exists in modern browsers and Node 18+
- const cryptoObj = (globalThis as any).crypto
- if (!cryptoObj?.getRandomValues) {
- throw new Error("crypto.getRandomValues not available")
- }
- const limit = Math.floor(0x1_0000_0000 / range) * range // largest multiple of range < 2^32
- let x: number
- do {
- cryptoObj.getRandomValues(buf)
- x = buf[0]
- } while (x >= limit)
- return min + (x % range)
- }
- // If you're on Node 16+, you can replace the whole function with:
- // import { randomInt } from "node:crypto"
- // const secureRandomIntInclusive = (min: number, max: number) => randomInt(min, max + 1)
- // --- Your controller, just better RNG ---
- export abstract class DiceController {
- abstract throwDice(): IDicePair
- }
- export class RandomDiceController extends DiceController {
- throwDice(): IDicePair {
- const dice1 = secureRandomIntInclusive(1, 6)
- const dice2 = secureRandomIntInclusive(1, 6)
- return { dice1, dice2 }
- }
- }
- // Optional convenience if you ever just want the sum:
- // export const roll2d6 = () => secureRandomIntInclusive(1, 6) + secureRandomIntInclusive(1, 6)
Add Comment
Please, Sign In to add comment