VicBot Dice Roller(Python 2.7)

时间:2016-04-30 00:38:49

标签: python python-2.7

我说实话:我真的不知道自己在做什么。

我想这样做,所以VicBot(对于Python 2.7)可以" roll" "骰子"在命令" / roll xdy" x是die的数量,y是这些die的边数。

所以,更直接的我需要能够请求x变量≥y,并让它们显示"(变量)+(变量)=(总和)"

所有VicBot都可以在这里找到:https://github.com/Vicyorus/VicBot

(如果你想知道:我在完成之前意外发布了这个问题。)

1 个答案:

答案 0 :(得分:0)

我不太了解您的聊天机器人,也不想深入了解您在问题中包含的所有代码(如果有的话,我甚至都不清楚)是您编写的代码,而不是机器人附带的示例代码。

我能做的就是解决碾压问题。这很简单。您只需要Python的random模块和一些字符串操作和格式化代码。

import random

def roll_dice(dice_string):
    """Parse a string like "3d6" and return a string showing the die rolls and their sum"""
    number_of_dice, number_of_sides = map(int, dice_string.split("d"))
    rolls = [random.randint(1, number_of_sides) for _ in range(number_of_dice)]
    output_string = "{} = {}".format(" + ".join(map(str(rolls)), sum(rolls))
    return output_string

示例输出:

>>> roll_dice("5d6")
'6 + 6 + 5 + 5 + 6 = 28'
>>> roll_dice("5d6")
'1 + 5 + 1 + 2 + 2 = 11'
>>> roll_dice("3d100")
'16 + 83 + 56 = 155'
>>> roll_dice("1d20")
'18 = 18'

希望代码非常自我解释。函数中的四个语句各做一件事:解析输入,生成请求的随机数,将它们格式化为字符串以进行输出,最后返回字符串。执行实际随机数生成的第二行可能有助于作为单独的函数提取(获取整数参数并返回整数列表)。