Esempio n. 1
0
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    if content_type != 'text' or 'forward_from' in msg:
        return
    for command in reversed(COMMANDS):
        if msg['text'].startswith(command):
            expression = msg['text'][len(command):]
            break
    else:
        return
    #print("Command:", msg['text'])
    print(expression)
    try:
        tokens, reason = parse(expression)
        print(expression, tokens, reason)
        rolled = roll(tokens)
        result = count(rolled)
        print(tokens)
        if reason:
            reason += '\n'
        bot.sendMessage(chat_id, '🎲 %s%s -> %s = <b>%d</b>'
                        % (reason, ' '.join(tokens),
                           ' '.join(map(mystr, rolled)), result),
                        parse_mode='HTML')
    except Exception as e:
        print_exc()
        bot.sendMessage(chat_id, '‼ Какая-то хрень ‼')
Esempio n. 2
0
def buildComment(hasEdge, stringPool):
    """A method to build the comment to reply with
    
    Parameters
    ----------
    hasEdge: Boolean
    indicates if the person spent edge on the roll
    stringPool: String
    refers to the Pool Size as a String
    """

    #a variable to turn the debugger on and off
    debug = False

    #convert the pool size into a number
    pool = int(float(stringPool))

    #run the bebugger if neccessary
    #debug.debugBuildReply(debug, pool, hasEdge)

    #get the result of the roll
    result = roller.roll(pool, hasEdge)

    #start to build the reply, placing in the number of successes
    reply_text = 'You got %d successes' % result[0]

    #if the person had a glitch, indicate it in the repsonse
    if result[1]:
        reply_text += ', You also got a glitch'

    #add contact info to flag me if the bot is failing
    reply_text += r' If you think I screwed up contact /u/Mindflayer94'

    #return the reply
    return reply_text
Esempio n. 3
0
def roll_exec(irc, message):
    '''
        A !roll comand has the following structure:
            !roll diceAmount+d+diceSize+"+"+modifier

        * Dice amount is an integer up to 20000
        * Dice Size is an integer
        * Modifier is an integer that is added onto the roll after

        The !Roll command can also have this structure:
            !!roll d+diceAmount+d+diceSize+"+"+modifier

        * Dice amount is the result of a roll of said size and then proceeds
            to roll that many of the following dice
        * Dice Size is an integer
        * Modifier is an integer that is added onto the roll after
    '''

    diceNumbers = roller.getRolledNumbers(message.text)
    messageToSend = ''

    # -------------------------------------------------------------------
    #   Hard limits on the dice sizes
    # -------------------------------------------------------------------

    if diceNumbers[0] > 10:
        diceNumbers[0] = 10

    if diceNumbers[0] < 1:
        diceNumbers[0] = 1

    if diceNumbers[1] > 2000:
        diceNumbers[1] = 2000

    if diceNumbers[1] < 1:
        diceNumbers[1] = 1

    if diceNumbers[2] < 1:
        diceNumbers[2] = 1
    rolledArray = roller.roll(diceNumbers[0], diceNumbers[1], diceNumbers[2])

    for rollNum in rolledArray:
        # REMINDER: make a message maker function cause this is ugly!
        if (diceNumbers[3] == 0):
            messageToSend = (messageToSend + "\x0312,15(" +
                             str(diceNumbers[1]) + "d" + str(diceNumbers[2]) +
                             ") \x032,15[" + str(rollNum) +
                             "]\x031,15 : \x034,15{" +
                             str(rollNum + diceNumbers[3]) + "} ")
        else:
            messageToSend = (messageToSend + "\x0312,15(" +
                             str(diceNumbers[1]) + "d" + str(diceNumbers[2]) +
                             "+" + str(diceNumbers[3]) + ") \x032,15[" +
                             str(rollNum) + "+" + str(diceNumbers[3]) +
                             "]\x031,15 : \x034,15{" +
                             str(rollNum + diceNumbers[3]) + "} ")

    irc.send(message.reply(messageToSend))
Esempio n. 4
0
    def test_roll_subtract(self, mock_die):
        mock_d6 = Mock()
        mock_d6.roll.return_value = [sentinel.d6_1, sentinel.d6_2]
        mock_die.return_value = mock_d6

        result = roll(['-', '2d6'])

        mock_die.assert_called_once_with(6)
        mock_d6.roll.assert_called_once_with(2)
        self.assertEqual(result, ['-', (sentinel.d6_1, sentinel.d6_2)])
Esempio n. 5
0
    def test_roll_die(self, mock_die):
        mock_d6 = Mock()
        mock_d6.roll.return_value = sentinel.d6
        mock_die.return_value = mock_d6

        result = roll(['d6'])

        mock_die.assert_called_once_with(6)
        mock_d6.roll.assert_called_once_with(1)
        self.assertEqual(result, [(sentinel.d6, )])
