Skip to main content
3 of 4
added 222 characters in body
AlexV
  • 7.3k
  • 2
  • 23
  • 47

@Linny already told you about list comprehensions. His suggestion would currently lead to the following code:

roll = [roll_die() for _ in range(0, dice)]

result = sorted(roll)
if keep == 'highest':
    result.reverse()

Looking at the documentation of sorted(...), reveals that is also accepts a an argument called reversed. Using that extra parameter allows the code piece above to be rewritten as

result = sorted(roll, reverse=(keep == 'highest'))

Another neat list-trick is that you can use outcome = [0, ] * keep_dice to generate a list of a given size with the same elements at all spots. However, be warned of the caveats.


Depending on which Python versions the code should run on, maybe also have a look at the new f-string formatting. Using them allows code like

embed = discord.Embed(title='**Dragon Eye** Ability Test for {}'.format(ctx.author.name),
                      description='Rolling {}d10, keep {} {}'.format(dice, keep, keep_dice),
                      color=0x22a7f0)

to be rewritten as

embed = discord.Embed(title=f'**Dragon Eye** Ability Test for {ctx.author.name}',
                      description=f'Rolling {dice}d10, keep {keep} {keep_dice}',
                      color=0x22a7f0)

f-strings are very powerful and also allow more complex expressions to be used:

embed.add_field(
    name='Additional Info',
    value=f'**Critical {"Success" if critical else "Fail"}**',
    inline=True
)

The string flags 'highest'/'lowest' could be replaced with an Enum. IDEs with autocompletion can help with them and therefore it's easier to avoid typos. However, this will slightly increase the effort needed to print them nicely for the user. In this special case a simple bool variable would also work, since you only have two possible values. The enum as well as the bool version could then use a ternary expression for printing if you want to follow this route.

AlexV
  • 7.3k
  • 2
  • 23
  • 47