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}"):
guess = chr(ord(reaction.emoji)-127397) self.bot.log("They reacted to the hangman message")
await self.bot.games.gameLoops.runHangman(channel,"#"+str(user.id),command="guess "+guess) if ord(reaction.emoji) in range(127462,127488):
guess = chr(ord(reaction.emoji)-127397)
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,86 +31,128 @@ 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)
correctGuess = 0
for x, letter in enumerate(game["word"]): if validGuess:
if guess == letter: self.bot.log("Guessed the letter")
correctGuess += 1 correctGuess = 0
self.bot.database["hangman games"].update_one({"_id":channel},{"$set":{"guessed."+str(x):True}})
if correctGuess == 0: for x, letter in enumerate(game["word"]):
self.bot.database["hangman games"].update_one({"_id":channel},{"$inc":{"misses":1}}) if guess == letter:
correctGuess += 1
self.bot.database["hangman games"].update_one({"_id":channel},{"$set":{"guessed."+str(x):True}})
self.bot.database["hangman games"].update_one({"_id":channel},{"$push":{"guessed letters":guess}}) if correctGuess == 0:
self.bot.database["hangman games"].update_one({"_id":channel},{"$inc":{"misses":1}})
remainingLetters = list(string.ascii_uppercase) self.bot.database["hangman games"].update_one({"_id":channel},{"$push":{"guessed letters":guess}})
game = self.bot.database["hangman games"].find_one({"_id":channel}) remainingLetters = list(string.ascii_uppercase)
for letter in game["guessed letters"]: game = self.bot.database["hangman games"].find_one({"_id":channel})
remainingLetters.remove(letter)
if correctGuess == 1: for letter in game["guessed letters"]:
message = f"Guessed {guess}. There was 1 {guess} in the word." remainingLetters.remove(letter)
else:
message = f"Guessed {guess}. There were {correctGuess} {guess}s in the word."
try: if correctGuess == 1:
self.draw.drawImage(channel) sendMessage = f"Guessed {guess}. There was 1 {guess} in the word."
except:
self.bot.log("Error drawing image (error code 1710)")
if game["misses"] == 6:
self.hangmanStop(channel)
return message+" You've guessed wrong six times and have lost the game.", True, True, []
elif all(i == True for i in game["guessed"]):
self.hangmanStop(channel)
self.bot.money.addMoney(user,15)
return message+" You've guessed the word! Congratulations! Adding 15 GwendoBucks to your account", True, True, []
else:
return message, True, True, remainingLetters
else:
return f"You've already guessed {guess}", False, False, []
else:
return "", False, False, []
else: else:
return "", False, False, [] sendMessage = f"Guessed {guess}. There were {correctGuess} {guess}s in the word."
else:
return "There's no Hangman game going on in this channel", False, False, [] self.draw.drawImage(channel)
if game["misses"] == 6:
self.bot.database["hangman games"].delete_one({"_id":channel})
sendMessage += " You've guessed wrong six times and have lost the game."
remainingLetters = []
elif all(i == True for i in game["guessed"]):
self.bot.database["hangman games"].delete_one({"_id":channel})
self.bot.money.addMoney(user,15)
sendMessage += " You've guessed the word! Congratulations! Adding 15 GwendoBucks to your account"
remainingLetters = []
await message.channel.send(sendMessage)
with open(f"resources/games/oldImages/hangman{channel}", "r") as f:
oldMessageIDs = f.read().splitlines()
for oldID in oldMessageIDs:
oldMessage = await message.channel.fetch_message(int(oldID))
self.bot.log("Deleting old message")
await oldMessage.delete()
filePath = f"resources/games/hangmanBoards/hangmanBoard{channel}.png"
newImage = await message.channel.send(file = discord.File(filePath))
if len(remainingLetters) > 0:
if len(remainingLetters) > 15:
blankMessage = await message.channel.send("_ _")
reactionMessages = {newImage : remainingLetters[:15], blankMessage : remainingLetters[15:]}
else:
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)
def parseHangman(self,channel,user,command):
if command == "start":
try:
return self.hangmanStart(channel,user)
except:
self.bot.log("Error starting game (error code 1730)")
elif command == "stop":
return self.hangmanStop(channel)
elif command.startswith("guess "):
guess = command[6:].upper()
try:
return self.hangmanGuess(channel,user,guess)
except:
self.bot.log("Error in guessing (Error Code 1720)")
else:
return "I didn't understand that", False, False, []

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,8 +111,11 @@ 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)})
gameMessage = True if user == game["player"]:
gameMessage = True
break
return gameMessage return gameMessage