hangman

This commit is contained in:
NikolajDanger
2021-04-22 20:36:06 +02:00
committed by Nikolaj
parent 8236c38a3f
commit 8f6c8b06be

View File

@ -1,22 +1,53 @@
import json """
import requests Deals with commands and logic for hangman games.
import datetime
import string
import discord
import math
import random
from discord_slash.context import SlashContext *Classes*
from PIL import ImageDraw, Image, ImageFont ---------
Hangman()
Deals with the game logic of hangman.
DrawHangman()
Draws the image shown to the player.
"""
import requests # Used for getting the word in Hangman.start()
import datetime # Used for generating the game id
import string # string.ascii_uppercase used
import discord # Used for discord.file and type hints
import math # Used by DrawHangman(), mainly for drawing circles
import random # Used to draw poorly
from discord_slash.context import SlashContext # Used for typehints
from PIL import ImageDraw, Image, ImageFont # Used to draw the image
class Hangman(): class Hangman():
"""
Controls hangman commands and game logic.
*Methods*
---------
start(ctx: SlashContext)
stop(ctx: SlashContext)
guess(message: discord.message, user: str, guess: str)
"""
def __init__(self, bot): def __init__(self, bot):
self.bot = bot """
self.draw = DrawHangman(bot) Initialize the class.
self.APIURL = "https://api.wordnik.com/v4/words.json/randomWords?"
apiKey = self.bot.credentials.wordnikKey *Attributes*
self.APIPARAMS = { ------------
draw: DrawHangman
The DrawHangman used to draw the hangman image.
APIURL: str
The url to get the words from.
APIPARAMS: dict
The parameters to pass to every api call.
"""
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, "hasDictionaryDef": True,
"minCorpusCount": 5000, "minCorpusCount": 5000,
"maxCorpusCount": -1, "maxCorpusCount": -1,
@ -29,20 +60,28 @@ class Hangman():
} }
async def start(self, ctx: SlashContext): async def start(self, ctx: SlashContext):
await self.bot.defer(ctx) """
Start a game of hangman.
*Parameters*
------------
ctx: SlashContext
The context of the command.
"""
await self.__bot.defer(ctx)
channel = str(ctx.channel_id) channel = str(ctx.channel_id)
user = f"#{ctx.author.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) userName = self.__bot.databaseFuncs.getName(user)
startedGame = False startedGame = False
if game is None: if game is None:
word = "-" word = "-"
while "-" in word or "." in word: while "-" in word or "." in word:
response = requests.get(self.APIURL, params=self.APIPARAMS) response = requests.get(self.__APIURL, params=self.__APIPARAMS)
word = list(response.json()[0]["word"].upper()) word = list(response.json()[0]["word"].upper())
self.bot.log("Found the word \""+"".join(word)+"\"") self.__bot.log("Found the word \""+"".join(word)+"\"")
guessed = [False] * len(word) guessed = [False] * len(word)
gameID = datetime.datetime.now().strftime("%Y%m%d%H%M%S") gameID = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
newGame = { newGame = {
@ -54,20 +93,20 @@ class Hangman():
"misses": 0, "misses": 0,
"guessed": guessed "guessed": guessed
} }
self.bot.database["hangman games"].insert_one(newGame) self.__bot.database["hangman games"].insert_one(newGame)
remainingLetters = list(string.ascii_uppercase) remainingLetters = list(string.ascii_uppercase)
self.draw.drawImage(channel) self.__draw.drawImage(channel)
logMessage = "Game started" logMessage = "Game started"
sendMessage = f"{userName} started game of hangman." sendMessage = f"{userName} started game of hangman."
startedGame = True startedGame = True
else: else:
logMessage = "There was already a game going on" logMessage = "There was already a game going on"
sendMessage = self.bot.longStrings["Hangman going on"] sendMessage = self.__bot.longStrings["Hangman going on"]
self.bot.log(logMessage) self.__bot.log(logMessage)
await ctx.send(sendMessage) await ctx.send(sendMessage)
if startedGame: if startedGame:
@ -92,29 +131,49 @@ class Hangman():
await message.add_reaction(emoji) await message.add_reaction(emoji)
async def stop(self, ctx: SlashContext): async def stop(self, ctx: SlashContext):
"""
Stop the game of hangman.
*Parameters*
------------
ctx: SlashContext
The context of the command.
"""
channel = str(ctx.channel.id) channel = str(ctx.channel.id)
game = self.bot.database["hangman games"].find_one({"_id": channel}) game = self.__bot.database["hangman games"].find_one({"_id": channel})
if game is None: if game is None:
await ctx.send("There's no game going on") await ctx.send("There's no game going on")
elif f"#{ctx.author.id}" != game["player"]: elif f"#{ctx.author.id}" != game["player"]:
await ctx.send("You can't end a game you're not in") await ctx.send("You can't end a game you're not in")
else: 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: with open(f"resources/games/oldImages/hangman{channel}", "r") as f:
messages = f.read().splitlines() messages = f.read().splitlines()
for message in messages: for message in messages:
oldMessage = await ctx.channel.fetch_message(int(message)) oldMessage = await ctx.channel.fetch_message(int(message))
self.bot.log("Deleting old message") self.__bot.log("Deleting old message")
await oldMessage.delete() await oldMessage.delete()
await ctx.send("Game stopped") await ctx.send("Game stopped")
async def guess(self, message: discord.Message, user: str, guess: str): async def guess(self, message: discord.Message, user: str, guess: str):
"""
Guess a letter.
*Parameters*
------------
message: discord.Message
The message that the reaction was placed on.
user: str
The id of the user.
guess: str
The guess.
"""
channel = str(message.channel.id) channel = str(message.channel.id)
hangmanGames = self.bot.database["hangman games"] hangmanGames = self.__bot.database["hangman games"]
game = hangmanGames.find_one({"_id": channel}) game = hangmanGames.find_one({"_id": channel})
gameExists = (game is not None) gameExists = (game is not None)
@ -123,7 +182,7 @@ class Hangman():
validGuess = (gameExists and singleLetter and newGuess) validGuess = (gameExists and singleLetter and newGuess)
if validGuess: if validGuess:
self.bot.log("Guessed the letter") self.__bot.log("Guessed the letter")
correctGuess = 0 correctGuess = 0
for x, letter in enumerate(game["word"]): for x, letter in enumerate(game["word"]):
@ -153,16 +212,16 @@ class Hangman():
sendMessage = "Guessed {}. There were {} {}s in the word." sendMessage = "Guessed {}. There were {} {}s in the word."
sendMessage = sendMessage.format(guess, correctGuess, guess) sendMessage = sendMessage.format(guess, correctGuess, guess)
self.draw.drawImage(channel) self.__draw.drawImage(channel)
if game["misses"] == 6: if game["misses"] == 6:
hangmanGames.delete_one({"_id": channel}) hangmanGames.delete_one({"_id": channel})
sendMessage += self.bot.longStrings["Hangman lost game"] sendMessage += self.__bot.longStrings["Hangman lost game"]
remainingLetters = [] remainingLetters = []
elif all(game["guessed"]): elif all(game["guessed"]):
hangmanGames.delete_one({"_id": channel}) hangmanGames.delete_one({"_id": channel})
self.bot.money.addMoney(user, 15) self.__bot.money.addMoney(user, 15)
sendMessage += self.bot.longStrings["Hangman guessed word"] sendMessage += self.__bot.longStrings["Hangman guessed word"]
remainingLetters = [] remainingLetters = []
await message.channel.send(sendMessage) await message.channel.send(sendMessage)
@ -172,7 +231,7 @@ class Hangman():
for oldID in oldMessageIDs: for oldID in oldMessageIDs:
oldMessage = await message.channel.fetch_message(int(oldID)) oldMessage = await message.channel.fetch_message(int(oldID))
self.bot.log("Deleting old message") self.__bot.log("Deleting old message")
await oldMessage.delete() await oldMessage.delete()
boardsPath = "resources/games/hangmanBoards/" boardsPath = "resources/games/hangmanBoards/"
@ -206,34 +265,63 @@ class Hangman():
class DrawHangman(): class DrawHangman():
"""
Draws the image of the hangman game.
*Methods*
---------
drawImage(channel: str)
"""
def __init__(self, bot): def __init__(self, bot):
self.bot = bot """
self.CIRCLESIZE = 120 Initialize the class.
self.LINEWIDTH = 12
self.BODYSIZE = 210 *Attributes*
self.LIMBSIZE = 60 ------------
self.ARMPOSITION = 60 CIRCLESIZE
LINEWIDTH
BODYSIZE
LIMBSIZE
ARMPOSITION
MANX, MANY
LETTERLINELENGTH
LETTERLINEDISTANCE
GALLOWX, GALLOWY
PHI
FONT
SMALLFONT
"""
self.__bot = bot
self.__CIRCLESIZE = 120
self.__LINEWIDTH = 12
MANPADDING = self.LINEWIDTH*4 self.__BODYSIZE = 210
self.MANX = (self.LIMBSIZE*2)+MANPADDING self.__LIMBSIZE = 60
self.MANY = (self.CIRCLESIZE+self.BODYSIZE+self.LIMBSIZE)+MANPADDING self.__ARMPOSITION = 60
self.LETTERLINELENGTH = 90 self.__MANX = (self.__LIMBSIZE*2)
self.LETTERLINEDISTANCE = 30 self.__MANY = (self.__CIRCLESIZE+self.__BODYSIZE+self.__LIMBSIZE)
MANPADDING = self.__LINEWIDTH*4
self.__MANX += MANPADDING
self.__MANY += MANPADDING
self.GALLOWX, self.GALLOWY = 360, 600 self.__LETTERLINELENGTH = 90
self.GOLDENRATIO = 1-(1 / ((1 + 5 ** 0.5) / 2)) self.__LETTERLINEDISTANCE = 30
LETTERSIZE = 75 self.__GALLOWX, self.__GALLOWY = 360, 600
TEXTSIZE = 70 self.__PHI = 1-(1 / ((1 + 5 ** 0.5) / 2))
LETTERSIZE = 75 # Wrong guesses letter size
WORDSIZE = 70 # Correct guesses letter size
FONTPATH = "resources/fonts/comic-sans-bold.ttf" FONTPATH = "resources/fonts/comic-sans-bold.ttf"
self.FONT = ImageFont.truetype(FONTPATH, LETTERSIZE) self.__FONT = ImageFont.truetype(FONTPATH, LETTERSIZE)
self.SMALLFONT = ImageFont.truetype(FONTPATH, TEXTSIZE) self.__SMALLFONT = ImageFont.truetype(FONTPATH, WORDSIZE)
def calcDeviance(self, preDeviance, preDevianceAccuracy, positionChange, def __deviate(self, preDeviance: int, preDevianceAccuracy: int,
maxmin, maxAcceleration): positionChange: float, maxmin: int,
maxAcceleration: float):
randomDeviance = random.uniform(-positionChange, positionChange) randomDeviance = random.uniform(-positionChange, positionChange)
devianceAccuracy = preDevianceAccuracy + randomDeviance devianceAccuracy = preDevianceAccuracy + randomDeviance
if devianceAccuracy > maxmin * maxAcceleration: if devianceAccuracy > maxmin * maxAcceleration:
@ -248,14 +336,14 @@ class DrawHangman():
deviance = -maxmin deviance = -maxmin
return deviance, devianceAccuracy return deviance, devianceAccuracy
def badCircle(self): def __badCircle(self):
circlePadding = (self.LINEWIDTH*3) circlePadding = (self.__LINEWIDTH*3)
imageWidth = self.CIRCLESIZE+circlePadding imageWidth = self.__CIRCLESIZE+circlePadding
imageSize = (imageWidth, imageWidth) imageSize = (imageWidth, imageWidth)
background = Image.new("RGBA", imageSize, color=(0, 0, 0, 0)) 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 middle = (self.__CIRCLESIZE+(self.__LINEWIDTH*3))/2
devianceX = 0 devianceX = 0
devianceY = 0 devianceY = 0
devianceAccuracyX = 0 devianceAccuracyX = 0
@ -267,42 +355,42 @@ class DrawHangman():
devianceXParams = [ devianceXParams = [
devianceX, devianceX,
devianceAccuracyX, devianceAccuracyX,
self.LINEWIDTH/100, self.__LINEWIDTH/100,
self.LINEWIDTH, self.__LINEWIDTH,
0.03 0.03
] ]
devianceYParams = [ devianceYParams = [
devianceY, devianceY,
devianceAccuracyY, devianceAccuracyY,
self.LINEWIDTH/100, self.__LINEWIDTH/100,
self.LINEWIDTH, self.__LINEWIDTH,
0.03 0.03
] ]
devianceX, devianceAccuracyX = self.calcDeviance(*devianceXParams) devianceX, devianceAccuracyX = self.__deviate(*devianceXParams)
devianceY, devianceAccuracyY = self.calcDeviance(*devianceYParams) devianceY, devianceAccuracyY = self.__deviate(*devianceYParams)
radians = math.radians(degree+start) radians = math.radians(degree+start)
circleX = (math.cos(radians) * (self.CIRCLESIZE/2)) circleX = (math.cos(radians) * (self.__CIRCLESIZE/2))
circleY = (math.sin(radians) * (self.CIRCLESIZE/2)) circleY = (math.sin(radians) * (self.__CIRCLESIZE/2))
x = middle + circleX - (self.LINEWIDTH/2) + devianceX x = middle + circleX - (self.__LINEWIDTH/2) + devianceX
y = middle + circleY - (self.LINEWIDTH/2) + devianceY y = middle + circleY - (self.__LINEWIDTH/2) + devianceY
circlePosition = [(x, y), (x+self.LINEWIDTH, y+self.LINEWIDTH)] circlePosition = [(x, y), (x+self.__LINEWIDTH, y+self.__LINEWIDTH)]
d.ellipse(circlePosition, fill=(0, 0, 0, 255)) d.ellipse(circlePosition, fill=(0, 0, 0, 255))
return background return background
def badLine(self, length: int, rotated: bool = False): def __badLine(self, length: int, rotated: bool = False):
if rotated: if rotated:
w, h = length+self.LINEWIDTH*3, self.LINEWIDTH*3 w, h = length+self.__LINEWIDTH*3, self.__LINEWIDTH*3
else: else:
w, h = self.LINEWIDTH*3, length+self.LINEWIDTH*3 w, h = self.__LINEWIDTH*3, length+self.__LINEWIDTH*3
background = Image.new("RGBA", (w, h), color=(0, 0, 0, 0)) background = Image.new("RGBA", (w, h), color=(0, 0, 0, 0))
d = ImageDraw.Draw(background, "RGBA") d = ImageDraw.Draw(background, "RGBA")
possibleDeviance = int(self.LINEWIDTH/3) possibleDeviance = int(self.__LINEWIDTH/3)
devianceX = random.randint(-possibleDeviance, possibleDeviance) devianceX = random.randint(-possibleDeviance, possibleDeviance)
devianceY = 0 devianceY = 0
devianceAccuracyX = 0 devianceAccuracyX = 0
@ -312,45 +400,46 @@ class DrawHangman():
devianceParamsX = [ devianceParamsX = [
devianceX, devianceX,
devianceAccuracyX, devianceAccuracyX,
self.LINEWIDTH/1000, self.__LINEWIDTH/1000,
self.LINEWIDTH, self.__LINEWIDTH,
0.004 0.004
] ]
devianceParamsY = [ devianceParamsY = [
devianceY, devianceY,
devianceAccuracyY, devianceAccuracyY,
self.LINEWIDTH/1000, self.__LINEWIDTH/1000,
self.LINEWIDTH, self.__LINEWIDTH,
0.004 0.004
] ]
devianceX, devianceAccuracyX = self.calcDeviance(*devianceParamsX) devianceX, devianceAccuracyX = self.__deviate(*devianceParamsX)
devianceY, devianceAccuracyY = self.calcDeviance(*devianceParamsY) devianceY, devianceAccuracyY = self.__deviate(*devianceParamsY)
if rotated: if rotated:
x = self.LINEWIDTH + pixel + devianceX x = self.__LINEWIDTH + pixel + devianceX
y = self.LINEWIDTH + devianceY y = self.__LINEWIDTH + devianceY
else: else:
x = self.LINEWIDTH + devianceX x = self.__LINEWIDTH + devianceX
y = self.LINEWIDTH + pixel + devianceY y = self.__LINEWIDTH + pixel + devianceY
circlePosition = [(x, y), (x+self.LINEWIDTH, y+self.LINEWIDTH)] circlePosition = [(x, y), (x+self.__LINEWIDTH, y+self.__LINEWIDTH)]
d.ellipse(circlePosition, fill=(0, 0, 0, 255)) d.ellipse(circlePosition, fill=(0, 0, 0, 255))
return background return background
def drawMan(self, misses: int): def __drawMan(self, misses: int, seed: str):
manSize = (self.MANX, self.MANY) random.seed(seed)
manSize = (self.__MANX, self.__MANY)
background = Image.new("RGBA", manSize, color=(0, 0, 0, 0)) background = Image.new("RGBA", manSize, color=(0, 0, 0, 0))
if misses >= 1: if misses >= 1:
head = self.badCircle() head = self.__badCircle()
pasteX = (self.MANX-(self.CIRCLESIZE+(self.LINEWIDTH*3)))//2 pasteX = (self.__MANX-(self.__CIRCLESIZE+(self.__LINEWIDTH*3)))//2
pastePosition = (pasteX, 0) pastePosition = (pasteX, 0)
background.paste(head, pastePosition, head) background.paste(head, pastePosition, head)
if misses >= 2: if misses >= 2:
body = self.badLine(self.BODYSIZE) body = self.__badLine(self.__BODYSIZE)
pasteX = (self.MANX-(self.LINEWIDTH*3))//2 pasteX = (self.__MANX-(self.__LINEWIDTH*3))//2
pastePosition = (pasteX, self.CIRCLESIZE) pastePosition = (pasteX, self.__CIRCLESIZE)
background.paste(body, pastePosition, body) background.paste(body, pastePosition, body)
if misses >= 3: if misses >= 3:
@ -358,30 +447,33 @@ class DrawHangman():
else: else:
limbs = [] limbs = []
random.seed(seed)
for limb in limbs: for limb in limbs:
limbDrawing = self.badLine(self.LIMBSIZE, True) limbDrawing = self.__badLine(self.__LIMBSIZE, True)
xPosition = (self.MANX-(self.LINEWIDTH*3))//2 xPosition = (self.__MANX-(self.__LINEWIDTH*3))//2
if limb[1] == "a": if limb[1] == "a":
rotation = random.randint(-45, 45) rotation = random.randint(-45, 45)
shift = math.sin(math.radians(rotation)) shift = math.sin(math.radians(rotation))
compensation = int(shift*(self.LIMBSIZE+(self.LINEWIDTH*3))) lineLength = self.__LIMBSIZE+(self.__LINEWIDTH*3)
compensation = int(shift*lineLength)
limbDrawing = limbDrawing.rotate(rotation, expand=1) limbDrawing = limbDrawing.rotate(rotation, expand=1)
yPosition = self.CIRCLESIZE + self.ARMPOSITION + compensation yPosition = self.__CIRCLESIZE + self.__ARMPOSITION
if limb == "ra": if limb == "ra":
compensation = min(-compensation, 0) compensation = min(-compensation, 0)
else: else:
xPosition -= self.LIMBSIZE xPosition -= self.__LIMBSIZE
compensation = min(compensation, 0) compensation = min(compensation, 0)
yPosition += compensation
else: else:
rotation = random.randint(-15, 15) rotation = random.randint(-15, 15)
yPosition = self.CIRCLESIZE+self.BODYSIZE yPosition = self.__CIRCLESIZE+self.__BODYSIZE-self.__LINEWIDTH
if limb == "rl": if limb == "rl":
xPosition -= self.LINEWIDTH
limbDrawing = limbDrawing.rotate(rotation-45, expand=1) limbDrawing = limbDrawing.rotate(rotation-45, expand=1)
else: else:
yPosition -= self.LINEWIDTH xPosition += -limbDrawing.size[0]+self.__LINEWIDTH*3
xPosition += -limbDrawing.size[0]+self.LINEWIDTH*3
limbDrawing = limbDrawing.rotate(rotation+45, expand=1) limbDrawing = limbDrawing.rotate(rotation+45, expand=1)
pastePosition = (xPosition, yPosition) pastePosition = (xPosition, yPosition)
@ -389,11 +481,11 @@ class DrawHangman():
return background return background
def badText(self, text: str, big: bool, color: tuple = (0, 0, 0, 255)): def __badText(self, text: str, big: bool, color: tuple = (0, 0, 0, 255)):
if big: if big:
font = self.FONT font = self.__FONT
else: else:
font = self.SMALLFONT font = self.__SMALLFONT
w, h = font.getsize(text) w, h = font.getsize(text)
img = Image.new("RGBA", (w, h), color=(0, 0, 0, 0)) img = Image.new("RGBA", (w, h), color=(0, 0, 0, 0))
d = ImageDraw.Draw(img, "RGBA") d = ImageDraw.Draw(img, "RGBA")
@ -401,109 +493,118 @@ class DrawHangman():
d.text((0, 0), text, font=font, fill=color) d.text((0, 0), text, font=font, fill=color)
return img return img
def drawGallows(self): def __drawGallows(self):
gallowSize = (self.GALLOWX, self.GALLOWY) gallowSize = (self.__GALLOWX, self.__GALLOWY)
background = Image.new("RGBA", gallowSize, color=(0, 0, 0, 0)) background = Image.new("RGBA", gallowSize, color=(0, 0, 0, 0))
bottomLine = self.badLine(int(self.GALLOWX * 0.75), True) bottomLine = self.__badLine(int(self.__GALLOWX * 0.75), True)
bottomLineX = int(self.GALLOWX * 0.125) bottomLineX = int(self.__GALLOWX * 0.125)
bottomLineY = self.GALLOWY-(self.LINEWIDTH*4) bottomLineY = self.__GALLOWY-(self.__LINEWIDTH*4)
pastePosition = (bottomLineX, bottomLineY) pastePosition = (bottomLineX, bottomLineY)
background.paste(bottomLine, pastePosition, bottomLine) background.paste(bottomLine, pastePosition, bottomLine)
lineTwo = self.badLine(self.GALLOWY-self.LINEWIDTH*6) lineTwo = self.__badLine(self.__GALLOWY-self.__LINEWIDTH*6)
lineTwoX = int(self.GALLOWX*(0.75*self.GOLDENRATIO)) lineTwoX = int(self.__GALLOWX*(0.75*self.__PHI))
lineTwoY = self.LINEWIDTH*2 lineTwoY = self.__LINEWIDTH*2
pastePosition = (lineTwoX, lineTwoY) pastePosition = (lineTwoX, lineTwoY)
background.paste(lineTwo, pastePosition, lineTwo) background.paste(lineTwo, pastePosition, lineTwo)
topLine = self.badLine(int(self.GALLOWY*0.30), True) topLine = self.__badLine(int(self.__GALLOWY*0.30), True)
pasteX = int(self.GALLOWX*(0.75*self.GOLDENRATIO))-self.LINEWIDTH pasteX = int(self.__GALLOWX*(0.75*self.__PHI))-self.__LINEWIDTH
pastePosition = (pasteX, self.LINEWIDTH*3) pastePosition = (pasteX, self.__LINEWIDTH*3)
background.paste(topLine, pastePosition, topLine) background.paste(topLine, pastePosition, topLine)
lastLine = self.badLine(int(self.GALLOWY*0.125)) lastLine = self.__badLine(int(self.__GALLOWY*0.125))
pasteX += int(self.GALLOWY*0.30) pasteX += int(self.__GALLOWY*0.30)
background.paste(lastLine, (pasteX, self.LINEWIDTH*3), lastLine) background.paste(lastLine, (pasteX, self.__LINEWIDTH*3), lastLine)
return background return background
def drawLetterLines(self, word: str, guessed: list, misses: int): def __drawLetterLines(self, word: str, guessed: list, misses: int):
imageWidth = (self.LETTERLINELENGTH+self.LETTERLINEDISTANCE)*len(word) letterWidth = self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE
imageSize = (imageWidth, self.LETTERLINELENGTH+self.LINEWIDTH*3) imageWidth = letterWidth*len(word)
imageSize = (imageWidth, self.__LETTERLINELENGTH+self.__LINEWIDTH*3)
letterLines = Image.new("RGBA", imageSize, color=(0, 0, 0, 0)) letterLines = Image.new("RGBA", imageSize, color=(0, 0, 0, 0))
for x, letter in enumerate(word): for x, letter in enumerate(word):
line = self.badLine(self.LETTERLINELENGTH, True) line = self.__badLine(self.__LETTERLINELENGTH, True)
pasteX = x*(self.LETTERLINELENGTH+self.LETTERLINEDISTANCE) pasteX = x*(self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE)
pastePosition = (pasteX, self.LETTERLINELENGTH) pastePosition = (pasteX, self.__LETTERLINELENGTH)
letterLines.paste(line, pastePosition, line) letterLines.paste(line, pastePosition, line)
if guessed[x]: if guessed[x]:
letterDrawing = self.badText(letter, True) letterDrawing = self.__badText(letter, True)
letterWidth = self.FONT.getsize(letter)[0] letterWidth = self.__FONT.getsize(letter)[0]
letterX = x*(self.LETTERLINELENGTH+self.LETTERLINEDISTANCE) letterX = x*(self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE)
letterX -= (letterWidth//2) letterX -= (letterWidth//2)
letterX += (self.LETTERLINELENGTH//2)+(self.LINEWIDTH*2) letterX += (self.__LETTERLINELENGTH//2)+(self.__LINEWIDTH*2)
letterLines.paste(letterDrawing, (letterX, 0), letterDrawing) letterLines.paste(letterDrawing, (letterX, 0), letterDrawing)
elif misses == 6: elif misses == 6:
letterDrawing = self.badText(letter, True, (242, 66, 54)) letterDrawing = self.__badText(letter, True, (242, 66, 54))
letterWidth = self.FONT.getsize(letter)[0] letterWidth = self.__FONT.getsize(letter)[0]
letterX = x*(self.LETTERLINELENGTH+self.LETTERLINEDISTANCE) letterX = x*(self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE)
letterX -= (letterWidth//2) letterX -= (letterWidth//2)
letterX += (self.LETTERLINELENGTH//2)+(self.LINEWIDTH*2) letterX += (self.__LETTERLINELENGTH//2)+(self.__LINEWIDTH*2)
letterLines.paste(letterDrawing, (letterX, 0), letterDrawing) letterLines.paste(letterDrawing, (letterX, 0), letterDrawing)
return letterLines return letterLines
def shortestDist(self, positions: list, newPosition: tuple): def __shortestDist(self, positions: list, newPosition: tuple):
shortestDist = math.inf __shortestDist = math.inf
x, y = newPosition x, y = newPosition
for i, j in positions: for i, j in positions:
xDistance = abs(i-x) xDistance = abs(i-x)
yDistance = abs(j-y) yDistance = abs(j-y)
dist = math.sqrt(xDistance**2+yDistance**2) dist = math.sqrt(xDistance**2+yDistance**2)
if shortestDist > dist: if __shortestDist > dist:
shortestDist = dist __shortestDist = dist
return shortestDist return __shortestDist
def drawMisses(self, guesses: list, word: str): def __drawMisses(self, guesses: list, word: str):
background = Image.new("RGBA", (600, 400), color=(0, 0, 0, 0)) background = Image.new("RGBA", (600, 400), color=(0, 0, 0, 0))
pos = [] pos = []
for guess in guesses: for guess in guesses:
if guess not in word: if guess not in word:
placed = False placed = False
while not placed: while not placed:
letter = self.badText(guess, True) letter = self.__badText(guess, True)
w, h = self.FONT.getsize(guess) w, h = self.__FONT.getsize(guess)
x = random.randint(0, 600-w) x = random.randint(0, 600-w)
y = random.randint(0, 400-h) y = random.randint(0, 400-h)
if self.shortestDist(pos, (x, y)) > 70: if self.__shortestDist(pos, (x, y)) > 70:
pos.append((x, y)) pos.append((x, y))
background.paste(letter, (x, y), letter) background.paste(letter, (x, y), letter)
placed = True placed = True
return background return background
def drawImage(self, channel: str): def drawImage(self, channel: str):
self.bot.log("Drawing hangman image", channel) """
game = self.bot.database["hangman games"].find_one({"_id": channel}) Draw a hangman Image.
*Parameters*
------------
channel: str
The id of the channel the game is in.
"""
self.__bot.log("Drawing hangman image", channel)
game = self.__bot.database["hangman games"].find_one({"_id": channel})
random.seed(game["game ID"]) random.seed(game["game ID"])
background = Image.open("resources/paper.jpg") background = Image.open("resources/paper.jpg")
gallow = self.drawGallows() gallow = self.__drawGallows()
man = self.drawMan(game["misses"]) man = self.__drawMan(game["misses"], game["game ID"])
random.seed(game["game ID"]) random.seed(game["game ID"])
letterLineParams = [game["word"], game["guessed"], game["misses"]] letterLineParams = [game["word"], game["guessed"], game["misses"]]
letterLines = self.drawLetterLines(*letterLineParams) letterLines = self.__drawLetterLines(*letterLineParams)
random.seed(game["game ID"]) random.seed(game["game ID"])
misses = self.drawMisses(game["guessed letters"], game["word"]) misses = self.__drawMisses(game["guessed letters"], game["word"])
background.paste(gallow, (100, 100), gallow) background.paste(gallow, (100, 100), gallow)
background.paste(man, (300, 210), man) background.paste(man, (300, 210), man)
background.paste(letterLines, (120, 840), letterLines) background.paste(letterLines, (120, 840), letterLines)
background.paste(misses, (600, 150), misses) background.paste(misses, (600, 150), misses)
missesText = self.badText("MISSES", False) missesText = self.__badText("MISSES", False)
missesTextWidth = missesText.size[0] missesTextWidth = missesText.size[0]
background.paste(missesText, (850-missesTextWidth//2, 50), missesText) background.paste(missesText, (850-missesTextWidth//2, 50), missesText)