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): self.bot = bot self.draw = DrawHangman(bot) 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: 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}) userName = self.bot.databaseFuncs.getName(user) startedGame = False if game is None: word = "-" while "-" in word or "." in word: 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 } self.bot.database["hangman games"].insert_one(newGame) remainingLetters = list(string.ascii_uppercase) self.draw.drawImage(channel) logMessage = "Game started" sendMessage = f"{userName} started game of hangman." startedGame = True else: logMessage = "There was already a game going on" sendMessage = self.bot.longStrings["Hangman going on"] self.bot.log(logMessage) await ctx.send(sendMessage) if startedGame: 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:] } 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: SlashContext): channel = str(ctx.channel.id) game = self.bot.database["hangman games"].find_one({"_id": channel}) if game is None: await ctx.send("There's no game going on") 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}) with open(f"resources/games/oldImages/hangman{channel}", "r") as f: messages = f.read().splitlines() 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: discord.Message, user: str, guess: str): channel = str(message.channel.id) hangmanGames = self.bot.database["hangman games"] game = hangmanGames.find_one({"_id": channel}) 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) if validGuess: self.bot.log("Guessed the letter") correctGuess = 0 for x, letter in enumerate(game["word"]): if guess == letter: correctGuess += 1 updater = {"$set": {f"guessed.{x}": True}} hangmanGames.update_one({"_id": channel}, updater) if correctGuess == 0: updater = {"$inc": {"misses": 1}} hangmanGames.update_one({"_id": channel}, updater) updater = {"$push": {"guessed letters": guess}} hangmanGames.update_one({"_id": channel}, updater) remainingLetters = list(string.ascii_uppercase) game = hangmanGames.find_one({"_id": channel}) for letter in game["guessed letters"]: remainingLetters.remove(letter) if correctGuess == 1: sendMessage = "Guessed {}. There was 1 {} in the word." sendMessage = sendMessage.format(guess, guess) else: sendMessage = "Guessed {}. There were {} {}s in the word." sendMessage = sendMessage.format(guess, correctGuess, guess) self.draw.drawImage(channel) if game["misses"] == 6: hangmanGames.delete_one({"_id": channel}) sendMessage += self.bot.longStrings["Hangman lost game"] remainingLetters = [] 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) 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() 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:] } else: blankMessage = "" reactionMessages = {newImage: remainingLetters} if blankMessage != "": oldMessages = f"{newImage.id}\n{blankMessage.id}" else: oldMessages = str(newImage.id) oldImagePath = f"resources/games/oldImages/hangman{channel}" with open(oldImagePath, "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) class DrawHangman(): def __init__(self, bot): self.bot = bot self.CIRCLESIZE = 120 self.LINEWIDTH = 12 self.BODYSIZE = 210 self.LIMBSIZE = 60 self.ARMPOSITION = 60 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.GOLDENRATIO = 1-(1 / ((1 + 5 ** 0.5) / 2)) LETTERSIZE = 75 TEXTSIZE = 70 FONTPATH = "resources/fonts/comic-sans-bold.ttf" self.FONT = ImageFont.truetype(FONTPATH, LETTERSIZE) self.SMALLFONT = ImageFont.truetype(FONTPATH, TEXTSIZE) 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): 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") middle = (self.CIRCLESIZE+(self.LINEWIDTH*3))/2 devianceX = 0 devianceY = 0 devianceAccuracyX = 0 devianceAccuracyY = 0 start = random.randint(-100, -80) degreesAmount = 360 + random.randint(-10, 30) for degree in range(degreesAmount): 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) + 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)) return background def badLine(self, length, rotated = False): if rotated: w, h = length+self.LINEWIDTH*3, self.LINEWIDTH*3 else: w, h = self.LINEWIDTH*3,length+self.LINEWIDTH*3 background = Image.new("RGBA",(w,h),color=(0,0,0,0)) d = ImageDraw.Draw(background,"RGBA") devianceX = random.randint(-int(self.LINEWIDTH/3),int(self.LINEWIDTH/3)) devianceY = 0 devianceAccuracyX = 0 devianceAccuracyY = 0 for pixel in range(length): 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 + devianceX y = self.LINEWIDTH + devianceY else: x = self.LINEWIDTH + devianceX y = self.LINEWIDTH + pixel + devianceY d.ellipse([(x,y),(x+self.LINEWIDTH,y+self.LINEWIDTH)],fill=(0,0,0,255)) return background def drawMan(self, misses): background = Image.new("RGBA",(self.MANX,self.MANY),color=(0,0,0,0)) if misses >= 1: head = self.badCircle() background.paste(head,(int((self.MANX-(self.CIRCLESIZE+(self.LINEWIDTH*3)))/2),0),head) if misses >= 2: body = self.badLine(self.BODYSIZE) background.paste(body,(int((self.MANX-(self.LINEWIDTH*3))/2),self.CIRCLESIZE),body) if misses >= 3: limbs = random.sample(["rl","ll","ra","la"],min(misses-2,4)) else: limbs = [] for limb in limbs: if limb == "ra": limbDrawing = self.badLine(self.LIMBSIZE,True) rotation = random.randint(-45,45) xPosition = int((self.MANX-(self.LINEWIDTH*3))/2) rotationCompensation = min(-int(math.sin(math.radians(rotation))*(self.LIMBSIZE+(self.LINEWIDTH*3))),0) yPosition = self.CIRCLESIZE+self.ARMPOSITION + rotationCompensation limbDrawing = limbDrawing.rotate(rotation,expand=1) background.paste(limbDrawing,(xPosition,yPosition),limbDrawing) elif limb == "la": limbDrawing = self.badLine(self.LIMBSIZE,True) rotation = random.randint(-45,45) xPosition = int((self.MANX-(self.LINEWIDTH*3))/2)-self.LIMBSIZE rotationCompensation = min(int(math.sin(math.radians(rotation))*(self.LIMBSIZE+(self.LINEWIDTH*3))),0) yPosition = self.CIRCLESIZE+self.ARMPOSITION + rotationCompensation limbDrawing = limbDrawing.rotate(rotation,expand=1) background.paste(limbDrawing,(xPosition,yPosition),limbDrawing) elif limb == "rl": limbDrawing = self.badLine(self.LIMBSIZE,True) rotation = random.randint(-15,15) 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,(xPosition,yPosition),limbDrawing) elif limb == "ll": limbDrawing = self.badLine(self.LIMBSIZE,True) rotation = random.randint(-15,15) limbDrawing = limbDrawing.rotate(rotation+45,expand=1) 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 def badText(self, text, big, color=(0,0,0,255)): if big: font = self.FONT else: font = self.SMALLFONT w, h = font.getsize(text) img = Image.new("RGBA",(w,h),color=(0,0,0,0)) d = ImageDraw.Draw(img,"RGBA") d.text((0,0),text,font=font,fill=color) return img def drawGallows(self): background = Image.new("RGBA",(self.GALLOWX,self.GALLOWY),color=(0,0,0,0)) bottomLine = self.badLine(int(self.GALLOWX*0.75),True) background.paste(bottomLine,(int(self.GALLOWX*0.125),self.GALLOWY-(self.LINEWIDTH*4)),bottomLine) lineTwo = self.badLine(self.GALLOWY-self.LINEWIDTH*6) background.paste(lineTwo,(int(self.GALLOWX*(0.75*self.GOLDENRATIO)),self.LINEWIDTH*2),lineTwo) topLine = self.badLine(int(self.GALLOWY*0.30),True) background.paste(topLine,(int(self.GALLOWX*(0.75*self.GOLDENRATIO))-self.LINEWIDTH,self.LINEWIDTH*3),topLine) lastLine = self.badLine(int(self.GALLOWY*0.125)) background.paste(lastLine,((int(self.GALLOWX*(0.75*self.GOLDENRATIO))+int(self.GALLOWY*0.30)-self.LINEWIDTH),self.LINEWIDTH*3),lastLine) return background def drawLetterLines(self, word,guessed,misses): letterLines = Image.new("RGBA",((self.LETTERLINELENGTH+self.LETTERLINEDISTANCE)*len(word),self.LETTERLINELENGTH+self.LINEWIDTH*3),color=(0,0,0,0)) for x, letter in enumerate(word): line = self.badLine(self.LETTERLINELENGTH,True) letterLines.paste(line,(x*(self.LETTERLINELENGTH+self.LETTERLINEDISTANCE),self.LETTERLINELENGTH),line) 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) 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) return letterLines def shortestDist(self,positions,newPosition): shortestDist = math.inf x, y = newPosition for i, j in positions: xDistance = abs(i-x) yDistance = abs(j-y) dist = math.sqrt(xDistance**2+yDistance**2) if shortestDist > dist: shortestDist = dist return shortestDist def drawMisses(self,guesses,word): background = Image.new("RGBA",(600,400),color=(0,0,0,0)) pos = [] for guess in guesses: if guess not in word: placed = False while placed == False: letter = self.badText(guess,True) w, h = self.FONT.getsize(guess) x = random.randint(0,600-w) y = random.randint(0,400-h) if self.shortestDist(pos,(x,y)) > 70: pos.append((x,y)) background.paste(letter,(x,y),letter) placed = True return background def drawImage(self,channel): self.bot.log("Drawing hangman image", channel) game = self.bot.database["hangman games"].find_one({"_id":channel}) random.seed(game["game ID"]) background = Image.open("resources/paper.jpg") try: gallow = self.drawGallows() except: self.bot.log("Error drawing gallows (error code 1711)") try: man = self.drawMan(game["misses"]) except: self.bot.log("Error drawing stick figure (error code 1712)") random.seed(game["game ID"]) try: letterLines = self.drawLetterLines(game["word"],game["guessed"],game["misses"]) except: self.bot.log("error drawing letter lines (error code 1713)") random.seed(game["game ID"]) try: misses = self.drawMisses(game["guessed letters"],game["word"]) except: self.bot.log("Error drawing misses (error code 1714)") background.paste(gallow,(100,100),gallow) background.paste(man,(300,210),man) background.paste(letterLines,(120,840),letterLines) background.paste(misses,(600,150),misses) missesText = self.badText("MISSES",False) missesTextWidth = missesText.size[0] background.paste(missesText,(850-int(missesTextWidth/2),50),missesText) background.save("resources/games/hangmanBoards/hangmanBoard"+channel+".png")