Browse Source

Added support for modifiers.

main
Nichole Mattera 4 months ago
parent
commit
66f400d0e6
  1. 61
      cogs/basic.py

61
cogs/basic.py

@ -7,55 +7,42 @@ import re
class Roll:
_roll_regex = None
def __init__(self, roll_definition):
# Parse the name of the roll if provided.
if ":" in roll_definition:
roll_definition_name_divide = roll_definition.split(":")
self.name = roll_definition_name_divide[0]
roll_definition = roll_definition_name_divide[1]
else:
self.name = ""
# Parse when the user just passes in a number. (Ex. "6", "20")
if roll_definition.isnumeric():
self.times = 1
self.die = int(roll_definition)
elif "d" in roll_definition:
roll_definition_components = roll_definition.split("d")
# Parse when the user passes in a number prefixed with a "d". (Ex. "d6", "d20")
if len(roll_definition_components) == 1:
self.times = 1
if roll_definition_components[0].isnumeric():
self.die = int(roll_definition_components[0])
else:
raise ValueError
matches = self.roll_regex().match(roll_definition)
if matches is None:
raise ValueError
_, name, _, times, die, modifier = matches.groups()
self.name = name
self.times = int(times) if times is not None else 1
self.modifier = int(modifier) if modifier is not None else 0
if die is None:
raise ValueError
# Parse when the user passes in a number prefixed with how many times followed by a "d". (Ex. "1d6", "2d20")
elif len(roll_definition_components) == 2:
if roll_definition_components[0].isnumeric():
self.times = int(roll_definition_components[0])
else:
self.times = 1
self.die = int(die)
if roll_definition_components[1].isnumeric():
self.die = int(roll_definition_components[1])
else:
raise ValueError
else:
raise ValueError
@classmethod
def roll_regex(cls):
if cls._roll_regex is None:
cls._roll_regex = re.compile(r"((.*):)?((\d+)?d)?(\d+)([+-]\d+)?")
return cls._roll_regex
def execute(self):
if self.times != 1:
result = ""
total = 0
for i in range(self.times):
value = random.randint(1, self.die)
value = random.randint(1, self.die) + self.modifier
result += f"{value}, "
total += value
return f"{result[0:-2]} (Total: {total})"
else:
return str(random.randint(1, self.die))
return str(random.randint(1, self.die) + self.modifier)
class Basic(Cog):
@ -99,7 +86,7 @@ class Basic(Cog):
for index, roll in enumerate(rollList):
try:
rollObj = Roll(roll)
if rollObj.name == "":
if rollObj.name is None:
embed.add_field(
name=f"Roll {index + 1}", value=rollObj.execute(), inline=False
)

Loading…
Cancel
Save