如何让Discord国旗猜谜Bot持续运行,结束后自动开启新游戏?
实现Discord国旗猜谜Bot自动续局功能
要让Bot在单局结束后自动启动新游戏,核心是把单局游戏逻辑放进无限循环里,同时可以加个主动退出的机制,避免游戏一直无法停止。以下是修改后的完整代码:
@bot.command(name='flags', description='Play a flag guessing game') async def flag_game(ctx:commands.Context): """Start a flag guessing game that auto-restarts after each round.""" # 用无限循环实现自动续局 while True: # Randomly select a flag from the list. random_flag = random.choice(list(flags.keys())) # Send a "Drawing..." message with an emoji. drawing_message = await ctx.send("Drawing... :checkered_flag:") await ctx.reply("Flag Game Started") await ctx.channel.purge(limit=1) # Wait for 3 seconds. await asyncio.sleep(3) # Edit the message to show the flag. flag_emoji = flags[random_flag] embed = discord.Embed(title='Flag Game', description=f"Here is the flag of one of the countries. What is the name of this country?\n输入`!quit`可退出游戏") embed.add_field(name="Flag:", value=flag_emoji, inline=False) await drawing_message.edit(content=None, embed=embed) # Wait for the user's response. try: # 扩展check条件,允许用户输入!quit退出游戏 response = await bot.wait_for( "message", check=lambda m: m.author == ctx.author and m.channel == ctx.channel, timeout=30.0 ) # 处理退出指令 if response.content.lower() == "!quit": await ctx.send("游戏已退出,感谢参与!") break # 跳出循环,终止游戏 # Check the response, ignoring case. if response.content.lower() == random_flag.lower(): await ctx.send(f"恭喜答对!这是{random_flag}的国旗。") else: await ctx.send(f"答错啦,正确答案是{random_flag}。") except asyncio.TimeoutError: await ctx.send("答题超时,自动开始下一局游戏!") # 超时后不终止,继续循环启动新局 # 移除原有的else return,让循环自动进入下一轮
关键改动说明
- 无限循环包裹逻辑:用
while True把单局游戏的所有步骤包起来,每局结束后自动执行下一轮。 - 添加主动退出机制:在等待用户响应时,允许输入
!quit触发退出,用break跳出循环终止游戏。 - 超时处理优化:超时后不再结束游戏,而是提示后直接进入下一局。
- 更新提示信息:在Embed里增加退出指令的提示,让用户知道如何终止游戏。
内容的提问来源于stack exchange,提问作者Usi Ogbeide
相关产品推荐
相关产品推荐

