jeffdeon

Random Dice Algorithm

Sep 27th, 2020
5,008
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. export abstract class DiceController {
  2.     abstract throwDice(): IDicePair
  3. }
  4.  
  5. export class RandomDiceController extends DiceController {
  6.  
  7.     throwDice(): IDicePair {
  8.         return this.throwRandomDice()
  9.     }
  10.  
  11.     private throwRandomDice(): IDicePair {
  12.         const dicePair = {
  13.             dice1: randomNumberBetween(1, 6),
  14.             dice2: randomNumberBetween(1, 6),
  15.         }
  16.         return dicePair
  17.     }
  18. }
  19.  
  20. /// Includes the values given
  21. export function randomNumberBetween(minValue: number, maxValue: number): number {
  22.     return Math.floor(Math.random() * (maxValue - minValue + 1)) + minValue
  23. }
Advertisement
Comments
  • Texasdevelp
    34 days
    # text 1.63 KB | 0 0
    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)
Add Comment
Please, Sign In to add comment