python - 在使用 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 =''
解决方案
您可以设置机器人的属性。
client.roll_1 = "..."
这些在您拥有客户对象的任何地方都可用。
如果您想在其他地方使用该变量,当然最好在代码开头声明一个标准值,但您也可以检查该属性是否存在
if hasattr(client, "roll_1"):
# work with client.roll_1
else:
# roll_1 wasn't defined yet
我希望我能帮上忙
推荐阅读
- php - 社交名流:合并具有相同电子邮件的帐户
- python - 如何使用highlight.js(或其他东西)在R闪亮中突出Python和其他语言
- oracle-apex - 无法在 Oracle APEX 中访问请求 URL
- android - Android - 如何制作这个视差动画(见动画)
- c - 如何在 C 中更改加载程序
- java - 如果下游有多个operator,flink会发送重复记录吗
- javascript - 简单的 jQuery 函数在 IE Edge 上不起作用,显示 SCRIPT1006: Expected ')'
- javascript - JavaScript 超时重置机制
- java - 需要帮助在java中填充数组
- swift - 如何检测数组是否已完全循环通过