Skip to content

Instantly share code, notes, and snippets.

@jkingsman
Last active August 20, 2020 23:32
Show Gist options
  • Save jkingsman/d17c05ea9efa01c3f31366ba721b2c1d to your computer and use it in GitHub Desktop.
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)
#!/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("")
@jkingsman
Copy link
Author

jkingsman commented Aug 20, 2020

[16:28:18L/23:28:18Z] jack at NewDesktop in /mnt/d/Jack Kingsman (Personal)/Projects/Development/dice
Δ DEX=3; export DEX; STAM=2; export STAM

[16:28:28L/23:28:28Z] jack at NewDesktop in /mnt/d/Jack Kingsman (Personal)/Projects/Development/dice
Δ ./roll.py 2d6 + 2 + DEX
Rolling 2x 6-sided die
Got [2, 6]
+ 8
+ literal 2
+ DEX (3)
Total is 13

[16:29:05L/23:29:05Z] jack at NewDesktop in /mnt/d/Jack Kingsman (Personal)/Projects/Development/dice
Δ ./roll.py
roll> 2d9 + d4 + 72 + STAM + DEX
Rolling 2x 9-sided die
Got [7, 9]
+ 16
Rolling 1x 4-sided die
Got [3]
+ 3
+ literal 72
+ STAM (2)
+ DEX (3)
Total is 96

roll> 1d4 + 2d9 + 2d14
Rolling 1x 4-sided die
Got [3]
+ 3
Rolling 2x 9-sided die
Got [9, 5]
+ 14
Rolling 2x 14-sided die
Got [4, 6]
+ 10
Total is 27
roll>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment