問題描述
這個問題可能很復雜,我的大腦無法很好地解釋它,所以請用這個蹩腳的解釋來解釋,我的問題,當你觸發一個命令時,例如 .start 它將開始讓我們說一個基于文本的游戲,當然您將擁有能夠實際玩游戲的命令,但我擔心人們仍然可以觸發游戲內命令而無需啟動游戲.
This question might be complicated and my brain can't really explain it well so please bare with this crappy explanation, My question, When you trigger a command for example .start it will start let's say a text based game, of course you would have the commands to be able to actually play the game however my concern is people can still trigger the ingame commands without needing to start the game for example .
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
我的意思是,有沒有辦法只有在游戲本身被激活時才能使用游戲中的命令?附加問題:您將如何存儲用戶的信息,例如基本上保存游戲(您實際上不需要回答這個問題,因為我想自己學習,但任何提示都會很棒!)
What i'm saying is, is there a way of only being able to use the in-game commands only when the game itself is activated? Additional Question: How would you store a user's information like basically saving the game (You don't really need to answer this as i would like to learn this myself but any tips would be great!)
推薦答案
首先,我們需要一些對象來存儲特定會話的狀態.我們可以把這個對象稱為Game
.我們將維護 discord.User
s 到 Game
s 的映射.此映射中存在的 User
表示他們正在玩游戲.一些基礎知識類似于:
First, we want some object that stores the state of a particular session. We can just call this object Game
. We'll maintain a mapping of discord.User
s to Game
s. A User
existing in this mapping means that they are playing the game. Some basics would look something like:
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")
您可以做一些事情來擴展它:利用 check
s 和 CommandError
s 來避免重復檢查會話的代碼;確保 Game
是 pickleable,并編寫使用pickle保存游戲的代碼;寫一個比收集石頭更有趣的游戲.
Some things you could do to extend this: make use of check
s and CommandError
s to avoid having to repeat the code for checking sessions; make sure that Game
s are pickleable, and write code for saving games using pickle; write a game that's more fun than collecting rocks.
這篇關于如何僅在觸發當前命令時使用命令?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!