Download:
child 12:49aec9763d9e
parent 10:9fa8b4b32368
11:1be0d90ed46b
Anton Shestakov <av6@dwimlabs.net>, Sat, 14 May 2016 14:07:31 +0800
rollbot: finally, roll command (basic <X>D<Y>)

1 файлов изменено, 35 вставок(+), 0 удалений(-) [+]
rollbot.py file | annotate | diff | comparison | revisions
--- a/rollbot.py Sat May 14 14:05:49 2016 +0800
+++ b/rollbot.py Sat May 14 14:07:31 2016 +0800
@@ -1,5 +1,7 @@
#!/usr/bin/env python
import logging
+import random
+import re
import sys
from argparse import ArgumentParser, FileType, SUPPRESS
@@ -24,6 +26,38 @@
return '(no help available, try experimenting)'
+class Roll(Command):
+ name = 'roll'
+ regex = re.compile('^(?P<times>\d+)?d(?P<sides>\d+)$', re.IGNORECASE)
+
+ def usage(self):
+ return '%s <X>D<Y> means roll Y-sided die X times, if X is 1 it can be omitted' % self.name
+
+ def respond(self, words, message):
+ if len(words) == 2:
+ match = self.regex.match(words[1])
+ if match is not None:
+ times = match.group('times')
+ if times is None:
+ times = 1
+ sides = match.group('sides')
+ rolls, total = self.roll(int(times), int(sides))
+ return self.format(rolls, total)
+
+ return '%s usage: %s' % (self.name, self.usage())
+
+ def roll(self, times, sides):
+ results = [random.randint(1, sides) for i in range(times)]
+ total = sum(results)
+ return results, total
+
+ def format(self, rolls, total):
+ if len(rolls) == 1:
+ return '%d' % total
+ else:
+ return '(%s) = %d' % (' + '.join('%d' % r for r in rolls), total)
+
+
class Help(Command):
name = 'help'
@@ -53,6 +87,7 @@
self.prefix = prefix
self.commands = {}
+ self.add_command(Roll)
self.add_command(Help)
self.add_event_handler('session_start', self.start)