Converted all hangman functionality to slash commands

This commit is contained in:
NikolajDanger
2021-04-04 15:12:34 +02:00
parent 75e90d4166
commit e4a44fffef
5 changed files with 133 additions and 115 deletions

View File

@@ -99,16 +99,16 @@ class HangmanCog(commands.Cog):
def __init__(self,bot): def __init__(self,bot):
"""Runs game stuff.""" """Runs game stuff."""
self.bot = bot self.bot = bot
# Starts a game of Hangman # Starts a game of Hangman
@cog_ext.cog_subcommand(**params["hangmanStart"]) @cog_ext.cog_subcommand(**params["hangmanStart"])
async def hangmanStart(self, ctx): async def hangmanStart(self, ctx):
await ctx.defer() await self.bot.games.hangman.start(ctx)
await self.bot.games.gameLoops.runHangman(ctx.channel,"#"+str(ctx.author.id),"start", ctx)
# Stops a game of Hangman # Stops a game of Hangman
@cog_ext.cog_subcommand(**params["hangmanStop"]) @cog_ext.cog_subcommand(**params["hangmanStop"])
async def hangmanStop(self, ctx): async def hangmanStop(self, ctx):
await self.bot.games.gameLoops.runHangman(ctx.channel,"#"+str(ctx.author.id),"stop", ctx) await self.bot.games.hangman.stop(ctx)
class HexCog(commands.Cog): class HexCog(commands.Cog):
@@ -147,6 +147,7 @@ class HexCog(commands.Cog):
async def hexPlace(self, ctx, coordinates): async def hexPlace(self, ctx, coordinates):
await self.bot.games.gameLoops.runHex(ctx, "place "+coordinates, "#"+str(ctx.author.id)) await self.bot.games.gameLoops.runHex(ctx, "place "+coordinates, "#"+str(ctx.author.id))
def setup(bot): def setup(bot):
bot.add_cog(GamesCog(bot)) bot.add_cog(GamesCog(bot))
bot.add_cog(BlackjackCog(bot)) bot.add_cog(BlackjackCog(bot))

View File

@@ -39,9 +39,13 @@ class ReactionCog(commands.Cog):
else: else:
imdbName = imdbIds[showPick-1] imdbName = imdbIds[showPick-1]
await self.bot.other.bedreNetflix.addShow(channel,imdbName) await self.bot.other.bedreNetflix.addShow(channel,imdbName)
elif self.bot.databaseFuncs.hangmanReactionTest(channel,message) and ord(reaction.emoji) in range(127462,127488): elif self.bot.databaseFuncs.hangmanReactionTest(channel, message, f"#{user.id}"):
self.bot.log("They reacted to the hangman message")
if ord(reaction.emoji) in range(127462,127488):
guess = chr(ord(reaction.emoji)-127397) guess = chr(ord(reaction.emoji)-127397)
await self.bot.games.gameLoops.runHangman(channel,"#"+str(user.id),command="guess "+guess) await self.bot.games.hangman.guess(message, f"#{user.id}", guess)
else:
self.bot.log("Bot they didn't react with a valid guess")
def setup(bot): def setup(bot):
bot.add_cog(ReactionCog(bot)) bot.add_cog(ReactionCog(bot))

View File

@@ -90,43 +90,6 @@ class GameLoops():
self.bot.databaseFuncs.deleteGame("connect 4 games",channelId) self.bot.databaseFuncs.deleteGame("connect 4 games",channelId)
async def runHangman(self,channel,user,command = "start", ctx = None):
try:
response, showImage, deleteImage, remainingLetters = self.bot.games.hangman.parseHangman(str(channel.id),user,command)
except:
self.bot.log("Error parsing command (error code 1701)")
if response != "":
if ctx is None:
await channel.send(response)
else:
await ctx.send(response)
self.bot.log(response,str(channel.id))
if showImage:
if deleteImage:
await self.deleteMessage("hangman"+str(channel.id),channel)
oldImage = await channel.send(file = discord.File("resources/games/hangmanBoards/hangmanBoard"+str(channel.id)+".png"))
if len(remainingLetters) > 15:
otherMessage = await channel.send("_ _")
reactionMessages = {oldImage : remainingLetters[:15],otherMessage : remainingLetters[15:]}
else:
otherMessage = ""
reactionMessages = {oldImage : remainingLetters}
oldMessages = str(oldImage.id)
if otherMessage != "":
oldMessages += "\n"+str(otherMessage.id)
with open("resources/games/oldImages/hangman"+str(channel.id), "w") as f:
f.write(oldMessages)
try:
for message, letters in reactionMessages.items():
for letter in letters:
emoji = chr(ord(letter)+127397)
await message.add_reaction(emoji)
except:
self.bot.log("Image deleted before adding all reactions")
# Runs Hex # Runs Hex
async def runHex(self,ctx,command,user): async def runHex(self,ctx,command,user):
channelId = ctx.channel_id channelId = ctx.channel_id

View File

@@ -1,4 +1,4 @@
import json, urllib, datetime, string import json, urllib, datetime, string, discord
from .hangmanDraw import DrawHangman from .hangmanDraw import DrawHangman
@@ -9,8 +9,13 @@ class Hangman():
self.bot = bot self.bot = bot
self.draw = DrawHangman(bot) self.draw = DrawHangman(bot)
def hangmanStart(self,channel,user): async def start(self, ctx):
await ctx.defer()
channel = str(ctx.channel_id)
user = f"#{ctx.author.id}"
game = self.bot.database["hangman games"].find_one({"_id":channel}) game = self.bot.database["hangman games"].find_one({"_id":channel})
userName = self.bot.databaseFuncs.getName(user)
startedGame = False
if game == None: if game == None:
apiKey = self.bot.credentials.wordnikKey apiKey = self.bot.credentials.wordnikKey
@@ -26,26 +31,60 @@ class Hangman():
remainingLetters = list(string.ascii_uppercase) remainingLetters = list(string.ascii_uppercase)
try:
self.draw.drawImage(channel) self.draw.drawImage(channel)
except:
self.bot.log("Error drawing image (error code 1710)")
return f"{self.bot.databaseFuncs.getName(user)} started game of hangman.", True, False, remainingLetters
else:
return "There's already a Hangman game going on in the channel", False, False, []
def hangmanStop(self,channel): logMessage = "Game started"
sendMessage = f"{userName} started game of hangman."
startedGame = True
else:
logMessage = "There was already a game going on"
sendMessage = "There's already a Hangman game going on in the channel"
self.bot.log(logMessage)
await ctx.send(sendMessage)
if startedGame:
filePath = f"resources/games/hangmanBoards/hangmanBoard{channel}.png"
newImage = await ctx.channel.send(file = discord.File(filePath))
blankMessage = await ctx.channel.send("_ _")
reactionMessages = {newImage : remainingLetters[:15], blankMessage : remainingLetters[15:]}
oldMessages = f"{newImage.id}\n{blankMessage.id}"
with open(f"resources/games/oldImages/hangman{channel}", "w") as f:
f.write(oldMessages)
for message, letters in reactionMessages.items():
for letter in letters:
emoji = chr(ord(letter)+127397)
await message.add_reaction(emoji)
async def stop(self, ctx):
channel = str(ctx.channel.id)
self.bot.database["hangman games"].delete_one({"_id":channel}) self.bot.database["hangman games"].delete_one({"_id":channel})
return "Game stopped.", False, False, [] with open(f"resources/games/oldImages/hangman{channel}", "r") as f:
messages = f.read().splitlines()
def hangmanGuess(self,channel,user,guess): for message in messages:
oldMessage = await ctx.channel.fetch_message(int(message))
self.bot.log("Deleting old message")
await oldMessage.delete()
await ctx.send("Game stopped")
async def guess(self, message, user, guess):
channel = str(message.channel.id)
game = self.bot.database["hangman games"].find_one({"_id":channel}) game = self.bot.database["hangman games"].find_one({"_id":channel})
if game != None: gameExists = (game != None)
if user == game["player"]: singleLetter = (len(guess) == 1 and guess.isalpha())
if len(guess) == 1 and guess in list(string.ascii_uppercase): newGuess = (guess not in game["guessed letters"])
if guess not in game["guessed letters"]: validGuess = (gameExists and singleLetter and newGuess)
if validGuess:
self.bot.log("Guessed the letter")
correctGuess = 0 correctGuess = 0
for x, letter in enumerate(game["word"]): for x, letter in enumerate(game["word"]):
@@ -66,46 +105,54 @@ class Hangman():
remainingLetters.remove(letter) remainingLetters.remove(letter)
if correctGuess == 1: if correctGuess == 1:
message = f"Guessed {guess}. There was 1 {guess} in the word." sendMessage = f"Guessed {guess}. There was 1 {guess} in the word."
else: else:
message = f"Guessed {guess}. There were {correctGuess} {guess}s in the word." sendMessage = f"Guessed {guess}. There were {correctGuess} {guess}s in the word."
try:
self.draw.drawImage(channel) self.draw.drawImage(channel)
except:
self.bot.log("Error drawing image (error code 1710)")
if game["misses"] == 6: if game["misses"] == 6:
self.hangmanStop(channel) self.bot.database["hangman games"].delete_one({"_id":channel})
return message+" You've guessed wrong six times and have lost the game.", True, True, [] sendMessage += " You've guessed wrong six times and have lost the game."
remainingLetters = []
elif all(i == True for i in game["guessed"]): elif all(i == True for i in game["guessed"]):
self.hangmanStop(channel) self.bot.database["hangman games"].delete_one({"_id":channel})
self.bot.money.addMoney(user,15) self.bot.money.addMoney(user,15)
return message+" You've guessed the word! Congratulations! Adding 15 GwendoBucks to your account", True, True, [] sendMessage += " You've guessed the word! Congratulations! Adding 15 GwendoBucks to your account"
else: remainingLetters = []
return message, True, True, remainingLetters
else:
return f"You've already guessed {guess}", False, False, []
else:
return "", False, False, []
else:
return "", False, False, []
else:
return "There's no Hangman game going on in this channel", False, False, []
def parseHangman(self,channel,user,command): await message.channel.send(sendMessage)
if command == "start":
try: with open(f"resources/games/oldImages/hangman{channel}", "r") as f:
return self.hangmanStart(channel,user) oldMessageIDs = f.read().splitlines()
except:
self.bot.log("Error starting game (error code 1730)") for oldID in oldMessageIDs:
elif command == "stop": oldMessage = await message.channel.fetch_message(int(oldID))
return self.hangmanStop(channel) self.bot.log("Deleting old message")
elif command.startswith("guess "): await oldMessage.delete()
guess = command[6:].upper()
try: filePath = f"resources/games/hangmanBoards/hangmanBoard{channel}.png"
return self.hangmanGuess(channel,user,guess) newImage = await message.channel.send(file = discord.File(filePath))
except:
self.bot.log("Error in guessing (Error Code 1720)") if len(remainingLetters) > 0:
if len(remainingLetters) > 15:
blankMessage = await message.channel.send("_ _")
reactionMessages = {newImage : remainingLetters[:15], blankMessage : remainingLetters[15:]}
else: else:
return "I didn't understand that", False, False, [] blankMessage = ""
reactionMessages = {newImage : remainingLetters}
if blankMessage != "":
oldMessages = f"{newImage.id}\n{blankMessage.id}"
else:
oldMessages = str(newImage.id)
with open(f"resources/games/oldImages/hangman{channel}", "w") as f:
f.write(oldMessages)
for message, letters in reactionMessages.items():
for letter in letters:
emoji = chr(ord(letter)+127397)
await message.add_reaction(emoji)

View File

@@ -100,7 +100,7 @@ class databaseFuncs():
else: else:
return False, 0 return False, 0
def hangmanReactionTest(self, channel,message): def hangmanReactionTest(self, channel, message, user):
try: try:
with open("resources/games/oldImages/hangman"+str(channel.id), "r") as f: with open("resources/games/oldImages/hangman"+str(channel.id), "r") as f:
oldMessages = f.read().splitlines() oldMessages = f.read().splitlines()
@@ -111,9 +111,12 @@ class databaseFuncs():
for oldMessage in oldMessages: for oldMessage in oldMessages:
oldMessageID = int(oldMessage) oldMessageID = int(oldMessage)
if message.id == oldMessageID: if message.id == oldMessageID:
self.bot.log("They reacted to the hangman game") game = self.bot.database["hangman games"].find_one({"_id":str(channel.id)})
if user == game["player"]:
gameMessage = True gameMessage = True
break
return gameMessage return gameMessage
def bedreNetflixReactionTest(self, channel, message): def bedreNetflixReactionTest(self, channel, message):