Even more converting to slash commands

This commit is contained in:
NikolajDanger
2021-03-29 17:01:01 +02:00
parent 232f97d0c8
commit e8c7fb95e5
22 changed files with 487 additions and 191 deletions

View File

@ -481,8 +481,8 @@ class Blackjack():
self.bot.database["blackjack games"].update_one({"_id":channel},
{"$set":{"user hands."+user:newHand}})
logThis(self.bot.funcs.getName(user)+" entered the game")
return self.bot.funcs.getName(user)+" entered the game"
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}"
else:
logThis(user+" doesn't have enough GwendoBucks")
return "You don't have enough GwendoBucks to place that bet"
@ -711,9 +711,10 @@ class Blackjack():
blackjackMinCards = 50
blackjackDecks = 4
channel = ctx.message.channel.id
channel = ctx.channel_id
# Starts the game
if content == "":
await ctx.send("Staring a new game of blackjack")
cardsLeft = 0
cards = self.bot.database["blackjack cards"].find_one({"_id":str(channel)})
if cards != None:
@ -723,14 +724,14 @@ class Blackjack():
if cardsLeft < blackjackMinCards:
self.blackjackShuffle(blackjackDecks,str(channel))
logThis("Shuffling the blackjack deck...",str(channel))
await ctx.send("Shuffling the deck...")
await ctx.channel.send("Shuffling the deck...")
new_message = self.blackjackStart(str(channel))
if new_message == "started":
new_message = "Blackjack game started. Use \"!blackjack bet [amount]\" to enter the game within the next 30 seconds."
await ctx.send(new_message)
oldImage = await ctx.send(file = discord.File("resources/games/blackjackTables/blackjackTable"+str(channel)+".png"))
await ctx.channel.send(new_message)
oldImage = await ctx.channel.send(file = discord.File("resources/games/blackjackTables/blackjackTable"+str(channel)+".png"))
with open("resources/games/oldImages/blackjack"+str(channel), "w") as f:
f.write(str(oldImage.id))
@ -743,45 +744,45 @@ class Blackjack():
if len(game["user hands"]) == 0:
gamedone = True
await ctx.send("No one entered the game. Ending the game.")
await ctx.channel.send("No one entered the game. Ending the game.")
gameID = game["gameID"]
# Loop of game rounds
if gamedone == False:
logThis("!blackjack calling self.blackjackLoop()",str(channel))
await self.blackjackLoop(ctx.message.channel,1,gameID)
await self.blackjackLoop(ctx.channel,1,gameID)
else:
new_message = self.blackjackFinish(str(channel))
await ctx.send(new_message)
await ctx.channel.send(new_message)
else:
await ctx.send(new_message)
await ctx.channel.send(new_message)
# Entering game and placing bet
elif content.startswith("bet"):
commands = content.split(" ")
amount = int(commands[1])
response = self.blackjackPlayerDrawHand(str(channel),"#"+str(ctx.message.author.id),amount)
response = self.blackjackPlayerDrawHand(str(channel),"#"+str(ctx.author.id),amount)
await ctx.send(response)
# Hitting
elif content.startswith("hit"):
if content == "hit":
response = self.blackjackHit(str(channel),"#"+str(ctx.message.author.id))
response = self.blackjackHit(str(channel),"#"+str(ctx.author.id))
else:
commands = content.split(" ")
try:
handNumber = int(commands[1])
except:
handNumber = 0
response = self.blackjackHit(str(channel),"#"+str(ctx.message.author.id),handNumber)
response = self.blackjackHit(str(channel),"#"+str(ctx.author.id),handNumber)
if response.startswith("accept"):
await ctx.message.add_reaction("👍")
await ctx.send(f"{ctx.author.display_name} hit")
#try:
if response[6] == "T":
gameID = self.bot.database["blackjack games"].find_one({"_id":str(channel)})["gameID"]
logThis("Hit calling self.blackjackLoop()",str(channel))
await self.blackjackLoop(ctx.message.channel,int(response[7:])+1,gameID)
await self.blackjackLoop(ctx.channel,int(response[7:])+1,gameID)
#except:
# logThis("Something fucked up (error code 1320)",str(channel))
else:
@ -791,22 +792,22 @@ class Blackjack():
# Standing
elif content.startswith("stand"):
if content == "hit":
response = self.blackjackStand(str(channel),"#"+str(ctx.message.author.id))
response = self.blackjackStand(str(channel),"#"+str(ctx.author.id))
else:
commands = content.split(" ")
try:
handNumber = int(commands[1])
except:
handNumber = 0
response = self.blackjackStand(str(channel),"#"+str(ctx.message.author.id),handNumber)
response = self.blackjackStand(str(channel),"#"+str(ctx.author.id),handNumber)
if response.startswith("accept"):
await ctx.message.add_reaction("👍")
await ctx.send(f"{ctx.author.display_name} is standing")
#try:
if response[6] == "T":
gameID = self.bot.database["blackjack games"].find_one({"_id":str(channel)})["gameID"]
logThis("Stand calling self.blackjackLoop()",str(channel))
await self.blackjackLoop(ctx.message.channel,int(response[7:])+1,gameID)
await self.blackjackLoop(ctx.channel,int(response[7:])+1,gameID)
#except:
# logThis("Something fucked up (error code 1320)",str(channel))
else:
@ -819,7 +820,7 @@ class Blackjack():
handNumber = int(commands[1])
except:
handNumber = 0
response, roundDone = self.blackjackDouble(str(channel),"#"+str(ctx.message.author.id),handNumber)
response, roundDone = self.blackjackDouble(str(channel),"#"+str(ctx.author.id),handNumber)
await ctx.send(response)
@ -827,7 +828,7 @@ class Blackjack():
if roundDone[0] == "T":
gameID = self.bot.database["blackjack games"].find_one({"_id":str(channel)})["gameID"]
logThis("Double calling self.blackjackLoop()",str(channel))
await self.blackjackLoop(ctx.message.channel,int(roundDone[1:])+1,gameID)
await self.blackjackLoop(ctx.channel,int(roundDone[1:])+1,gameID)
except:
logThis("Something fucked up (error code 1320)",str(channel))
@ -838,7 +839,7 @@ class Blackjack():
handNumber = int(commands[1])
except:
handNumber = 0
response, roundDone = self.blackjackSplit(str(channel),"#"+str(ctx.message.author.id),handNumber)
response, roundDone = self.blackjackSplit(str(channel),"#"+str(ctx.author.id),handNumber)
await ctx.send(response)
@ -846,7 +847,7 @@ class Blackjack():
if roundDone[0] == "T":
gameID = self.bot.database["blackjack games"].find_one({"_id":str(channel)})["gameID"]
logThis("Split calling self.blackjackLoop()",str(channel))
await self.blackjackLoop(ctx.message.channel,int(roundDone[1:])+1,gameID)
await self.blackjackLoop(ctx.channel,int(roundDone[1:])+1,gameID)
except:
logThis("Something fucked up (error code 1320)")
@ -857,7 +858,7 @@ class Blackjack():
hilo = str(data["hilo"])
else:
hilo = "0"
await ctx.send(hilo)
await ctx.send(hilo, hidden=True)
# Shuffles the blackjack deck
elif content.startswith("shuffle"):
@ -874,7 +875,7 @@ class Blackjack():
cardsLeft = len(cards["cards"])
decksLeft = round(cardsLeft/52,1)
await ctx.send(str(cardsLeft)+" cards, "+str(decksLeft)+" decks")
await ctx.send(str(cardsLeft)+" cards, "+str(decksLeft)+" decks", hidden=True)
else:
logThis("Not a command (error code 1301)")

