🧹 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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

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)

View File

@ -28,7 +28,7 @@ class HexGame():
await ctx.send("You can't surrender when you're not a player.")
else:
opponent = (players.index(user) + 1) % 2
opponentName = self.bot.database_funcs.get_name(players[opponent])
opponent_name = self.bot.database_funcs.get_name(players[opponent])
self.bot.database["hex games"].update_one({"_id":channel},{"$set":{"winner":opponent + 1}})
await ctx.send(f"{ctx.author.display_name} surrendered")
@ -71,9 +71,9 @@ class HexGame():
self.draw.drawSwap(channel)
opponent = game["players"][::-1][game["turn"]-1]
gwendoTurn = (opponent == f"#{self.bot.user.id}")
opponentName = self.bot.database_funcs.get_name(opponent)
await ctx.send(f"The color of the players were swapped. It is now {opponentName}'s turn")
gwendolyn_turn = (opponent == f"#{self.bot.user.id}")
opponent_name = self.bot.database_funcs.get_name(opponent)
await ctx.send(f"The color of the players were swapped. It is now {opponent_name}'s turn")
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "r") as f:
old_image = await ctx.channel.fetch_message(int(f.read()))
@ -90,7 +90,7 @@ class HexGame():
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "w") as f:
f.write(str(old_image.id))
if gwendoTurn:
if gwendolyn_turn:
await self.hexAI(ctx)
# Starts the game
@ -100,109 +100,109 @@ class HexGame():
channel = str(ctx.channel_id)
game = self.bot.database["hex games"].find_one({"_id":channel})
startedGame = False
canStart = True
started_game = False
can_start = True
if game != None:
sendMessage = "There's already a hex game going on in this channel"
send_message = "There's already a hex game going on in this channel"
log_message = "There was already a game going on"
canStart = False
can_start = False
else:
if type(opponent) == int:
# Opponent is Gwendolyn
if opponent in range(1, 6):
opponentName = "Gwendolyn"
opponent_name = "Gwendolyn"
difficulty = int(opponent)
diffText = f" with difficulty {difficulty}"
difficulty_text = f" with difficulty {difficulty}"
opponent = f"#{self.bot.user.id}"
else:
sendMessage = "Difficulty doesn't exist"
send_message = "Difficulty doesn't exist"
log_message = "They tried to play against a difficulty that doesn't exist"
canStart = False
can_start = False
elif type(opponent) == discord.member.Member:
if opponent.bot:
# User has challenged a bot
if opponent == self.bot.user:
# It was Gwendolyn
opponentName = "Gwendolyn"
opponent_name = "Gwendolyn"
difficulty = 2
diffText = f" with difficulty {difficulty}"
difficulty_text = f" with difficulty {difficulty}"
opponent = f"#{self.bot.user.id}"
else:
sendMessage = "You can't challenge a bot!"
send_message = "You can't challenge a bot!"
log_message = "They tried to challenge a bot"
canStart = False
can_start = False
else:
# Opponent is another player
if ctx.author != opponent:
opponentName = opponent.display_name
opponent_name = opponent.display_name
opponent = f"#{opponent.id}"
difficulty = 5
diffText = ""
difficulty_text = ""
else:
sendMessage = "You can't play against yourself"
send_message = "You can't play against yourself"
log_message = "They tried to play against themself"
canStart = False
can_start = False
else:
canStart = False
can_start = False
log_message = f"Opponent was neither int or member. It was {type(opponent)}"
sendMessage = "Something went wrong"
send_message = "Something went wrong"
if canStart:
if can_start:
# board is 11x11
board = [[0 for i in range(self.BOARDWIDTH)] for j in range(self.BOARDWIDTH)]
players = [user, opponent]
random.shuffle(players) # random starting player
gameHistory = []
newGame = {"_id":channel,"board":board, "winner":0,
new_game = {"_id":channel,"board":board, "winner":0,
"players":players, "turn":1, "difficulty":difficulty, "gameHistory":gameHistory}
self.bot.database["hex games"].insert_one(newGame)
self.bot.database["hex games"].insert_one(new_game)
# draw the board
self.draw.drawBoard(channel)
gwendoTurn = (players[0] == f"#{self.bot.user.id}")
startedGame = True
gwendolyn_turn = (players[0] == f"#{self.bot.user.id}")
started_game = True
turnName = self.bot.database_funcs.get_name(players[0])
sendMessage = f"Started Hex game against {opponentName}{diffText}. It's {turnName}'s turn"
turn_name = self.bot.database_funcs.get_name(players[0])
send_message = f"Started Hex game against {opponent_name}{difficulty_text}. It's {turn_name}'s turn"
log_message = "Game started"
await ctx.send(sendMessage)
await ctx.send(send_message)
self.bot.log(log_message)
if startedGame:
if started_game:
file_path = f"gwendolyn/resources/games/hex_boards/board{ctx.channel_id}.png"
newImage = await ctx.channel.send(file = discord.File(file_path))
new_image = await ctx.channel.send(file = discord.File(file_path))
with open(f"gwendolyn/resources/games/old_images/hex{ctx.channel_id}", "w") as f:
f.write(str(newImage.id))
f.write(str(new_image.id))
if gwendoTurn:
if gwendolyn_turn:
await self.hexAI(ctx)
# Places a piece at the given location and checks things afterwards
async def placeHex(self, ctx, position : str, user):
channel = str(ctx.channel_id)
game = self.bot.database["hex games"].find_one({"_id":channel})
placedPiece = False
placed_piece = False
if game == None:
sendMessage = "There's no game in this channel"
send_message = "There's no game in this channel"
self.bot.log("There was no game going on")
elif not (position[0].isalpha() and position[1:].isnumeric() and len(position) in [2, 3]):
sendMessage = "The position must be a letter followed by a number."
send_message = "The position must be a letter followed by a number."
self.bot.log(f"The position was not valid, {position}")
else:
players = game["players"]
if user not in players:
sendMessage = f"You can't place when you're not in the game. The game's players are: {self.bot.database_funcs.get_name(game['players'][0])} and {self.bot.database_funcs.get_name(game['players'][1])}."
send_message = f"You can't place when you're not in the game. The game's players are: {self.bot.database_funcs.get_name(game['players'][0])} and {self.bot.database_funcs.get_name(game['players'][1])}."
self.bot.log("They aren't in the game")
elif players[game["turn"]-1] != user:
sendMessage = "It's not your turn"
send_message = "It's not your turn"
self.bot.log("It wasn't their turn")
else:
player = game["turn"]
@ -215,7 +215,7 @@ class HexGame():
if board is None:
self.bot.log("It was an invalid position")
sendMessage = ("That's an invalid position. You must place your piece on an empty field.")
send_message = ("That's an invalid position. You must place your piece on an empty field.")
else:
# If the move is valid:
self.bot.database["hex games"].update_one({"_id":channel},{"$set":{"board":board}})
@ -227,34 +227,34 @@ class HexGame():
winner = self.evaluateBoard(game["board"])[1]
if winner == 0: # Continue with the game.
gameWon = False
sendMessage = self.bot.database_funcs.get_name(game["players"][player-1])+" placed at "+position.upper()+". It's now "+self.bot.database_funcs.get_name(game["players"][turn-1])+"'s turn."# The score is "+str(score)
game_won = False
send_message = self.bot.database_funcs.get_name(game["players"][player-1])+" placed at "+position.upper()+". It's now "+self.bot.database_funcs.get_name(game["players"][turn-1])+"'s turn."# The score is "+str(score)
else: # Congratulations!
gameWon = True
game_won = True
self.bot.database["hex games"].update_one({"_id":channel},{"$set":{"winner":winner}})
sendMessage = self.bot.database_funcs.get_name(game["players"][player-1])+" placed at "+position.upper()+" and won!"
send_message = self.bot.database_funcs.get_name(game["players"][player-1])+" placed at "+position.upper()+" and won!"
if game["players"][winner-1] != f"#{self.bot.user.id}":
winAmount = game["difficulty"]*10
sendMessage += " Adding "+str(winAmount)+" GwendoBucks to their account."
win_amount = game["difficulty"]*10
send_message += " Adding "+str(win_amount)+" GwendoBucks to their account."
self.bot.database["hex games"].update_one({"_id":channel},
{"$push":{"gameHistory":(int(position[1])-1, ord(position[0])-97)}})
# Is it now Gwendolyn's turn?
gwendoTurn = False
gwendolyn_turn = False
if game["players"][turn-1] == f"#{self.bot.user.id}":
self.bot.log("It's Gwendolyn's turn")
gwendoTurn = True
gwendolyn_turn = True
placedPiece = True
placed_piece = True
if user == f"#{self.bot.user.id}":
await ctx.channel.send(sendMessage)
await ctx.channel.send(send_message)
else:
await ctx.send(sendMessage)
await ctx.send(send_message)
if placedPiece:
if placed_piece:
# Update the board
self.draw.drawHexPlacement(channel,player, position)
@ -270,7 +270,7 @@ class HexGame():
file_path = f"gwendolyn/resources/games/hex_boards/board{channel}.png"
old_image = await ctx.channel.send(file = discord.File(file_path))
if gameWon:
if game_won:
self.bot.log("Dealing with the winning player")
game = self.bot.database["hex games"].find_one({"_id":channel})
@ -284,7 +284,7 @@ class HexGame():
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "w") as f:
f.write(str(old_image.id))
if gwendoTurn:
if gwendolyn_turn:
await self.hexAI(ctx)
# Returns a board where the placement has ocurred
@ -314,11 +314,11 @@ class HexGame():
game = self.bot.database["hex games"].find_one({"_id":channel})
if user not in game["players"]:
sendMessage = "You're not a player in the game"
send_message = "You're not a player in the game"
elif len(game["gameHistory"]) == 0:
sendMessage = "You can't undo nothing"
send_message = "You can't undo nothing"
elif user != game["players"][(game["turn"] % 2)]: # If it's not your turn
sendMessage = "It's not your turn"
send_message = "It's not your turn"
else:
turn = game["turn"]
self.bot.log("Undoing {}'s last move".format(self.bot.database_funcs.get_name(user)))
@ -332,10 +332,10 @@ class HexGame():
# Update the board
self.draw.drawHexPlacement(channel,0,"abcdefghijk"[lastMove[1]]+str(lastMove[0]+1)) # The zero makes the hex disappear
sendMessage = f"You undid your last move at {lastMove}"
send_message = f"You undid your last move at {lastMove}"
undid = True
await ctx.send(sendMessage)
await ctx.send(send_message)
if undid:
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "r") as f:
old_image = await ctx.channel.fetch_message(int(f.read()))
@ -417,20 +417,20 @@ class HexGame():
return scores[2]-scores[1], winner
def minimaxHex(self, board, depth, alpha, beta, maximizingPlayer):
def minimaxHex(self, board, depth, alpha, beta, maximizing_player):
# The depth is how many moves ahead the computer checks. This value is the difficulty.
if depth == 0 or 0 not in sum(board,[]):
score = self.evaluateBoard(board)[0]
return score
# if final depth is not reached, look another move ahead:
if maximizingPlayer: # red player predicts next move
if maximizing_player: # red player predicts next move
maxEval = -math.inf
possiblePlaces = [i for i,v in enumerate(sum(board,[])) if v == 0]
#self.bot.log("Judging a red move at depth {}".format(depth))
for i in possiblePlaces:
testBoard = copy.deepcopy(board)
testBoard[i // self.BOARDWIDTH][i % self.BOARDWIDTH] = 1 # because maximizingPlayer is Red which is number 1
evaluation = self.minimaxHex(testBoard,depth-1,alpha,beta,False)
test_board = copy.deepcopy(board)
test_board[i // self.BOARDWIDTH][i % self.BOARDWIDTH] = 1 # because maximizing_player is Red which is number 1
evaluation = self.minimaxHex(test_board,depth-1,alpha,beta,False)
maxEval = max(maxEval, evaluation)
alpha = max(alpha, evaluation)
if beta <= alpha:
@ -442,9 +442,9 @@ class HexGame():
possiblePlaces = [i for i,v in enumerate(sum(board,[])) if v == 0]
#self.bot.log("Judging a blue move at depth {}".format(depth))
for i in possiblePlaces:
testBoard = copy.deepcopy(board)
testBoard[i // self.BOARDWIDTH][i % self.BOARDWIDTH] = 2 # because minimizingPlayer is Blue which is number 2
evaluation = self.minimaxHex(testBoard,depth-1,alpha,beta,True)
test_board = copy.deepcopy(board)
test_board[i // self.BOARDWIDTH][i % self.BOARDWIDTH] = 2 # because minimizingPlayer is Blue which is number 2
evaluation = self.minimaxHex(test_board,depth-1,alpha,beta,True)
minEval = min(minEval, evaluation)
beta = min(beta, evaluation)
if beta <= alpha:

View File

@ -62,8 +62,8 @@ class Invest():
portfolio: str
The portfolio.
"""
investmentsDatabase = self.bot.database["investments"]
userInvestments = investmentsDatabase.find_one({"_id": user})
investments_database = self.bot.database["investments"]
userInvestments = investments_database.find_one({"_id": user})
user_name = self.bot.database_funcs.get_name(user)
@ -101,7 +101,7 @@ class Invest():
*Returns*
---------
sendMessage: str
send_message: str
The message to return to the user.
"""
if buyAmount < 100:
@ -111,9 +111,9 @@ class Invest():
elif self.getPrice(stock) <= 0:
return f"{stock} is not traded on the american market."
else:
investmentsDatabase = self.bot.database["investments"]
investments_database = self.bot.database["investments"]
stockPrice = self.getPrice(stock)
userInvestments = investmentsDatabase.find_one({"_id": user})
userInvestments = investments_database.find_one({"_id": user})
self.bot.money.addMoney(user, -1*buyAmount)
stock = stock.upper()
@ -126,18 +126,18 @@ class Invest():
currentValue = int(valueChange * value["purchased"])
newAmount = currentValue + buyAmount
valuePath = f"investments.{stock}.value at purchase"
updater = {"$set": {valuePath: stockPrice}}
investmentsDatabase.update_one({"_id": user}, updater)
value_path = f"investments.{stock}.value at purchase"
updater = {"$set": {value_path: stockPrice}}
investments_database.update_one({"_id": user}, updater)
purchasedPath = f"investments.{stock}.purchased"
updater = {"$set": {purchasedPath: newAmount}}
investmentsDatabase.update_one({"_id": user}, updater)
purchased_path = f"investments.{stock}.purchased"
updater = {"$set": {purchased_path: newAmount}}
investments_database.update_one({"_id": user}, updater)
if value["purchased for"] != "?":
purchasedForPath = f"investments.{stock}.purchased for"
updater = {"$set": {purchasedForPath: buyAmount}}
investmentsDatabase.update_one({"_id": user}, updater)
purchasedFor_path = f"investments.{stock}.purchased for"
updater = {"$set": {purchasedFor_path: buyAmount}}
investments_database.update_one({"_id": user}, updater)
else:
updater = {
"$set": {
@ -148,9 +148,9 @@ class Invest():
}
}
}
investmentsDatabase.update_one({"_id": user}, updater)
investments_database.update_one({"_id": user}, updater)
else:
newUser = {
new_user = {
"_id": user,
"investments": {
stock: {
@ -160,12 +160,12 @@ class Invest():
}
}
}
investmentsDatabase.insert_one(newUser)
investments_database.insert_one(new_user)
user_name = self.bot.database_funcs.get_name(user)
sendMessage = "{} bought {} GwendoBucks worth of {} stock"
sendMessage = sendMessage.format(user_name, buyAmount, stock)
return sendMessage
send_message = "{} bought {} GwendoBucks worth of {} stock"
send_message = send_message.format(user_name, buyAmount, stock)
return send_message
def sellStock(self, user: str, stock: str, sellAmount: int):
"""
@ -182,15 +182,15 @@ class Invest():
*Returns*
---------
sendMessage: str
send_message: str
The message to return to the user.
"""
if sellAmount <= 0:
return "no"
else:
investmentsDatabase = self.bot.database["investments"]
userData = investmentsDatabase.find_one({"_id": user})
userInvestments = userData["investments"]
investments_database = self.bot.database["investments"]
user_data = investments_database.find_one({"_id": user})
userInvestments = user_data["investments"]
stock = stock.upper()
@ -199,29 +199,29 @@ class Invest():
stockPrice = self.getPrice(stock)
priceChange = (stockPrice / value["value at purchase"])
purchasedAmount = int(priceChange * value["purchased"])
purchasedPath = f"investments.{stock}.purchased"
updater = {"$set": {purchasedPath: purchasedAmount}}
investmentsDatabase.update_one({"_id": user}, updater)
valueAtPurchasePath = f"investments.{stock}.value at purchase"
updater = {"$set": {valueAtPurchasePath: stockPrice}}
investmentsDatabase.update_one({"_id": user}, updater)
purchased_path = f"investments.{stock}.purchased"
updater = {"$set": {purchased_path: purchasedAmount}}
investments_database.update_one({"_id": user}, updater)
valueAtPurchase_path = f"investments.{stock}.value at purchase"
updater = {"$set": {valueAtPurchase_path: stockPrice}}
investments_database.update_one({"_id": user}, updater)
if value["purchased"] >= sellAmount:
self.bot.money.addMoney(user, sellAmount)
if sellAmount < value["purchased"]:
purchasedPath = f"investments.{stock}.purchased"
updater = {"$inc": {purchasedPath: -sellAmount}}
investmentsDatabase.update_one({"_id": user}, updater)
purchased_path = f"investments.{stock}.purchased"
updater = {"$inc": {purchased_path: -sellAmount}}
investments_database.update_one({"_id": user}, updater)
purchasedForPath = f"investments.{stock}.purchased for"
updater = {"$set": {purchasedForPath: "?"}}
investmentsDatabase.update_one({"_id": user}, updater)
purchasedFor_path = f"investments.{stock}.purchased for"
updater = {"$set": {purchasedFor_path: "?"}}
investments_database.update_one({"_id": user}, updater)
else:
updater = {"$unset": {f"investments.{stock}": ""}}
investmentsDatabase.update_one({"_id": user}, updater)
investments_database.update_one({"_id": user}, updater)
user_name = self.bot.database_funcs.get_name(user)
sendMessage = "{} sold {} GwendoBucks worth of {} stock"
return sendMessage.format(user_name, sellAmount, stock)
send_message = "{} sold {} GwendoBucks worth of {} stock"
return send_message.format(user_name, sellAmount, stock)
else:
return f"You don't have enough {stock} stocks to do that"
else:

View File

@ -51,10 +51,10 @@ class Money():
"""
self.bot.log("checking "+user+"'s account balance")
userData = self.database["users"].find_one({"_id": user})
user_data = self.database["users"].find_one({"_id": user})
if userData is not None:
return userData["money"]
if user_data is not None:
return user_data["money"]
else:
return 0
@ -90,18 +90,18 @@ class Money():
"""
self.bot.log("adding "+str(amount)+" to "+user+"'s account")
userData = self.database["users"].find_one({"_id": user})
user_data = self.database["users"].find_one({"_id": user})
if userData is not None:
if user_data is not None:
updater = {"$inc": {"money": amount}}
self.database["users"].update_one({"_id": user}, updater)
else:
newUser = {
new_user = {
"_id": user,
"user name": self.bot.database_funcs.get_name(user),
"money": amount
}
self.database["users"].insert_one(newUser)
self.database["users"].insert_one(new_user)
# Transfers money from one user to another
async def giveMoney(self, ctx: discord_slash.context.SlashContext,
@ -125,15 +125,15 @@ class Money():
if member.display_name.lower() == username.lower():
username = member.display_name
user_id = f"#{member.id}"
newUser = {
new_user = {
"_id": user_id,
"user name": username,
"money": 0
}
self.bot.database["users"].insert_one(newUser)
self.bot.database["users"].insert_one(new_user)
userid = f"#{ctx.author.id}"
userData = self.database["users"].find_one({"_id": userid})
user_data = self.database["users"].find_one({"_id": userid})
targetUser = self.bot.database_funcs.get_id(username)
if amount <= 0:
@ -142,7 +142,7 @@ class Money():
elif targetUser is None:
self.bot.log("They weren't in the system")
await ctx.send("The target doesn't exist")
elif userData is None or userData["money"] < amount:
elif user_data is None or user_data["money"] < amount:
self.bot.log("They didn't have enough GwendoBucks")
await ctx.send("You don't have that many GwendoBuck")
else:

View File

@ -45,7 +45,7 @@ class Trivia():
*Returns*
---------
sendMessage: str
send_message: str
The message to return to the user.
"""
triviaQuestions = self.bot.database["trivia questions"]
@ -110,7 +110,7 @@ class Trivia():
*Returns*
---------
sendMessage: str
send_message: str
The message to send if the function failed.
"""
triviaQuestions = self.bot.database["trivia questions"]
@ -185,10 +185,10 @@ class Trivia():
self.bot.database_funcs.delete_game(*delete_gameParams)
self.bot.log("Time's up for the trivia question", channelId)
sendMessage = self.bot.long_strings["Trivia time up"]
formatParams = [chr(correctAnswer), options[correctAnswer-97]]
sendMessage = sendMessage.format(*formatParams)
await ctx.send(sendMessage)
send_message = self.bot.long_strings["Trivia time up"]
format_parameters = [chr(correctAnswer), options[correctAnswer-97]]
send_message = send_message.format(*format_parameters)
await ctx.send(send_message)
else:
await ctx.send(question, hidden=True)