Last active
May 7, 2021 15:25
-
-
Save AusIV/c5df4f6c352740a3ae16 to your computer and use it in GitHub Desktop.
A Python script that uses Parsley to roll dice in the usual D&D notation
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 parsley | |
def roll(x, y, k=None): | |
k = k or x | |
if k > 0: | |
s = slice(0, k) | |
else: | |
s = slice(k, x) | |
return sum(sorted((random.randrange(1, y+1) for _ in range(x)), reverse=True )[s]) | |
grammar = parsley.makeGrammar(""" | |
dice = number:x 'd' number:y keep?:k -> roll(x, y, k) | |
keep = 'k' '-'?:sign number:k -> int("%s%s" % (sign or "", k)) | |
die = 'd' number:y -> roll(1, y) | |
number = <digit+>:ds -> int(ds) | |
value = die | dice | number | |
op = '+' | '-' | |
expr2 = value:left ws op:op ws expr:right -> left + right if op == '+' else left - right | |
expr = expr2 | value | |
ws = ' '? | |
""", {'roll': roll}) | |
if __name__ == "__main__": | |
import sys | |
if sys.argv[1:]: | |
print(grammar(" ".join(sys.argv[1:])).expr()) | |
else: | |
while True: | |
print(grammar(input("Dice: ")).expr()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment