Texasdevelp
Aug 27th, 2025
2
0
Never
This is comment for paste Random Dice Algorithm
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // you actually made dice rolls worse
  2.  
  3. // Types you already implied
  4. export interface IDicePair { dice1: number; dice2: number }
  5.  
  6. // --- Tiny, safe RNG helpers (unbiased + crypto) ---
  7. function secureRandomIntInclusive(min: number, max: number): number {
  8. if (!Number.isInteger(min) || !Number.isInteger(max) || max < min) {
  9. throw new Error("invalid bounds")
  10. }
  11. const range = max - min + 1
  12. // Use 32-bit values and rejection sampling to avoid modulo bias.
  13. const buf = new Uint32Array(1)
  14. // globalThis.crypto exists in modern browsers and Node 18+
  15. const cryptoObj = (globalThis as any).crypto
  16. if (!cryptoObj?.getRandomValues) {
  17. throw new Error("crypto.getRandomValues not available")
  18. }
  19.  
  20. const limit = Math.floor(0x1_0000_0000 / range) * range // largest multiple of range < 2^32
  21. let x: number
  22. do {
  23. cryptoObj.getRandomValues(buf)
  24. x = buf[0]
  25. } while (x >= limit)
  26.  
  27. return min + (x % range)
  28. }
  29.  
  30. // If you're on Node 16+, you can replace the whole function with:
  31. // import { randomInt } from "node:crypto"
  32. // const secureRandomIntInclusive = (min: number, max: number) => randomInt(min, max + 1)
  33.  
  34. // --- Your controller, just better RNG ---
  35. export abstract class DiceController {
  36. abstract throwDice(): IDicePair
  37. }
  38.  
  39. export class RandomDiceController extends DiceController {
  40. throwDice(): IDicePair {
  41. const dice1 = secureRandomIntInclusive(1, 6)
  42. const dice2 = secureRandomIntInclusive(1, 6)
  43. return { dice1, dice2 }
  44. }
  45. }
  46.  
  47. // Optional convenience if you ever just want the sum:
  48. // export const roll2d6 = () => secureRandomIntInclusive(1, 6) + secureRandomIntInclusive(1, 6)
Advertisement
Add Comment
Please, Sign In to add comment