Esempio n. 6
0
def success_histogram(sample_size, attr, n, bins=0, path='/tmp/stats.png'):
    """Generates a histogram plot, returns (success data, figure bytes or path string)
    """
    data = np.empty(sample_size)
    for i in range(sample_size):
        data[i] = roller.roll(attr, 0, n, min_success=-attr - n).total

    # neat trick with np.unique for data for bar graph
    labels, counts = np.unique(data, return_counts=True)
    fig, ax = plt.subplots(1, 1)

    ax.set_title(
        "Attribute score = {attr}, {n}d10; {samples} {sample_noun}".format(
            attr=attr,
            n=n,
            die_noun='die' if n == 1 else 'dice',
            samples=sample_size,
            sample_noun='sample' if sample_size == 1 else 'samples'))
    ax.set_xlabel("Successes")
    ax.set_ylabel("Instances")
    ax.set_xticks(labels)

    # https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/barchart.html
    rects = ax.bar(labels, counts, align='center')
    for rect in rects:
        h = rect.get_height()
        w = rect.get_width()
        percentage = h / sample_size * 100

        # annotate each rect with a label
        ax.annotate(
            '{:.1f}%'.format(percentage),
            xy=(rect.get_x() + w / 2, h),  # xy coord tuple of annotation
            xytext=(0, 3),  # offset of text
            textcoords="offset points",  #
            ha='center',  # center horizontal alignment
            va='bottom'  # bottom vertical alignment
        )
        ax.annotate(
            '{}'.format(h),
            xy=(rect.get_x() + w / 2, h),  # xy coord tuple of annotation
            xytext=(0, 12),  # offset of text
            textcoords="offset points",  #
            ha='center',  # center horizontal alignment
            va='bottom'  # bottom vertical alignment
        )

    ax.set_ymargin(0.15)  # add 15% extra space at top to fit labels

    # increase figure width with more data
    # TODO figure out a more elegant way to handle this
    fig.set_figwidth(1 * len(labels), forward=True)

    plt.savefig(path)
    return path
Esempio n. 7
0
async def on_message(message):
    if message.content.startswith('!r') or message.content.startswith(
            '/r'):  # TODO: Limit to !r and !roll
        log(message.channel.name, message.author.name, message.content)
        tmp = await client.send_message(message.channel, 'Rolling...')
        # Roll the dices
        dice_expression = message.content[message.content.find(' ') +
                                          1:].strip()
        try:
            result = roller.roll(dice_expression)
            response = 'Rolled: ' + result
        except:
            response = "Sorry I don't understand that roll '{}'".format(
                dice_expression)

        log(message.channel.name, 'dicebot', response)
        await client.edit_message(tmp, response)
    elif message.content in ('!help', '/help'):
        await client.send_message(message.channel, 'try `!r 1d6+1d2+2`')
Esempio n. 8
0
async def roll(text : str):
  messageToSend = ""
  diceNumbers = roller.getRolledNumbers(text.upper(), False)
  results = roller.roll(diceNumbers[0], diceNumbers[1], diceNumbers[2])
  for res in results:
    res += diceNumbers[3]

  for rollNum in results:
    if(diceNumbers[3] == 0):
        messageToSend = (messageToSend + 
                        "("+str(diceNumbers[1])+
                        "d"+str(diceNumbers[2])+") ["+
                        str(rollNum)+"] : {"+
                        str(rollNum+diceNumbers[3])+"} \n")
    else:
        messageToSend = (messageToSend + "("+
                         str(diceNumbers[1])+"d"+
                         str(diceNumbers[2])+"+"+
                         str(diceNumbers[3])+") ["+
                         str(rollNum)+"+"+
                         str(diceNumbers[3])+
                         "] : {"+
                         str(rollNum+diceNumbers[3])+"} \n")
  await client.say(messageToSend)
Esempio n. 9
0
def cmd_roll(args):
    if len(args) == 0:
        return "Please provide an attribute score\n" + help_roll

    try:
        attr = int(args[0])
        args = args[1:]
    except ValueError:
        return "`{num}` is not a valid integer".format(num=args[0])

    bonus = 0
    if len(args) > 0:
        try:
            bonus = int(args[0])
            args = args[1:]
        except ValueError:
            return "`{num}` is not a valid integer".format(num=args[0])

    n = attr
    if len(args) > 0:
        try:
            if args[0][0] == '+':
                # relative add
                n = attr + int(args[0][1:])
            else:
                # absolute count
                n = int(args[0])
            args = args[1:]
        except ValueError:
            return "`{num}` is not a valid integer".format(num=args[0])

    if n <= 0:
        return Message("Number of dice to be rolled must be greater than 0")
    if n > MAXIMUM_DICE:
        return "`{num}` exceeds the number of dice that can be rolled ({max_dice})".format(
            num=n, max_dice=MAXIMUM_DICE)

    result = roller.roll(attr, bonus, n)

    # print rolls
    msg = ""
    for roll in result.rolls[0:-1]:
        if roll <= attr: fmt = '**'
        elif roll == 10: fmt = '~~'
        else: fmt = ''
        msg += "{fmt}{val}{fmt}, ".format(fmt=fmt, val=str(roll))
    if len(result.rolls) > 0:
        roll = result.rolls[-1]
        if roll <= attr: fmt = '**'
        elif roll == 10: fmt = '~~'
        else: fmt = ''
        msg += "{fmt}{val}{fmt}".format(fmt=fmt, val=str(roll))

    # print explanation
    msg +=\
