Skip to content

Instantly share code, notes, and snippets.

@brenttaylor
Last active September 24, 2017 14:16
Show Gist options
  • Save brenttaylor/f9a088b3c3ac01516eef1d4cfd377b11 to your computer and use it in GitHub Desktop.
Save brenttaylor/f9a088b3c3ac01516eef1d4cfd377b11 to your computer and use it in GitHub Desktop.
A tabletop dice roller in python that horribly abuses the language.
import random
import re
import sys
from functools import lru_cache
@lru_cache()
def generate_die(sides):
return list(range(1, sides + 1))
class Roller:
_dice_pattern = re.compile(r'^d([0-9]+)$')
def __getattr__(self, attr):
if attr in self.__dict__:
return self.__dict__[attr]
dice_match = re.search(self._dice_pattern, attr)
if dice_match:
die_size = int(dice_match.groups()[0])
def die_roller(nDice=1):
dX = generate_die(die_size)
return [random.choice(dX) for x in range(nDice)]
self.__dict__[attr] = die_roller
return die_roller
raise AttributeError("type object'Roller' has no attribute '{0}'".format(attr))
random.seed()
sys.modules[__name__] = Roller()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment