Skip to content

Instantly share code, notes, and snippets.

@matt-morris
Last active January 8, 2021 16:18
Show Gist options
  • Save matt-morris/1db335652f2d04ab4b077d48c9d03ff4 to your computer and use it in GitHub Desktop.
Save matt-morris/1db335652f2d04ab4b077d48c9d03ff4 to your computer and use it in GitHub Desktop.
are your dice all the way across the room? i got you....

javascript

// e.g. roll(2).d(8) + roll().d(4) + 11
const roll = (n = 1) => ({
  d: (sides) =>
    Array.from({ length: n }, () => Math.ceil(Math.random() * sides)).reduce(
      (x, y) => x + y,
      0
    ),
})

ruby

class Integer
  # monkey patch for rolling virtual dice
  # e.g. 2.d8 + 1.d4 + 11
  def method_missing(name)
    if name[/^d\d+$/]
      n = name[1..-1].to_i
      self.times.map { rand(1..n) }.sum
    end
  end
end

python

from random import randrange

class Roll(object):
    """
    e.g. Roll(2).d(8) + Roll().d(4) + 11
    """
    def __init__(self, n=1):
        self.n = n
    
    def d(self, sides):
        return sum([randrange(1, sides) for _ in range(1, self.n)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment