✨ PEP in utils
This commit is contained in:
6
gwendolyn/funcs/games/__init__.py
Normal file
6
gwendolyn/funcs/games/__init__.py
Normal file
@ -0,0 +1,6 @@
|
||||
"""Functions for games Gwendolyn can play."""
|
||||
|
||||
__all__ = ["Money", "Games"]
|
||||
|
||||
from .money import Money
|
||||
from .games_container import Games
|
1469
gwendolyn/funcs/games/blackjack.py
Normal file
1469
gwendolyn/funcs/games/blackjack.py
Normal file
File diff suppressed because it is too large
Load Diff
1068
gwendolyn/funcs/games/connect_four.py
Normal file
1068
gwendolyn/funcs/games/connect_four.py
Normal file
File diff suppressed because it is too large
Load Diff
48
gwendolyn/funcs/games/games_container.py
Normal file
48
gwendolyn/funcs/games/games_container.py
Normal file
@ -0,0 +1,48 @@
|
||||
"""
|
||||
Has a container for game functions.
|
||||
|
||||
*Classes*
|
||||
---------
|
||||
Games
|
||||
Container for game functions.
|
||||
"""
|
||||
|
||||
|
||||
from .invest import Invest
|
||||
from .trivia import Trivia
|
||||
from .blackjack import Blackjack
|
||||
from .connect_four import ConnectFour
|
||||
from .hangman import Hangman
|
||||
from .hex import HexGame
|
||||
|
||||
|
||||
class Games():
|
||||
"""
|
||||
Contains game classes.
|
||||
|
||||
*Attributes*
|
||||
------------
|
||||
bot: Gwendolyn
|
||||
The instance of Gwendolyn.
|
||||
invest
|
||||
Contains investment functions.
|
||||
blackjack
|
||||
Contains blackjack functions.
|
||||
connect_four
|
||||
Contains connect four functions.
|
||||
hangman
|
||||
Contains hangman functions.
|
||||
hex
|
||||
Contains hex functions
|
||||
"""
|
||||
|
||||
def __init__(self, bot):
|
||||
"""Initialize the container."""
|
||||
self.bot = bot
|
||||
|
||||
self.invest = Invest(bot)
|
||||
self.trivia = Trivia(bot)
|
||||
self.blackjack = Blackjack(bot)
|
||||
self.connect_four = ConnectFour(bot)
|
||||
self.hangman = Hangman(bot)
|
||||
self.hex = HexGame(bot)
|
612
gwendolyn/funcs/games/hangman.py
Normal file
612
gwendolyn/funcs/games/hangman.py
Normal file
@ -0,0 +1,612 @@
|
||||
"""
|
||||
Deals with commands and logic for hangman games.
|
||||
|
||||
*Classes*
|
||||
---------
|
||||
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():
|
||||
"""
|
||||
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):
|
||||
"""
|
||||
Initialize the class.
|
||||
|
||||
*Attributes*
|
||||
------------
|
||||
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["wordnik_key"]
|
||||
self.__APIPARAMS = {
|
||||
"hasDictionaryDef": True,
|
||||
"minCorpusCount": 5000,
|
||||
"maxCorpusCount": -1,
|
||||
"minDictionaryCount": 1,
|
||||
"maxDictionaryCount": -1,
|
||||
"minLength": 3,
|
||||
"maxLength": 11,
|
||||
"limit": 1,
|
||||
"api_key": apiKey
|
||||
}
|
||||
|
||||
async def start(self, ctx: SlashContext):
|
||||
"""
|
||||
Start a game of hangman.
|
||||
|
||||
*Parameters*
|
||||
------------
|
||||
ctx: SlashContext
|
||||
The context of the command.
|
||||
"""
|
||||
await self.__bot.defer(ctx)
|
||||
channel = str(ctx.channel_id)
|
||||
user = f"#{ctx.author.id}"
|
||||
game = self.__bot.database["hangman games"].find_one({"_id": channel})
|
||||
user_name = self.__bot.database_funcs.get_name(user)
|
||||
startedGame = False
|
||||
|
||||
if game is None:
|
||||
word = "-"
|
||||
while "-" in word or "." in word:
|
||||
response = requests.get(self.__APIURL, params=self.__APIPARAMS)
|
||||
word = list(response.json()[0]["word"].upper())
|
||||
|
||||
self.__bot.log("Found the word \""+"".join(word)+"\"")
|
||||
guessed = [False] * len(word)
|
||||
gameID = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
|
||||
newGame = {
|
||||
"_id": channel,
|
||||
"player": user,
|
||||
"guessed letters": [],
|
||||
"word": word,
|
||||
"game ID": gameID,
|
||||
"misses": 0,
|
||||
"guessed": guessed
|
||||
}
|
||||
self.__bot.database["hangman games"].insert_one(newGame)
|
||||
|
||||
remainingLetters = list(string.ascii_uppercase)
|
||||
|
||||
self.__draw.drawImage(channel)
|
||||
|
||||
log_message = "Game started"
|
||||
sendMessage = f"{user_name} started game of hangman."
|
||||
startedGame = True
|
||||
else:
|
||||
log_message = "There was already a game going on"
|
||||
sendMessage = self.__bot.long_strings["Hangman going on"]
|
||||
|
||||
self.__bot.log(log_message)
|
||||
await ctx.send(sendMessage)
|
||||
|
||||
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))
|
||||
|
||||
blankMessage = await ctx.channel.send("_ _")
|
||||
reactionMessages = {
|
||||
newImage: remainingLetters[:15],
|
||||
blankMessage: remainingLetters[15:]
|
||||
}
|
||||
|
||||
old_messages = f"{newImage.id}\n{blankMessage.id}"
|
||||
|
||||
with open(f"gwendolyn/resources/games/old_images/hangman{channel}", "w") as f:
|
||||
f.write(old_messages)
|
||||
|
||||
for message, letters in reactionMessages.items():
|
||||
for letter in letters:
|
||||
emoji = chr(ord(letter)+127397)
|
||||
await message.add_reaction(emoji)
|
||||
|
||||
async def stop(self, ctx: SlashContext):
|
||||
"""
|
||||
Stop the game of hangman.
|
||||
|
||||
*Parameters*
|
||||
------------
|
||||
ctx: SlashContext
|
||||
The context of the command.
|
||||
"""
|
||||
channel = str(ctx.channel.id)
|
||||
game = self.__bot.database["hangman games"].find_one({"_id": channel})
|
||||
|
||||
if game is None:
|
||||
await ctx.send("There's no game going on")
|
||||
elif f"#{ctx.author.id}" != game["player"]:
|
||||
await ctx.send("You can't end a game you're not in")
|
||||
else:
|
||||
self.__bot.database["hangman games"].delete_one({"_id": channel})
|
||||
|
||||
with open(f"gwendolyn/resources/games/old_images/hangman{channel}", "r") as f:
|
||||
messages = f.read().splitlines()
|
||||
|
||||
for message in messages:
|
||||
old_message = await ctx.channel.fetch_message(int(message))
|
||||
self.__bot.log("Deleting old message")
|
||||
await old_message.delete()
|
||||
|
||||
await ctx.send("Game stopped")
|
||||
|
||||
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)
|
||||
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)
|
||||
|
||||
if validGuess:
|
||||
self.__bot.log("Guessed the letter")
|
||||
correctGuess = 0
|
||||
|
||||
for x, letter in enumerate(game["word"]):
|
||||
if guess == letter:
|
||||
correctGuess += 1
|
||||
updater = {"$set": {f"guessed.{x}": True}}
|
||||
hangman_games.update_one({"_id": channel}, updater)
|
||||
|
||||
if correctGuess == 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)
|
||||
|
||||
game = hangman_games.find_one({"_id": channel})
|
||||
|
||||
for letter in game["guessed letters"]:
|
||||
remainingLetters.remove(letter)
|
||||
|
||||
if correctGuess == 1:
|
||||
sendMessage = "Guessed {}. There was 1 {} in the word."
|
||||
sendMessage = sendMessage.format(guess, guess)
|
||||
else:
|
||||
sendMessage = "Guessed {}. There were {} {}s in the word."
|
||||
sendMessage = sendMessage.format(guess, correctGuess, guess)
|
||||
|
||||
self.__draw.drawImage(channel)
|
||||
|
||||
if game["misses"] == 6:
|
||||
hangman_games.delete_one({"_id": channel})
|
||||
sendMessage += self.__bot.long_strings["Hangman lost game"]
|
||||
remainingLetters = []
|
||||
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 = []
|
||||
|
||||
await message.channel.send(sendMessage)
|
||||
|
||||
with open(f"gwendolyn/resources/games/old_images/hangman{channel}", "r") as f:
|
||||
old_message_ids = f.read().splitlines()
|
||||
|
||||
for oldID in old_message_ids:
|
||||
old_message = await message.channel.fetch_message(int(oldID))
|
||||
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))
|
||||
|
||||
if len(remainingLetters) > 0:
|
||||
if len(remainingLetters) > 15:
|
||||
blankMessage = await message.channel.send("_ _")
|
||||
reactionMessages = {
|
||||
newImage: remainingLetters[:15],
|
||||
blankMessage: remainingLetters[15:]
|
||||
}
|
||||
else:
|
||||
blankMessage = ""
|
||||
reactionMessages = {newImage: remainingLetters}
|
||||
|
||||
if blankMessage != "":
|
||||
old_messages = f"{newImage.id}\n{blankMessage.id}"
|
||||
else:
|
||||
old_messages = str(newImage.id)
|
||||
|
||||
old_imagePath = f"gwendolyn/resources/games/old_images/hangman{channel}"
|
||||
with open(old_imagePath, "w") as f:
|
||||
f.write(old_messages)
|
||||
|
||||
for message, letters in reactionMessages.items():
|
||||
for letter in letters:
|
||||
emoji = chr(ord(letter)+127397)
|
||||
await message.add_reaction(emoji)
|
||||
|
||||
|
||||
class DrawHangman():
|
||||
"""
|
||||
Draws the image of the hangman game.
|
||||
|
||||
*Methods*
|
||||
---------
|
||||
drawImage(channel: str)
|
||||
"""
|
||||
|
||||
def __init__(self, bot):
|
||||
"""
|
||||
Initialize the class.
|
||||
|
||||
*Attributes*
|
||||
------------
|
||||
CIRCLESIZE
|
||||
LINEWIDTH
|
||||
BODYSIZE
|
||||
LIMBSIZE
|
||||
ARMPOSITION
|
||||
MANX, MANY
|
||||
LETTERLINELENGTH
|
||||
LETTERLINEDISTANCE
|
||||
GALLOWX, GALLOWY
|
||||
PHI
|
||||
FONT
|
||||
SMALLFONT
|
||||
"""
|
||||
self.__bot = bot
|
||||
self.__CIRCLESIZE = 120
|
||||
self.__LINEWIDTH = 12
|
||||
|
||||
self.__BODYSIZE = 210
|
||||
self.__LIMBSIZE = 60
|
||||
self.__ARMPOSITION = 60
|
||||
|
||||
self.__MANX = (self.__LIMBSIZE*2)
|
||||
self.__MANY = (self.__CIRCLESIZE+self.__BODYSIZE+self.__LIMBSIZE)
|
||||
MANPADDING = self.__LINEWIDTH*4
|
||||
self.__MANX += MANPADDING
|
||||
self.__MANY += MANPADDING
|
||||
|
||||
self.__LETTERLINELENGTH = 90
|
||||
self.__LETTERLINEDISTANCE = 30
|
||||
|
||||
self.__GALLOWX, self.__GALLOWY = 360, 600
|
||||
self.__PHI = 1-(1 / ((1 + 5 ** 0.5) / 2))
|
||||
|
||||
LETTERSIZE = 75 # Wrong guesses letter size
|
||||
WORDSIZE = 70 # Correct guesses letter size
|
||||
|
||||
FONTPATH = "gwendolyn/resources/fonts/comic-sans-bold.ttf"
|
||||
self.__FONT = ImageFont.truetype(FONTPATH, LETTERSIZE)
|
||||
self.__SMALLFONT = ImageFont.truetype(FONTPATH, WORDSIZE)
|
||||
|
||||
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
|
||||
|
||||
deviance = preDeviance + devianceAccuracy
|
||||
if deviance > maxmin:
|
||||
deviance = maxmin
|
||||
elif deviance < -maxmin:
|
||||
deviance = -maxmin
|
||||
return deviance, devianceAccuracy
|
||||
|
||||
def __badCircle(self):
|
||||
circlePadding = (self.__LINEWIDTH*3)
|
||||
imageWidth = self.__CIRCLESIZE+circlePadding
|
||||
imageSize = (imageWidth, imageWidth)
|
||||
background = Image.new("RGBA", imageSize, color=(0, 0, 0, 0))
|
||||
|
||||
d = ImageDraw.Draw(background, "RGBA")
|
||||
middle = (self.__CIRCLESIZE+(self.__LINEWIDTH*3))/2
|
||||
devianceX = 0
|
||||
devianceY = 0
|
||||
devianceAccuracyX = 0
|
||||
devianceAccuracyY = 0
|
||||
start = random.randint(-100, -80)
|
||||
degreesAmount = 360 + random.randint(-10, 30)
|
||||
|
||||
for degree in range(degreesAmount):
|
||||
devianceXParams = [
|
||||
devianceX,
|
||||
devianceAccuracyX,
|
||||
self.__LINEWIDTH/100,
|
||||
self.__LINEWIDTH,
|
||||
0.03
|
||||
]
|
||||
devianceYParams = [
|
||||
devianceY,
|
||||
devianceAccuracyY,
|
||||
self.__LINEWIDTH/100,
|
||||
self.__LINEWIDTH,
|
||||
0.03
|
||||
]
|
||||
devianceX, devianceAccuracyX = self.__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))
|
||||
|
||||
x = middle + circleX - (self.__LINEWIDTH/2) + devianceX
|
||||
y = middle + circleY - (self.__LINEWIDTH/2) + devianceY
|
||||
|
||||
circlePosition = [(x, y), (x+self.__LINEWIDTH, y+self.__LINEWIDTH)]
|
||||
d.ellipse(circlePosition, fill=(0, 0, 0, 255))
|
||||
|
||||
return background
|
||||
|
||||
def __badLine(self, length: int, rotated: bool = False):
|
||||
if rotated:
|
||||
w, h = length+self.__LINEWIDTH*3, self.__LINEWIDTH*3
|
||||
else:
|
||||
w, h = self.__LINEWIDTH*3, length+self.__LINEWIDTH*3
|
||||
background = Image.new("RGBA", (w, h), color=(0, 0, 0, 0))
|
||||
|
||||
d = ImageDraw.Draw(background, "RGBA")
|
||||
|
||||
possibleDeviance = int(self.__LINEWIDTH/3)
|
||||
devianceX = random.randint(-possibleDeviance, possibleDeviance)
|
||||
devianceY = 0
|
||||
devianceAccuracyX = 0
|
||||
devianceAccuracyY = 0
|
||||
|
||||
for pixel in range(length):
|
||||
devianceParamsX = [
|
||||
devianceX,
|
||||
devianceAccuracyX,
|
||||
self.__LINEWIDTH/1000,
|
||||
self.__LINEWIDTH,
|
||||
0.004
|
||||
]
|
||||
devianceParamsY = [
|
||||
devianceY,
|
||||
devianceAccuracyY,
|
||||
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
|
||||
else:
|
||||
x = self.__LINEWIDTH + devianceX
|
||||
y = self.__LINEWIDTH + pixel + devianceY
|
||||
|
||||
circlePosition = [(x, y), (x+self.__LINEWIDTH, y+self.__LINEWIDTH)]
|
||||
d.ellipse(circlePosition, fill=(0, 0, 0, 255))
|
||||
|
||||
return background
|
||||
|
||||
def __drawMan(self, misses: int, seed: str):
|
||||
random.seed(seed)
|
||||
manSize = (self.__MANX, self.__MANY)
|
||||
background = Image.new("RGBA", manSize, 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)
|
||||
if misses >= 2:
|
||||
body = self.__badLine(self.__BODYSIZE)
|
||||
pasteX = (self.__MANX-(self.__LINEWIDTH*3))//2
|
||||
pastePosition = (pasteX, self.__CIRCLESIZE)
|
||||
background.paste(body, pastePosition, body)
|
||||
|
||||
if misses >= 3:
|
||||
limbs = random.sample(["rl", "ll", "ra", "la"], min(misses-2, 4))
|
||||
else:
|
||||
limbs = []
|
||||
|
||||
random.seed(seed)
|
||||
|
||||
for limb in limbs:
|
||||
limbDrawing = self.__badLine(self.__LIMBSIZE, True)
|
||||
xPosition = (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
|
||||
if limb == "ra":
|
||||
compensation = min(-compensation, 0)
|
||||
else:
|
||||
xPosition -= self.__LIMBSIZE
|
||||
compensation = min(compensation, 0)
|
||||
|
||||
yPosition += compensation
|
||||
else:
|
||||
rotation = random.randint(-15, 15)
|
||||
yPosition = self.__CIRCLESIZE+self.__BODYSIZE-self.__LINEWIDTH
|
||||
if limb == "rl":
|
||||
limbDrawing = limbDrawing.rotate(rotation-45, expand=1)
|
||||
else:
|
||||
xPosition += -limbDrawing.size[0]+self.__LINEWIDTH*3
|
||||
limbDrawing = limbDrawing.rotate(rotation+45, expand=1)
|
||||
|
||||
pastePosition = (xPosition, yPosition)
|
||||
background.paste(limbDrawing, pastePosition, limbDrawing)
|
||||
|
||||
return background
|
||||
|
||||
def __badText(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")
|
||||
|
||||
d.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))
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
lastLine = self.__badLine(int(self.__GALLOWY*0.125))
|
||||
pasteX += int(self.__GALLOWY*0.30)
|
||||
background.paste(lastLine, (pasteX, self.__LINEWIDTH*3), lastLine)
|
||||
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)
|
||||
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)
|
||||
|
||||
return letterLines
|
||||
|
||||
def __shortestDist(self, positions: list, newPosition: tuple):
|
||||
__shortestDist = math.inf
|
||||
x, y = newPosition
|
||||
for i, j in positions:
|
||||
xDistance = abs(i-x)
|
||||
yDistance = abs(j-y)
|
||||
dist = math.sqrt(xDistance**2+yDistance**2)
|
||||
if __shortestDist > dist:
|
||||
__shortestDist = dist
|
||||
return __shortestDist
|
||||
|
||||
def __drawMisses(self, guesses: 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)
|
||||
w, h = self.__FONT.getsize(guess)
|
||||
x = random.randint(0, 600-w)
|
||||
y = random.randint(0, 400-h)
|
||||
if self.__shortestDist(pos, (x, y)) > 70:
|
||||
pos.append((x, y))
|
||||
background.paste(letter, (x, y), letter)
|
||||
placed = True
|
||||
return background
|
||||
|
||||
def drawImage(self, channel: str):
|
||||
"""
|
||||
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"])
|
||||
|
||||
background = Image.open("gwendolyn/resources/paper.jpg")
|
||||
gallow = self.__drawGallows()
|
||||
man = self.__drawMan(game["misses"], game["game ID"])
|
||||
|
||||
random.seed(game["game ID"])
|
||||
letterLineParams = [game["word"], game["guessed"], game["misses"]]
|
||||
letterLines = self.__drawLetterLines(*letterLineParams)
|
||||
|
||||
random.seed(game["game ID"])
|
||||
misses = self.__drawMisses(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(misses, (600, 150), misses)
|
||||
|
||||
missesText = self.__badText("MISSES", False)
|
||||
missesTextWidth = missesText.size[0]
|
||||
background.paste(missesText, (850-missesTextWidth//2, 50), missesText)
|
||||
|
||||
boardPath = f"gwendolyn/resources/games/hangman_boards/hangman_board{channel}.png"
|
||||
background.save(boardPath)
|
643
gwendolyn/funcs/games/hex.py
Normal file
643
gwendolyn/funcs/games/hex.py
Normal file
@ -0,0 +1,643 @@
|
||||
import random
|
||||
import copy
|
||||
import math
|
||||
import discord
|
||||
import math
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
class HexGame():
|
||||
def __init__(self, bot):
|
||||
self.bot = bot
|
||||
self.draw = DrawHex(bot)
|
||||
self.BOARDWIDTH = 11
|
||||
self.ALLPOSITIONS = [(i,j) for i in range(11) for j in range(11)]
|
||||
self.ALLSET = set(self.ALLPOSITIONS)
|
||||
self.EMPTYDIJKSTRA = {}
|
||||
for position in self.ALLPOSITIONS:
|
||||
self.EMPTYDIJKSTRA[position] = math.inf # an impossibly high number
|
||||
self.HEXDIRECTIONS = [(0,1),(-1,1),(-1,0),(0,-1),(1,-1),(1,0)]
|
||||
|
||||
async def surrender(self, ctx):
|
||||
channel = str(ctx.channel_id)
|
||||
game = self.bot.database["hex games"].find_one({"_id":channel})
|
||||
user = f"#{ctx.author.id}"
|
||||
players = game["players"]
|
||||
|
||||
if user not in players:
|
||||
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])
|
||||
self.bot.database["hex games"].update_one({"_id":channel},{"$set":{"winner":opponent + 1}})
|
||||
await ctx.send(f"{ctx.author.display_name} surrendered")
|
||||
|
||||
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "r") as f:
|
||||
old_image = await ctx.channel.fetch_message(int(f.read()))
|
||||
|
||||
if old_image is not None:
|
||||
await old_image.delete()
|
||||
else:
|
||||
self.bot.log("The old image was already deleted")
|
||||
|
||||
self.bot.log("Sending the image")
|
||||
file_path = f"gwendolyn/resources/games/hex_boards/board{channel}.png"
|
||||
old_image = await ctx.channel.send(file = discord.File(file_path))
|
||||
|
||||
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "w") as f:
|
||||
f.write(str(old_image.id))
|
||||
|
||||
self.bot.database["hex games"].delete_one({"_id":channel})
|
||||
|
||||
# Swap
|
||||
async def swap(self, ctx):
|
||||
channel = str(ctx.channel_id)
|
||||
game = self.bot.database["hex games"].find_one({"_id":channel})
|
||||
user = f"#{ctx.author.id}"
|
||||
|
||||
if game is None:
|
||||
await ctx.send("You can't swap nothing")
|
||||
elif user not in game["players"]:
|
||||
await ctx.send("You're not in the game")
|
||||
elif len(game["gameHistory"]) != 1: # Only after the first move
|
||||
await ctx.send("You can only swap as the second player after the very first move.")
|
||||
elif user != game["players"][game["turn"]-1]:
|
||||
await ctx.send("You can only swap after your opponent has placed their piece")
|
||||
else:
|
||||
self.bot.database["hex games"].update_one({"_id":channel},
|
||||
{"$set":{"players":game["players"][::-1]}}) # Swaps their player-number
|
||||
|
||||
# Swaps the color of the hexes on the board drawing:
|
||||
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")
|
||||
|
||||
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "r") as f:
|
||||
old_image = await ctx.channel.fetch_message(int(f.read()))
|
||||
|
||||
if old_image is not None:
|
||||
await old_image.delete()
|
||||
else:
|
||||
self.bot.log("The old image was already deleted")
|
||||
|
||||
self.bot.log("Sending the image")
|
||||
file_path = f"gwendolyn/resources/games/hex_boards/board{channel}.png"
|
||||
old_image = await ctx.channel.send(file = discord.File(file_path))
|
||||
|
||||
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "w") as f:
|
||||
f.write(str(old_image.id))
|
||||
|
||||
if gwendoTurn:
|
||||
await self.hexAI(ctx)
|
||||
|
||||
# Starts the game
|
||||
async def start(self, ctx, opponent):
|
||||
await self.bot.defer(ctx)
|
||||
user = f"#{ctx.author.id}"
|
||||
channel = str(ctx.channel_id)
|
||||
game = self.bot.database["hex games"].find_one({"_id":channel})
|
||||
|
||||
startedGame = False
|
||||
canStart = True
|
||||
|
||||
if game != None:
|
||||
sendMessage = "There's already a hex game going on in this channel"
|
||||
log_message = "There was already a game going on"
|
||||
canStart = False
|
||||
else:
|
||||
if type(opponent) == int:
|
||||
# Opponent is Gwendolyn
|
||||
if opponent in range(1, 6):
|
||||
opponentName = "Gwendolyn"
|
||||
difficulty = int(opponent)
|
||||
diffText = f" with difficulty {difficulty}"
|
||||
opponent = f"#{self.bot.user.id}"
|
||||
else:
|
||||
sendMessage = "Difficulty doesn't exist"
|
||||
log_message = "They tried to play against a difficulty that doesn't exist"
|
||||
canStart = 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"
|
||||
difficulty = 2
|
||||
diffText = f" with difficulty {difficulty}"
|
||||
opponent = f"#{self.bot.user.id}"
|
||||
else:
|
||||
sendMessage = "You can't challenge a bot!"
|
||||
log_message = "They tried to challenge a bot"
|
||||
canStart = False
|
||||
else:
|
||||
# Opponent is another player
|
||||
if ctx.author != opponent:
|
||||
opponentName = opponent.display_name
|
||||
opponent = f"#{opponent.id}"
|
||||
difficulty = 5
|
||||
diffText = ""
|
||||
else:
|
||||
sendMessage = "You can't play against yourself"
|
||||
log_message = "They tried to play against themself"
|
||||
canStart = False
|
||||
else:
|
||||
canStart = False
|
||||
log_message = f"Opponent was neither int or member. It was {type(opponent)}"
|
||||
sendMessage = "Something went wrong"
|
||||
|
||||
if canStart:
|
||||
# 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,
|
||||
"players":players, "turn":1, "difficulty":difficulty, "gameHistory":gameHistory}
|
||||
|
||||
self.bot.database["hex games"].insert_one(newGame)
|
||||
|
||||
# draw the board
|
||||
self.draw.drawBoard(channel)
|
||||
|
||||
gwendoTurn = (players[0] == f"#{self.bot.user.id}")
|
||||
startedGame = True
|
||||
|
||||
turnName = self.bot.database_funcs.get_name(players[0])
|
||||
sendMessage = f"Started Hex game against {opponentName}{diffText}. It's {turnName}'s turn"
|
||||
log_message = "Game started"
|
||||
|
||||
await ctx.send(sendMessage)
|
||||
self.bot.log(log_message)
|
||||
|
||||
if startedGame:
|
||||
file_path = f"gwendolyn/resources/games/hex_boards/board{ctx.channel_id}.png"
|
||||
newImage = 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))
|
||||
|
||||
if gwendoTurn:
|
||||
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
|
||||
|
||||
if game == None:
|
||||
sendMessage = "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."
|
||||
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])}."
|
||||
self.bot.log("They aren't in the game")
|
||||
elif players[game["turn"]-1] != user:
|
||||
sendMessage = "It's not your turn"
|
||||
self.bot.log("It wasn't their turn")
|
||||
else:
|
||||
player = game["turn"]
|
||||
turn = game["turn"]
|
||||
board = game["board"]
|
||||
|
||||
self.bot.log("Placing a piece on the board with placeHex()")
|
||||
# Places on board
|
||||
board = self.placeOnHexBoard(board,player,position)
|
||||
|
||||
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.")
|
||||
else:
|
||||
# If the move is valid:
|
||||
self.bot.database["hex games"].update_one({"_id":channel},{"$set":{"board":board}})
|
||||
turn = (turn % 2) + 1
|
||||
self.bot.database["hex games"].update_one({"_id":channel},{"$set":{"turn":turn}})
|
||||
|
||||
# Checking for a win
|
||||
self.bot.log("Checking for win")
|
||||
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)
|
||||
|
||||
else: # Congratulations!
|
||||
gameWon = 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!"
|
||||
if game["players"][winner-1] != f"#{self.bot.user.id}":
|
||||
winAmount = game["difficulty"]*10
|
||||
sendMessage += " Adding "+str(winAmount)+" 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
|
||||
if game["players"][turn-1] == f"#{self.bot.user.id}":
|
||||
self.bot.log("It's Gwendolyn's turn")
|
||||
gwendoTurn = True
|
||||
|
||||
placedPiece = True
|
||||
|
||||
if user == f"#{self.bot.user.id}":
|
||||
await ctx.channel.send(sendMessage)
|
||||
else:
|
||||
await ctx.send(sendMessage)
|
||||
|
||||
if placedPiece:
|
||||
# Update the board
|
||||
self.draw.drawHexPlacement(channel,player, position)
|
||||
|
||||
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "r") as f:
|
||||
old_image = await ctx.channel.fetch_message(int(f.read()))
|
||||
|
||||
if old_image is not None:
|
||||
await old_image.delete()
|
||||
else:
|
||||
self.bot.log("The old image was already deleted")
|
||||
|
||||
self.bot.log("Sending the image")
|
||||
file_path = f"gwendolyn/resources/games/hex_boards/board{channel}.png"
|
||||
old_image = await ctx.channel.send(file = discord.File(file_path))
|
||||
|
||||
if gameWon:
|
||||
self.bot.log("Dealing with the winning player")
|
||||
game = self.bot.database["hex games"].find_one({"_id":channel})
|
||||
|
||||
winner = game["winner"]
|
||||
if game["players"][winner-1] != f"#{self.bot.user.id}":
|
||||
winnings = game["difficulty"]*10
|
||||
self.bot.money.addMoney(game["players"][winner-1].lower(),winnings)
|
||||
|
||||
self.bot.database["hex games"].delete_one({"_id":channel})
|
||||
else:
|
||||
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "w") as f:
|
||||
f.write(str(old_image.id))
|
||||
|
||||
if gwendoTurn:
|
||||
await self.hexAI(ctx)
|
||||
|
||||
# Returns a board where the placement has ocurred
|
||||
def placeOnHexBoard(self, board,player,position):
|
||||
# Translates the position
|
||||
position = position.lower()
|
||||
# Error handling
|
||||
column = ord(position[0]) - 97 # ord() translates from letter to number
|
||||
row = int(position[1:]) - 1
|
||||
if column not in range(self.BOARDWIDTH) or row not in range(self.BOARDWIDTH):
|
||||
self.bot.log("Position out of bounds")
|
||||
return None
|
||||
# Place at the position
|
||||
if board[row][column] == 0:
|
||||
board[row][column] = player
|
||||
return board
|
||||
else:
|
||||
self.bot.log("Cannot place on existing piece (error code 1532)")
|
||||
return None
|
||||
|
||||
# After your move, you have the option to undo get your turn back #TimeTravel
|
||||
async def undo(self, ctx):
|
||||
channel = str(ctx.channel_id)
|
||||
user = f"#{ctx.author.id}"
|
||||
undid = False
|
||||
|
||||
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"
|
||||
elif len(game["gameHistory"]) == 0:
|
||||
sendMessage = "You can't undo nothing"
|
||||
elif user != game["players"][(game["turn"] % 2)]: # If it's not your turn
|
||||
sendMessage = "It's not your turn"
|
||||
else:
|
||||
turn = game["turn"]
|
||||
self.bot.log("Undoing {}'s last move".format(self.bot.database_funcs.get_name(user)))
|
||||
|
||||
lastMove = game["gameHistory"].pop()
|
||||
game["board"][lastMove[0]][lastMove[1]] = 0
|
||||
self.bot.database["hex games"].update_one({"_id":channel},
|
||||
{"$set":{"board":game["board"]}})
|
||||
self.bot.database["hex games"].update_one({"_id":channel},
|
||||
{"$set":{"turn":turn%2 + 1}})
|
||||
|
||||
# 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}"
|
||||
undid = True
|
||||
|
||||
await ctx.send(sendMessage)
|
||||
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()))
|
||||
|
||||
if old_image is not None:
|
||||
await old_image.delete()
|
||||
else:
|
||||
self.bot.log("The old image was already deleted")
|
||||
|
||||
self.bot.log("Sending the image")
|
||||
file_path = f"gwendolyn/resources/games/hex_boards/board{channel}.png"
|
||||
old_image = await ctx.channel.send(file = discord.File(file_path))
|
||||
|
||||
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "w") as f:
|
||||
f.write(str(old_image.id))
|
||||
|
||||
|
||||
# Plays as the AI
|
||||
async def hexAI(self, ctx):
|
||||
channel = str(ctx.channel_id)
|
||||
self.bot.log("Figuring out best move")
|
||||
game = self.bot.database["hex games"].find_one({"_id":channel})
|
||||
board = game["board"]
|
||||
|
||||
if len(game["gameHistory"]):
|
||||
lastMove = game["gameHistory"][-1]
|
||||
else:
|
||||
lastMove = (5,5)
|
||||
|
||||
# These moves are the last move +- 2.
|
||||
moves = [[(lastMove[0]+j-2,lastMove[1]+i-2) for i in range(5) if lastMove[1]+i-2 in range(11)] for j in range(5) if lastMove[0]+j-2 in range(11)]
|
||||
moves = sum(moves,[])
|
||||
movesCopy = moves.copy()
|
||||
for move in movesCopy:
|
||||
if board[move[0]][move[1]] != 0:
|
||||
moves.remove(move)
|
||||
chosenMove = random.choice(moves)
|
||||
|
||||
placement = "abcdefghijk"[chosenMove[1]]+str(chosenMove[0]+1)
|
||||
self.bot.log(f"ChosenMove is {chosenMove} at {placement}")
|
||||
|
||||
await self.placeHex(ctx, placement, f"#{self.bot.user.id}")
|
||||
|
||||
|
||||
def evaluateBoard(self, board):
|
||||
scores = {1:0, 2:0}
|
||||
winner = 0
|
||||
# Here, I use Dijkstra's algorithm to evaluate the board, as proposed by this article: https://towardsdatascience.com/hex-creating-intelligent-adversaries-part-2-heuristics-dijkstras-algorithm-597e4dcacf93
|
||||
for player in [1,2]:
|
||||
Distance = copy.deepcopy(self.EMPTYDIJKSTRA)
|
||||
# Initialize the starting hexes. For the blue player, this is the leftmost column. For the red player, this is the tom row.
|
||||
for start in (self.ALLPOSITIONS[::11] if player == 2 else self.ALLPOSITIONS[:11]):
|
||||
# An empty hex adds a of distance of 1. A hex of own color add distance 0. Opposite color adds infinite distance.
|
||||
Distance[start] = 1 if (board[start[0]][start[1]] == 0) else 0 if (board[start[0]][start[1]] == player) else math.inf
|
||||
visited = set() # Also called sptSet, short for "shortest path tree Set"
|
||||
for _ in range(self.BOARDWIDTH**2): # We can at most check every 121 hexes
|
||||
# Find the next un-visited hex, that has the lowest distance
|
||||
remainingHexes = self.ALLSET.difference(visited)
|
||||
A = [Distance[k] for k in remainingHexes] # Find the distance to each un-visited hex
|
||||
u = list(remainingHexes)[A.index(min(A))] # Chooses the one with the lowest distance
|
||||
|
||||
# Find neighbors of the hex u
|
||||
for di in self.HEXDIRECTIONS:
|
||||
v = (u[0] + di[0] , u[1] + di[1]) # v is a neighbor of u
|
||||
if v[0] in range(11) and v[1] in range(11) and v not in visited:
|
||||
new_dist = Distance[u] + (1 if (board[v[0]][v[1]] == 0) else 0 if (board[v[0]][v[1]] == player) else math.inf)
|
||||
Distance[v] = min(Distance[v], new_dist)
|
||||
# After a hex has been visited, this is noted
|
||||
visited.add(u)
|
||||
#self.bot.log("Distance from player {}'s start to {} is {}".format(player,u,Distance[u]))
|
||||
if u[player-1] == 10: # if the right coordinate of v is 10, it means we're at the goal
|
||||
scores[player] = Distance[u] # A player's score is the shortest distance to goal. Which equals the number of remaining moves they need to win if unblocked by the opponent.
|
||||
break
|
||||
else:
|
||||
self.bot.log("For some reason, no path to the goal was found. ")
|
||||
if scores[player] == 0:
|
||||
winner = player
|
||||
break # We don't need to check the other player's score, if player1 won.
|
||||
return scores[2]-scores[1], winner
|
||||
|
||||
|
||||
def minimaxHex(self, board, depth, alpha, beta, maximizingPlayer):
|
||||
# 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
|
||||
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)
|
||||
maxEval = max(maxEval, evaluation)
|
||||
alpha = max(alpha, evaluation)
|
||||
if beta <= alpha:
|
||||
#self.bot.log("Just pruned something!")
|
||||
break
|
||||
return maxEval
|
||||
else: # blue player predicts next move
|
||||
minEval = math.inf
|
||||
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)
|
||||
minEval = min(minEval, evaluation)
|
||||
beta = min(beta, evaluation)
|
||||
if beta <= alpha:
|
||||
#self.bot.log("Just pruned something!")
|
||||
break
|
||||
return minEval
|
||||
|
||||
class DrawHex():
|
||||
def __init__(self,bot):
|
||||
self.bot = bot
|
||||
# Defining all the variables
|
||||
self.CANVASWIDTH = 2400
|
||||
self.CANVASHEIGHT = 1800
|
||||
self.SIDELENGTH = 75
|
||||
|
||||
# The offsets centers the board in the picture
|
||||
self.XOFFSET = self.CANVASWIDTH/2 - 8*math.sqrt(3)*self.SIDELENGTH
|
||||
|
||||
# The offsets are the coordinates of the upperleft point in the
|
||||
# upperleftmost hexagon
|
||||
self.YOFFSET = self.CANVASHEIGHT/2 - 8*self.SIDELENGTH
|
||||
|
||||
# The whole width of one hexagon
|
||||
self.HEXAGONWIDTH = math.sqrt(3) * self.SIDELENGTH
|
||||
|
||||
# The height difference between two layers
|
||||
self.HEXAGONHEIGHT = 1.5 * self.SIDELENGTH
|
||||
self.FONTSIZE = 45
|
||||
self.TEXTCOLOR = (0,0,0)
|
||||
self.FONT = ImageFont.truetype('gwendolyn/resources/fonts/futura-bold.ttf', self.FONTSIZE)
|
||||
|
||||
self.LINETHICKNESS = 15
|
||||
self.HEXTHICKNESS = 6 # This is half the width of the background lining between every hex
|
||||
self.XTHICKNESS = self.HEXTHICKNESS * math.cos(math.pi/6)
|
||||
self.YTHICKNESS = self.HEXTHICKNESS * math.sin(math.pi/6)
|
||||
self.BACKGROUNDCOLOR = (230,230,230)
|
||||
self.BETWEENCOLOR = (231,231,231)
|
||||
self.BLANKCOLOR = "lightgrey"
|
||||
self.PIECECOLOR = {1:(237,41,57),2:(0,165,255),0:self.BLANKCOLOR} # player1 is red, player2 is blue
|
||||
self.BOARDCOORDINATES = [ [(self.XOFFSET + self.HEXAGONWIDTH*(column + row/2),self.YOFFSET + self.HEXAGONHEIGHT*row) for column in range(11)] for row in range(11)] # These are the coordinates for the upperleft corner of every hex
|
||||
self.COLHEXTHICKNESS = 4 # When placing a hex, it is a little bigger than the underlying hex in the background (4 < 6)
|
||||
self.COLXTHICKNESS = self.COLHEXTHICKNESS * math.cos(math.pi/6)
|
||||
self.COLYTHICKNESS = self.COLHEXTHICKNESS * math.sin(math.pi/6)
|
||||
# The Name display things:
|
||||
self.NAMESIZE = 60
|
||||
self.NAMEFONT = ImageFont.truetype('gwendolyn/resources/fonts/futura-bold.ttf', self.NAMESIZE)
|
||||
self.XNAME = {1:175, 2:self.CANVASWIDTH-100}
|
||||
self.YNAME = {1:self.CANVASHEIGHT-150, 2:150}
|
||||
self.NAMEHEXPADDING = 90
|
||||
self.SMALLWIDTH = self.HEXAGONWIDTH * 0.6
|
||||
self.SMALLSIDELENGTH = self.SIDELENGTH * 0.6
|
||||
|
||||
def drawBoard(self, channel):
|
||||
self.bot.log("Drawing empty Hex board")
|
||||
|
||||
# Creates the empty image
|
||||
im = Image.new('RGB', size=(self.CANVASWIDTH, self.CANVASHEIGHT),color = self.BACKGROUNDCOLOR)
|
||||
# 'd' is a shortcut to drawing on the image
|
||||
d = ImageDraw.Draw(im,"RGBA")
|
||||
|
||||
# Drawing all the hexagons
|
||||
for column in self.BOARDCOORDINATES:
|
||||
for startingPoint in column:
|
||||
x = startingPoint[0]
|
||||
y = startingPoint[1]
|
||||
d.polygon([
|
||||
(x, y),
|
||||
(x+self.HEXAGONWIDTH/2, y-0.5*self.SIDELENGTH),
|
||||
(x+self.HEXAGONWIDTH, y),
|
||||
(x+self.HEXAGONWIDTH, y+self.SIDELENGTH),
|
||||
(x+self.HEXAGONWIDTH/2, y+1.5*self.SIDELENGTH),
|
||||
(x, y+self.SIDELENGTH),
|
||||
],fill = self.BETWEENCOLOR)
|
||||
d.polygon([
|
||||
(x+self.XTHICKNESS, y + self.YTHICKNESS),
|
||||
(x+self.HEXAGONWIDTH/2, y-0.5*self.SIDELENGTH + self.HEXTHICKNESS),
|
||||
(x+self.HEXAGONWIDTH-self.XTHICKNESS, y + self.YTHICKNESS),
|
||||
(x+self.HEXAGONWIDTH-self.XTHICKNESS, y+self.SIDELENGTH - self.YTHICKNESS),
|
||||
(x+self.HEXAGONWIDTH/2, y+1.5*self.SIDELENGTH - self.HEXTHICKNESS),
|
||||
(x+self.XTHICKNESS, y+self.SIDELENGTH - self.YTHICKNESS),
|
||||
],fill = self.BLANKCOLOR)
|
||||
|
||||
# Draw color on the outside of the board
|
||||
# Top line, red
|
||||
d.line(sum((sum([(point[0],point[1],point[0]+self.HEXAGONWIDTH/2,point[1]-self.HEXAGONHEIGHT+self.SIDELENGTH) for point in self.BOARDCOORDINATES[0]],()),(self.BOARDCOORDINATES[0][10][0]+self.HEXAGONWIDTH*3/4,self.BOARDCOORDINATES[0][10][1]-self.SIDELENGTH/4)),()),
|
||||
fill = self.PIECECOLOR[1],width = self.LINETHICKNESS)
|
||||
# Bottom line, red
|
||||
d.line(sum(((self.BOARDCOORDINATES[10][0][0]+self.HEXAGONWIDTH/4,self.BOARDCOORDINATES[10][0][1]+self.SIDELENGTH*5/4),sum([(point[0]+self.HEXAGONWIDTH/2,point[1]+self.HEXAGONHEIGHT,point[0]+self.HEXAGONWIDTH,point[1]+self.SIDELENGTH) for point in self.BOARDCOORDINATES[10]],())),()),
|
||||
fill = self.PIECECOLOR[1],width = self.LINETHICKNESS)
|
||||
# Left line, blue
|
||||
d.line(sum((sum([(row[0][0],row[0][1],row[0][0],row[0][1]+self.SIDELENGTH) for row in self.BOARDCOORDINATES],()),(self.BOARDCOORDINATES[10][0][0]+self.HEXAGONWIDTH/4,self.BOARDCOORDINATES[10][0][1]+self.SIDELENGTH*5/4)),()),
|
||||
fill = self.PIECECOLOR[2],width = self.LINETHICKNESS)
|
||||
# Right line, blue
|
||||
d.line(sum(((self.BOARDCOORDINATES[0][10][0]+self.HEXAGONWIDTH*3/4,self.BOARDCOORDINATES[0][10][1]-self.SIDELENGTH/4),sum([(row[10][0]+self.HEXAGONWIDTH,row[10][1],row[10][0]+self.HEXAGONWIDTH,row[10][1]+self.SIDELENGTH) for row in self.BOARDCOORDINATES],())),()),
|
||||
fill = self.PIECECOLOR[2],width = self.LINETHICKNESS)
|
||||
|
||||
# Writes "abc..", "123.." on the columns and rows
|
||||
for i in range(11):
|
||||
# Top letters
|
||||
d.text( (self.XOFFSET + self.HEXAGONWIDTH*i, self.YOFFSET-66) , "ABCDEFGHIJK"[i], font=self.FONT, fill=self.TEXTCOLOR)
|
||||
# Bottom letters
|
||||
d.text( (self.XOFFSET + self.HEXAGONWIDTH*(i+11.5/2), self.YOFFSET - 15 + 11*self.HEXAGONHEIGHT) , "ABCDEFGHIJK"[i], font=self.FONT, fill=self.TEXTCOLOR)
|
||||
# Left numbers
|
||||
d.multiline_text( (self.XOFFSET + self.HEXAGONWIDTH*i/2 - 72 -4*(i>8), self.YOFFSET + 18 + i*self.HEXAGONHEIGHT) , str(i+1), font=self.FONT, fill=self.TEXTCOLOR, align="right")
|
||||
# Right numbers
|
||||
d.text( (self.XOFFSET + self.HEXAGONWIDTH*(i/2+11) + 30 , self.YOFFSET + 6 + i*self.HEXAGONHEIGHT) , str(i+1), font=self.FONT, fill=self.TEXTCOLOR)
|
||||
|
||||
# Write player names and color
|
||||
game = self.bot.database["hex games"].find_one({"_id":channel})
|
||||
|
||||
for p in [1,2]:
|
||||
playername = self.bot.database_funcs.get_name(game["players"][p-1])
|
||||
# Draw name
|
||||
x = self.XNAME[p]
|
||||
x -= self.NAMEFONT.getsize(playername)[0] if p==2 else 0 # player2's name is right-aligned
|
||||
y = self.YNAME[p]
|
||||
d.text((x,y),playername, font=self.NAMEFONT, fill = self.TEXTCOLOR)
|
||||
# Draw a half-size Hexagon to indicate the player's color
|
||||
x -= self.NAMEHEXPADDING # To the left of both names
|
||||
d.polygon([
|
||||
(x, y),
|
||||
(x+self.SMALLWIDTH/2, y-self.SMALLSIDELENGTH/2),
|
||||
(x+self.SMALLWIDTH, y),
|
||||
(x+self.SMALLWIDTH, y+self.SMALLSIDELENGTH),
|
||||
(x+self.SMALLWIDTH/2, y+self.SMALLSIDELENGTH*3/2),
|
||||
(x, y+self.SMALLSIDELENGTH),
|
||||
],fill = self.PIECECOLOR[p])
|
||||
|
||||
im.save("gwendolyn/resources/games/hex_boards/board"+channel+".png")
|
||||
|
||||
|
||||
|
||||
|
||||
def drawHexPlacement(self, channel,player,position):
|
||||
FILEPATH = "gwendolyn/resources/games/hex_boards/board"+channel+".png"
|
||||
self.bot.log(f"Drawing a newly placed hex. Filename: board{channel}.png")
|
||||
|
||||
# Translates position
|
||||
# We don't need to error-check, because the position is already checked in placeOnHexBoard()
|
||||
position = position.lower()
|
||||
column = ord(position[0])-97 # ord() translates from letter to number
|
||||
row = int(position[1:])-1
|
||||
|
||||
# Find the coordinates for the filled hex drawing
|
||||
hex_coords = [
|
||||
(self.BOARDCOORDINATES[row][column][0]+self.COLXTHICKNESS, self.BOARDCOORDINATES[row][column][1] + self.COLYTHICKNESS),
|
||||
(self.BOARDCOORDINATES[row][column][0]+self.HEXAGONWIDTH/2, self.BOARDCOORDINATES[row][column][1]-0.5*self.SIDELENGTH + self.COLHEXTHICKNESS),
|
||||
(self.BOARDCOORDINATES[row][column][0]+self.HEXAGONWIDTH-self.COLXTHICKNESS, self.BOARDCOORDINATES[row][column][1] + self.COLYTHICKNESS),
|
||||
(self.BOARDCOORDINATES[row][column][0]+self.HEXAGONWIDTH-self.COLXTHICKNESS, self.BOARDCOORDINATES[row][column][1]+self.SIDELENGTH - self.COLYTHICKNESS),
|
||||
(self.BOARDCOORDINATES[row][column][0]+self.HEXAGONWIDTH/2, self.BOARDCOORDINATES[row][column][1]+1.5*self.SIDELENGTH - self.COLHEXTHICKNESS),
|
||||
(self.BOARDCOORDINATES[row][column][0]+self.COLXTHICKNESS, self.BOARDCOORDINATES[row][column][1]+self.SIDELENGTH - self.COLYTHICKNESS),
|
||||
]
|
||||
|
||||
# Opens the image
|
||||
try:
|
||||
with Image.open(FILEPATH) as im:
|
||||
d = ImageDraw.Draw(im,"RGBA")
|
||||
# Draws the hex piece
|
||||
d.polygon(hex_coords,fill = self.PIECECOLOR[player], outline = self.BETWEENCOLOR)
|
||||
|
||||
# Save
|
||||
im.save(FILEPATH)
|
||||
except:
|
||||
self.bot.log("Error drawing new hex on board (error code 1541")
|
||||
|
||||
def drawSwap(self, channel):
|
||||
FILEPATH = "gwendolyn/resources/games/hex_boards/board"+channel+".png"
|
||||
game = self.bot.database["hex games"].find_one({"_id":channel})
|
||||
# Opens the image
|
||||
try:
|
||||
with Image.open(FILEPATH) as im:
|
||||
d = ImageDraw.Draw(im,"RGBA")
|
||||
|
||||
# Write player names and color
|
||||
for p in [1,2]:
|
||||
playername = self.bot.database_funcs.get_name(game["players"][p%2])
|
||||
|
||||
x = self.XNAME[p]
|
||||
x -= self.NAMEFONT.getsize(playername)[0] if p==2 else 0 # player2's name is right-aligned
|
||||
y = self.YNAME[p]
|
||||
|
||||
# Draw a half-size Hexagon to indicate the player's color
|
||||
x -= self.NAMEHEXPADDING # To the left of both names
|
||||
d.polygon([
|
||||
(x, y),
|
||||
(x+self.SMALLWIDTH/2, y-self.SMALLSIDELENGTH/2),
|
||||
(x+self.SMALLWIDTH, y),
|
||||
(x+self.SMALLWIDTH, y+self.SMALLSIDELENGTH),
|
||||
(x+self.SMALLWIDTH/2, y+self.SMALLSIDELENGTH*3/2),
|
||||
(x, y+self.SMALLSIDELENGTH),
|
||||
],fill = self.PIECECOLOR[p % 2 + 1])
|
||||
|
||||
# Save
|
||||
im.save(FILEPATH)
|
||||
except:
|
||||
self.bot.log("Error drawing swap (error code 1542)")
|
286
gwendolyn/funcs/games/invest.py
Normal file
286
gwendolyn/funcs/games/invest.py
Normal file
@ -0,0 +1,286 @@
|
||||
"""
|
||||
Contains functions relating to invest commands.
|
||||
|
||||
*Classes*
|
||||
---------
|
||||
Invest
|
||||
Contains all the code for the invest commands.
|
||||
"""
|
||||
import discord # Used for embeds
|
||||
from discord_slash.context import SlashContext # Used for type hints
|
||||
|
||||
|
||||
class Invest():
|
||||
"""
|
||||
Contains all the invest functions.
|
||||
|
||||
*Methods*
|
||||
---------
|
||||
getPrice(symbol: str) -> int
|
||||
getPortfolio(user: str) -> str
|
||||
buyStock(user: str, stock: str: buyAmount: int) -> str
|
||||
sellStock(user: str, stock: str, buyAmount: int) -> str
|
||||
parseInvest(ctx: discord_slash.context.SlashContext,
|
||||
parameters: str)
|
||||
"""
|
||||
|
||||
def __init__(self, bot):
|
||||
"""Initialize the class."""
|
||||
self.bot = bot
|
||||
|
||||
def getPrice(self, symbol: str):
|
||||
"""
|
||||
Get the price of a stock.
|
||||
|
||||
*Parameters*
|
||||
------------
|
||||
symbol: str
|
||||
The symbol of the stock to get the price of.
|
||||
|
||||
*Returns*
|
||||
---------
|
||||
price: int
|
||||
The price of the stock.
|
||||
"""
|
||||
res = self.bot.finnhub_client.quote(symbol.upper())
|
||||
if res == {}:
|
||||
return 0
|
||||
else:
|
||||
return int(res["c"] * 100)
|
||||
|
||||
def getPortfolio(self, user: str):
|
||||
"""
|
||||
Get the stock portfolio of a user.
|
||||
|
||||
*Parameters*
|
||||
------------
|
||||
user: str
|
||||
The id of the user to get the portfolio of.
|
||||
|
||||
*Returns*
|
||||
---------
|
||||
portfolio: str
|
||||
The portfolio.
|
||||
"""
|
||||
investmentsDatabase = self.bot.database["investments"]
|
||||
userInvestments = investmentsDatabase.find_one({"_id": user})
|
||||
|
||||
user_name = self.bot.database_funcs.get_name(user)
|
||||
|
||||
if userInvestments in [None, {}]:
|
||||
return f"{user_name} does not have a stock portfolio."
|
||||
else:
|
||||
portfolio = f"**Stock portfolio for {user_name}**"
|
||||
|
||||
for key, value in list(userInvestments["investments"].items()):
|
||||
purchaseValue = value["purchased for"]
|
||||
stockPrice = self.getPrice(key)
|
||||
valueAtPurchase = value["value at purchase"]
|
||||
purchasedStock = value["purchased"]
|
||||
valueChange = (stockPrice / valueAtPurchase)
|
||||
currentValue = int(valueChange * purchasedStock)
|
||||
portfolio += f"\n**{key}**: ___{currentValue} GwendoBucks___"
|
||||
|
||||
if purchaseValue != "?":
|
||||
portfolio += f" (purchased for {purchaseValue})"
|
||||
|
||||
return portfolio
|
||||
|
||||
def buyStock(self, user: str, stock: str, buyAmount: int):
|
||||
"""
|
||||
Buy an amount of a specific stock.
|
||||
|
||||
*Paramaters*
|
||||
------------
|
||||
user: str
|
||||
The id of the user buying.
|
||||
stock: str
|
||||
The symbol of the stock to buy.
|
||||
buyAmount: int
|
||||
The amount of GwendoBucks to use to buy the stock.
|
||||
|
||||
*Returns*
|
||||
---------
|
||||
sendMessage: str
|
||||
The message to return to the user.
|
||||
"""
|
||||
if buyAmount < 100:
|
||||
return "You cannot buy stocks for less than 100 GwendoBucks"
|
||||
elif self.bot.money.checkBalance(user) < buyAmount:
|
||||
return "You don't have enough money for that"
|
||||
elif self.getPrice(stock) <= 0:
|
||||
return f"{stock} is not traded on the american market."
|
||||
else:
|
||||
investmentsDatabase = self.bot.database["investments"]
|
||||
stockPrice = self.getPrice(stock)
|
||||
userInvestments = investmentsDatabase.find_one({"_id": user})
|
||||
|
||||
self.bot.money.addMoney(user, -1*buyAmount)
|
||||
stock = stock.upper()
|
||||
|
||||
if userInvestments is not None:
|
||||
userInvestments = userInvestments["investments"]
|
||||
if stock in userInvestments:
|
||||
value = userInvestments[stock]
|
||||
valueChange = (stockPrice / value["value at purchase"])
|
||||
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)
|
||||
|
||||
purchasedPath = f"investments.{stock}.purchased"
|
||||
updater = {"$set": {purchasedPath: newAmount}}
|
||||
investmentsDatabase.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)
|
||||
else:
|
||||
updater = {
|
||||
"$set": {
|
||||
"investments.{stock}": {
|
||||
"purchased": buyAmount,
|
||||
"value at purchase": stockPrice,
|
||||
"purchased for": buyAmount
|
||||
}
|
||||
}
|
||||
}
|
||||
investmentsDatabase.update_one({"_id": user}, updater)
|
||||
else:
|
||||
newUser = {
|
||||
"_id": user,
|
||||
"investments": {
|
||||
stock: {
|
||||
"purchased": buyAmount,
|
||||
"value at purchase": stockPrice,
|
||||
"purchased for": buyAmount
|
||||
}
|
||||
}
|
||||
}
|
||||
investmentsDatabase.insert_one(newUser)
|
||||
|
||||
user_name = self.bot.database_funcs.get_name(user)
|
||||
sendMessage = "{} bought {} GwendoBucks worth of {} stock"
|
||||
sendMessage = sendMessage.format(user_name, buyAmount, stock)
|
||||
return sendMessage
|
||||
|
||||
def sellStock(self, user: str, stock: str, sellAmount: int):
|
||||
"""
|
||||
Sell an amount of a specific stock.
|
||||
|
||||
*Paramaters*
|
||||
------------
|
||||
user: str
|
||||
The id of the user selling.
|
||||
stock: str
|
||||
The symbol of the stock to sell.
|
||||
buyAmount: int
|
||||
The amount of GwendoBucks to sell for.
|
||||
|
||||
*Returns*
|
||||
---------
|
||||
sendMessage: 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"]
|
||||
|
||||
stock = stock.upper()
|
||||
|
||||
if userInvestments is not None and stock in userInvestments:
|
||||
value = userInvestments[stock]
|
||||
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)
|
||||
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)
|
||||
|
||||
purchasedForPath = f"investments.{stock}.purchased for"
|
||||
updater = {"$set": {purchasedForPath: "?"}}
|
||||
investmentsDatabase.update_one({"_id": user}, updater)
|
||||
else:
|
||||
updater = {"$unset": {f"investments.{stock}": ""}}
|
||||
investmentsDatabase.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)
|
||||
else:
|
||||
return f"You don't have enough {stock} stocks to do that"
|
||||
else:
|
||||
return f"You don't have any {stock} stock"
|
||||
|
||||
async def parseInvest(self, ctx: SlashContext, parameters: str):
|
||||
"""
|
||||
Parse an invest command. TO BE DELETED.
|
||||
|
||||
*Parameters*
|
||||
------------
|
||||
ctx: discord_slash.context.SlashContext
|
||||
The context of the slash command.
|
||||
parameters: str
|
||||
The parameters of the command.
|
||||
"""
|
||||
await self.bot.defer(ctx)
|
||||
user = f"#{ctx.author.id}"
|
||||
|
||||
if parameters.startswith("check"):
|
||||
commands = parameters.split(" ")
|
||||
if len(commands) == 1:
|
||||
response = self.getPortfolio(user)
|
||||
else:
|
||||
price = self.getPrice(commands[1])
|
||||
if price == 0:
|
||||
response = "{} is not traded on the american market."
|
||||
response = response.format(commands[0].upper())
|
||||
else:
|
||||
price = f"{price:,}".replace(",", ".")
|
||||
response = self.bot.long_strings["Stock value"]
|
||||
response = response.format(commands[1].upper(), price)
|
||||
|
||||
elif parameters.startswith("buy"):
|
||||
commands = parameters.split(" ")
|
||||
if len(commands) == 3:
|
||||
response = self.buyStock(user, commands[1], int(commands[2]))
|
||||
else:
|
||||
response = self.bot.long_strings["Stock parameters"]
|
||||
|
||||
elif parameters.startswith("sell"):
|
||||
commands = parameters.split(" ")
|
||||
if len(commands) == 3:
|
||||
response = self.sellStock(user, commands[1], int(commands[2]))
|
||||
else:
|
||||
response = self.bot.long_strings["Stock parameters"]
|
||||
|
||||
else:
|
||||
response = "Incorrect parameters"
|
||||
|
||||
if response.startswith("**"):
|
||||
responses = response.split("\n")
|
||||
text = "\n".join(responses[1:])
|
||||
embedParams = {
|
||||
"title": responses[0],
|
||||
"description": text,
|
||||
"colour": 0x00FF00
|
||||
}
|
||||
em = discord.Embed(**embedParams)
|
||||
await ctx.send(embed=em)
|
||||
else:
|
||||
await ctx.send(response)
|
151
gwendolyn/funcs/games/money.py
Normal file
151
gwendolyn/funcs/games/money.py
Normal file
@ -0,0 +1,151 @@
|
||||
"""
|
||||
Contains the code that deals with money.
|
||||
|
||||
*Classes*
|
||||
---------
|
||||
Money
|
||||
Deals with money.
|
||||
"""
|
||||
import discord_slash # Used for typehints
|
||||
import discord # Used for typehints
|
||||
|
||||
|
||||
class Money():
|
||||
"""
|
||||
Deals with money.
|
||||
|
||||
*Methods*
|
||||
---------
|
||||
checkBalance(user: str)
|
||||
sendBalance(ctx: discord_slash.context.SlashContext)
|
||||
addMoney(user: str, amount: int)
|
||||
giveMoney(ctx: discord_slash.context.SlashContext, user: discord.User,
|
||||
amount: int)
|
||||
|
||||
*Attributes*
|
||||
------------
|
||||
bot: Gwendolyn
|
||||
The instance of Gwendolyn
|
||||
database: pymongo.Client
|
||||
The mongo database
|
||||
"""
|
||||
|
||||
def __init__(self, bot):
|
||||
"""Initialize the class."""
|
||||
self.bot = bot
|
||||
self.database = bot.database
|
||||
|
||||
def checkBalance(self, user: str):
|
||||
"""
|
||||
Get the account balance of a user.
|
||||
|
||||
*Parameters*
|
||||
------------
|
||||
user: str
|
||||
The user to get the balance of.
|
||||
|
||||
*Returns*
|
||||
---------
|
||||
balance: int
|
||||
The balance of the user's account.
|
||||
"""
|
||||
self.bot.log("checking "+user+"'s account balance")
|
||||
|
||||
userData = self.database["users"].find_one({"_id": user})
|
||||
|
||||
if userData is not None:
|
||||
return userData["money"]
|
||||
else:
|
||||
return 0
|
||||
|
||||
async def sendBalance(self, ctx: discord_slash.context.SlashContext):
|
||||
"""
|
||||
Get your own account balance.
|
||||
|
||||
*Parameters*
|
||||
------------
|
||||
ctx: discord_slash.context.SlashContext
|
||||
The context of the command.
|
||||
"""
|
||||
await self.bot.defer(ctx)
|
||||
response = self.checkBalance("#"+str(ctx.author.id))
|
||||
user_name = ctx.author.display_name
|
||||
if response == 1:
|
||||
new_message = f"{user_name} has {response} GwendoBuck"
|
||||
else:
|
||||
new_message = f"{user_name} has {response} GwendoBucks"
|
||||
await ctx.send(new_message)
|
||||
|
||||
# Adds money to the account of a user
|
||||
def addMoney(self, user: str, amount: int):
|
||||
"""
|
||||
Add money to a user account.
|
||||
|
||||
*Parameters*
|
||||
------------
|
||||
user: str
|
||||
The id of the user to give money.
|
||||
amount: int
|
||||
The amount to add to the user's account.
|
||||
"""
|
||||
self.bot.log("adding "+str(amount)+" to "+user+"'s account")
|
||||
|
||||
userData = self.database["users"].find_one({"_id": user})
|
||||
|
||||
if userData is not None:
|
||||
updater = {"$inc": {"money": amount}}
|
||||
self.database["users"].update_one({"_id": user}, updater)
|
||||
else:
|
||||
newUser = {
|
||||
"_id": user,
|
||||
"user name": self.bot.database_funcs.get_name(user),
|
||||
"money": amount
|
||||
}
|
||||
self.database["users"].insert_one(newUser)
|
||||
|
||||
# Transfers money from one user to another
|
||||
async def giveMoney(self, ctx: discord_slash.context.SlashContext,
|
||||
user: discord.User, amount: int):
|
||||
"""
|
||||
Give someone else money from your account.
|
||||
|
||||
*Parameters*
|
||||
------------
|
||||
ctx: discord_slash.context.SlashContext
|
||||
The context of the command.
|
||||
user: discord.User
|
||||
The user to give money.
|
||||
amount: int
|
||||
The amount to transfer.
|
||||
"""
|
||||
await self.bot.defer(ctx)
|
||||
username = user.display_name
|
||||
if self.bot.database_funcs.get_id(username) is None:
|
||||
async for member in ctx.guild.fetch_members(limit=None):
|
||||
if member.display_name.lower() == username.lower():
|
||||
username = member.display_name
|
||||
user_id = f"#{member.id}"
|
||||
newUser = {
|
||||
"_id": user_id,
|
||||
"user name": username,
|
||||
"money": 0
|
||||
}
|
||||
self.bot.database["users"].insert_one(newUser)
|
||||
|
||||
userid = f"#{ctx.author.id}"
|
||||
userData = self.database["users"].find_one({"_id": userid})
|
||||
targetUser = self.bot.database_funcs.get_id(username)
|
||||
|
||||
if amount <= 0:
|
||||
self.bot.log("They tried to steal")
|
||||
await ctx.send("Yeah, no. You can't do that")
|
||||
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:
|
||||
self.bot.log("They didn't have enough GwendoBucks")
|
||||
await ctx.send("You don't have that many GwendoBuck")
|
||||
else:
|
||||
self.addMoney(f"#{ctx.author.id}", -1 * amount)
|
||||
self.addMoney(targetUser, amount)
|
||||
await ctx.send(f"Transferred {amount} GwendoBucks to {username}")
|
205
gwendolyn/funcs/games/trivia.py
Normal file
205
gwendolyn/funcs/games/trivia.py
Normal file
@ -0,0 +1,205 @@
|
||||
"""
|
||||
Contains code for trivia games.
|
||||
|
||||
*Classes*
|
||||
---------
|
||||
Trivia
|
||||
Contains all the code for the trivia commands.
|
||||
"""
|
||||
import urllib # Used to get data from api
|
||||
import json # Used to read data from api
|
||||
import random # Used to shuffle answers
|
||||
import asyncio # Used to sleep
|
||||
|
||||
from discord_slash.context import SlashContext # Used for type hints
|
||||
|
||||
|
||||
class Trivia():
|
||||
"""
|
||||
Contains the code for trivia games.
|
||||
|
||||
*Methods*
|
||||
---------
|
||||
triviaStart(channel: str) -> str, str, str
|
||||
triviaAnswer(user: str, channel: str, command: str) -> str
|
||||
triviaCountPoints(channel: str)
|
||||
triviaParse(ctx: SlashContext, answer: str)
|
||||
"""
|
||||
|
||||
def __init__(self, bot):
|
||||
"""Initialize the class."""
|
||||
self.bot = bot
|
||||
|
||||
def triviaStart(self, channel: str):
|
||||
"""
|
||||
Start a game of trivia.
|
||||
|
||||
Downloads a question with answers, shuffles the wrong answers
|
||||
with the correct answer and returns the questions and answers.
|
||||
Also saves the question in the database.
|
||||
|
||||
*Parameters*
|
||||
------------
|
||||
channel: str
|
||||
The id of the channel to start the game in
|
||||
|
||||
*Returns*
|
||||
---------
|
||||
sendMessage: str
|
||||
The message to return to the user.
|
||||
"""
|
||||
triviaQuestions = self.bot.database["trivia questions"]
|
||||
question = triviaQuestions.find_one({"_id": channel})
|
||||
|
||||
self.bot.log(f"Trying to find a trivia question for {channel}")
|
||||
|
||||
if question is None:
|
||||
apiUrl = "https://opentdb.com/api.php?amount=10&type=multiple"
|
||||
with urllib.request.urlopen(apiUrl) as response:
|
||||
data = json.loads(response.read())
|
||||
|
||||
question = data["results"][0]["question"]
|
||||
self.bot.log(f"Found the question \"{question}\"")
|
||||
answers = data["results"][0]["incorrect_answers"]
|
||||
answers.append(data["results"][0]["correct_answer"])
|
||||
random.shuffle(answers)
|
||||
correctAnswer = data["results"][0]["correct_answer"]
|
||||
correctAnswer = answers.index(correctAnswer) + 97
|
||||
|
||||
newQuestion = {
|
||||
"_id": channel,
|
||||
"answer": str(chr(correctAnswer)),
|
||||
"players": {}
|
||||
}
|
||||
triviaQuestions.insert_one(newQuestion)
|
||||
|
||||
replacements = {
|
||||
"'": "\'",
|
||||
""": "\"",
|
||||
"“": "\"",
|
||||
"”": "\"",
|
||||
"é": "é"
|
||||
}
|
||||
question = data["results"][0]["question"]
|
||||
|
||||
for key, value in replacements.items():
|
||||
question = question.replace(key, value)
|
||||
|
||||
for answer in answers:
|
||||
for key, value in replacements.items():
|
||||
answer = answer.replace(key, value)
|
||||
|
||||
return question, answers, correctAnswer
|
||||
else:
|
||||
log_message = "There was already a trivia question for that channel"
|
||||
self.bot.log(log_message)
|
||||
return self.bot.long_strings["Trivia going on"], "", ""
|
||||
|
||||
def triviaAnswer(self, user: str, channel: str, command: str):
|
||||
"""
|
||||
Answer the current trivia question.
|
||||
|
||||
*Parameters*
|
||||
------------
|
||||
user: str
|
||||
The id of the user who answered.
|
||||
channel: str
|
||||
The id of the channel the game is in.
|
||||
command: str
|
||||
The user's answer.
|
||||
|
||||
*Returns*
|
||||
---------
|
||||
sendMessage: str
|
||||
The message to send if the function failed.
|
||||
"""
|
||||
triviaQuestions = self.bot.database["trivia questions"]
|
||||
question = triviaQuestions.find_one({"_id": channel})
|
||||
|
||||
if command not in ["a", "b", "c", "d"]:
|
||||
self.bot.log("I didn't quite understand that")
|
||||
return "I didn't quite understand that"
|
||||
elif question is None:
|
||||
self.bot.log("There's no question right now")
|
||||
return "There's no question right now"
|
||||
elif user in question["players"]:
|
||||
self.bot.log(f"{user} has already answered this question")
|
||||
return f"{user} has already answered this question"
|
||||
else:
|
||||
self.bot.log(f"{user} answered the question in {channel}")
|
||||
|
||||
updater = {"$set": {f"players.{user}": command}}
|
||||
triviaQuestions.update_one({"_id": channel}, updater)
|
||||
return None
|
||||
|
||||
def triviaCountPoints(self, channel: str):
|
||||
"""
|
||||
Add money to every winner's account.
|
||||
|
||||
*Parameters*
|
||||
------------
|
||||
channel: str
|
||||
The id of the channel the game is in.
|
||||
"""
|
||||
triviaQuestions = self.bot.database["trivia questions"]
|
||||
question = triviaQuestions.find_one({"_id": channel})
|
||||
|
||||
self.bot.log("Counting points for question in "+channel)
|
||||
|
||||
if question is not None:
|
||||
for player, answer in question["players"].items():
|
||||
if answer == question["answer"]:
|
||||
self.bot.money.addMoney(player, 1)
|
||||
else:
|
||||
self.bot.log("Couldn't find the questio")
|
||||
|
||||
return None
|
||||
|
||||
async def triviaParse(self, ctx: SlashContext, answer: str):
|
||||
"""
|
||||
Parse a trivia command.
|
||||
|
||||
*Parameters*
|
||||
------------
|
||||
ctx: SlashContext
|
||||
The context of the command.
|
||||
answer: str
|
||||
The answer, if any.
|
||||
"""
|
||||
await self.bot.defer(ctx)
|
||||
channelId = str(ctx.channel_id)
|
||||
if answer == "":
|
||||
question, options, correctAnswer = self.triviaStart(channelId)
|
||||
if options != "":
|
||||
results = "**"+question+"**\n"
|
||||
for x, option in enumerate(options):
|
||||
results += chr(x+97) + ") "+option+"\n"
|
||||
|
||||
await ctx.send(results)
|
||||
|
||||
await asyncio.sleep(60)
|
||||
|
||||
self.triviaCountPoints(channelId)
|
||||
|
||||
delete_gameParams = ["trivia questions", channelId]
|
||||
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)
|
||||
else:
|
||||
await ctx.send(question, hidden=True)
|
||||
|
||||
elif answer in ["a", "b", "c", "d"]:
|
||||
userId = f"#{ctx.author.id}"
|
||||
response = self.triviaAnswer(userId, channelId, answer)
|
||||
if response is None:
|
||||
user_name = ctx.author.display_name
|
||||
await ctx.send(f"{user_name} answered **{answer}**")
|
||||
else:
|
||||
await ctx.send(response)
|
||||
else:
|
||||
self.bot.log("I didn't understand that", channelId)
|
||||
await ctx.send("I didn't understand that")
|
Reference in New Issue
Block a user