Fully converted to slash commands

This commit is contained in:
NikolajDanger
2021-03-31 00:38:51 +02:00
parent a8a7e5eabd
commit b345720468
50 changed files with 1102 additions and 1111 deletions

View File

@ -6,7 +6,7 @@ import discord
from shutil import copyfile
from funcs import logThis, replaceMultiple
from utils import replaceMultiple
from .blackjackDraw import DrawBlackjack
class Blackjack():
@ -16,7 +16,7 @@ class Blackjack():
# Shuffles the blackjack cards
def blackjackShuffle(self, decks, channel):
logThis("Shuffling the blackjack deck")
self.bot.log("Shuffling the blackjack deck")
with open("resources/games/deckofCards.txt","r") as f:
deck = f.read()
@ -27,7 +27,7 @@ class Blackjack():
self.bot.database["blackjack cards"].update_one({"_id":channel},{"$set":{"_id":channel,"cards":allDecks}},upsert=True)
# Creates hilo file
logThis("creating hilo doc for "+channel)
self.bot.log("creating hilo doc for "+channel)
data = 0
self.bot.database["hilo"].update_one({"_id":channel},{"$set":{"_id":channel,"hilo":data}},upsert=True)
@ -35,7 +35,7 @@ class Blackjack():
# Calculates the value of a blackjack hand
def calcHandValue(self, hand : list):
logThis("Calculating hand value")
self.bot.log("Calculating hand value", level = 10)
values = []
values.append(0)
@ -58,13 +58,13 @@ class Blackjack():
if value <= 21:
handValue = value
logThis("Calculated "+str(hand)+" to be "+str(handValue))
self.bot.log("Calculated "+str(hand)+" to be "+str(handValue), level = 10)
return handValue
# Draws a card from the deck
def drawCard(self, channel):
logThis("drawing a card")
self.bot.log("drawing a card", level = 10)
drawnCard = self.bot.database["blackjack cards"].find_one({"_id":channel})["cards"][0]
self.bot.database["blackjack cards"].update_one({"_id":channel},{"$pop":{"cards":-1}})
@ -97,7 +97,7 @@ class Blackjack():
# Goes to the next round and calculates some stuff
def blackjackContinue(self, channel):
logThis("Continuing blackjack game")
self.bot.log("Continuing blackjack game", level = 10)
game = self.bot.database["blackjack games"].find_one({"_id":channel})
done = False
@ -109,20 +109,20 @@ class Blackjack():
message = "All players are standing. The dealer now shows his cards and draws."
if game["all standing"]:
logThis("All are standing")
self.bot.log("All are standing")
done = self.dealerDraw(channel)
message = "The dealer draws a card."
game = self.bot.database["blackjack games"].find_one({"_id":channel})
logThis("Testing if all are standing")
self.bot.log("Testing if all are standing", level = 10)
for user in game["user hands"]:
try:
newUser, allStanding, preAllStanding = self.testIfStanding(game["user hands"][user],allStanding,preAllStanding,True)
self.bot.database["blackjack games"].update_one({"_id":channel},{"$set":{"user hands."+user:newUser}})
except:
logThis("Error in testing if all are standing (error code 1331)")
self.bot.log("Error in testing if all are standing (error code 1331)")
if allStanding:
self.bot.database["blackjack games"].update_one({"_id":channel},{"$set":{"all standing":True}})
@ -130,7 +130,7 @@ class Blackjack():
try:
self.draw.drawImage(channel)
except:
logThis("Error drawing blackjack table (error code 1340)")
self.bot.log("Error drawing blackjack table (error code 1340)")
if allStanding:
if done == False:
@ -209,19 +209,19 @@ class Blackjack():
return response + str(roundDone)[0] + str(game["round"])
else:
logThis(user+" is already standing")
self.bot.log(user+" is already standing")
return "You can't hit when you're standing"
else:
logThis(user+" has already hit this round")
self.bot.log(user+" has already hit this round")
return "You've already hit this round"
else:
logThis(user+" tried to hit on the 0th round")
self.bot.log(user+" tried to hit on the 0th round")
return "You can't hit before you see your cards"
else:
logThis(user+" didn't specify a hand")
self.bot.log(user+" didn't specify a hand")
return "You need to specify a hand"
else:
logThis(user+" tried to hit without being in the game")
self.bot.log(user+" tried to hit without being in the game")
return "You have to enter the game before you can hit"
@ -267,27 +267,27 @@ class Blackjack():
roundDone = self.isRoundDone(self.bot.database["blackjack games"].find_one({"_id":channel}))
return "Adding another "+str(bet)+" GwendoBucks to "+self.bot.funcs.getName(user)+"'s bet and drawing another card.",str(roundDone)[0] + str(game["round"])
return "Adding another "+str(bet)+" GwendoBucks to "+self.bot.databaseFuncs.getName(user)+"'s bet and drawing another card.",str(roundDone)[0] + str(game["round"])
else:
logThis(user+" doesn't have enough GwendoBucks")
self.bot.log(user+" doesn't have enough GwendoBucks")
return "You don't have enough GwendoBucks",""
else:
logThis(user+" tried to double on round "+str(game["round"]))
self.bot.log(user+" tried to double on round "+str(game["round"]))
return "You can only double down on the first round",""
else:
logThis(user+" is already standing")
self.bot.log(user+" is already standing")
return "You can't double when you're standing",""
else:
logThis(user+" has already hit this round")
self.bot.log(user+" has already hit this round")
return "You've already hit this round",""
else:
logThis(user+" tried to double on the 0th round")
self.bot.log(user+" tried to double on the 0th round")
return "You can't double down before you see your cards",""
else:
logThis(user+" didn't specify a hand")
self.bot.log(user+" didn't specify a hand")
return "You need to specify which hand"
else:
logThis(user+" tried to double without being in the game")
self.bot.log(user+" tried to double without being in the game")
return "You can't double when you're not in the game",""
# When players try to stand
@ -322,19 +322,19 @@ class Blackjack():
return response + str(roundDone)[0] + str(game["round"])
else:
logThis(user+" is already standing")
self.bot.log(user+" is already standing")
return "You're already standing"
else:
logThis(user+" has already hit this round")
self.bot.log(user+" has already hit this round")
return "You've already hit this round"
else:
logThis(user+" tried to stand on the first round")
self.bot.log(user+" tried to stand on the first round")
return "You can't stand before you see your cards"
else:
logThis(user+" didn't specify a hand")
self.bot.log(user+" didn't specify a hand")
return "You need to specify which hand"
else:
logThis(user+" tried to stand without being in the game")
self.bot.log(user+" tried to stand without being in the game")
return "You have to enter the game before you can stand"
# When players try to split
@ -355,7 +355,7 @@ class Blackjack():
elif handNumber == 3:
hand = game["user hands"][user]["third hand"]
else:
logThis(user+" tried to hit without specifying which hand")
self.bot.log(user+" tried to hit without specifying which hand")
return "You have to specify the hand you're hitting with."
if game["user hands"][user]["split"] == 1:
@ -365,7 +365,7 @@ class Blackjack():
newHand = game["user hands"][user]["fourth hand"]
otherHand = 4
else:
logThis(user+" tried to split without specifying which hand")
self.bot.log(user+" tried to split without specifying which hand")
return "You have to specify the hand you're splitting.",""
if game["user hands"][user]["split"] < 3:
@ -430,34 +430,34 @@ class Blackjack():
roundDone = self.isRoundDone(self.bot.database["blackjack games"].find_one({"_id":channel}))
return "Splitting "+self.bot.funcs.getName(user)+"'s hand into 2. Adding their original bet to the second hand. You can use \"!Blackjack hit/stand/double 1\" and \"!Blackjack hit/stand/double 2\" to play the different hands.",str(roundDone)[0] + str(game["round"])
return "Splitting "+self.bot.databaseFuncs.getName(user)+"'s hand into 2. Adding their original bet to the second hand. You can use \"!Blackjack hit/stand/double 1\" and \"!Blackjack hit/stand/double 2\" to play the different hands.",str(roundDone)[0] + str(game["round"])
else:
logThis(user+" doesn't have enough GwendoBucks")
self.bot.log(user+" doesn't have enough GwendoBucks")
return "You don't have enough GwendoBucks",""
else:
logThis(user+" tried to split 2 different cards")
self.bot.log(user+" tried to split 2 different cards")
return "Your cards need to have the same value to split",""
else:
logThis(user+" tried to split later than they could")
self.bot.log(user+" tried to split later than they could")
return "You can only split on the first round",""
else:
logThis(user+" is already standing")
self.bot.log(user+" is already standing")
return "You can't split when you're standing",""
else:
logThis(user+" has already hit this round")
self.bot.log(user+" has already hit this round")
return "You've already hit this round",""
else:
logThis(user+" tried to split on the 0th round")
self.bot.log(user+" tried to split on the 0th round")
return "You can't split before you see your cards",""
else:
logThis(user+" tried to split more than three times")
self.bot.log(user+" tried to split more than three times")
return "You can only split 3 times",""
# Player enters the game and draws a hand
def blackjackPlayerDrawHand(self,channel,user,bet):
game = self.bot.database["blackjack games"].find_one({"_id":channel})
logThis(self.bot.funcs.getName(user)+" is trying to join the game in "+channel)
self.bot.log(self.bot.databaseFuncs.getName(user)+" is trying to join the game in "+channel)
if game != None:
if user not in game["user hands"]:
@ -481,32 +481,32 @@ class Blackjack():
self.bot.database["blackjack games"].update_one({"_id":channel},
{"$set":{"user hands."+user:newHand}})
logThis(f"{self.bot.funcs.getName(user)} entered the game with a bet of {bet}")
return f"{self.bot.funcs.getName(user)} entered the game with a bet of {bet}"
self.bot.log(f"{self.bot.databaseFuncs.getName(user)} entered the game with a bet of {bet}")
return f"{self.bot.databaseFuncs.getName(user)} entered the game with a bet of {bet}"
else:
logThis(user+" doesn't have enough GwendoBucks")
self.bot.log(user+" doesn't have enough GwendoBucks")
return "You don't have enough GwendoBucks to place that bet"
else:
logThis(user+" tried to bet a negative amount")
self.bot.log(user+" tried to bet a negative amount")
return "You can't bet a negative amount"
else:
logThis("The table is no longer open for bets")
self.bot.log("The table is no longer open for bets")
return "The table is no longer open for bets"
else:
logThis("There are already 5 players in the game.")
self.bot.log("There are already 5 players in the game.")
return "There's already a maximum of players at the table."
else:
logThis(user+" is already in the game")
self.bot.log(user+" is already in the game")
return "You've already entered this game"
else:
logThis("There is no game going on in "+channel)
self.bot.log("There is no game going on in "+channel)
return "There is no game going on in this channel"
# Starts a game of blackjack
def blackjackStart(self,channel:str):
game = self.bot.database["blackjack games"].find_one({"_id":channel})
logThis("Trying to start a blackjack game in "+channel)
self.bot.log("Trying to start a blackjack game in "+channel)
if game == None:
@ -524,7 +524,7 @@ class Blackjack():
return "started"
else:
logThis("There is already a blackjack game going on in "+channel)
self.bot.log("There is already a blackjack game going on in "+channel)
return "There's already a blackjack game going on. Try again in a few minutes."
# Ends the game and calculates winnings
@ -540,26 +540,23 @@ class Blackjack():
try:
for user in game["user hands"]:
try:
winnings, netWinnings, reason = self.calcWinnings(game["user hands"][user],dealerValue,True,dealerBlackjack,dealerBusted)
except:
logThis("Error calculating winnings for "+str(user)+" (error code 1312)")
winnings, netWinnings, reason = self.calcWinnings(game["user hands"][user],dealerValue,True,dealerBlackjack,dealerBusted)
if winnings < 0:
if winnings == -1:
finalWinnings += self.bot.funcs.getName(user)+" lost "+str(-1 * winnings)+" GwendoBuck "+reason+"\n"
finalWinnings += self.bot.databaseFuncs.getName(user)+" lost "+str(-1 * winnings)+" GwendoBuck "+reason+"\n"
else:
finalWinnings += self.bot.funcs.getName(user)+" lost "+str(-1 * winnings)+" GwendoBucks "+reason+"\n"
finalWinnings += self.bot.databaseFuncs.getName(user)+" lost "+str(-1 * winnings)+" GwendoBucks "+reason+"\n"
else:
if winnings == 1:
finalWinnings += self.bot.funcs.getName(user)+" won "+str(winnings)+" GwendoBuck "+reason+"\n"
finalWinnings += self.bot.databaseFuncs.getName(user)+" won "+str(winnings)+" GwendoBuck "+reason+"\n"
else:
finalWinnings += self.bot.funcs.getName(user)+" won "+str(winnings)+" GwendoBucks "+reason+"\n"
finalWinnings += self.bot.databaseFuncs.getName(user)+" won "+str(winnings)+" GwendoBucks "+reason+"\n"
self.bot.money.addMoney(user,netWinnings)
except:
logThis("Error calculating winnings (error code 1311)")
self.bot.log("Error calculating winnings (error code 1311)")
self.bot.database["blackjack games"].delete_one({"_id":channel})
@ -567,7 +564,7 @@ class Blackjack():
def calcWinnings(self,hand, dealerValue, topLevel, dealerBlackjack, dealerBusted):
logThis("Calculating winnings")
self.bot.log("Calculating winnings", level = 10)
reason = ""
bet = hand["bet"]
winnings = -1 * bet
@ -637,7 +634,7 @@ class Blackjack():
return hand, handNumber
except:
logThis("Problem with getHandNumber() (error code 1322)")
self.bot.log("Problem with getHandNumber() (error code 1322)")
def isRoundDone(self,game):
roundDone = True
@ -662,14 +659,14 @@ class Blackjack():
# Loop of blackjack game rounds
async def blackjackLoop(self,channel,gameRound,gameID):
logThis("Loop "+str(gameRound),str(channel.id))
self.bot.log("Loop "+str(gameRound),str(channel.id), level = 10)
with open("resources/games/oldImages/blackjack"+str(channel.id), "r") as f:
oldImage = await channel.fetch_message(int(f.read()))
new_message, allStanding, gamedone = self.blackjackContinue(str(channel.id))
if new_message != "":
logThis(new_message,str(channel.id))
self.bot.log(new_message,str(channel.id), level = 10)
await channel.send(new_message)
if gamedone == False:
await oldImage.delete()
@ -683,7 +680,7 @@ class Blackjack():
else:
await asyncio.sleep(120)
except:
logThis("Loop "+str(gameRound)+" interrupted (error code 1321)")
self.bot.log("Loop "+str(gameRound)+" interrupted (error code 1321)")
game = self.bot.database["blackjack games"].find_one({"_id":str(channel.id)})
@ -693,18 +690,18 @@ class Blackjack():
if gameRound == realRound and realGameID == gameID:
if gamedone == False:
logThis("Loop "+str(gameRound)+" calling self.blackjackLoop()",str(channel.id))
self.bot.log("Loop "+str(gameRound)+" calling self.blackjackLoop()",str(channel.id))
await self.blackjackLoop(channel,gameRound+1,gameID)
else:
try:
new_message = self.blackjackFinish(str(channel.id))
except:
logThis("Something fucked up (error code 1310)")
self.bot.log("Something fucked up (error code 1310)")
await channel.send(new_message)
else:
logThis("Ending loop on round "+str(gameRound),str(channel.id))
self.bot.log("Ending loop on round "+str(gameRound),str(channel.id), level = 10)
else:
logThis("Ending loop on round "+str(gameRound),str(channel.id))
self.bot.log("Ending loop on round "+str(gameRound),str(channel.id), level = 10)
async def parseBlackjack(self,content, ctx):
# Blackjack shuffle variables
@ -714,7 +711,7 @@ class Blackjack():
channel = ctx.channel_id
# Starts the game
if content == "":
await ctx.send("Staring a new game of blackjack")
await ctx.send("Starting a new game of blackjack")
cardsLeft = 0
cards = self.bot.database["blackjack cards"].find_one({"_id":str(channel)})
if cards != None:
@ -723,7 +720,7 @@ class Blackjack():
# Shuffles if not enough cards
if cardsLeft < blackjackMinCards:
self.blackjackShuffle(blackjackDecks,str(channel))
logThis("Shuffling the blackjack deck...",str(channel))
self.bot.log("Shuffling the blackjack deck...",str(channel))
await ctx.channel.send("Shuffling the deck...")
new_message = self.blackjackStart(str(channel))
@ -749,7 +746,7 @@ class Blackjack():
# Loop of game rounds
if gamedone == False:
logThis("!blackjack calling self.blackjackLoop()",str(channel))
self.bot.log("!blackjack calling self.blackjackLoop()",str(channel))
await self.blackjackLoop(ctx.channel,1,gameID)
else:
new_message = self.blackjackFinish(str(channel))
@ -781,10 +778,10 @@ class Blackjack():
#try:
if response[6] == "T":
gameID = self.bot.database["blackjack games"].find_one({"_id":str(channel)})["gameID"]
logThis("Hit calling self.blackjackLoop()",str(channel))
self.bot.log("Hit calling self.blackjackLoop()",str(channel))
await self.blackjackLoop(ctx.channel,int(response[7:])+1,gameID)
#except:
# logThis("Something fucked up (error code 1320)",str(channel))
# self.bot.log("Something fucked up (error code 1320)",str(channel))
else:
await ctx.send(response)
@ -806,10 +803,10 @@ class Blackjack():
#try:
if response[6] == "T":
gameID = self.bot.database["blackjack games"].find_one({"_id":str(channel)})["gameID"]
logThis("Stand calling self.blackjackLoop()",str(channel))
self.bot.log("Stand calling self.blackjackLoop()",str(channel))
await self.blackjackLoop(ctx.channel,int(response[7:])+1,gameID)
#except:
# logThis("Something fucked up (error code 1320)",str(channel))
# self.bot.log("Something fucked up (error code 1320)",str(channel))
else:
await ctx.send(response)
@ -827,10 +824,10 @@ class Blackjack():
try:
if roundDone[0] == "T":
gameID = self.bot.database["blackjack games"].find_one({"_id":str(channel)})["gameID"]
logThis("Double calling self.blackjackLoop()",str(channel))
self.bot.log("Double calling self.blackjackLoop()",str(channel))
await self.blackjackLoop(ctx.channel,int(roundDone[1:])+1,gameID)
except:
logThis("Something fucked up (error code 1320)",str(channel))
self.bot.log("Something fucked up (error code 1320)",str(channel))
# Splitting hand
elif content.startswith("split"):
@ -846,10 +843,10 @@ class Blackjack():
try:
if roundDone[0] == "T":
gameID = self.bot.database["blackjack games"].find_one({"_id":str(channel)})["gameID"]
logThis("Split calling self.blackjackLoop()",str(channel))
self.bot.log("Split calling self.blackjackLoop()",str(channel))
await self.blackjackLoop(ctx.channel,int(roundDone[1:])+1,gameID)
except:
logThis("Something fucked up (error code 1320)")
self.bot.log("Something fucked up (error code 1320)")
# Returning current hi-lo value
elif content.startswith("hilo"):
@ -863,7 +860,7 @@ class Blackjack():
# Shuffles the blackjack deck
elif content.startswith("shuffle"):
self.blackjackShuffle(blackjackDecks,str(channel))
logThis("Shuffling the blackjack deck...",str(channel))
self.bot.log("Shuffling the blackjack deck...",str(channel))
await ctx.send("Shuffling the deck...")
@ -878,6 +875,6 @@ class Blackjack():
await ctx.send(str(cardsLeft)+" cards, "+str(decksLeft)+" decks", hidden=True)
else:
logThis("Not a command (error code 1301)")
self.bot.log("Not a command (error code 1301)")
await ctx.send("I didn't quite understand that (error code 1301)")

View File

@ -1,5 +1,4 @@
from PIL import Image, ImageDraw, ImageFont
from funcs import logThis
border = 100
placement = [0,0]
@ -10,11 +9,11 @@ class DrawBlackjack():
self.bot = bot
def drawImage(self,channel):
logThis("Drawing blackjack table",channel)
self.bot.log("Drawing blackjack table",channel, level = 10)
game = self.bot.database["blackjack games"].find_one({"_id":channel})
fnt = ImageFont.truetype('resources/futura-bold.ttf', 50)
fntSmol = ImageFont.truetype('resources/futura-bold.ttf', 40)
fnt = ImageFont.truetype('resources/fonts/futura-bold.ttf', 50)
fntSmol = ImageFont.truetype('resources/fonts/futura-bold.ttf', 40)
borderSmol = int(border/3.5)
table = Image.open("resources/games/blackjackTable.png")
@ -31,14 +30,14 @@ class DrawBlackjack():
else:
dealerHand = self.drawHand(game["dealer hand"],False,dealerBusted,dealerBlackjack)
except:
logThis("Error drawing dealer hand (error code 1341a)")
self.bot.log("Error drawing dealer hand (error code 1341a)")
table.paste(dealerHand,(800-borderSmol,20-borderSmol),dealerHand)
for x in range(len(hands)):
key, value = list(hands.items())[x]
key = self.bot.funcs.getName(key)
#logThis("Drawing "+key+"'s hand")
key = self.bot.databaseFuncs.getName(key)
#self.bot.log("Drawing "+key+"'s hand")
userHand = self.drawHand(value["hand"],False,value["busted"],value["blackjack"])
try:
if value["split"] == 3:
@ -62,7 +61,7 @@ class DrawBlackjack():
else:
table.paste(userHand,(32-borderSmol+(384*placement[x]),680-borderSmol),userHand)
except:
logThis("Error drawing player hands (error code 1341b)")
self.bot.log("Error drawing player hands (error code 1341b)")
textWidth = fnt.getsize(key)[0]
if textWidth < 360:
@ -79,15 +78,15 @@ class DrawBlackjack():
textImage.text((32+(384*placement[x])+117-int(textWidth/2)+2,1020+2),key,fill=(0,0,0), font=fntSmol)
textImage.text((32+(384*placement[x])+117-int(textWidth/2),1015),key,fill=(255,255,255), font=fntSmol)
logThis("Saving table image")
self.bot.log("Saving table image", level = 10)
table.save("resources/games/blackjackTables/blackjackTable"+channel+".png")
return
def drawHand(self, hand, dealer, busted, blackjack):
logThis("Drawing hand "+str(hand)+", "+str(busted)+", "+str(blackjack))
fnt = ImageFont.truetype('resources/futura-bold.ttf', 200)
fnt2 = ImageFont.truetype('resources/futura-bold.ttf', 120)
self.bot.log("Drawing hand "+str(hand)+", "+str(busted)+", "+str(blackjack), level = 10)
fnt = ImageFont.truetype('resources/fonts/futura-bold.ttf', 200)
fnt2 = ImageFont.truetype('resources/fonts/futura-bold.ttf', 120)
length = len(hand)
background = Image.new("RGBA", ((border*2)+691+(125*(length-1)),(border*2)+1065),(0,0,0,0))
textImage = ImageDraw.Draw(background)
@ -114,7 +113,7 @@ class DrawBlackjack():
w, h = background.size
textHeight = 290+border
#logThis("Drawing busted/blackjack")
#self.bot.log("Drawing busted/blackjack")
if busted:
textWidth = fnt.getsize("BUSTED")[0]
textImage.text((int(w/2)-int(textWidth/2)-10,textHeight+20-10),"BUSTED",fill=(0,0,0), font=fnt)
@ -138,5 +137,5 @@ class DrawBlackjack():
textImage.text((int(w/2)-int(textWidth/2)+3,textHeight+3),"BLACKJACK",fill=(255,255,255), font=fnt2)
textImage.text((int(w/2)-int(textWidth/2),textHeight),"BLACKJACK",fill=(155,123,0), font=fnt2)
#logThis("Returning resized image")
#self.bot.log("Returning resized image")
return background.resize((int(w/3.5),int(h/3.5)),resample=Image.BILINEAR)

View File

@ -3,7 +3,6 @@ import copy
import math
from .connectFourDraw import drawConnectFour
from funcs import logThis
AIScores = {
"middle": 3,
@ -45,7 +44,7 @@ class connectFour():
return "That difficulty doesn't exist", False, False, False, False
except:
# Opponent is another player
opponent = self.bot.funcs.getID(opponent)
opponent = self.bot.databaseFuncs.getID(opponent)
if opponent != None:
difficulty = 5
diffText = ""
@ -71,7 +70,7 @@ class connectFour():
if players[0] == "Gwendolyn":
gwendoTurn = True
return "Started game against "+self.bot.funcs.getName(opponent)+diffText+". It's "+self.bot.funcs.getName(players[0])+"'s turn", True, False, False, gwendoTurn
return "Started game against "+self.bot.databaseFuncs.getName(opponent)+diffText+". It's "+self.bot.databaseFuncs.getName(players[0])+"'s turn", True, False, False, gwendoTurn
else:
return "There's already a connect 4 game going on in this channel", False, False, False, False
@ -89,7 +88,7 @@ class connectFour():
turn = (game["turn"]+1)%2
self.bot.database["connect 4 games"].update_one({"_id":channel},{"$set":{"turn":turn}})
logThis("Checking for win")
self.bot.log("Checking for win", level = 10)
won, winDirection, winCoordinates = self.isWon(board)
if won != 0:
@ -99,7 +98,7 @@ class connectFour():
self.bot.database["connect 4 games"].update_one({"_id":channel},
{"$set":{"win coordinates":winCoordinates}})
message = self.bot.funcs.getName(game["players"][won-1])+" placed a piece in column "+str(column+1)+" and won."
message = self.bot.databaseFuncs.getName(game["players"][won-1])+" placed a piece in column "+str(column+1)+" and won."
winAmount = int(game["difficulty"])**2+5
if game["players"][won-1] != "Gwendolyn":
message += " Adding "+str(winAmount)+" GwendoBucks to their account."
@ -108,12 +107,12 @@ class connectFour():
message = "It's a draw!"
else:
gameWon = False
message = self.bot.funcs.getName(game["players"][player-1])+" placed a piece in column "+str(column+1)+". It's now "+self.bot.funcs.getName(game["players"][turn])+"'s turn."
message = self.bot.databaseFuncs.getName(game["players"][player-1])+" placed a piece in column "+str(column+1)+". It's now "+self.bot.databaseFuncs.getName(game["players"][turn])+"'s turn."
gwendoTurn = False
if game["players"][turn] == "Gwendolyn":
logThis("It's Gwendolyn's turn")
self.bot.log("It's Gwendolyn's turn", level = 10)
gwendoTurn = True
self.draw.drawImage(channel)
@ -166,7 +165,7 @@ class connectFour():
if user == game["players"][turn]:
piece = turn + 1
else:
logThis("It wasn't their turn")
self.bot.log("It wasn't their turn", level = 10)
return "It's not your turn!", False, False, False, False
column = int(commands[1])-1
else:
@ -236,7 +235,7 @@ class connectFour():
# Plays as the AI
async def connectFourAI(self, channel):
logThis("Figuring out best move")
self.bot.log("Figuring out best move", level = 10)
game = self.bot.database["connect 4 games"].find_one({"_id":channel})
board = game["board"]
@ -249,7 +248,7 @@ class connectFour():
testBoard = self.placeOnBoard(testBoard,player,column)
if testBoard != None:
scores[column] = await self.minimax(testBoard,difficulty,player%2+1,player,-math.inf,math.inf,False)
logThis("Best score for column "+str(column)+" is "+str(scores[column]))
self.bot.log("Best score for column "+str(column)+" is "+str(scores[column]), level = 10)
possibleScores = scores.copy()

View File

@ -1,15 +1,14 @@
import math
from PIL import Image, ImageDraw, ImageFont
from funcs import logThis
class drawConnectFour():
def __init__(self,bot):
def __init__(self, bot):
self.bot = bot
# Draws the whole thing
def drawImage(self, channel):
logThis("Drawing connect four board")
self.bot.log("Drawing connect four board", level = 10)
game = self.bot.database["connect 4 games"].find_one({"_id":channel})
board = game["board"]
@ -34,7 +33,7 @@ class drawConnectFour():
white = (255,255,255,160)
winBarColor = (250,250,250,255)
fnt = ImageFont.truetype('resources/futura-bold.ttf', exampleCircles)
fnt = ImageFont.truetype('resources/fonts/futura-bold.ttf', exampleCircles)
boardSize = [w-(2*(border+gridBorder)),h-(2*(border+gridBorder))]
placeGridSize = [math.floor(boardSize[0]/7),math.floor(boardSize[1]/6)]
@ -44,12 +43,12 @@ class drawConnectFour():
if game["players"][0] == "Gwendolyn":
player1 = "Gwendolyn"
else:
player1 = self.bot.funcs.getName(game["players"][0])
player1 = self.bot.databaseFuncs.getName(game["players"][0])
if game["players"][1] == "Gwendolyn":
player2 = "Gwendolyn"
else:
player2 = self.bot.funcs.getName(game["players"][1])
player2 = self.bot.databaseFuncs.getName(game["players"][1])
background = Image.new("RGB", (w,h+bottomBorder),backgroundColor)

View File

@ -1,8 +1,6 @@
import asyncio
import discord
from funcs import logThis
class GameLoops():
def __init__(self,bot):
self.bot = bot
@ -16,7 +14,7 @@ class GameLoops():
for message in messages:
oldMessage = await channel.fetch_message(int(message))
logThis("Deleting old message")
self.bot.log("Deleting old message", level = 10)
await oldMessage.delete()
except:
oldMessage = ""
@ -31,22 +29,22 @@ class GameLoops():
if channelId is None:
channelId = str(ctx.channel_id)
response, showImage, deleteImage, gameDone, gwendoTurn = self.bot.connectFour.parseconnectFour(command,channelId, user)
response, showImage, deleteImage, gameDone, gwendoTurn = self.bot.games.connectFour.parseconnectFour(command,channelId, user)
if hasattr(ctx, "send"):
await ctx.send(response)
else:
await ctx.channel.send(response)
logThis(response,channelId)
self.bot.log(response, channelId, level = 10)
if showImage:
if deleteImage:
oldImage = await self.deleteMessage("connectFour"+channelId,ctx.channel)
oldImage = await ctx.channel.send(file = discord.File("resources/games/connect4Boards/board"+channelId+".png"))
if gameDone == False:
if gwendoTurn:
response, showImage, deleteImage, gameDone, gwendoTurn = await self.bot.connectFour.connectFourAI(channelId)
response, showImage, deleteImage, gameDone, gwendoTurn = await self.bot.games.connectFour.connectFourAI(channelId)
await ctx.channel.send(response)
logThis(response,channelId)
self.bot.log(response,channelId, level = 10)
if showImage:
if deleteImage:
await oldImage.delete()
@ -60,7 +58,7 @@ class GameLoops():
await oldImage.add_reaction(reaction)
except:
logThis("Image deleted before I could react to all of them")
self.bot.log("Image deleted before I could react to all of them", level = 10)
else:
with open("resources/games/oldImages/connectFour"+channelId, "w") as f:
@ -70,7 +68,7 @@ class GameLoops():
for reaction in reactions:
await oldImage.add_reaction(reaction)
except:
logThis("Image deleted before I could react to all of them")
self.bot.log("Image deleted before I could react to all of them", level = 10)
if gameDone:
game = self.bot.database["connect 4 games"].find_one({"_id":channelId})
@ -81,7 +79,7 @@ class GameLoops():
await oldImage.delete()
except:
logThis("The old image was already deleted")
self.bot.log("The old image was already deleted")
winner = game["winner"]
difficulty = int(game["difficulty"])
@ -90,19 +88,19 @@ class GameLoops():
if game["players"][winner-1].lower() != "gwendolyn":
self.bot.money.addMoney(game["players"][winner-1].lower(),reward)
self.bot.funcs.deleteGame("connect 4 games",channelId)
self.bot.databaseFuncs.deleteGame("connect 4 games",channelId)
async def runHangman(self,channel,user,command = "start", ctx = None):
try:
response, showImage, deleteImage, remainingLetters = self.bot.hangman.parseHangman(str(channel.id),user,command)
response, showImage, deleteImage, remainingLetters = self.bot.games.hangman.parseHangman(str(channel.id),user,command)
except:
logThis("Error parsing command (error code 1701)")
self.bot.log("Error parsing command (error code 1701)")
if response != "":
if ctx is None:
await channel.send(response)
else:
await ctx.send(response)
logThis(response,str(channel.id))
self.bot.log(response,str(channel.id), level = 10)
if showImage:
if deleteImage:
await self.deleteMessage("hangman"+str(channel.id),channel)
@ -127,34 +125,34 @@ class GameLoops():
emoji = chr(ord(letter)+127397)
await message.add_reaction(emoji)
except:
logThis("Image deleted before adding all reactions")
self.bot.log("Image deleted before adding all reactions", level = 10)
# Runs Hex
async def runHex(self,ctx,command,user):
channelId = ctx.channel_id
try:
response, showImage, deleteImage, gameDone, gwendoTurn = self.bot.hex.parseHex(command,str(channelId),user)
response, showImage, deleteImage, gameDone, gwendoTurn = self.bot.games.hex.parseHex(command,str(channelId),user)
except:
logThis("Error parsing command (error code 1510)")
self.bot.log("Error parsing command (error code 1510)")
await ctx.send(response)
logThis(response,str(channelId))
self.bot.log(response,str(channelId), level = 10)
if showImage:
if deleteImage:
try:
oldImage = await self.deleteMessage("hex"+str(channelId),ctx.channel)
except:
logThis("Error deleting old image (error code 1501)")
self.bot.log("Error deleting old image (error code 1501)")
oldImage = await ctx.channel.send(file = discord.File("resources/games/hexBoards/board"+str(channelId)+".png"))
if gwendoTurn and not gameDone:
try:
response, showImage, deleteImage, gameDone, gwendoTurn = self.bot.hex.hexAI(str(channelId))
response, showImage, deleteImage, gameDone, gwendoTurn = self.bot.games.hex.hexAI(str(channelId))
except:
response, showImage, deleteImage, gameDone, gwendoTurn = "An AI error ocurred",False,False,False,False
logThis("AI error (error code 1520)")
self.bot.log("AI error (error code 1520)")
await ctx.channel.send(response)
logThis(response,str(channelId))
self.bot.log(response,str(channelId), level = 10)
if showImage:
if deleteImage:
await oldImage.delete()
@ -171,4 +169,4 @@ class GameLoops():
winnings = game["difficulty"]*10
self.bot.money.addMoney(game["players"][winner-1].lower(),winnings)
self.bot.funcs.deleteGame("hex games",str(channelId))
self.bot.databaseFuncs.deleteGame("hex games",str(channelId))

View File

@ -10,10 +10,10 @@ class Games():
def __init__(self, bot):
self.bot = bot
bot.invest = Invest(bot)
bot.trivia = Trivia(bot)
bot.blackjack = Blackjack(bot)
bot.connectFour = connectFour(bot)
bot.gameLoops = GameLoops(bot)
bot.hangman = Hangman(bot)
bot.hex = HexGame(bot)
self.invest = Invest(bot)
self.trivia = Trivia(bot)
self.blackjack = Blackjack(bot)
self.connectFour = connectFour(bot)
self.gameLoops = GameLoops(bot)
self.hangman = Hangman(bot)
self.hex = HexGame(bot)

View File

@ -1,7 +1,6 @@
import json, urllib, datetime, string
from .hangmanDraw import DrawHangman
from funcs import logThis
apiUrl = "https://api.wordnik.com/v4/words.json/randomWords?hasDictionaryDef=true&minCorpusCount=5000&maxCorpusCount=-1&minDictionaryCount=1&maxDictionaryCount=-1&minLength=3&maxLength=11&limit=1&api_key="
@ -19,7 +18,7 @@ class Hangman():
while "-" in word or "." in word:
with urllib.request.urlopen(apiUrl+apiKey) as p:
word = list(json.load(p)[0]["word"].upper())
logThis("Found the word \""+"".join(word)+"\"")
self.bot.log("Found the word \""+"".join(word)+"\"", level = 10)
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}
@ -30,8 +29,8 @@ class Hangman():
try:
self.draw.drawImage(channel)
except:
logThis("Error drawing image (error code 1710)")
return f"{self.bot.funcs.getName(user)} started game of hangman.", True, False, remainingLetters
self.bot.log("Error drawing image (error code 1710)")
return f"{self.bot.databaseFuncs.getName(user)} started game of hangman.", True, False, remainingLetters
else:
return "There's already a Hangman game going on in the channel", False, False, []
@ -74,7 +73,7 @@ class Hangman():
try:
self.draw.drawImage(channel)
except:
logThis("Error drawing image (error code 1710)")
self.bot.log("Error drawing image (error code 1710)")
if game["misses"] == 6:
self.hangmanStop(channel)
@ -99,7 +98,7 @@ class Hangman():
try:
return self.hangmanStart(channel,user)
except:
logThis("Error starting game (error code 1730)")
self.bot.log("Error starting game (error code 1730)")
elif command == "stop":
return self.hangmanStop(channel)
elif command.startswith("guess "):
@ -107,6 +106,6 @@ class Hangman():
try:
return self.hangmanGuess(channel,user,guess)
except:
logThis("Error in guessing (Error Code 1720)")
self.bot.log("Error in guessing (Error Code 1720)")
else:
return "I didn't understand that", False, False, []

View File

@ -1,7 +1,6 @@
import math, random
from PIL import ImageDraw, Image, ImageFont
from funcs import logThis
circleDegrees = 360
circleSize = 120
@ -23,8 +22,8 @@ letterLineDistance = 30
gallowx, gallowy = 360,600
goldenRatio = 1-(1 / ((1 + 5 ** 0.5) / 2))
fnt = ImageFont.truetype('resources/comic-sans-bold.ttf', letterSize)
smolfnt = ImageFont.truetype('resources/comic-sans-bold.ttf', textSize)
fnt = ImageFont.truetype('resources/fonts/comic-sans-bold.ttf', letterSize)
smolfnt = ImageFont.truetype('resources/fonts/comic-sans-bold.ttf', textSize)
backgroundColor = (255,255,255,255)
@ -213,7 +212,7 @@ class DrawHangman():
return background
def drawImage(self,channel):
logThis("Drawing hangman image",channel)
self.bot.log("Drawing hangman image", channel, level = 10)
game = self.bot.database["hangman games"].find_one({"_id":channel})
random.seed(game["game ID"])
@ -222,24 +221,24 @@ class DrawHangman():
try:
gallow = self.drawGallows()
except:
logThis("Error drawing gallows (error code 1711)")
self.bot.log("Error drawing gallows (error code 1711)")
try:
man = self.drawMan(game["misses"])
except:
logThis("Error drawing stick figure (error code 1712)")
self.bot.log("Error drawing stick figure (error code 1712)")
random.seed(game["game ID"])
try:
letterLines = self.drawLetterLines(game["word"],game["guessed"],game["misses"])
except:
logThis("error drawing letter lines (error code 1713)")
self.bot.log("error drawing letter lines (error code 1713)")
random.seed(game["game ID"])
try:
misses = self.drawMisses(game["guessed letters"],game["word"])
except:
logThis("Error drawing misses (error code 1714)")
self.bot.log("Error drawing misses (error code 1714)")
background.paste(gallow,(100,100),gallow)
background.paste(man,(300,210),man)

View File

@ -3,7 +3,6 @@ import copy
import math
from .hexDraw import DrawHex
from funcs import logThis
BOARDWIDTH = 11
ALL_POSITIONS = [(i,j) for i in range(11) for j in range(11)]
@ -29,7 +28,7 @@ class HexGame():
# Starting a game
if len(commands) == 1: # if the commands is "!hex start", the opponent is Gwendolyn at difficulty 2
commands.append("2")
logThis("Starting a hex game with hexStart(). "+str(user)+" challenged "+commands[1])
self.bot.log("Starting a hex game with hexStart(). "+str(user)+" challenged "+commands[1], level = 10)
return self.hexStart(channel,user,commands[1]) # commands[1] is the opponent
# If using a command with no game, return error
@ -60,7 +59,7 @@ class HexGame():
if user in players:
opponent = (players.index(user) + 1) % 2
self.bot.database["hex games"].update_one({"_id":channel},{"$set":{"winner":opponent + 1}})
return "{} surrendered. That means {} won! Adding 30 Gwendobucks to their account.".format(self.bot.funcs.getName(user),self.bot.funcs.getName(players[opponent])), False, False, True, False
return "{} surrendered. That means {} won! Adding 30 Gwendobucks to their account.".format(self.bot.databaseFuncs.getName(user),self.bot.databaseFuncs.getName(players[opponent])), False, False, True, False
else:
return "You can't surrender when you're not a player.", False, False, False, False
@ -99,7 +98,7 @@ class HexGame():
int(opponent)
return "That difficulty doesn't exist", False, False, False, False
except:
opponent = self.bot.funcs.getID(opponent)
opponent = self.bot.databaseFuncs.getID(opponent)
if opponent == None:
return "I can't find that user", False, False, False, False
else:
@ -123,7 +122,7 @@ class HexGame():
gwendoTurn = True if players[0] == "Gwendolyn" else False
showImage = True
return "Started Hex game against "+self.bot.funcs.getName(opponent)+ diffText+". It's "+self.bot.funcs.getName(players[0])+"'s turn", showImage, False, False, gwendoTurn
return "Started Hex game against "+self.bot.databaseFuncs.getName(opponent)+ diffText+". It's "+self.bot.databaseFuncs.getName(players[0])+"'s turn", showImage, False, False, gwendoTurn
else:
return "There's already a hex game going on in this channel", False, False, False, False
@ -143,7 +142,7 @@ class HexGame():
if player == turn:
board = game["board"]
logThis("Placing a piece on the board with placeHex()")
self.bot.log("Placing a piece on the board with placeHex()", level = 10)
# Places on board
board = self.placeOnHexBoard(board,player,position)
@ -154,17 +153,17 @@ class HexGame():
self.bot.database["hex games"].update_one({"_id":channel},{"$set":{"turn":turn}})
# Checking for a win
logThis("Checking for win")
self.bot.log("Checking for win", level = 10)
winner = self.evaluateBoard(game["board"])[1]
if winner == 0: # Continue with the game.
gameWon = False
message = self.bot.funcs.getName(game["players"][player-1])+" placed at "+position.upper()+". It's now "+self.bot.funcs.getName(game["players"][turn-1])+"'s turn."# The score is "+str(score)
message = self.bot.databaseFuncs.getName(game["players"][player-1])+" placed at "+position.upper()+". It's now "+self.bot.databaseFuncs.getName(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}})
message = self.bot.funcs.getName(game["players"][player-1])+" placed at "+position.upper()+" and won!"
message = self.bot.databaseFuncs.getName(game["players"][player-1])+" placed at "+position.upper()+" and won!"
if game["players"][winner-1] != "Gwendolyn":
winAmount = game["difficulty"]*10
message += " Adding "+str(winAmount)+" GwendoBucks to their account."
@ -175,7 +174,7 @@ class HexGame():
# Is it now Gwendolyn's turn?
gwendoTurn = False
if game["players"][turn-1] == "Gwendolyn":
logThis("It's Gwendolyn's turn")
self.bot.log("It's Gwendolyn's turn", level = 10)
gwendoTurn = True
# Update the board
@ -188,10 +187,10 @@ class HexGame():
return message, False, False, False, False
else:
# Move out of turn
message = "It isn't your turn, it is "+self.bot.funcs.getName(game["players"][turn-1])+"'s turn."
message = "It isn't your turn, it is "+self.bot.databaseFuncs.getName(game["players"][turn-1])+"'s turn."
return message, False, False, False, False
else:
message = "You can't place when you're not in the game. The game's players are: "+self.bot.funcs.getName(game["players"][0])+" and "+self.bot.funcs.getName(game["players"][1])+"."
message = "You can't place when you're not in the game. The game's players are: "+self.bot.databaseFuncs.getName(game["players"][0])+" and "+self.bot.databaseFuncs.getName(game["players"][1])+"."
return message, False, False, False, False
else:
return "There's no game in this channel", False, False, False, False
@ -205,17 +204,17 @@ class HexGame():
column = ord(position[0]) - 97 # ord() translates from letter to number
row = int(position[1:]) - 1
if column not in range(BOARDWIDTH) or row not in range(BOARDWIDTH):
logThis("Position out of bounds (error code 1533)")
self.bot.log("Position out of bounds (error code 1533)")
return "Error. That position is out of bounds."
except:
logThis("Invalid position (error code 1531)")
self.bot.log("Invalid position (error code 1531)")
return "Error. The position should be a letter followed by a number, e.g. \"e2\"."
# Place at the position
if board[row][column] == 0:
board[row][column] = player
return board
else:
logThis("Cannot place on existing piece (error code 1532)")
self.bot.log("Cannot place on existing piece (error code 1532)")
return "Error. You must place on an empty space."
# After your move, you have the option to undo get your turn back #TimeTravel
@ -227,7 +226,7 @@ class HexGame():
turn = game["turn"]
# You can only undo after your turn, which is the opponent's turn.
if user == game["players"][(turn % 2)]: # If it's not your turn
logThis("Undoing {}'s last move".format(self.bot.funcs.getName(user)))
self.bot.log("Undoing {}'s last move".format(self.bot.databaseFuncs.getName(user)), level = 10)
lastMove = game["gameHistory"].pop()
game["board"][lastMove[0]][lastMove[1]] = 0
@ -252,7 +251,7 @@ class HexGame():
# Plays as the AI
def hexAI(self, channel):
logThis("Figuring out best move")
self.bot.log("Figuring out best move", level = 10)
game = self.bot.database["hex games"].find_one({"_id":channel})
board = game["board"]
@ -286,7 +285,7 @@ class HexGame():
if evaluateBoard(testBoard)[0] != current_score: # only think about a move if it improves the score (it's impossible to get worse)
# Testing a move and evaluating it
judgements[i] = minimaxHex(testBoard,difficulty,-math.inf,math.inf,GwenColor==2)
logThis("Best score for place {} is {}".format((i // BOARDWIDTH,i % BOARDWIDTH),judgements[i]))
self.bot.log("Best score for place {} is {}".format((i // BOARDWIDTH,i % BOARDWIDTH),judgements[i]))
bestScore = max(judgements) if (GwenColor == 1) else min(judgements) # this line has an error
indices = [i for i, x in enumerate(judgements) if x == bestScore] # which moves got that score?
@ -294,7 +293,7 @@ class HexGame():
chosenMove = (i // BOARDWIDTH , i % BOARDWIDTH)
"""
placement = "abcdefghijk"[chosenMove[1]]+str(chosenMove[0]+1)
logThis("ChosenMove is {} at {}".format(chosenMove,placement))
self.bot.log("ChosenMove is {} at {}".format(chosenMove,placement), level = 10)
return self.placeHex(channel,placement, "Gwendolyn")
@ -323,12 +322,12 @@ class HexGame():
Distance[v] = min(Distance[v], new_dist)
# After a hex has been visited, this is noted
visited.add(u)
#logThis("Distance from player {}'s start to {} is {}".format(player,u,Distance[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:
logThis("For some reason, no path to the goal was found. ")
self.bot.log("For some reason, no path to the goal was found. ", level = 10)
if scores[player] == 0:
winner = player
break # We don't need to check the other player's score, if player1 won.
@ -344,7 +343,7 @@ class HexGame():
if maximizingPlayer: # red player predicts next move
maxEval = -math.inf
possiblePlaces = [i for i,v in enumerate(sum(board,[])) if v == 0]
#logThis("Judging a red move at depth {}".format(depth))
#self.bot.log("Judging a red move at depth {}".format(depth))
for i in possiblePlaces:
testBoard = copy.deepcopy(board)
testBoard[i // BOARDWIDTH][i % BOARDWIDTH] = 1 # because maximizingPlayer is Red which is number 1
@ -352,13 +351,13 @@ class HexGame():
maxEval = max(maxEval, evaluation)
alpha = max(alpha, evaluation)
if beta <= alpha:
#logThis("Just pruned something!")
#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]
#logThis("Judging a blue move at depth {}".format(depth))
#self.bot.log("Judging a blue move at depth {}".format(depth))
for i in possiblePlaces:
testBoard = copy.deepcopy(board)
testBoard[i // BOARDWIDTH][i % BOARDWIDTH] = 2 # because minimizingPlayer is Blue which is number 2
@ -366,7 +365,7 @@ class HexGame():
minEval = min(minEval, evaluation)
beta = min(beta, evaluation)
if beta <= alpha:
#logThis("Just pruned something!")
#self.bot.log("Just pruned something!")
break
return minEval

View File

@ -1,7 +1,6 @@
import math
from PIL import Image, ImageDraw, ImageFont
from funcs import logThis
# Defining all the variables
CANVAS_WIDTH = 2400
@ -13,7 +12,7 @@ HEXAGONWIDTH = math.sqrt(3) * SIDELENGTH # the whole width of one hexagon
HEXAGONHEIGHT = 1.5 * SIDELENGTH # not really the entire height, but the height difference between two layers
FONTSIZE = 45
TEXTCOLOR = (0,0,0)
fnt = ImageFont.truetype('resources/futura-bold.ttf', FONTSIZE)
fnt = ImageFont.truetype('resources/fonts/futura-bold.ttf', FONTSIZE)
LINETHICKNESS = 15
HEXTHICKNESS = 6 # This is half the width of the background lining between every hex
@ -29,7 +28,7 @@ COLX_THICKNESS = COLHEXTHICKNESS * math.cos(math.pi/6)
COLY_THICKNESS = COLHEXTHICKNESS * math.sin(math.pi/6)
# The Name display things:
NAMESIZE = 60
NAME_fnt = ImageFont.truetype('resources/futura-bold.ttf', NAMESIZE)
NAME_fnt = ImageFont.truetype('resources/fonts/futura-bold.ttf', NAMESIZE)
X_NAME = {1:175, 2:CANVAS_WIDTH-100}
Y_NAME = {1:CANVAS_HEIGHT-150, 2:150}
NAMEHEXPADDING = 90
@ -41,7 +40,7 @@ class DrawHex():
self.bot = bot
def drawBoard(self, channel):
logThis("Drawing empty Hex board")
self.bot.log("Drawing empty Hex board")
# Creates the empty image
im = Image.new('RGB', size=(CANVAS_WIDTH, CANVAS_HEIGHT),color = BACKGROUND_COLOR)
@ -99,7 +98,7 @@ class DrawHex():
game = self.bot.database["hex games"].find_one({"_id":channel})
for p in [1,2]:
playername = self.bot.funcs.getName(game["players"][p-1])
playername = self.bot.databaseFuncs.getName(game["players"][p-1])
# Draw name
x = X_NAME[p]
x -= NAME_fnt.getsize(playername)[0] if p==2 else 0 # player2's name is right-aligned
@ -123,7 +122,7 @@ class DrawHex():
def drawHexPlacement(self, channel,player,position):
FILEPATH = "resources/games/hexBoards/board"+channel+".png"
logThis("Drawing a newly placed hex. Filepath: "+FILEPATH)
self.bot.log("Drawing a newly placed hex. Filepath: "+FILEPATH)
# Translates position
# We don't need to error-check, because the position is already checked in placeOnHexBoard()
@ -151,7 +150,7 @@ class DrawHex():
# Save
im.save(FILEPATH)
except:
logThis("Error drawing new hex on board (error code 1541")
self.bot.log("Error drawing new hex on board (error code 1541")
def drawSwap(self, channel):
FILEPATH = "resources/games/hexBoards/board"+channel+".png"
@ -163,7 +162,7 @@ class DrawHex():
# Write player names and color
for p in [1,2]:
playername = self.bot.funcs.getName(game["players"][p%2])
playername = self.bot.databaseFuncs.getName(game["players"][p%2])
x = X_NAME[p]
x -= NAME_fnt.getsize(playername)[0] if p==2 else 0 # player2's name is right-aligned
@ -183,4 +182,4 @@ class DrawHex():
# Save
im.save(FILEPATH)
except:
logThis("Error drawing swap (error code 1542)")
self.bot.log("Error drawing swap (error code 1542)")

View File

@ -1,5 +1,5 @@
class Invest():
def __init__(self,bot):
def __init__(self, bot):
self.bot = bot
def getPrice(self, symbol : str):
@ -13,9 +13,9 @@ class Invest():
userInvestments = self.bot.database["investments"].find_one({"_id":user})
if userInvestments in [None,{}]:
return f"{self.bot.funcs.getName(user)} does not have a stock portfolio."
return f"{self.bot.databaseFuncs.getName(user)} does not have a stock portfolio."
else:
portfolio = f"**Stock portfolio for {self.bot.funcs.getName(user)}**"
portfolio = f"**Stock portfolio for {self.bot.databaseFuncs.getName(user)}**"
for key, value in list(userInvestments["investments"].items()):
purchaseValue = value["purchased for"]
@ -60,7 +60,7 @@ class Invest():
newUser = {"_id":user,"investments":{stock : {"purchased" : buyAmount, "value at purchase" : stockPrice, "purchased for" : buyAmount}}}
self.bot.database["investments"].insert_one(newUser)
return f"{self.bot.funcs.getName(user)} bought {buyAmount} GwendoBucks worth of {stock} stock"
return f"{self.bot.databaseFuncs.getName(user)} bought {buyAmount} GwendoBucks worth of {stock} stock"
else:
return f"{stock} is not traded on the american market."
else:
@ -95,7 +95,7 @@ class Invest():
self.bot.database["investments"].update_one({"_id":user},
{"$unset":{"investments."+stock:""}})
return f"{self.bot.funcs.getName(user)} sold {sellAmount} GwendoBucks worth of {stock} stock"
return f"{self.bot.databaseFuncs.getName(user)} sold {sellAmount} GwendoBucks worth of {stock} stock"
else:
return f"You don't have enough {stock} stocks to do that"
else:

View File

@ -1,5 +1,3 @@
from funcs import logThis
class Money():
def __init__(self, bot):
@ -8,7 +6,7 @@ class Money():
# Returns the account balance for a user
def checkBalance(self, user):
logThis("checking "+user+"'s account balance")
self.bot.log("checking "+user+"'s account balance", level = 10)
userData = self.database["users"].find_one({"_id":user})
@ -18,19 +16,19 @@ class Money():
# Adds money to the account of a user
def addMoney(self,user,amount):
logThis("adding "+str(amount)+" to "+user+"'s account")
self.bot.log("adding "+str(amount)+" to "+user+"'s account", level = 10)
userData = self.database["users"].find_one({"_id":user})
if userData != None:
self.database["users"].update_one({"_id":user},{"$inc":{"money":amount}})
else:
self.database["users"].insert_one({"_id":user,"user name":self.bot.funcs.getName(user),"money":amount})
self.database["users"].insert_one({"_id":user,"user name":self.bot.databaseFuncs.getName(user),"money":amount})
# Transfers money from one user to another
def giveMoney(self,user,targetUser,amount):
userData = self.database["users"].find_one({"_id":user})
targetUser = self.bot.funcs.getID(targetUser)
targetUser = self.bot.databaseFuncs.getID(targetUser)
if amount > 0:
if targetUser != None:
@ -38,16 +36,16 @@ class Money():
if userData["money"] >= amount:
self.addMoney(user,-1 * amount)
self.addMoney(targetUser,amount)
return "Transferred "+str(amount)+" GwendoBucks to "+self.bot.funcs.getName(targetUser)
return "Transferred "+str(amount)+" GwendoBucks to "+self.bot.databaseFuncs.getName(targetUser)
else:
logThis("They didn't have enough GwendoBucks (error code 1223b)")
self.bot.log("They didn't have enough GwendoBucks (error code 1223b)")
return "You don't have that many GwendoBucks (error code 1223b)"
else:
logThis("They didn't have enough GwendoBucks (error code 1223a)")
self.bot.log("They didn't have enough GwendoBucks (error code 1223a)")
return "You don't have that many GwendoBucks (error code 1223a)"
else:
logThis("They weren't in the system")
self.bot.log("They weren't in the system")
return "The target doesn't exist"
else:
logThis("They tried to steal")
self.bot.log("They tried to steal")
return "Yeah, no. You can't do that"

View File

@ -2,8 +2,6 @@ import json
import urllib
import random
from funcs import logThis
class Trivia():
def __init__(self, bot):
self.bot = bot
@ -13,13 +11,13 @@ class Trivia():
def triviaStart(self, channel : str):
question = self.bot.database["trivia questions"].find_one({"_id":channel})
logThis("Trying to find a trivia question for "+channel)
self.bot.log("Trying to find a trivia question for "+channel)
if question == None:
with urllib.request.urlopen("https://opentdb.com/api.php?amount=10&type=multiple") as response:
data = json.loads(response.read())
logThis("Found the question \""+data["results"][0]["question"]+"\"")
self.bot.log("Found the question \""+data["results"][0]["question"]+"\"")
answers = data["results"][0]["incorrect_answers"]
answers.append(data["results"][0]["correct_answer"])
random.shuffle(answers)
@ -43,7 +41,7 @@ class Trivia():
return question, answers, correctAnswer
else:
logThis("There was already a trivia question for that channel (error code 1106)")
self.bot.log("There was already a trivia question for that channel (error code 1106)")
return "There's already a trivia question going on. Try again in like, a minute (error code 1106)", "", ""
# Lets players answer a trivia question
@ -53,19 +51,19 @@ class Trivia():
if command in ["a","b","c","d"]:
if question != None:
if user not in question["players"]:
logThis(user+" answered the question in "+channel)
self.bot.log(user+" answered the question in "+channel)
self.bot.database["trivia questions"].update_one({"_id":channel},{"$set":{"players."+user : command}})
return "Locked in "+user+"'s answer"
else:
logThis(user+" has already answered this question (error code 1105)")
self.bot.log(user+" has already answered this question (error code 1105)")
return user+" has already answered this question (error code 1105)"
else:
logThis("There's no question right now (error code 1104)")
self.bot.log("There's no question right now (error code 1104)")
return "There's no question right now (error code 1104)"
else:
logThis("I didn't quite understand that (error code 1103)")
self.bot.log("I didn't quite understand that (error code 1103)")
return "I didn't quite understand that (error code 1103)"
@ -73,7 +71,7 @@ class Trivia():
def triviaCountPoints(self, channel : str):
question = self.bot.database["trivia questions"].find_one({"_id":channel})
logThis("Counting points for question in "+channel)
self.bot.log("Counting points for question in "+channel)
if question != None:
for player, answer in question["players"].items():
@ -82,6 +80,6 @@ class Trivia():
else:
logThis("Couldn't find the question (error code 1102)")
self.bot.log("Couldn't find the question (error code 1102)")
return None