2009-03-15 04:14:07 +00:00
|
|
|
"""
|
2009-04-18 00:13:54 +00:00
|
|
|
dice.py: written by Scaevolus 2008, updated 2009
|
2009-03-15 04:14:07 +00:00
|
|
|
simulates dicerolls
|
|
|
|
"""
|
|
|
|
import re
|
|
|
|
import random
|
|
|
|
|
2009-03-16 04:30:46 +00:00
|
|
|
import hook
|
|
|
|
|
2009-03-15 04:14:07 +00:00
|
|
|
whitespace_re = re.compile(r'\s+')
|
|
|
|
valid_diceroll_re = re.compile(r'^[+-]?(\d+|\d*d\d+)([+-](\d+|\d*d\d+))*$')
|
|
|
|
sign_re = re.compile(r'[+-]?(?:\d*d)?\d+')
|
|
|
|
split_re = re.compile(r'([\d+-]*)d?(\d*)')
|
|
|
|
|
2009-04-18 00:57:18 +00:00
|
|
|
|
2009-03-15 04:14:07 +00:00
|
|
|
def nrolls(count, n):
|
|
|
|
"roll an n-sided die count times"
|
|
|
|
if n < 2: #it's a coin
|
|
|
|
if count < 5000:
|
2009-04-18 00:57:18 +00:00
|
|
|
return sum(random.randint(0, 1) for x in xrange(count))
|
2009-03-15 04:14:07 +00:00
|
|
|
else: #fake it
|
2009-04-18 00:57:18 +00:00
|
|
|
return int(random.normalvariate(.5*count, (.75*count)**.5))
|
2009-03-15 04:14:07 +00:00
|
|
|
else:
|
|
|
|
if count < 5000:
|
2009-04-18 00:57:18 +00:00
|
|
|
return sum(random.randint(1, n) for x in xrange(count))
|
2009-03-15 04:14:07 +00:00
|
|
|
else: #fake it
|
|
|
|
return int(random.normalvariate(.5*(1+n)*count,
|
|
|
|
(((n+1)*(2*n+1)/6.-(.5*(1+n))**2)*count)**.5))
|
|
|
|
|
2009-04-18 00:57:18 +00:00
|
|
|
|
2009-03-16 04:30:46 +00:00
|
|
|
@hook.command
|
2009-03-15 07:25:32 +00:00
|
|
|
def dice(input):
|
2009-03-15 04:14:07 +00:00
|
|
|
".dice <diceroll> - simulates dicerolls, e.g. .dice 2d20-d5+4 roll 2 " \
|
|
|
|
"D20s, subtract 1D5, add 4"
|
2009-03-15 07:25:32 +00:00
|
|
|
if not input.strip():
|
2009-03-15 04:14:07 +00:00
|
|
|
return dice.__doc__
|
|
|
|
|
2009-03-15 07:25:32 +00:00
|
|
|
spec = whitespace_re.sub('', input)
|
2009-03-15 04:14:07 +00:00
|
|
|
if not valid_diceroll_re.match(spec):
|
|
|
|
return "Invalid diceroll"
|
|
|
|
sum = 0
|
|
|
|
groups = sign_re.findall(spec)
|
|
|
|
for roll in groups:
|
|
|
|
count, side = split_re.match(roll).groups()
|
|
|
|
if side == "":
|
|
|
|
sum += int(count)
|
|
|
|
else:
|
2009-04-18 00:57:18 +00:00
|
|
|
count = int(count) if count not in" +-" else 1
|
2009-03-15 04:14:07 +00:00
|
|
|
side = int(side)
|
|
|
|
try:
|
|
|
|
if count > 0:
|
|
|
|
sum += nrolls(count, side)
|
|
|
|
else:
|
|
|
|
sum -= nrolls(abs(count), side)
|
|
|
|
except OverflowError:
|
|
|
|
return "Thanks for overflowing a float, jerk >:["
|
2009-04-18 00:57:18 +00:00
|
|
|
|
2009-03-15 04:14:07 +00:00
|
|
|
return str(sum)
|