python - 如何更新 discord.py 中的变量
问题描述
在这段代码中,我尝试在一个数字上赌博,只要我做对了,它就会给我 1 美元,但在这里我想在用户得到正确答案后更新变量,例如当用户得到第一个答案正确时,他得到 1美元,当他的第二个答案正确时,他得到 2 美元,即 +1,因此,每次他得到正确的赌博时,用户都会得到 +1 美元,但问题是它不会超过 1,即使在之后仍然保持在 1 美元我答对了10个。所以,关于如何解决它的任何想法
import discord
from discord.ext import commands
import random
import json
clients = commands.Bot(command_prefix='!')
Bot = discord.Client()
@Bot.event
async def on_ready():
print('ready')
@clients.command()
async def Gamble(ctx, num):
number = random.randint(1,2)
nums = 0
content = []
if int(num) == number:
nums = nums + 1
await ctx.send("Congratulations! you won 1 dollar")
content.append(nums)
print(content)
if int(num) != number:
await ctx.send('Better luck next time')
print(content)
client.run('TOKEN')
解决方案
尝试这个:
content = []
@bot.command()
async def Gamble(ctx, num):
global content
flag = False
for i in content:
if i[0] != ctx.author.name:
flag = False
else:
flag = True
if not flag:
content.append([ctx.author.name, 0])
number = random.randint(1, 2)
if int(num) == number:
await ctx.send("Congratulations! you won 1 dollar")
for i in content:
if i[0] == ctx.author.name:
i[1] += 1
print(content)
elif int(num) != number:
await ctx.send('Better luck next time')
print(content)
首先,我在全局范围内创建了一个名为 的列表content
,并global content
在Gamble
函数中添加以指示我正在引用全局content
列表。然后我检查了使用gamble命令的人之前是否已经使用过它。如果此人以前没有使用过它,那么它将在列表中创建一个子content
列表,并且它将用户名作为子列表中的第一个元素,并将分数(最初为 0)作为第二个元素. 然后,如果用户猜对了数字,代码将尝试在列表中找到该人的用户名,并仅更新该特定用户的点值。
推荐阅读
- python - filecmp 是否进行精确比较?
- event-handling - 如何避免事件被一般事件覆盖?
- scala - scala 泛型类型参数产生关于将 java.lang.Double 转换为 double 的 ClassCastException
- python - 2D Array update 实际上更新了两个不同的数组?
- c++ - Visual Studio:解决项目依赖项的构建标志/设置
- reactjs - Nextjs api“pages/api”在 vercel 服务器上不起作用
- kotlin - Kotlin MockK 抛出 NullPointerException
- google-cloud-platform - 谷歌云监控 - 设置自定义监控
- python - numpy 数组的条件语句
- java - 这个 IntelliJ 检查警告是误报吗?