Last active
August 20, 2020 23:32
-
-
Save jkingsman/d17c05ea9efa01c3f31366ba721b2c1d to your computer and use it in GitHub Desktop.
Automated dice roller for D&D with optional inclusion of envvars (e.g. DEX = 3; export DEX; ./roll.py 2d6 + DEX)
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
#!/usr/bin/env python3 | |
import os | |
import random | |
import sys | |
def process_roll_string(roll_string): | |
roll_components = roll_string.replace(" ", "").split("+") | |
total_sum = 0 | |
for roll_component in roll_components: | |
if roll_component.isnumeric(): | |
# normal number | |
print(f"+ literal {roll_component}") | |
total_sum += int(roll_component) | |
continue | |
elif "d" in roll_component: | |
# one or more dice | |
count, faces = roll_component.split("d") | |
if count == '': | |
count = 1 | |
print(f"Rolling {count}x {faces}-sided die") | |
rolls = [random.randint(1, int(faces)) for i in range(int(count))] | |
print(f"Got {rolls}") | |
roll_sum = sum(rolls) | |
print(f"+ {roll_sum}") | |
total_sum += roll_sum | |
else: | |
# literal roll component | |
env_val = os.environ.get(roll_component, None) | |
if env_val and env_val.isnumeric(): | |
print(f"+ {roll_component} ({env_val})") | |
total_sum += int(env_val) | |
else: | |
print(f"No env var found or invalid value for {roll_component}. (Did you remember to export?)") | |
print(f"Total is {total_sum}") | |
if len(sys.argv) > 1: | |
# input is via CLI | |
roll_string = " ".join(sys.argv[1:]) | |
process_roll_string(roll_string) | |
else: | |
# start interactive | |
while True: | |
raw_roll = input("roll> ") | |
process_roll_string(raw_roll) | |
print("") |
Author
jkingsman
commented
Aug 20, 2020
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment