首页 > 解决方案 > 在使用 discord.py 编写机器人时,我可以避免在 python 中使用全局变量吗?

问题描述

我正在使用 discord.py 开发我的第一个编程项目,一个不和谐的机器人。我想添加一个带有骰子的小游戏,但为此我使用了全局变量。我知道建议不要使用它们,我想知道,有没有一种方法可以在不使用全局变量的情况下做同样的事情?

这是我的代码:

dice_list = ['1', '2', '3', '4', '5', '6']
roll_1 = ''
roll_2 = ''
player_1 = ''
player_2 = ''
@client.command()
async def dice(ctx):
    global roll_1
    global roll_2
    global player_1
    global player_2
    if roll_1 == '':
        roll_1 = random.choice(dice_list)
        player_1 = ctx.message.author
        await ctx.send(f'{ctx.message.author.mention} rolled **{roll_1}**!')
    else:
        if ctx.message.author != player_1:
            roll_2 = random.choice(dice_list)
            player_2 = ctx.message.author
            await ctx.send(f'{ctx.message.author.mention} rolled **{roll_2}**!')
        else:
            await ctx.send(f'You already rolled {roll_1}, wait for someone to play with you.')
        if roll_1 > roll_2 and player_2 != '':
            await ctx.send(f'{player_1} won!')
            roll_1 = ''
            roll_2 = ''
            player_1 =''
            player_2 =''
        elif roll_2 > roll_1 and player_2 != '':
            await ctx.send(f'{player_2} won!')
            roll_1 = ''
            roll_2 = ''
            player_1 =''
            player_2 =''
        elif player_2 != '':
            await ctx.send('Tie!')
            roll_1 = ''
            roll_2 = ''
            player_1 =''
            player_2 =''

标签: pythondiscord

解决方案


您可以设置机器人的属性。

client.roll_1 = "..."

这些在您拥有客户对象的任何地方都可用。

如果您想在其他地方使用该变量,当然最好在代码开头声明一个标准值,但您也可以检查该属性是否存在

if hasattr(client, "roll_1"):
    # work with client.roll_1
else:
    # roll_1 wasn't defined yet

我希望我能帮上忙


推荐阅读