import discord from discord.ext.commands import Bot bot = Bot(command_prefix='!') @bot.command() async def tictactoe(ctx): game = TicTacToe() await ctx.send(game.draw_board()) # This method prints the game's board. def check(message): return message.author == ctx.author and message.content.isdigit() \ and int(message.content) in range(1, 10) and game.check_move(int(message.content)-1) while not game.game_over: try: message = await bot.wait_for('message', check=check, timeout=30.0) except asyncio.TimeoutError: await ctx.send("Timeout reached.") game.game_over = True else: move = int(message.content) - 1 game.apply_move(move) await ctx.send(game.draw_board()) if game.check_winner() is not None: winner = game.check_winner() await ctx.send(f"Game over! {winner} wins!") game.game_over = True if game.check_tie(): await ctx.send(f"Game over! It's a tie!") break bot.run('TOKEN')
import discord from discord.ext import commands bot = commands.Bot(command_prefix='!') class Hangman: def __init__(self, word): self.word = word self.word_state = '* '*len(word) self.guesses = [] self.attempts = 5 def apply_guess(self, guess): if guess in self.word: self.update_word(guess) else: self.attempts -= 1 self.guesses.append(guess) def update_word(self, guess): for i, char in enumerate(self.word): if guess == char: self.word_state = self.word_state[:2*i] + guess + self.word_state[2*i+1:] def is_game_over(self): if self.attempts == 0: return True, f"Game Over! The word was {self.word}." elif ''.join(self.word_state.split()) == self.word: return True, f"Congratulations! You won with {self.attempts} attempts left!" else: return False, '' def draw_hangman(self): # Prints hangman image based on the number of attempts left. pass bot = Bot(command_prefix='!') @bot.command() async def hangman(ctx, word=None): if word is None: await ctx.send("Please provide a word to start a game.") return game = Hangman(word.upper()) await ctx.send(f"You have {game.attempts} attempts to guess this word: {game.word_state}") def check_guess(message): return message.author == ctx.author and len(message.content) == 1 and message.content.isalpha() \ and message.content.upper() not in game.guesses while not game.is_game_over()[0]: try: message = await bot.wait_for('message', check=check_guess, timeout=30.0) except asyncio.TimeoutError: await ctx.send("Timeout reached.") break else: guess = message.content.upper() game.apply_guess(guess) await ctx.send(f"You have {game.attempts} attempts to guess this word: {game.word_state}") if game.is_game_over()[0]: await ctx.send(game.is_game_over()[1]) bot.run('TOKEN')Python Discord Game uses the Discord API and the discord.ext.commands module to interact with the Discord platform. It also uses asyncio module to manage multiple tasks, such as waiting for user input during the game.