fulvia/modules/dice.py

52 lines
1.3 KiB
Python
Raw Normal View History

2018-03-16 03:13:43 -04:00
#!/usr/bin/env python3
"""
Dice rolling, the core function of any IRC bot.
"""
import re
2020-01-08 09:27:34 -05:00
import random
2018-03-16 03:13:43 -04:00
import module
@module.commands("roll", "dice", "d")
@module.example(".roll 3d1+1", "You roll 3d1+1: (1+1+1)+1 = 4")
def roll(bot, trigger):
"""
2020-01-08 09:27:34 -05:00
.dice XdY[+Z], rolls dice and reports the result.
2018-03-16 03:13:43 -04:00
2020-01-08 09:27:34 -05:00
X is the number of dice. Y is the number of faces in the dice. Z is
the constant to be applied to the end result.
2018-03-16 03:13:43 -04:00
"""
2020-01-07 18:58:19 -05:00
if len(trigger.args) < 2:
2020-01-08 09:27:34 -05:00
return bot.reply("Roll what?")
regex = re.compile(r'(\d+)?d(\d+)([+-]\d+)?')
reg = re.match(regex, trigger.args[1])
if not reg:
return bot.reply("Invalid dice notation.")
num_dice = int(reg.groups()[0]) if reg.groups()[0] else 1
num_sides = int(reg.groups()[1])
modifier = int(reg.groups()[2]) if reg.groups()[2] else 0
num_dice = min(num_dice, 100)
num_sides = min(num_sides, 1000)
results = []
for _ in range(num_dice):
2020-02-01 19:36:26 -05:00
result = random.randint(1, num_sides)
2020-01-08 09:27:34 -05:00
results.append(result)
total = sum(results) + modifier
msg = f"You roll {num_dice}d{num_sides}"
if modifier:
if modifier > 0:
msg += '+'
msg += str(modifier)
msg += ': '
msg += '(' + '+'.join([str(a) for a in results]) + ')'
if modifier:
if modifier > 0:
msg += '+'
msg += str(modifier)
msg += " = " + str(total)
2018-03-16 03:13:43 -04:00
bot.reply(msg)