Skip to content

Instantly share code, notes, and snippets.

@judy2k
Last active February 19, 2019 11:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save judy2k/cb92e8b4146d610988ebd1178628f21b to your computer and use it in GitHub Desktop.
Save judy2k/cb92e8b4146d610988ebd1178628f21b to your computer and use it in GitHub Desktop.
An Infinite Bag of Dice
import random
import re
import sys
def _roll_func(count, sides):
def _roll():
return sum(random.randint(1, sides) for _ in range(count))
return _roll
class DBag:
def __getattr__(self, name):
if name.startswith("roll_"):
match = re.match(r"roll_(?P<count>\d*)d(?P<sides>\d+)", name)
if match:
count_string = match.group("count")
if count_string == "":
count = 1
else:
count = int(count_string)
sides = int(match.group("sides"))
return _roll_func(count, sides)
raise AttributeError(f"{__class__.__name__!r} object has no attribute {name!r}")
sys.modules["dbag"] = DBag()
import dbag
print(f"D6: {dbag.roll_d6()}")
print(f"3D6: {dbag.roll_3d6()}")
print(f"3D20: {dbag.roll_3d20()}")
# OMG I really didn't expect the following to work:
from dbag import roll_d6 as d6
print(f"D6 {d6()}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment