🧹 More refactoring

This commit is contained in:
Nikolaj
2021-08-17 18:05:41 +02:00
parent 074a06e863
commit 573d081734
31 changed files with 1971 additions and 1787 deletions

View File

@ -8,12 +8,12 @@ Deals with commands and logic for hangman games.
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
import requests # Used for getting the word in Hangman.start()
import discord # Used for discord.file and type hints
from discord_slash.context import SlashContext # Used for typehints
from PIL import ImageDraw, Image, ImageFont # Used to draw the image
@ -38,16 +38,16 @@ class Hangman():
------------
draw: DrawHangman
The DrawHangman used to draw the hangman image.
APIURL: str
API_url: 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["wordnik_key"]
self.__APIPARAMS = {
self.__API_url = "https://api.wordnik.com/v4/words.json/randomWords?" # pylint: disable=invalid-name
api_key = self.__bot.credentials["wordnik_key"]
self.__APIPARAMS = { # pylint: disable=invalid-name
"hasDictionaryDef": True,
"minCorpusCount": 5000,
"maxCorpusCount": -1,
@ -56,7 +56,7 @@ class Hangman():
"minLength": 3,
"maxLength": 11,
"limit": 1,
"api_key": apiKey
"api_key": api_key
}
async def start(self, ctx: SlashContext):
@ -73,59 +73,60 @@ class Hangman():
user = f"#{ctx.author.id}"
game = self.__bot.database["hangman games"].find_one({"_id": channel})
user_name = self.__bot.database_funcs.get_name(user)
startedGame = False
started_game = False
if game is None:
word = "-"
while "-" in word or "." in word:
response = requests.get(self.__APIURL, params=self.__APIPARAMS)
response = requests.get(self.__API_url, 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 = {
game_id = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
new_game = {
"_id": channel,
"player": user,
"guessed letters": [],
"word": word,
"game ID": gameID,
"game ID": game_id,
"misses": 0,
"guessed": guessed
}
self.__bot.database["hangman games"].insert_one(newGame)
self.__bot.database["hangman games"].insert_one(new_game)
remainingLetters = list(string.ascii_uppercase)
remaining_letters = list(string.ascii_uppercase)
self.__draw.drawImage(channel)
self.__draw.draw_image(channel)
log_message = "Game started"
sendMessage = f"{user_name} started game of hangman."
startedGame = True
send_message = f"{user_name} started game of hangman."
started_game = True
else:
log_message = "There was already a game going on"
sendMessage = self.__bot.long_strings["Hangman going on"]
send_message = self.__bot.long_strings["Hangman going on"]
self.__bot.log(log_message)
await ctx.send(sendMessage)
await ctx.send(send_message)
if startedGame:
boardsPath = "gwendolyn/resources/games/hangman_boards/"
file_path = f"{boardsPath}hangman_board{channel}.png"
newImage = await ctx.channel.send(file=discord.File(file_path))
if started_game:
boards_path = "gwendolyn/resources/games/hangman_boards/"
file_path = f"{boards_path}hangman_board{channel}.png"
new_image = await ctx.channel.send(file=discord.File(file_path))
blankMessage = await ctx.channel.send("_ _")
reactionMessages = {
newImage: remainingLetters[:15],
blankMessage: remainingLetters[15:]
blank_message = await ctx.channel.send("_ _")
reaction_messages = {
new_image: remaining_letters[:15],
blank_message: remaining_letters[15:]
}
old_messages = f"{newImage.id}\n{blankMessage.id}"
old_messages = f"{new_image.id}\n{blank_message.id}"
old_images_path = "gwendolyn/resources/games/old_images/"
with open(f"gwendolyn/resources/games/old_images/hangman{channel}", "w") as f:
f.write(old_messages)
with open(old_images_path+f"hangman{channel}", "w") as file_pointer:
file_pointer.write(old_messages)
for message, letters in reactionMessages.items():
for message, letters in reaction_messages.items():
for letter in letters:
emoji = chr(ord(letter)+127397)
await message.add_reaction(emoji)
@ -148,9 +149,10 @@ class Hangman():
await ctx.send("You can't end a game you're not in")
else:
self.__bot.database["hangman games"].delete_one({"_id": channel})
old_images_path = "gwendolyn/resources/games/old_images/"
with open(f"gwendolyn/resources/games/old_images/hangman{channel}", "r") as f:
messages = f.read().splitlines()
with open(old_images_path+f"hangman{channel}", "r") as file_pointer:
messages = file_pointer.read().splitlines()
for message in messages:
old_message = await ctx.channel.fetch_message(int(message))
@ -176,89 +178,91 @@ class Hangman():
hangman_games = self.__bot.database["hangman games"]
game = hangman_games.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)
game_exists = (game is not None)
single_letter = (len(guess) == 1 and guess.isalpha())
new_guess = (guess not in game["guessed letters"])
valid_guess = (game_exists and single_letter and new_guess)
if validGuess:
if valid_guess:
self.__bot.log("Guessed the letter")
correctGuess = 0
correct_guess = 0
for x, letter in enumerate(game["word"]):
for i, letter in enumerate(game["word"]):
if guess == letter:
correctGuess += 1
updater = {"$set": {f"guessed.{x}": True}}
correct_guess += 1
updater = {"$set": {f"guessed.{i}": True}}
hangman_games.update_one({"_id": channel}, updater)
if correctGuess == 0:
if correct_guess == 0:
updater = {"$inc": {"misses": 1}}
hangman_games.update_one({"_id": channel}, updater)
updater = {"$push": {"guessed letters": guess}}
hangman_games.update_one({"_id": channel}, updater)
remainingLetters = list(string.ascii_uppercase)
remaining_letters = list(string.ascii_uppercase)
game = hangman_games.find_one({"_id": channel})
for letter in game["guessed letters"]:
remainingLetters.remove(letter)
remaining_letters.remove(letter)
if correctGuess == 1:
sendMessage = "Guessed {}. There was 1 {} in the word."
sendMessage = sendMessage.format(guess, guess)
if correct_guess == 1:
send_message = "Guessed {}. There was 1 {} in the word."
send_message = send_message.format(guess, guess)
else:
sendMessage = "Guessed {}. There were {} {}s in the word."
sendMessage = sendMessage.format(guess, correctGuess, guess)
send_message = "Guessed {}. There were {} {}s in the word."
send_message = send_message.format(guess, correct_guess, guess)
self.__draw.drawImage(channel)
self.__draw.draw_image(channel)
if game["misses"] == 6:
hangman_games.delete_one({"_id": channel})
sendMessage += self.__bot.long_strings["Hangman lost game"]
remainingLetters = []
send_message += self.__bot.long_strings["Hangman lost game"]
remaining_letters = []
elif all(game["guessed"]):
hangman_games.delete_one({"_id": channel})
self.__bot.money.addMoney(user, 15)
sendMessage += self.__bot.long_strings["Hangman guessed word"]
remainingLetters = []
send_message += self.__bot.long_strings["Hangman guessed word"]
remaining_letters = []
await message.channel.send(sendMessage)
await message.channel.send(send_message)
old_images_path = "gwendolyn/resources/games/old_images/"
with open(f"gwendolyn/resources/games/old_images/hangman{channel}", "r") as f:
old_message_ids = f.read().splitlines()
with open(old_images_path+f"hangman{channel}", "r") as file_pointer:
old_message_ids = file_pointer.read().splitlines()
for oldID in old_message_ids:
old_message = await message.channel.fetch_message(int(oldID))
for old_id in old_message_ids:
old_message = await message.channel.fetch_message(int(old_id))
self.__bot.log("Deleting old message")
await old_message.delete()
boardsPath = "gwendolyn/resources/games/hangman_boards/"
file_path = f"{boardsPath}hangman_board{channel}.png"
newImage = await message.channel.send(file=discord.File(file_path))
boards_path = "gwendolyn/resources/games/hangman_boards/"
file_path = f"{boards_path}hangman_board{channel}.png"
new_image = await message.channel.send(file=discord.File(file_path))
if len(remainingLetters) > 0:
if len(remainingLetters) > 15:
blankMessage = await message.channel.send("_ _")
reactionMessages = {
newImage: remainingLetters[:15],
blankMessage: remainingLetters[15:]
if len(remaining_letters) > 0:
if len(remaining_letters) > 15:
blank_message = await message.channel.send("_ _")
reaction_messages = {
new_image: remaining_letters[:15],
blank_message: remaining_letters[15:]
}
else:
blankMessage = ""
reactionMessages = {newImage: remainingLetters}
blank_message = ""
reaction_messages = {new_image: remaining_letters}
if blankMessage != "":
old_messages = f"{newImage.id}\n{blankMessage.id}"
if blank_message != "":
old_messages = f"{new_image.id}\n{blank_message.id}"
else:
old_messages = str(newImage.id)
old_messages = str(new_image.id)
old_imagePath = f"gwendolyn/resources/games/old_images/hangman{channel}"
with open(old_imagePath, "w") as f:
f.write(old_messages)
old_images_path = "gwendolyn/resources/games/old_images/"
old_image_path = old_images_path + f"hangman{channel}"
with open(old_image_path, "w") as file_pointer:
file_pointer.write(old_messages)
for message, letters in reactionMessages.items():
for message, letters in reaction_messages.items():
for letter in letters:
emoji = chr(ord(letter)+127397)
await message.add_reaction(emoji)
@ -270,7 +274,7 @@ class DrawHangman():
*Methods*
---------
drawImage(channel: str)
draw_image(channel: str)
"""
def __init__(self, bot):
@ -293,6 +297,7 @@ class DrawHangman():
SMALLFONT
"""
self.__bot = bot
# pylint: disable=invalid-name
self.__CIRCLESIZE = 120
self.__LINEWIDTH = 12
@ -318,129 +323,132 @@ class DrawHangman():
FONTPATH = "gwendolyn/resources/fonts/comic-sans-bold.ttf"
self.__FONT = ImageFont.truetype(FONTPATH, LETTERSIZE)
self.__SMALLFONT = ImageFont.truetype(FONTPATH, WORDSIZE)
# pylint: enable=invalid-name
def __deviate(self, preDeviance: int, preDevianceAccuracy: int,
positionChange: float, maxmin: int,
maxAcceleration: float):
randomDeviance = random.uniform(-positionChange, positionChange)
devianceAccuracy = preDevianceAccuracy + randomDeviance
if devianceAccuracy > maxmin * maxAcceleration:
devianceAccuracy = maxmin * maxAcceleration
elif devianceAccuracy < -maxmin * maxAcceleration:
devianceAccuracy = -maxmin * maxAcceleration
def __deviate(self, pre_deviance: int, pre_deviance_accuracy: int,
position_change: float, maxmin: int,
max_acceleration: float):
random_deviance = random.uniform(-position_change, position_change)
deviance_accuracy = pre_deviance_accuracy + random_deviance
if deviance_accuracy > maxmin * max_acceleration:
deviance_accuracy = maxmin * max_acceleration
elif deviance_accuracy < -maxmin * max_acceleration:
deviance_accuracy = -maxmin * max_acceleration
deviance = preDeviance + devianceAccuracy
deviance = pre_deviance + deviance_accuracy
if deviance > maxmin:
deviance = maxmin
elif deviance < -maxmin:
deviance = -maxmin
return deviance, devianceAccuracy
return deviance, deviance_accuracy
def __badCircle(self):
circlePadding = (self.__LINEWIDTH*3)
imageWidth = self.__CIRCLESIZE+circlePadding
imageSize = (imageWidth, imageWidth)
background = Image.new("RGBA", imageSize, color=(0, 0, 0, 0))
def __bad_circle(self):
circle_padding = (self.__LINEWIDTH*3)
image_width = self.__CIRCLESIZE+circle_padding
image_size = (image_width, image_width)
background = Image.new("RGBA", image_size, color=(0, 0, 0, 0))
d = ImageDraw.Draw(background, "RGBA")
drawer = ImageDraw.Draw(background, "RGBA")
middle = (self.__CIRCLESIZE+(self.__LINEWIDTH*3))/2
devianceX = 0
devianceY = 0
devianceAccuracyX = 0
devianceAccuracyY = 0
deviance_x = 0
deviance_y = 0
deviance_accuracy_x = 0
deviance_accuracy_y = 0
start = random.randint(-100, -80)
degreesAmount = 360 + random.randint(-10, 30)
degreess_amount = 360 + random.randint(-10, 30)
for degree in range(degreesAmount):
devianceXParams = [
devianceX,
devianceAccuracyX,
for degree in range(degreess_amount):
deviance_x, deviance_accuracy_x = self.__deviate(
deviance_x,
deviance_accuracy_x,
self.__LINEWIDTH/100,
self.__LINEWIDTH,
0.03
]
devianceYParams = [
devianceY,
devianceAccuracyY,
)
deviance_y, deviance_accuracy_y = self.__deviate(
deviance_y,
deviance_accuracy_y,
self.__LINEWIDTH/100,
self.__LINEWIDTH,
0.03
]
devianceX, devianceAccuracyX = self.__deviate(*devianceXParams)
devianceY, devianceAccuracyY = self.__deviate(*devianceYParams)
)
radians = math.radians(degree+start)
circleX = (math.cos(radians) * (self.__CIRCLESIZE/2))
circleY = (math.sin(radians) * (self.__CIRCLESIZE/2))
circle_x = (math.cos(radians) * (self.__CIRCLESIZE/2))
circle_y = (math.sin(radians) * (self.__CIRCLESIZE/2))
x = middle + circleX - (self.__LINEWIDTH/2) + devianceX
y = middle + circleY - (self.__LINEWIDTH/2) + devianceY
position_x = middle + circle_x - (self.__LINEWIDTH/2) + deviance_x
position_y = middle + circle_y - (self.__LINEWIDTH/2) + deviance_y
circlePosition = [(x, y), (x+self.__LINEWIDTH, y+self.__LINEWIDTH)]
d.ellipse(circlePosition, fill=(0, 0, 0, 255))
circle_position = [
(position_x, position_y),
(position_x+self.__LINEWIDTH, position_y+self.__LINEWIDTH)
]
drawer.ellipse(circle_position, fill=(0, 0, 0, 255))
return background
def __badLine(self, length: int, rotated: bool = False):
def __bad_line(self, length: int, rotated: bool = False):
if rotated:
w, h = length+self.__LINEWIDTH*3, self.__LINEWIDTH*3
width, height = 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))
width, height = self.__LINEWIDTH*3, length+self.__LINEWIDTH*3
background = Image.new("RGBA", (width, height), color=(0, 0, 0, 0))
d = ImageDraw.Draw(background, "RGBA")
drawer = ImageDraw.Draw(background, "RGBA")
possibleDeviance = int(self.__LINEWIDTH/3)
devianceX = random.randint(-possibleDeviance, possibleDeviance)
devianceY = 0
devianceAccuracyX = 0
devianceAccuracyY = 0
possible_deviance = int(self.__LINEWIDTH/3)
deviance_x = random.randint(-possible_deviance, possible_deviance)
deviance_y = 0
deviance_accuracy_x = 0
deviance_accuracy_y = 0
for pixel in range(length):
devianceParamsX = [
devianceX,
devianceAccuracyX,
deviance_x, deviance_accuracy_x = self.__deviate(
deviance_x,
deviance_accuracy_x,
self.__LINEWIDTH/1000,
self.__LINEWIDTH,
0.004
]
devianceParamsY = [
devianceY,
devianceAccuracyY,
)
deviance_y, deviance_accuracy_y = self.__deviate(
deviance_y,
deviance_accuracy_y,
self.__LINEWIDTH/1000,
self.__LINEWIDTH,
0.004
]
devianceX, devianceAccuracyX = self.__deviate(*devianceParamsX)
devianceY, devianceAccuracyY = self.__deviate(*devianceParamsY)
)
if rotated:
x = self.__LINEWIDTH + pixel + devianceX
y = self.__LINEWIDTH + devianceY
position_x = self.__LINEWIDTH + pixel + deviance_x
position_y = self.__LINEWIDTH + deviance_y
else:
x = self.__LINEWIDTH + devianceX
y = self.__LINEWIDTH + pixel + devianceY
position_x = self.__LINEWIDTH + deviance_x
position_y = self.__LINEWIDTH + pixel + deviance_y
circlePosition = [(x, y), (x+self.__LINEWIDTH, y+self.__LINEWIDTH)]
d.ellipse(circlePosition, fill=(0, 0, 0, 255))
circle_position = [
(position_x, position_y),
(position_x+self.__LINEWIDTH, position_y+self.__LINEWIDTH)
]
drawer.ellipse(circle_position, fill=(0, 0, 0, 255))
return background
def __drawMan(self, misses: int, seed: str):
def __draw_man(self, misses: int, seed: str):
random.seed(seed)
manSize = (self.__MANX, self.__MANY)
background = Image.new("RGBA", manSize, color=(0, 0, 0, 0))
man_size = (self.__MANX, self.__MANY)
background = Image.new("RGBA", man_size, color=(0, 0, 0, 0))
if misses >= 1:
head = self.__badCircle()
pasteX = (self.__MANX-(self.__CIRCLESIZE+(self.__LINEWIDTH*3)))//2
pastePosition = (pasteX, 0)
background.paste(head, pastePosition, head)
head = self.__bad_circle()
paste_x = (self.__MANX-(self.__CIRCLESIZE+(self.__LINEWIDTH*3)))//2
paste_position = (paste_x, 0)
background.paste(head, paste_position, head)
if misses >= 2:
body = self.__badLine(self.__BODYSIZE)
pasteX = (self.__MANX-(self.__LINEWIDTH*3))//2
pastePosition = (pasteX, self.__CIRCLESIZE)
background.paste(body, pastePosition, body)
body = self.__bad_line(self.__BODYSIZE)
paste_x = (self.__MANX-(self.__LINEWIDTH*3))//2
paste_position = (paste_x, self.__CIRCLESIZE)
background.paste(body, paste_position, body)
if misses >= 3:
limbs = random.sample(["rl", "ll", "ra", "la"], min(misses-2, 4))
@ -450,131 +458,138 @@ class DrawHangman():
random.seed(seed)
for limb in limbs:
limbDrawing = self.__badLine(self.__LIMBSIZE, True)
xPosition = (self.__MANX-(self.__LINEWIDTH*3))//2
limb_drawing = self.__bad_line(self.__LIMBSIZE, True)
x_position = (self.__MANX-(self.__LINEWIDTH*3))//2
if limb[1] == "a":
rotation = random.randint(-45, 45)
shift = math.sin(math.radians(rotation))
lineLength = self.__LIMBSIZE+(self.__LINEWIDTH*3)
compensation = int(shift*lineLength)
limbDrawing = limbDrawing.rotate(rotation, expand=1)
yPosition = self.__CIRCLESIZE + self.__ARMPOSITION
line_length = self.__LIMBSIZE+(self.__LINEWIDTH*3)
compensation = int(shift*line_length)
limb_drawing = limb_drawing.rotate(rotation, expand=1)
y_position = self.__CIRCLESIZE + self.__ARMPOSITION
if limb == "ra":
compensation = min(-compensation, 0)
else:
xPosition -= self.__LIMBSIZE
x_position -= self.__LIMBSIZE
compensation = min(compensation, 0)
yPosition += compensation
y_position += compensation
else:
rotation = random.randint(-15, 15)
yPosition = self.__CIRCLESIZE+self.__BODYSIZE-self.__LINEWIDTH
y_position = self.__CIRCLESIZE+self.__BODYSIZE-self.__LINEWIDTH
if limb == "rl":
limbDrawing = limbDrawing.rotate(rotation-45, expand=1)
limb_drawing = limb_drawing.rotate(rotation-45, expand=1)
else:
xPosition += -limbDrawing.size[0]+self.__LINEWIDTH*3
limbDrawing = limbDrawing.rotate(rotation+45, expand=1)
x_position += -limb_drawing.size[0]+self.__LINEWIDTH*3
limb_drawing = limb_drawing.rotate(rotation+45, expand=1)
pastePosition = (xPosition, yPosition)
background.paste(limbDrawing, pastePosition, limbDrawing)
paste_position = (x_position, y_position)
background.paste(limb_drawing, paste_position, limb_drawing)
return background
def __badText(self, text: str, big: bool, color: tuple = (0, 0, 0, 255)):
def __bad_text(self, text: str, big: bool, color: tuple = (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")
width, height = font.getsize(text)
img = Image.new("RGBA", (width, height), color=(0, 0, 0, 0))
drawer = ImageDraw.Draw(img, "RGBA")
d.text((0, 0), text, font=font, fill=color)
drawer.text((0, 0), text, font=font, fill=color)
return img
def __drawGallows(self):
gallowSize = (self.__GALLOWX, self.__GALLOWY)
background = Image.new("RGBA", gallowSize, color=(0, 0, 0, 0))
def __draw_gallows(self):
gallow_size = (self.__GALLOWX, self.__GALLOWY)
background = Image.new("RGBA", gallow_size, color=(0, 0, 0, 0))
bottomLine = self.__badLine(int(self.__GALLOWX * 0.75), True)
bottomLineX = int(self.__GALLOWX * 0.125)
bottomLineY = self.__GALLOWY-(self.__LINEWIDTH*4)
pastePosition = (bottomLineX, bottomLineY)
background.paste(bottomLine, pastePosition, bottomLine)
bottom_line = self.__bad_line(int(self.__GALLOWX * 0.75), True)
bottom_line_x = int(self.__GALLOWX * 0.125)
bottom_line_y = self.__GALLOWY-(self.__LINEWIDTH*4)
paste_position = (bottom_line_x, bottom_line_y)
background.paste(bottom_line, paste_position, bottom_line)
lineTwo = self.__badLine(self.__GALLOWY-self.__LINEWIDTH*6)
lineTwoX = int(self.__GALLOWX*(0.75*self.__PHI))
lineTwoY = self.__LINEWIDTH*2
pastePosition = (lineTwoX, lineTwoY)
background.paste(lineTwo, pastePosition, lineTwo)
line_two = self.__bad_line(self.__GALLOWY-self.__LINEWIDTH*6)
line_two_x = int(self.__GALLOWX*(0.75*self.__PHI))
line_two_y = self.__LINEWIDTH*2
paste_position = (line_two_x, line_two_y)
background.paste(line_two, paste_position, line_two)
topLine = self.__badLine(int(self.__GALLOWY*0.30), True)
pasteX = int(self.__GALLOWX*(0.75*self.__PHI))-self.__LINEWIDTH
pastePosition = (pasteX, self.__LINEWIDTH*3)
background.paste(topLine, pastePosition, topLine)
top_line = self.__bad_line(int(self.__GALLOWY*0.30), True)
paste_x = int(self.__GALLOWX*(0.75*self.__PHI))-self.__LINEWIDTH
paste_position = (paste_x, self.__LINEWIDTH*3)
background.paste(top_line, paste_position, top_line)
lastLine = self.__badLine(int(self.__GALLOWY*0.125))
pasteX += int(self.__GALLOWY*0.30)
background.paste(lastLine, (pasteX, self.__LINEWIDTH*3), lastLine)
last_line = self.__bad_line(int(self.__GALLOWY*0.125))
paste_x += int(self.__GALLOWY*0.30)
background.paste(last_line, (paste_x, self.__LINEWIDTH*3), last_line)
return background
def __drawLetterLines(self, word: str, guessed: list, misses: int):
letterWidth = self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE
imageWidth = letterWidth*len(word)
imageSize = (imageWidth, self.__LETTERLINELENGTH+self.__LINEWIDTH*3)
letterLines = Image.new("RGBA", imageSize, color=(0, 0, 0, 0))
for x, letter in enumerate(word):
line = self.__badLine(self.__LETTERLINELENGTH, True)
pasteX = x*(self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE)
pastePosition = (pasteX, self.__LETTERLINELENGTH)
letterLines.paste(line, pastePosition, line)
if guessed[x]:
letterDrawing = self.__badText(letter, True)
letterWidth = self.__FONT.getsize(letter)[0]
letterX = x*(self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE)
letterX -= (letterWidth//2)
letterX += (self.__LETTERLINELENGTH//2)+(self.__LINEWIDTH*2)
letterLines.paste(letterDrawing, (letterX, 0), letterDrawing)
def __draw_letter_lines(self, word: str, guessed: list, misses: int):
letter_width = self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE
image_width = letter_width*len(word)
image_size = (image_width, self.__LETTERLINELENGTH+self.__LINEWIDTH*3)
letter_lines = Image.new("RGBA", image_size, color=(0, 0, 0, 0))
for i, letter in enumerate(word):
line = self.__bad_line(self.__LETTERLINELENGTH, True)
paste_x = i*(self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE)
paste_position = (paste_x, self.__LETTERLINELENGTH)
letter_lines.paste(line, paste_position, line)
if guessed[i]:
letter_drawing = self.__bad_text(letter, True)
letter_width = self.__FONT.getsize(letter)[0]
letter_x = i*(self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE)
letter_x -= (letter_width//2)
letter_x += (self.__LETTERLINELENGTH//2)+(self.__LINEWIDTH*2)
letter_lines.paste(
letter_drawing,
(letter_x, 0),
letter_drawing
)
elif misses == 6:
letterDrawing = self.__badText(letter, True, (242, 66, 54))
letterWidth = self.__FONT.getsize(letter)[0]
letterX = x*(self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE)
letterX -= (letterWidth//2)
letterX += (self.__LETTERLINELENGTH//2)+(self.__LINEWIDTH*2)
letterLines.paste(letterDrawing, (letterX, 0), letterDrawing)
letter_drawing = self.__bad_text(letter, True, (242, 66, 54))
letter_width = self.__FONT.getsize(letter)[0]
letter_x = i*(self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE)
letter_x -= (letter_width//2)
letter_x += (self.__LETTERLINELENGTH//2)+(self.__LINEWIDTH*2)
letter_lines.paste(
letter_drawing,
(letter_x, 0),
letter_drawing
)
return letterLines
return letter_lines
def __shortestDist(self, positions: list, newPosition: tuple):
__shortestDist = math.inf
x, y = newPosition
def __shortest_dist(self, positions: list, new_position: tuple):
shortest_dist = math.inf
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
x_distance = abs(i-new_position[0])
y_distance = abs(j-new_position[1])
dist = math.sqrt(x_distance**2+y_distance**2)
if shortest_dist > dist:
shortest_dist = dist
return shortest_dist
def __drawMisses(self, guesses: list, word: str):
def __draw_misses(self, guesses: list, word: str):
background = Image.new("RGBA", (600, 400), color=(0, 0, 0, 0))
pos = []
for guess in guesses:
if guess not in word:
placed = False
while not placed:
letter = self.__badText(guess, True)
letter = self.__bad_text(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:
if self.__shortest_dist(pos, (x, y)) > 70:
pos.append((x, y))
background.paste(letter, (x, y), letter)
placed = True
return background
def drawImage(self, channel: str):
def draw_image(self, channel: str):
"""
Draw a hangman Image.
@ -589,24 +604,24 @@ class DrawHangman():
random.seed(game["game ID"])
background = Image.open("gwendolyn/resources/paper.jpg")
gallow = self.__drawGallows()
man = self.__drawMan(game["misses"], game["game ID"])
gallow = self.__draw_gallows()
man = self.__draw_man(game["misses"], game["game ID"])
random.seed(game["game ID"])
letterLineParams = [game["word"], game["guessed"], game["misses"]]
letterLines = self.__drawLetterLines(*letterLineParams)
letter_line_parameters = [game["word"], game["guessed"], game["misses"]]
letter_lines = self.__draw_letter_lines(*letter_line_parameters)
random.seed(game["game ID"])
misses = self.__drawMisses(game["guessed letters"], game["word"])
misses = self.__draw_misses(game["guessed letters"], game["word"])
background.paste(gallow, (100, 100), gallow)
background.paste(man, (300, 210), man)
background.paste(letterLines, (120, 840), letterLines)
background.paste(letter_lines, (120, 840), letter_lines)
background.paste(misses, (600, 150), misses)
missesText = self.__badText("MISSES", False)
missesTextWidth = missesText.size[0]
background.paste(missesText, (850-missesTextWidth//2, 50), missesText)
misses_text = self.__bad_text("MISSES", False)
misses_text_width = misses_text.size[0]
background.paste(misses_text, (850-misses_text_width//2, 50), misses_text)
boardPath = f"gwendolyn/resources/games/hangman_boards/hangman_board{channel}.png"
background.save(boardPath)
board_path = f"gwendolyn/resources/games/hangman_boards/hangman_board{channel}.png"
background.save(board_path)