"""

Rolled {n} {n_noun} with an attribute score of {attr} and {bonus} bonus successes.
{successes} rolled {rs_noun}, {bonus} bonus {bs_noun}, and {negations} {neg_noun}

**Total successes: {total}  {emoji}**
""".format(n=n, n_noun=('die' if n==1 else 'dice'), attr=attr, bonus=result.bonus,
           successes=result.successes, negations=result.negations, total=result.total,
           rs_noun='success' if result.successes == 1 else 'successes',
           bs_noun='success' if result.bonus == 1 else 'successes',
           neg_noun='negation' if result.negations == 1 else 'negations',
           emoji=emoji_scale_absolute(result.total))

    return Message(content=msg)
Esempio n. 10
0
    Main file for Dice Roller 2.
"""

from roller import roll, rolls, show_rolls
from visual import visualize

while True:
    sides = int(
        input("What sided dice would you like to roll? (Press 0 to exit)\n"))
    # Exit condition.
    if (sides == 0):
        break

    num_dice = int(input("How many dice would you like to roll?\n"))

    output = roll(sides, num_dice)

    # Check for a critical.
    if (sides == 20 and num_dice == 1):
        if (output == 20):
            print("Critical Success!")
        elif (output == 1):
            print("Critical Failure!")

        print(output)

    print(output)

    show_die = input("Would you like to see your individual rolls? (y / n)\n")

    # Exit condition.
Esempio n. 11
0
 def test_roll_expr(self):
     result = roll(['1', '+', '1'])
     self.assertEqual(result, [1, '+', 1])
Esempio n. 12
0
 def test_roll_const(self):
     result = roll(['1'])
     self.assertEqual(result, [1])
Esempio n. 13
0
 def test_roll_nothing(self):
     result = roll([])
     self.assertEqual(result, [])
Esempio n. 14
0
            chann = rawhandle.getChannel(text, botnick)
            diceNumbers = roller.getRolledNumbers(command)
            messageToSend = ''

            #-------------------------------------------------------------------
            #   Hard limits on the dice sizes
            #-------------------------------------------------------------------

            if diceNumbers[0] > 10:
                diceNumbers[0] = 10
            
            if diceNumbers[1] > 2000:
                diceNumbers[1] = 2000

            rolledArray = roller.roll(diceNumbers[0],
                                      diceNumbers[1],
                                      diceNumbers[2])

            for rollNum in rolledArray:
                # REMINDER: make a message maker function cause this is ugly!
                if(diceNumbers[3] == 0):
                    messageToSend = (messageToSend + 
                                    "\x0312,15("+str(diceNumbers[1])+
                                    "d"+str(diceNumbers[2])+") \x032,15["+
                                    str(rollNum)+"]\x031,15 : \x034,15{"+
                                    str(rollNum+diceNumbers[3])+"} ")
                else:
                    messageToSend = (messageToSend + "\x0312,15("+
                                     str(diceNumbers[1])+"d"+
                                     str(diceNumbers[2])+"+"+
                                     str(diceNumbers[3])+") \x032,15["+
Esempio n. 15
0
window = gui.Window('Simple Dice Roller', layout)

# Event Loop to process "events" and get the "values" of the inputs
while True:
    event, values = window.read()

    window.FindElement('_output_').Update('')

    if event in ('Reset'):
        window.FindElement('_spin_').Update(value=1)

    elif event in ('D4'):
        if (values['_spin_'] != 1):
            r.multi_roll(str(values['_spin_']) + "d4")
        else:
            r.roll("d4")

    elif event in ('D6'):
        if (values['_spin_'] != 1):
            r.multi_roll(str(values['_spin_']) + "d6")
        else:
            r.roll("d6")

    elif event in ('D8'):
        if (values['_spin_'] != 1):
            r.multi_roll(str(values['_spin_']) + "d8")
        else:
            r.roll("d8")

    elif event in ('D10'):
        if (values['_spin_'] != 1):