This commit is contained in:
NikolajDanger
2020-04-01 00:59:02 +02:00
parent 9088aaf932
commit eb8fb0c2c2
11 changed files with 254 additions and 185 deletions

View File

@ -1,4 +1,3 @@
import logging
import random
import re
import traceback
@ -9,8 +8,7 @@ from re import IGNORECASE
import numexpr
from . import errors
logging.basicConfig(filename="gwendolyn.log", level=logging.INFO)
#from funcs import logThis
VALID_OPERATORS = 'k|rr|ro|mi|ma|ra|e|p'
VALID_OPERATORS_ARRAY = VALID_OPERATORS.split('|')
@ -41,10 +39,10 @@ def get_roll_comment(rollStr):
no_comment = ''
dice_set = re.split('([-+*/().=])', rollStr)
dice_set = [d for d in dice_set if not d in (None, '')]
logging.debug("Found dice set: " + str(dice_set))
#logThis("Found dice set: " + str(dice_set))
for index, dice in enumerate(dice_set):
match = DICE_PATTERN.match(dice)
logging.debug("Found dice group: " + str(match.groups()))
#logThis("Found dice group: " + str(match.groups()))
no_comment += dice.replace(match.group(5), '')
if match.group(5):
comment = match.group(5) + ''.join(dice_set[index + 1:])
@ -58,7 +56,7 @@ def get_roll_comment(rollStr):
class Roll(object):
def __init__(self, parts=None):
if parts is None:
if parts ==None:
parts = []
self.parts = parts
@ -85,10 +83,10 @@ class Roll(object):
# parse each, returning a SingleDiceResult
dice_set = re.split('([-+*/().=])', rollStr)
dice_set = [d for d in dice_set if not d in (None, '')]
logging.debug("Found dice set: " + str(dice_set))
#logThis("Found dice set: " + str(dice_set))
for index, dice in enumerate(dice_set):
match = DICE_PATTERN.match(dice)
logging.debug("Found dice group: " + str(match.groups()))
#logThis("Found dice group: " + str(match.groups()))
# check if it's dice
if match.group(1):
roll = self.roll_one(dice.replace(match.group(5), ''), adv)
@ -111,7 +109,7 @@ class Roll(object):
except SyntaxError:
raise errors.InvalidArgument("No dice found to roll.")
rolled = ' '.join(str(res) for res in self.parts if not isinstance(res, Comment))
if rollFor is '':
if rollFor =='':
rollFor = ''.join(str(c) for c in self.parts if isinstance(c, Comment))
# return final solution
if not inline:
@ -120,7 +118,7 @@ class Roll(object):
str(res) for res in self.parts if not isinstance(res, Comment)) + '\n**Total:** ' + str(
floor(total))
skeletonReply = reply
rollFor = rollFor if rollFor is not '' else 'Result'
rollFor = rollFor if rollFor != '' else 'Result'
reply = '**{}:** '.format(rollFor) + reply
if show_blurbs:
if adv == 1:
@ -138,7 +136,7 @@ class Roll(object):
reply = ' '.join(str(res) for res in self.parts if not isinstance(res, Comment)) + ' = `' + str(
floor(total)) + '`'
skeletonReply = reply
rollFor = rollFor if rollFor is not '' else 'Result'
rollFor = rollFor if rollFor != '' else 'Result'
reply = '**{}:** '.format(rollFor) + reply
if show_blurbs:
if adv == 1:
@ -157,7 +155,7 @@ class Roll(object):
skeleton=skeletonReply, raw_dice=self)
except Exception as ex:
if not isinstance(ex, (SyntaxError, KeyError, errors.AvraeException)):
logging.error('Error in roll() caused by roll {}:'.format(rollStr))
#logThis('Error in roll() caused by roll {}:'.format(rollStr))
traceback.print_exc()
return DiceResult(verbose_result="Invalid input: {}".format(ex))
@ -168,7 +166,7 @@ class Roll(object):
split = re.match(r'^([^\[\]]*?)\s*(\[.*\])?\s*$', dice)
dice = split.group(1).strip()
annotation = split.group(2)
result.annotation = annotation if annotation is not None else ''
result.annotation = annotation if annotation != None else ''
# Recognizes dice
obj = re.findall('\d+', dice)
obj = [int(x) for x in obj]
@ -180,21 +178,21 @@ class Roll(object):
raise errors.InvalidArgument('Please pass in the value of the dice.')
numDice = 1
diceVal = obj[0]
if adv is not 0 and diceVal == 20:
if adv != 0 and diceVal == 20:
numDice = 2
ops = ['k', 'h1'] if adv is 1 else ['k', 'l1']
ops = ['k', 'h1'] if adv ==1 else ['k', 'l1']
elif numArgs == 2:
numDice = obj[0]
diceVal = obj[-1]
if adv is not 0 and diceVal == 20:
ops = ['k', 'h' + str(numDice)] if adv is 1 else ['k', 'l' + str(numDice)]
if adv != 0 and diceVal == 20:
ops = ['k', 'h' + str(numDice)] if adv ==1 else ['k', 'l' + str(numDice)]
numDice = numDice * 2
else: # split into xdy and operators
numDice = obj[0]
diceVal = obj[1]
dice = re.split('(\d+d\d+)', dice)[-1]
ops = VALID_OPERATORS_2.split(dice)
ops = [a for a in ops if a is not None]
ops = [a for a in ops if a != None]
# dice repair/modification
if numDice > 300 or diceVal < 1:
@ -215,7 +213,7 @@ class Roll(object):
except:
result.rolled.append(SingleDice())
if ops is not None:
if ops != None:
rerollList = []
reroll_once = []
@ -226,7 +224,7 @@ class Roll(object):
valid_operators = VALID_OPERATORS_ARRAY
last_operator = None
for index, op in enumerate(ops):
if last_operator is not None and op in valid_operators and not op == last_operator:
if last_operator != None and op in valid_operators and not op == last_operator:
result.reroll(reroll_once, 1)
reroll_once = []
result.reroll(rerollList, greedy=True)
@ -240,10 +238,10 @@ class Roll(object):
if op == 'rr':
rerollList += parse_selectors([list_get(index + 1, 0, ops)], result, greedy=True)
if op == 'k':
keep = [] if keep is None else keep
keep = [] if keep ==None else keep
keep += parse_selectors([list_get(index + 1, 0, ops)], result)
if op == 'p':
keep = [] if keep is None else keep
keep = [] if keep ==None else keep
keep += parse_selectors([list_get(index + 1, 0, ops)], result, inverse=True)
if op == 'ro':
reroll_once += parse_selectors([list_get(index + 1, 0, ops)], result)
@ -280,9 +278,9 @@ class Part:
class SingleDiceGroup(Part):
def __init__(self, num_dice: int = 0, max_value: int = 0, rolled=None, annotation: str = "", result: str = "",
operators=None):
if operators is None:
if operators ==None:
operators = []
if rolled is None:
if rolled ==None:
rolled = []
self.num_dice = num_dice
self.max_value = max_value
@ -292,7 +290,7 @@ class SingleDiceGroup(Part):
self.operators = operators
def keep(self, rolls_to_keep):
if rolls_to_keep is None: return
if rolls_to_keep ==None: return
for _roll in self.rolled:
if not _roll.value in rolls_to_keep:
_roll.kept = False
@ -412,7 +410,7 @@ class SingleDice:
class Constant(Part):
def __init__(self, value: int = 0, annotation: str = ""):
self.value = value
self.annotation = annotation if annotation is not None else ''
self.annotation = annotation if annotation != None else ''
def __str__(self):
return "{0.value} {0.annotation}".format(self)
@ -426,8 +424,8 @@ class Constant(Part):
class Operator(Part):
def __init__(self, op: str = "+", annotation: str = ""):
self.op = op if op is not None else ''
self.annotation = annotation if annotation is not None else ''
self.op = op if op != None else ''
self.annotation = annotation if annotation != None else ''
def __str__(self):
return "{0.op} {0.annotation}".format(self)
@ -453,16 +451,16 @@ class Comment(Part):
def parse_selectors(opts, res, greedy=False, inverse=False):
"""Returns a list of ints."""
for o in range(len(opts)):
if opts[o][0] is 'h':
if opts[o][0] =='h':
opts[o] = nlargest(int(opts[o].split('h')[1]), (d.value for d in res.rolled if d.kept))
elif opts[o][0] is 'l':
elif opts[o][0] =='l':
opts[o] = nsmallest(int(opts[o].split('l')[1]), (d.value for d in res.rolled if d.kept))
elif opts[o][0] is '>':
elif opts[o][0] =='>':
if greedy:
opts[o] = list(range(int(opts[o].split('>')[1]) + 1, res.max_value + 1))
else:
opts[o] = [d.value for d in res.rolled if d.value > int(opts[o].split('>')[1])]
elif opts[o][0] is '<':
elif opts[o][0] =='<':
if greedy:
opts[o] = list(range(1, int(opts[o].split('<')[1])))
else:
@ -472,7 +470,7 @@ def parse_selectors(opts, res, greedy=False, inverse=False):
if isinstance(o, list):
out.extend(int(l) for l in o)
elif not greedy:
out.extend(int(o) for a in res.rolled if a.value is int(o) and a.kept)
out.extend(int(o) for a in res.rolled if a.value ==int(o) and a.kept)
else:
out.append(int(o))
@ -498,7 +496,7 @@ class DiceResult:
self.result = verbose_result
self.crit = crit
self.rolled = rolled
self.skeleton = skeleton if skeleton is not '' else verbose_result
self.skeleton = skeleton if skeleton != '' else verbose_result
self.raw_dice = raw_dice # Roll
def __str__(self):
@ -509,7 +507,7 @@ class DiceResult:
def consolidated(self):
"""Gets the most simplified version of the roll string."""
if self.raw_dice is None:
if self.raw_dice ==None:
return "0"
parts = [] # list of (part, annotation)
last_part = ""