View File

@ -2,7 +2,7 @@ import random
import copy
import math
from .fourInARowDraw import DrawFourInARow
from .connectFourDraw import drawConnectFour
from funcs import logThis
AIScores = {
@ -20,14 +20,14 @@ rowCount = 6
columnCount = 7
easy = True
class FourInARow():
class connectFour():
def __init__(self,bot):
self.bot = bot
self.draw = DrawFourInARow(bot)
self.draw = drawConnectFour(bot)
# Starts the game
def fourInARowStart(self, channel, user, opponent):
game = self.bot.database["4 in a row games"].find_one({"_id":channel})
def connectFourStart(self, channel, user, opponent):
game = self.bot.database["connect 4 games"].find_one({"_id":channel})
if game == None:
@ -62,7 +62,7 @@ class FourInARow():
newGame = {"_id":channel,"board": board,"winner":0,"win direction":"",
"win coordinates":[0,0],"players":players,"turn":0,"difficulty":difficulty}
self.bot.database["4 in a row games"].insert_one(newGame)
self.bot.database["connect 4 games"].insert_one(newGame)
self.draw.drawImage(channel)
@ -73,11 +73,11 @@ class FourInARow():
return "Started game against "+self.bot.funcs.getName(opponent)+diffText+". It's "+self.bot.funcs.getName(players[0])+"'s turn", True, False, False, gwendoTurn
else:
return "There's already a 4 in a row game going on in this channel", False, False, False, False
return "There's already a connect 4 game going on in this channel", False, False, False, False
# Places a piece at the lowest available point in a specific column
def placePiece(self, channel : str,player : int,column : int):
game = self.bot.database["4 in a row games"].find_one({"_id":channel})
game = self.bot.database["connect 4 games"].find_one({"_id":channel})
if game != None:
board = game["board"]
@ -85,18 +85,18 @@ class FourInARow():
board = self.placeOnBoard(board,player,column)
if board != None:
self.bot.database["4 in a row games"].update_one({"_id":channel},{"$set":{"board":board}})
self.bot.database["connect 4 games"].update_one({"_id":channel},{"$set":{"board":board}})
turn = (game["turn"]+1)%2
self.bot.database["4 in a row games"].update_one({"_id":channel},{"$set":{"turn":turn}})
self.bot.database["connect 4 games"].update_one({"_id":channel},{"$set":{"turn":turn}})
logThis("Checking for win")
won, winDirection, winCoordinates = self.isWon(board)
if won != 0:
gameWon = True
self.bot.database["4 in a row games"].update_one({"_id":channel},{"$set":{"winner":won}})
self.bot.database["4 in a row games"].update_one({"_id":channel},{"$set":{"win direction":winDirection}})
self.bot.database["4 in a row games"].update_one({"_id":channel},
self.bot.database["connect 4 games"].update_one({"_id":channel},{"$set":{"winner":won}})
self.bot.database["connect 4 games"].update_one({"_id":channel},{"$set":{"win direction":winDirection}})
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."
@ -139,19 +139,19 @@ class FourInARow():
return board
# Parses command
def parseFourInARow(self, command, channel, user):
def parseconnectFour(self, command, channel, user):
commands = command.split()
if command == "" or command == " ":
return "I didn't get that. Use \"!fourinarow start [opponent]\" to start a game. To play against the computer, use difficulty 1 through 5 as the [opponent].", False, False, False, False
return "I didn't get that. Use \"!connectFour start [opponent]\" to start a game. To play against the computer, use difficulty 1 through 5 as the [opponent].", False, False, False, False
elif commands[0] == "start":
# Starting a game
if len(commands) == 1: # if the commands is "!fourinarow start", the opponent is Gwendolyn
if len(commands) == 1: # if the commands is "!connectFour start", the opponent is Gwendolyn
commands.append("3")
return self.fourInARowStart(channel,user,commands[1]) # commands[1] is the opponent
return self.connectFourStart(channel,user,commands[1]) # commands[1] is the opponent
# Stopping the game
elif commands[0] == "stop":
game = self.bot.database["4 in a row games"].find_one({"_id":channel})
game = self.bot.database["connect 4 games"].find_one({"_id":channel})
if user in game["players"]:
return "Ending game.", False, False, True, False
@ -160,12 +160,21 @@ class FourInARow():
# Placing manually
elif commands[0] == "place":
try:
return self.placePiece(channel,int(commands[1]),int(commands[2])-1)
except:
return "I didn't get that. To place a piece use \"!fourinarow place [player number] [column]\" or press the corresponding message-reaction beneath the board.", False, False, False, False
if len(commands) == 2:
game = self.bot.database["connect 4 games"].find_one({"_id":channel})
turn = game["turn"]
if user == game["players"][turn]:
piece = turn + 1
else:
logThis("It wasn't their turn")
return "It's not your turn!", False, False, False, False
column = int(commands[1])-1
else:
column = int(commands[2])-1
piece = int(commands[1])
return self.placePiece(channel, piece, column)
else:
return "I didn't get that. Use \"!fourinarow start [opponent]\" to start a game. To play against the computer, use difficulty 1 through 5 as the [opponent].", False, False, False, False
return "I didn't get that. Use \"!connectFour start [opponent]\" to start a game. To play against the computer, use difficulty 1 through 5 as the [opponent].", False, False, False, False
# Checks if someone has won the game and returns the winner
def isWon(self, board):
@ -226,9 +235,9 @@ class FourInARow():
return won, winDirection, winCoordinates
# Plays as the AI
async def fourInARowAI(self, channel):
async def connectFourAI(self, channel):
logThis("Figuring out best move")
game = self.bot.database["4 in a row games"].find_one({"_id":channel})
game = self.bot.database["connect 4 games"].find_one({"_id":channel})
board = game["board"]
player = game["players"].index("Gwendolyn")+1

View File

@ -3,14 +3,14 @@ import math
from PIL import Image, ImageDraw, ImageFont
from funcs import logThis
class DrawFourInARow():
class drawConnectFour():
def __init__(self,bot):
self.bot = bot
# Draws the whole thing
def drawImage(self, channel):
logThis("Drawing four in a row board")
game = self.bot.database["4 in a row games"].find_one({"_id":channel})
logThis("Drawing connect four board")
game = self.bot.database["connect 4 games"].find_one({"_id":channel})
board = game["board"]
@ -153,4 +153,4 @@ class DrawFourInARow():
d.text((w-border-textWidth,exampleHeight),player2,font=fnt,fill=(0,0,0))
background.save("resources/games/4InARowBoards/board"+channel+".png")
background.save("resources/games/connect4Boards/board"+channel+".png")

View File

@ -23,36 +23,36 @@ class GameLoops():
return oldMessage
# Runs Four in a Row
async def fiar(self, channel,command,user):
try:
response, showImage, deleteImage, gameDone, gwendoTurn = self.bot.fourInARow.parseFourInARow(command,str(channel.id),user)
except:
logThis("Error parsing command (error code 1410)")
# Runs connect four
async def connectFour(self, ctx, command, user = None, channelId = None):
if user is None:
user = "#"+str(ctx.author.id)
await channel.send(response)
logThis(response,str(channel.id))
if channelId is None:
channelId = str(ctx.channel_id)
response, showImage, deleteImage, gameDone, gwendoTurn = self.bot.connectFour.parseconnectFour(command,channelId, user)
if hasattr(ctx, "send"):
await ctx.send(response)
else:
await ctx.channel.send(response)
logThis(response,channelId)
if showImage:
if deleteImage:
try:
oldImage = await self.deleteMessage("fourInARow"+str(channel.id),channel)
except:
logThis("Error deleting message (error code 1401)")
oldImage = await channel.send(file = discord.File("resources/games/4InARowBoards/board"+str(channel.id)+".png"))
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:
try:
response, showImage, deleteImage, gameDone, gwendoTurn = await self.bot.fourInARow.fourInARowAI(str(channel.id))
except:
logThis("AI error (error code 1420)")
await channel.send(response)
logThis(response,str(channel.id))
response, showImage, deleteImage, gameDone, gwendoTurn = await self.bot.connectFour.connectFourAI(channelId)
await ctx.channel.send(response)
logThis(response,channelId)
if showImage:
if deleteImage:
await oldImage.delete()
oldImage = await channel.send(file = discord.File("resources/games/4InARowBoards/board"+str(channel.id)+".png"))
oldImage = await ctx.channel.send(file = discord.File("resources/games/connect4Boards/board"+channelId+".png"))
if gameDone == False:
with open("resources/games/oldImages/fourInARow"+str(channel.id), "w") as f:
with open("resources/games/oldImages/connectFour"+channelId, "w") as f:
f.write(str(oldImage.id))
try:
reactions = ["1","2","3","4","5","6","7"]
@ -63,7 +63,7 @@ class GameLoops():
logThis("Image deleted before I could react to all of them")
else:
with open("resources/games/oldImages/fourInARow"+str(channel.id), "w") as f:
with open("resources/games/oldImages/connectFour"+channelId, "w") as f:
f.write(str(oldImage.id))
try:
reactions = ["1","2","3","4","5","6","7"]
@ -73,10 +73,10 @@ class GameLoops():
logThis("Image deleted before I could react to all of them")
if gameDone:
game = self.bot.database["4 in a row games"].find_one({"_id":str(channel.id)})
game = self.bot.database["connect 4 games"].find_one({"_id":channelId})
try:
with open("resources/games/oldImages/fourInARow"+str(channel.id), "r") as f:
with open("resources/games/oldImages/connectFour"+channelId, "r") as f:
oldImage = await channel.fetch_message(int(f.read()))
await oldImage.delete()
@ -90,15 +90,18 @@ class GameLoops():
if game["players"][winner-1].lower() != "gwendolyn":
self.bot.money.addMoney(game["players"][winner-1].lower(),reward)
self.bot.funcs.deleteGame("4 in a row games",str(channel.id))
self.bot.funcs.deleteGame("connect 4 games",channelId)
async def runHangman(self,channel,user,command = "start"):
async def runHangman(self,channel,user,command = "start", ctx = None):
try:
response, showImage, deleteImage, remainingLetters = self.bot.hangman.parseHangman(str(channel.id),user,command)
except:
logThis("Error parsing command (error code 1701)")
if response != "":
await channel.send(response)
if ctx is None:
await channel.send(response)
else:
await ctx.send(response)
logThis(response,str(channel.id))
if showImage:
if deleteImage:
@ -127,44 +130,45 @@ class GameLoops():
logThis("Image deleted before adding all reactions")
# Runs Hex
async def runHex(self,channel,command,user):
async def runHex(self,ctx,command,user):
channelId = ctx.channel_id
try:
response, showImage, deleteImage, gameDone, gwendoTurn = self.bot.hex.parseHex(command,str(channel.id),user)
response, showImage, deleteImage, gameDone, gwendoTurn = self.bot.hex.parseHex(command,str(channelId),user)
except:
logThis("Error parsing command (error code 1510)")
await channel.send(response)
await ctx.send(response)
logThis(response,str(channel.id))
logThis(response,str(channelId))
if showImage:
if deleteImage:
try:
oldImage = await self.deleteMessage("hex"+str(channel.id),channel)
oldImage = await self.deleteMessage("hex"+str(channelId),ctx.channel)
except:
logThis("Error deleting old image (error code 1501)")
oldImage = await channel.send(file = discord.File("resources/games/hexBoards/board"+str(channel.id)+".png"))
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(channel.id))
response, showImage, deleteImage, gameDone, gwendoTurn = self.bot.hex.hexAI(str(channelId))
except:
response, showImage, deleteImage, gameDone, gwendoTurn = "An AI error occured",False,False,False,False
response, showImage, deleteImage, gameDone, gwendoTurn = "An AI error ocurred",False,False,False,False
logThis("AI error (error code 1520)")
await channel.send(response)
logThis(response,str(channel.id))
await ctx.channel.send(response)
logThis(response,str(channelId))
if showImage:
if deleteImage:
await oldImage.delete()
oldImage = await channel.send(file = discord.File("resources/games/hexBoards/board"+str(channel.id)+".png"))
oldImage = await ctx.channel.send(file = discord.File("resources/games/hexBoards/board"+str(channelId)+".png"))
if not gameDone:
with open("resources/games/oldImages/hex"+str(channel.id), "w") as f:
with open("resources/games/oldImages/hex"+str(channelId), "w") as f:
f.write(str(oldImage.id))
if gameDone:
game = self.bot.database["hex games"].find_one({"_id":str(channel.id)})
game = self.bot.database["hex games"].find_one({"_id":str(channelId)})
winner = game["winner"]
if winner != 0 and game["players"][0] != game["players"][1]: # player1 != player2
winnings = game["difficulty"]*10
self.bot.money.addMoney(game["players"][winner-1].lower(),winnings)
self.bot.funcs.deleteGame("hex games",str(channel.id))
self.bot.funcs.deleteGame("hex games",str(channelId))

View File

@ -1,7 +1,7 @@
from .invest import Invest
from .trivia import Trivia
from .blackjack import Blackjack
from .fourInARow import FourInARow
from .connectFour import connectFour
from .gameLoops import GameLoops
from .hangman import Hangman
from .hex import HexGame
@ -13,7 +13,7 @@ class Games():
bot.invest = Invest(bot)
bot.trivia = Trivia(bot)
bot.blackjack = Blackjack(bot)
bot.fourInARow = FourInARow(bot)
bot.connectFour = connectFour(bot)
bot.gameLoops = GameLoops(bot)
bot.hangman = Hangman(bot)
bot.hex = HexGame(bot)

View File

@ -196,7 +196,7 @@ class HexGame():
else:
return "There's no game in this channel", False, False, False, False
# Returns a board where the placement has occured
# Returns a board where the placement has ocurred
def placeOnHexBoard(self, board,player,position):
# Translates the position
position = position.lower()