如何在一个命令中掷多个骰子

2024-05-20 18:45:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个discord机器人,我已经制作了一个掷骰子系统,但我想改进它。我想一次掷多个骰子,就像Avrae一样

@client.command(aliases=['r', 'dado', 'dice'])
async def roll(ctx, dados='', numero=20, conta='', ficha=''):
  rolagem = random.randint(1,int(numero))
  if conta == '':
        total = (int(rolagem))
  elif conta == '+':
         total = (int(rolagem) + int(ficha))
  elif conta == '-':
         total = (int(rolagem) - int(ficha))
  elif conta == 'x':
         total = (int(rolagem) * int(ficha))
  elif conta == '/':
         total = (int(rolagem) / int(ficha))
  if ficha == '':
          ficha = ''
  if total < 0:
          total = '1'
  if total == 0:
          total == '1'
  if rolagem == 20:
          rolagem = '**20**'
  if rolagem == 1:
          rolagem = '**1**'
  await ctx.send(f'{ctx.author.mention} 🎇 \n**Resultado**: D{numero} ({rolagem}) {conta} {ficha}\n**Total**: {total}')

因此,该命令的工作方式应该是:(前缀)r(要掷骰子的数量)(骰子),并显示如下结果:(掷骰子的数量):(骰子结果)(骰子结果的总和) 例如:-r5d20;5d20的结果:(1,5,8,16,20)(总和)。 我想知道我该怎么做


Tags: 数量if系统机器人骰子inttotalctx
1条回答
网友
1楼 · 发布于 2024-05-20 18:45:49

这是我编写的一个roll函数,经过修改,可以像您一样使用字符串:

import random


def roll(n='1', d='20', a='+', m='0'):
    res = []
    for i in range(int(n)):
        res.append(random.randint(1, int(d)))

    roll_modified = sum(res)
    if a == '+' or a == '-' or a == '*' or a == '/':
        roll_modified = eval('{}{}{}'.format(roll_modified, a, int(m)))

    if roll_modified < 1:
        roll_modified = 1

    return roll_modified, res

它使用eval来应用修饰符,因此请谨慎使用。我检查运算符的值,并对数字使用int(),以确保它是一个安全的表达式

像这样使用它:

roll_modified, res = roll('3', '20', '-', '2')
  • roll_modified是应用sum和修饰符后的结果
  • res是所有原始卷的列表

然后,您可以使用以下内容打印结果:

res_str = ["**{}**".format(x) if x == 20 or x == 1 else str(x) for x in res]
print(roll_modified, "[{}]".format(", ".join(res_str)))

将输出:

36 [14, 4, **20**]

相关问题 更多 >