Created
August 1, 2023 09:22
-
-
Save horstjens/4a205cb8fe498fe97857458cbdab51c7 to your computer and use it in GitHub Desktop.
dd_dice
This file contains 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 | |
# dice - simulate dungeon & dragons dice to generate random values | |
def dice(dicestring): | |
""" | |
1d6 -> random integer between 1 and 6 | |
2d6 -> random integer between 2 and 12 | |
1d20+5 -> random integer between 6 and 26 | |
""" | |
if dicestring.count("d") != 1: | |
raise ValueError("dicestring does not have one 'd'") | |
left, right = dicestring.split("d") | |
number_of_dice = int(left) | |
if ("+" in right) or ("-" in right): | |
sign = "+" if "+" in right else "-" | |
sides, delta = right.split(sign) | |
sides = int(sides) | |
delta = int(delta) | |
if sign == "-": | |
delta = -delta | |
else: | |
delta = 0 | |
sides = int(right) | |
text = dicestring+": " | |
result = 0 | |
for d in range(number_of_dice): | |
roll = random.randint(1, sides) | |
result += roll | |
if d > 0: | |
text+=f"+{roll}" | |
else: | |
text+= f"{roll}" | |
result += delta | |
if delta != 0: | |
if delta > 0: | |
text += f"+{delta}={result}" | |
else: | |
text += f"{delta}={result}" | |
return result, text | |
if __name__ == "__main__": | |
# testing | |
for _ in range(10): | |
print(dice("2d6+1")) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment