Last active
February 19, 2019 11:49
-
-
Save judy2k/cb92e8b4146d610988ebd1178628f21b to your computer and use it in GitHub Desktop.
An Infinite Bag of Dice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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