コード例 #1
0
ファイル: group.py プロジェクト: JamesMcClung/rollpy
def evaluate_blank(args: list, i: int) -> str:
    while blank in args[i]:
        if i + 1 == len(args):
            raise util.ParseException(
                "Failure: missing value for _ in '{}'".format(args[i]))

        if blank in args[i + 1]:
            # parse that blank first
            evaluate_blank(args, i + 1)

        # replace blanks with next value after executed
        if args[i + 1] == left_sep:
            # if the next arg is the beginning of a group, parse and execute the group
            depth = 0
            j = i + 1
            while depth >= 0:
                j += 1
                depth += 1 if args[j] == left_sep else (
                    -1 if args[j] == right_sep else 0)
            nextvalue = str(Group(args[i + 2:j]).execute(print_rolls=False))
            del args[i + 1:j + 1]
        elif expression.is_expression(args[i + 1]):
            # if the arg is an expression, evaluate it
            nextvalue = str(int(expression.parse_math(args[i + 1])))
            del args[i + 1]
        elif table.is_table(args[i + 1]):
            nextvalue = table.Table(args[i + 1]).execute()
            del args[i + 1]
        else:
            # try to parse next arg as a roll
            nextvalue = str(Roll(args[i + 1]).execute(print_output=False))
            del args[i + 1]

        # replace blank with resulting value
        args[i] = args[i].replace(blank, nextvalue, 1)
コード例 #2
0
ファイル: group.py プロジェクト: JamesMcClung/rollpy
    def __init__(self, args, depth=0):
        if len(args) == 0:
            raise util.ParseException("Failure: unable to parse empty group.")
        self.depth = depth

        self.all_tags = {t: None for t in tags.all_tag_strs}
        self.askedForStat = False

        i = 0
        firstStatFound = None
        while i < len(args):
            evaluate_blank(args, i)

            arg = args[i]

            # handle empty arg
            if not arg:
                pass

            # handle tags
            elif tag := tags.get_tag(arg, args[i + 1:]):
                self.all_tags[arg] = tag
                if arg in tags.stat_tag_strs:
                    firstStatFound = firstStatFound or arg
                    self.askedForStat = True
                if arg in tags.supertag_strs:
                    args.insert(i + 1, arg[1:])

            # handle modifiers
            elif modifier.is_modifier(arg):
                if self:  # if there is anything to modify
                    modifier.modify(self[-1], arg)
                else:
                    raise util.ParseException(
                        "Error: modifier '{}' requires something to modify.".
                        format(arg))
コード例 #3
0
ファイル: group.py プロジェクト: JamesMcClung/rollpy
                if self:  # if there is anything to modify
                    self[-1:] = [self[-1]] * int(multiplier_match.group(1))
                else:
                    raise util.ParseException(
                        "Error: multiplier '{}' requires something to multiply."
                        .format(arg))

            # handle separators for grouping
            elif arg == left_sep:
                depth = 1  # relative depth
                j = i
                while depth > 0:
                    j += 1
                    if j >= len(args):
                        raise util.ParseException(
                            "Unable to parse group from '{}' due to missing '{}'"
                            .format(" ".join(args), right_sep))

                    if args[j] == right_sep:
                        depth -= 1
                    elif args[j] == left_sep:
                        depth += 1
                self.append(Group(args[i + 1:j], self.depth + 1))
                i = j

            # check if it is an expression
            elif expression.is_expression(arg):
                self.append(expression.Expression(arg))

            # check if it is a table
            elif table.is_table(arg):
コード例 #4
0
import re

_expression_regex = re.compile(r"(?P<label>\w*)=(?P<expr>[\d\.\*\+-/]+)$")


def is_expression(arg: str) -> bool:
    """Determines if the given string is an expression."""
    return _expression_regex.match(arg)


def parse_math(arg: str) -> float:
    """A basic parser for math. Evaluates a string like '3+2.5*-2' to be -11.0. Returns a float."""
    if match := _expression_regex.match(arg):
        arg = match.group('expr')
    else:
        raise util.ParseException(
            "Failure: '{}' is not an expression.".format(arg))

    result = 0.0
    nextop = result.__add__
    num = ''
    # just do them in order, no PEMDAS
    for c in arg:
        if ('0' <= c and c <= '9') or c == '.':
            num += c
        elif not num and c == '-':
            num = '-'
        else:
            result = nextop(float(num))
            num = ''
            nextop = {
                '+': result.__add__,
コード例 #5
0
        if match.group("type") == "h":
            roll.ceil = val
        else:
            roll.floor = val

    # label modifier
    elif match := _label_regex.match(arg):
        roll.label = match.group("val")

    # reroll modifier
    elif match := _reroll_regex.match(arg):
        roll.reroll = int(match.group("val"))

    # invalid modifier
    else:
        raise util.ParseException("Invalid modifier: '{}'".format(arg))


def get_bonus_modifier(bonus: int) -> str:
    """Returns a valid bonus modifier."""
    return MODIFIER_INDICATOR + ("+" if bonus >= 0 else "") + str(bonus)


def get_count_modifier(mod: int, type: str = "times"):
    """Returns a valid count modifier.\n
    mod: a positive integer\n
    type: either 'times', 'plus', or 'set'"""
    return MODIFIER_INDICATOR + "count{}={}".format({
        'times': '*',
        'plus': '+',
        'set': ''
コード例 #6
0
import re
import util

# table syntax: {key1=val1;key2=val2}=key
_table_regex = re.compile(r"{(?P<items>(?:\w*=\w*[;}])+)=(?P<key>\d+)$")
_item_regex = re.compile(r"(?P<item>\w*=\w*)[;}]")

def is_table(arg: str) -> bool:
    return _table_regex.match(arg)

class Table(dict):
    def __init__(self, arg: str):
        if match := _table_regex.match(arg):
            items = match.group("items")
            self.key = match.group('key')
        else:
            raise util.ParseException("Failure: invalid table string '{}'".format(arg))
        
        for itemstr in _item_regex.finditer(items):
            item = itemstr.group('item').split('=')
            self[item[0]] = item[1]
    
    def execute(self, print_output: bool = False):
        result = self[self.key]
        if print_output:
            print("Outcome of table: " + result)
        return result