You would need to store all the active games somewhere. This would probably work fine in memory, but you may choose to use a database for persistence and sharing across multiple services/instances.
This storage below is client.games
which is a dictionary where the keys are the user's Discord ID and the value is an instance of Game
.
It is recommended to use discord.ext.commands
instead of using on_message
, especially with more complex commands. There is an overview on the docs which goes in-depth into why you might want to use it and how to get started.
For example:
import discord
class Card:
def __init__(self, suit: str, value: str) -> None:
self.suit = suit
self.value = value
class Game:
def __init__(self) -> None:
self.cards: list[Card] = []
def hit(self) -> Card:
# Return a random `Card` instance
raise NotImplementedError()
...
# Assuming you're not using `commands.Bot` and therefore not a `commands.Cog`
client = discord.Client(...)
client.games = {} # user_id: `Game`
...
@client.event
async def on_message(message):
if "$blackjack" == message.content:
game = Game()
card = game.hit()
# e.g. Send card and show existing cards, handle going bust
...
client.games[message.author.id] = game
if "$hit" == message.content:
# You can use .get() to avoid raising if they have not already started a game
game = client.games[message.author.id]
card = game.hit()
# e.g. Send card and show existing cards, handle going bust
...
if "$stand" == message.content:
...
# Once the game is over, remove it
client.games.pop(message.author.id)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…