From e0c38f0a0ad7b1d4d4aa85c178c0d5b5df3fe766 Mon Sep 17 00:00:00 2001 From: NikolajDanger Date: Sun, 18 Apr 2021 21:15:41 +0200 Subject: [PATCH] :sparkles: Hangman --- funcs/games/hangman.py | 261 +++++++++++++++++++++++-------------- resources/longStrings.json | 5 +- 2 files changed, 169 insertions(+), 97 deletions(-) diff --git a/funcs/games/hangman.py b/funcs/games/hangman.py index f330000..8da9592 100644 --- a/funcs/games/hangman.py +++ b/funcs/games/hangman.py @@ -1,32 +1,59 @@ -import json, urllib, datetime, string, discord -import math, random +import json +import requests +import datetime +import string +import discord +import math +import random +from discord_slash.context import SlashContext from PIL import ImageDraw, Image, ImageFont + class Hangman(): - def __init__(self,bot): + def __init__(self, bot): self.bot = bot self.draw = DrawHangman(bot) - self.APIURL = "https://api.wordnik.com/v4/words.json/randomWords?hasDictionaryDef=true&minCorpusCount=5000&maxCorpusCount=-1&minDictionaryCount=1&maxDictionaryCount=-1&minLength=3&maxLength=11&limit=1&api_key=" + self.APIURL = "https://api.wordnik.com/v4/words.json/randomWords?" + apiKey = self.bot.credentials.wordnikKey + self.APIPARAMS = { + "hasDictionaryDef": True, + "minCorpusCount": 5000, + "maxCorpusCount": -1, + "minDictionaryCount": 1, + "maxDictionaryCount": -1, + "minLength": 3, + "maxLength": 11, + "limit": 1, + "api_key": apiKey + } - async def start(self, ctx): + async def start(self, ctx: SlashContext): await self.bot.defer(ctx) 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: - apiKey = self.bot.credentials.wordnikKey + if game is None: word = "-" while "-" in word or "." in word: - with urllib.request.urlopen(self.APIURL+apiKey) as p: - word = list(json.load(p)[0]["word"].upper()) + response = requests.get(self.APIURL, params=self.APIPARAMS) + word = list(response.json()[0]["word"].upper()) + self.bot.log("Found the word \""+"".join(word)+"\"") guessed = [False] * len(word) - gameID = datetime.datetime.now().strftime('%Y%m%d%H%M%S') - newGame = {"_id":channel,"player" : user,"guessed letters" : [],"word" : word,"game ID" : gameID,"misses" : 0,"guessed" : guessed} + gameID = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + newGame = { + "_id": channel, + "player": user, + "guessed letters": [], + "word": word, + "game ID": gameID, + "misses": 0, + "guessed": guessed + } self.bot.database["hangman games"].insert_one(newGame) remainingLetters = list(string.ascii_uppercase) @@ -38,17 +65,21 @@ class Hangman(): startedGame = True else: logMessage = "There was already a game going on" - sendMessage = "There's already a Hangman game going on in the channel" + sendMessage = self.bot.longStrings["Hangman going on"] 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)) + boardsPath = "resources/games/hangmanBoards/" + filePath = f"{boardsPath}hangmanBoard{channel}.png" + newImage = await ctx.channel.send(file=discord.File(filePath)) - blankMessage = await ctx.channel.send("_ _") - reactionMessages = {newImage : remainingLetters[:15], blankMessage : remainingLetters[15:]} + blankMessage = await ctx.channel.send("_ _") + reactionMessages = { + newImage: remainingLetters[:15], + blankMessage: remainingLetters[15:] + } oldMessages = f"{newImage.id}\n{blankMessage.id}" @@ -60,7 +91,7 @@ class Hangman(): emoji = chr(ord(letter)+127397) await message.add_reaction(emoji) - async def stop(self, ctx): + async def stop(self, ctx: SlashContext): channel = str(ctx.channel.id) game = self.bot.database["hangman games"].find_one({"_id": channel}) @@ -69,7 +100,7 @@ class Hangman(): elif f"#{ctx.author.id}" != game["player"]: await ctx.send("You can't end a game you're not in") else: - self.bot.database["hangman games"].delete_one({"_id":channel}) + self.bot.database["hangman games"].delete_one({"_id": channel}) with open(f"resources/games/oldImages/hangman{channel}", "r") as f: messages = f.read().splitlines() @@ -81,11 +112,12 @@ class Hangman(): await ctx.send("Game stopped") - async def guess(self, message, user, guess): + async def guess(self, message: discord.Message, user: str, guess: str): channel = str(message.channel.id) - game = self.bot.database["hangman games"].find_one({"_id":channel}) + hangmanGames = self.bot.database["hangman games"] + game = hangmanGames.find_one({"_id": channel}) - gameExists = (game != None) + gameExists = (game is not None) singleLetter = (len(guess) == 1 and guess.isalpha()) newGuess = (guess not in game["guessed letters"]) validGuess = (gameExists and singleLetter and newGuess) @@ -97,35 +129,40 @@ class Hangman(): for x, letter in enumerate(game["word"]): if guess == letter: correctGuess += 1 - self.bot.database["hangman games"].update_one({"_id":channel},{"$set":{"guessed."+str(x):True}}) + updater = {"$set": {f"guessed.{x}": True}} + hangmanGames.update_one({"_id": channel}, updater) if correctGuess == 0: - self.bot.database["hangman games"].update_one({"_id":channel},{"$inc":{"misses":1}}) + updater = {"$inc": {"misses": 1}} + hangmanGames.update_one({"_id": channel}, updater) - self.bot.database["hangman games"].update_one({"_id":channel},{"$push":{"guessed letters":guess}}) + updater = {"$push": {"guessed letters": guess}} + hangmanGames.update_one({"_id": channel}, updater) remainingLetters = list(string.ascii_uppercase) - game = self.bot.database["hangman games"].find_one({"_id":channel}) + game = hangmanGames.find_one({"_id": channel}) for letter in game["guessed letters"]: remainingLetters.remove(letter) if correctGuess == 1: - sendMessage = f"Guessed {guess}. There was 1 {guess} in the word." + sendMessage = "Guessed {}. There was 1 {} in the word." + sendMessage = sendMessage.format(guess, guess) else: - sendMessage = f"Guessed {guess}. There were {correctGuess} {guess}s in the word." + sendMessage = "Guessed {}. There were {} {}s in the word." + sendMessage = sendMessage.format(guess, correctGuess, guess) 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." + hangmanGames.delete_one({"_id": channel}) + sendMessage += self.bot.longStrings["Hangman lost 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" + elif all(game["guessed"]): + hangmanGames.delete_one({"_id": channel}) + self.bot.money.addMoney(user, 15) + sendMessage += self.bot.longStrings["Hangman guessed word"] remainingLetters = [] await message.channel.send(sendMessage) @@ -138,23 +175,28 @@ class Hangman(): 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)) + boardsPath = "resources/games/hangmanBoards/" + filePath = f"{boardsPath}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:]} + blankMessage = await message.channel.send("_ _") + reactionMessages = { + newImage: remainingLetters[:15], + blankMessage: remainingLetters[15:] + } else: blankMessage = "" - reactionMessages = {newImage : remainingLetters} + 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: + oldImagePath = f"resources/games/oldImages/hangman{channel}" + with open(oldImagePath, "w") as f: f.write(oldMessages) for message, letters in reactionMessages.items(): @@ -162,58 +204,85 @@ class Hangman(): emoji = chr(ord(letter)+127397) await message.add_reaction(emoji) + class DrawHangman(): - def __init__(self,bot): + def __init__(self, bot): self.bot = bot self.CIRCLESIZE = 120 self.LINEWIDTH = 12 - self.BODYSIZE =210 + self.BODYSIZE = 210 self.LIMBSIZE = 60 self.ARMPOSITION = 60 - self.MANX = (self.LIMBSIZE*2)+self.LINEWIDTH*4 - self.MANY = (self.CIRCLESIZE+self.BODYSIZE+self.LIMBSIZE)+self.LINEWIDTH*4 + MANPADDING = self.LINEWIDTH*4 + self.MANX = (self.LIMBSIZE*2)+MANPADDING + self.MANY = (self.CIRCLESIZE+self.BODYSIZE+self.LIMBSIZE)+MANPADDING self.LETTERLINELENGTH = 90 self.LETTERLINEDISTANCE = 30 - self.GALLOWX, self.GALLOWY = 360,600 + self.GALLOWX, self.GALLOWY = 360, 600 self.GOLDENRATIO = 1-(1 / ((1 + 5 ** 0.5) / 2)) LETTERSIZE = 75 TEXTSIZE = 70 - self.FONT = ImageFont.truetype('resources/fonts/comic-sans-bold.ttf', LETTERSIZE) - self.SMALLFONT = ImageFont.truetype('resources/fonts/comic-sans-bold.ttf', TEXTSIZE) - def calcDeviance(self,preDev,preDevAcc,posChange,maxmin,maxAcceleration): - devAcc = preDevAcc + random.uniform(-posChange,posChange) - if devAcc > maxmin * maxAcceleration: devAcc = maxmin * maxAcceleration - elif devAcc < -maxmin * maxAcceleration: devAcc = -maxmin * maxAcceleration + FONTPATH = "resources/fonts/comic-sans-bold.ttf" + self.FONT = ImageFont.truetype(FONTPATH, LETTERSIZE) + self.SMALLFONT = ImageFont.truetype(FONTPATH, TEXTSIZE) - dev = preDev + devAcc - if dev > maxmin: dev = maxmin - elif dev < -maxmin: dev = -maxmin - return dev, devAcc + def calcDeviance(self, preDeviance, preDevianceAccuracy, positionChange, + maxmin, maxAcceleration): + randomDeviance = random.uniform(-positionChange, positionChange) + devianceAccuracy = preDevianceAccuracy + randomDeviance + if devianceAccuracy > maxmin * maxAcceleration: + devianceAccuracy = maxmin * maxAcceleration + elif devianceAccuracy < -maxmin * maxAcceleration: + devianceAccuracy = -maxmin * maxAcceleration + + deviance = preDeviance + devianceAccuracy + if deviance > maxmin: + deviance = maxmin + elif deviance < -maxmin: + deviance = -maxmin + return deviance, devianceAccuracy def badCircle(self): - background = Image.new("RGBA",(self.CIRCLESIZE+(self.LINEWIDTH*3),self.CIRCLESIZE+(self.LINEWIDTH*3)),color=(0,0,0,0)) + circlePadding = (self.LINEWIDTH*3) + imageWidth = self.CIRCLESIZE+circlePadding + imageSize = (imageWidth, imageWidth) + background = Image.new("RGBA", imageSize, color=(0, 0, 0, 0)) - d = ImageDraw.Draw(background,"RGBA") + d = ImageDraw.Draw(background, "RGBA") middle = (self.CIRCLESIZE+(self.LINEWIDTH*3))/2 - devx = 0 - devy = 0 - devAccx = 0 - devAccy = 0 - start = random.randint(-100,-80) - degreesAmount = 360 + random.randint(-10,30) + devianceX = 0 + devianceY = 0 + devianceAccuracyX = 0 + devianceAccuracyY = 0 + start = random.randint(-100, -80) + degreesAmount = 360 + random.randint(-10, 30) for degree in range(degreesAmount): - devx, devAccx = self.calcDeviance(devx,devAccx,self.LINEWIDTH/100,self.LINEWIDTH,0.03) - devy, devAccy = self.calcDeviance(devy,devAccy,self.LINEWIDTH/100,self.LINEWIDTH,0.03) + devianceXParams = [ + devianceX, + devianceAccuracyX, + self.LINEWIDTH/100, + self.LINEWIDTH, + 0.03 + ] + devianceYParams = [ + devianceY, + devianceAccuracyY, + self.LINEWIDTH/100, + self.LINEWIDTH, + 0.03 + ] + devianceX, devianceAccuracyX = self.calcDeviance(*devianceXParams) + devianceY, devianceAccuracyY = self.calcDeviance(*devianceYParams) - x = middle + (math.cos(math.radians(degree+start)) * (self.CIRCLESIZE/2)) - (self.LINEWIDTH/2) + devx - y = middle + (math.sin(math.radians(degree+start)) * (self.CIRCLESIZE/2)) - (self.LINEWIDTH/2) + devy + x = middle + (math.cos(math.radians(degree+start)) * (self.CIRCLESIZE/2)) - (self.LINEWIDTH/2) + devianceX + y = middle + (math.sin(math.radians(degree+start)) * (self.CIRCLESIZE/2)) - (self.LINEWIDTH/2) + devianceY d.ellipse([(x,y),(x+self.LINEWIDTH,y+self.LINEWIDTH)],fill=(0,0,0,255)) @@ -227,21 +296,21 @@ class DrawHangman(): background = Image.new("RGBA",(w,h),color=(0,0,0,0)) d = ImageDraw.Draw(background,"RGBA") - devx = random.randint(-int(self.LINEWIDTH/3),int(self.LINEWIDTH/3)) - devy = 0 - devAccx = 0 - devAccy = 0 + devianceX = random.randint(-int(self.LINEWIDTH/3),int(self.LINEWIDTH/3)) + devianceY = 0 + devianceAccuracyX = 0 + devianceAccuracyY = 0 for pixel in range(length): - devx, devAccx = self.calcDeviance(devx,devAccx,self.LINEWIDTH/1000,self.LINEWIDTH,0.004) - devy, devAccy = self.calcDeviance(devy,devAccy,self.LINEWIDTH/1000,self.LINEWIDTH,0.004) + devianceX, devianceAccuracyX = self.calcDeviance(devianceX,devianceAccuracyX,self.LINEWIDTH/1000,self.LINEWIDTH,0.004) + devianceY, devianceAccuracyY = self.calcDeviance(devianceY,devianceAccuracyY,self.LINEWIDTH/1000,self.LINEWIDTH,0.004) if rotated: - x = self.LINEWIDTH + pixel + devx - y = self.LINEWIDTH + devy + x = self.LINEWIDTH + pixel + devianceX + y = self.LINEWIDTH + devianceY else: - x = self.LINEWIDTH + devx - y = self.LINEWIDTH + pixel + devy + x = self.LINEWIDTH + devianceX + y = self.LINEWIDTH + pixel + devianceY d.ellipse([(x,y),(x+self.LINEWIDTH,y+self.LINEWIDTH)],fill=(0,0,0,255)) @@ -265,33 +334,33 @@ class DrawHangman(): if limb == "ra": limbDrawing = self.badLine(self.LIMBSIZE,True) rotation = random.randint(-45,45) - xpos = int((self.MANX-(self.LINEWIDTH*3))/2) + xPosition = int((self.MANX-(self.LINEWIDTH*3))/2) rotationCompensation = min(-int(math.sin(math.radians(rotation))*(self.LIMBSIZE+(self.LINEWIDTH*3))),0) - ypos = self.CIRCLESIZE+self.ARMPOSITION + rotationCompensation + yPosition = self.CIRCLESIZE+self.ARMPOSITION + rotationCompensation limbDrawing = limbDrawing.rotate(rotation,expand=1) - background.paste(limbDrawing,(xpos,ypos),limbDrawing) + background.paste(limbDrawing,(xPosition,yPosition),limbDrawing) elif limb == "la": limbDrawing = self.badLine(self.LIMBSIZE,True) rotation = random.randint(-45,45) - xpos = int((self.MANX-(self.LINEWIDTH*3))/2)-self.LIMBSIZE + xPosition = int((self.MANX-(self.LINEWIDTH*3))/2)-self.LIMBSIZE rotationCompensation = min(int(math.sin(math.radians(rotation))*(self.LIMBSIZE+(self.LINEWIDTH*3))),0) - ypos = self.CIRCLESIZE+self.ARMPOSITION + rotationCompensation + yPosition = self.CIRCLESIZE+self.ARMPOSITION + rotationCompensation limbDrawing = limbDrawing.rotate(rotation,expand=1) - background.paste(limbDrawing,(xpos,ypos),limbDrawing) + background.paste(limbDrawing,(xPosition,yPosition),limbDrawing) elif limb == "rl": limbDrawing = self.badLine(self.LIMBSIZE,True) rotation = random.randint(-15,15) - xpos = int((self.MANX-(self.LINEWIDTH*3))/2)-self.LINEWIDTH - ypos = self.CIRCLESIZE+self.BODYSIZE-self.LINEWIDTH + xPosition = int((self.MANX-(self.LINEWIDTH*3))/2)-self.LINEWIDTH + yPosition = self.CIRCLESIZE+self.BODYSIZE-self.LINEWIDTH limbDrawing = limbDrawing.rotate(rotation-45,expand=1) - background.paste(limbDrawing,(xpos,ypos),limbDrawing) + background.paste(limbDrawing,(xPosition,yPosition),limbDrawing) elif limb == "ll": limbDrawing = self.badLine(self.LIMBSIZE,True) rotation = random.randint(-15,15) limbDrawing = limbDrawing.rotate(rotation+45,expand=1) - xpos = int((self.MANX-(self.LINEWIDTH*3))/2)-limbDrawing.size[0]+self.LINEWIDTH*3 - ypos = self.CIRCLESIZE+self.BODYSIZE - background.paste(limbDrawing,(xpos,ypos),limbDrawing) + xPosition = int((self.MANX-(self.LINEWIDTH*3))/2)-limbDrawing.size[0]+self.LINEWIDTH*3 + yPosition = self.CIRCLESIZE+self.BODYSIZE + background.paste(limbDrawing,(xPosition,yPosition),limbDrawing) return background @@ -329,13 +398,13 @@ class DrawHangman(): if guessed[x]: letterDrawing = self.badText(letter,True) letterWidth = self.FONT.getsize(letter)[0] - letterx = int(x*(self.LETTERLINELENGTH+self.LETTERLINEDISTANCE)-(letterWidth/2)+(self.LETTERLINELENGTH*0.5)+(self.LINEWIDTH*2)) - letterLines.paste(letterDrawing,(letterx,0),letterDrawing) + letterX = int(x*(self.LETTERLINELENGTH+self.LETTERLINEDISTANCE)-(letterWidth/2)+(self.LETTERLINELENGTH*0.5)+(self.LINEWIDTH*2)) + letterLines.paste(letterDrawing,(letterX,0),letterDrawing) elif misses == 6: letterDrawing = self.badText(letter,True,(242,66,54)) letterWidth = self.FONT.getsize(letter)[0] - letterx = int(x*(self.LETTERLINELENGTH+self.LETTERLINEDISTANCE)-(letterWidth/2)+(self.LETTERLINELENGTH*0.5)+(self.LINEWIDTH*2)) - letterLines.paste(letterDrawing,(letterx,0),letterDrawing) + letterX = int(x*(self.LETTERLINELENGTH+self.LETTERLINEDISTANCE)-(letterWidth/2)+(self.LETTERLINELENGTH*0.5)+(self.LINEWIDTH*2)) + letterLines.paste(letterDrawing,(letterX,0),letterDrawing) return letterLines @@ -343,9 +412,9 @@ class DrawHangman(): shortestDist = math.inf x, y = newPosition for i, j in positions: - xdist = abs(i-x) - ydist = abs(j-y) - dist = math.sqrt(xdist**2+ydist**2) + xDistance = abs(i-x) + yDistance = abs(j-y) + dist = math.sqrt(xDistance**2+yDistance**2) if shortestDist > dist: shortestDist = dist return shortestDist diff --git a/resources/longStrings.json b/resources/longStrings.json index c0f1de8..b5d9c11 100644 --- a/resources/longStrings.json +++ b/resources/longStrings.json @@ -14,5 +14,8 @@ "Trivia going on": "There's already a trivia question going on. Try again in like, a minute", "Trivia time up": "Time's up! The answer was \"*{}) {}*\". Anyone who answered that has gotten 1 GwendoBuck", "Connect 4 going on": "There's already a connect 4 game going on in this channel", - "Connect 4 placed": "{} placed a piece in column {}. It's now {}'s turn" + "Connect 4 placed": "{} placed a piece in column {}. It's now {}'s turn", + "Hangman going on": "There's already a Hangman game going on in the channel", + "Hangman lost game": " You've guessed wrong six times and have lost the game.", + "Hangman guessed word": " You've guessed the word! Congratulations! Adding 15 GwendoBucks to your account" } \ No newline at end of file