仅在触发当前命令时如何使用命令?

时间:2018-06-30 06:32:30

标签: python python-3.x discord discord.py

这个问题可能很复杂,我的大脑无法真正很好地解释这个问题,所以请对此做出bare脚的解释,我的问题是,例如,当您触发命令时,启动它就可以说是一个基于文本的游戏。您将拥有能够实际玩游戏的命令,但是我担心的是,人们仍然可以触发游戏中的命令而无需启动游戏。例如

     if message.content.startswith("/play"):       #Here is the play command where you execute the game to start
         await client.send_message(message.channel, "Welcome to the game!")
     if message.content.startswith("/examine):
         await client.send_message(message.channel, "You examined the rock and well, got a rock!") #In-Game commands/movements

我的意思是,有一种方法只有在激活游戏本身时才能够使用游戏中的命令吗? 附加问题:您将如何像基本保存游戏一样存储用户的信息(您实际上不需要回答这个,因为我想自己学习,但是任何提示都很棒!)

1 个答案:

答案 0 :(得分:0)

首先,我们需要一些对象来存储特定会话的状态。我们可以仅将此对象称为Game。我们将维护从discord.UserGame的映射。此映射中存在User表示他们正在玩游戏。一些基础知识看起来像:

from discord.ext import commands

class Game:
    def __init__(self):
        self.points = 0
        self.inventory = []

bot = commands.Bot('/')

sessions = {}

@bot.command(pass_context=True)
async def play(ctx):
    if ctx.message.author.id in sessions:
        await bot.say("You're already playing")
        return
    sessions[ctx.message.author.id] = Game()
    await bot.say("Welcome to the game!")

@bot.command(pass_context=True)
async def quit(ctx):
    if ctx.message.author.id not in sessions:
        await bot.say("You're not playing the game")
        return
    del sessions[ctx.message.author.id]
    await bot.say("Game Over")

@bot.command(pass_context=True)
async def examine(ctx):
    session = sessions.get(ctx.message.author.id, None)
    if session is None:
        await bot.say("You're not playing the game")
        return
    session.inventory.append("A rock")
    await bot.say("You examined the rock and well, got a rock!")

bot.run("TOKEN")

您可以采取一些措施来扩展此范围:使用checkCommandError来避免重复检查会话的代码;确保Gamepickleable,并编写代码以使用pickle保存游戏;编写比收集岩石更有趣的游戏。

相关问题