Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 向RPG骰子不和谐机器人添加减法_Python_Python 3.x_Discord.py - Fatal编程技术网

Python 向RPG骰子不和谐机器人添加减法

Python 向RPG骰子不和谐机器人添加减法,python,python-3.x,discord.py,Python,Python 3.x,Discord.py,我正在构建一个可以同时计算多个骰子掷骰的机器人,到目前为止,我可以添加多个骰子和固定数字,但要进行减法,语法如下:#roll 1d20+-1d6,我一直在尝试键入“-”符号,但我找不到方法。代码如下 @bot.command(name="roll") async def roll(ctx, dices: str): l_dices = dices.split("+") length = len(l_dices) values = [

我正在构建一个可以同时计算多个骰子掷骰的机器人,到目前为止,我可以添加多个骰子和固定数字,但要进行减法,语法如下:#roll 1d20+-1d6,我一直在尝试键入“-”符号,但我找不到方法。代码如下

@bot.command(name="roll")
async def roll(ctx, dices: str):
    l_dices = dices.split("+")
    length = len(l_dices)
    values = []
    total = 0
    valueString = ""

    #loops through every dice/modifier
    for x in l_dices:
        #checks if it is a dice or modifier value
        if "d" in x:
            #splits between number of dices and number of sides in each dice
            number = int(x.split("d")[0])
            sides = int(x.split("d")[1])
            for i in range(number):
                #gets a random value in the range of the dice
                dice_result = random.randrange(1, sides + 1)
                values.append(dice_result)
                
                #adds every die to a list to show individual dice results
                if valueString == '':
                    valueString += str(dice_result)
                else:
                    valueString += ', ' + str(dice_result)
        else:
            #adds together every modifier
            total += int(x)
    #gets the final result
    total += sum(values)
    #show the final results in chat
    await ctx.send(ctx.message.author.mention + "\n:VALORES:\n" + valueString + "\n:RESULTADO:\n" + str(total))

问题在于,当前使用“+”作为分隔符,如您在中定义的:

l_dices = dices.split("+")
这意味着,您只是通过“+”符号来分隔命令的各个部分,而不是别的。因此,为了解决这个问题,您需要解决如何解析用户输入。我个人建议使用regex,因为这将允许您在将来很容易地添加更多分隔符。下面是一个通过+和-符号解析命令的快速代码段:

重新导入
def parsecommand(命令字符串):
commands=re.split(r“(\+\124; \-)”,命令字符串)
返回命令
这将解析命令字符串,按+或-,进行拆分,并添加输出符号。例如:

commandstr=“d6+d8-2d12” >>>打印(parsecommand(commandstr)) [“d6”、“+”、“d8”、“-”、“2d12”]
我相信你可以很容易地解析这个列表,运行你想要的任何计算:)

你能澄清这个问题吗?不确定你到底想对代码做什么(为了公平起见,我对rpg骰子一无所知)。只想能够直接进行减法。现在要减去一个数字,我需要写成(5+-3),但答案是什么?我不知道它应该做什么。使用
split(“+”)
可以得到不同的骰子,因此至少必须确定这一点