diff --git a/cogs/GameCogs.py b/cogs/GameCogs.py index 75d417e..50a11ff 100644 --- a/cogs/GameCogs.py +++ b/cogs/GameCogs.py @@ -78,27 +78,21 @@ class ConnectFourCog(commands.Cog): def __init__(self,bot): """Runs game stuff.""" self.bot = bot + # Start a game of connect four against a user @cog_ext.cog_subcommand(**params["connectFourStartUser"]) async def connectFourStartUser(self, ctx, user): - await ctx.defer() - await self.bot.games.gameLoops.connectFour(ctx, "start "+user.display_name) + await self.bot.games.connectFour.start(ctx, user) # Start a game of connect four against gwendolyn @cog_ext.cog_subcommand(**params["connectFourStartGwendolyn"]) async def connectFourStartGwendolyn(self, ctx, difficulty = 3): - await ctx.defer() - await self.bot.games.gameLoops.connectFour(ctx, "start "+str(difficulty)) + await self.bot.games.connectFour.start(ctx, difficulty) # Stop the current game of connect four - @cog_ext.cog_subcommand(**params["connectFourStop"]) - async def connectFourStop(self, ctx): - await self.bot.games.gameLoops.connectFour(ctx, "stop") - - # Place a piece in the current game of connect four - @cog_ext.cog_subcommand(**params["connectFourPlace"]) - async def connectFourPlace(self, ctx, column): - await self.bot.games.gameLoops.connectFour(ctx, "place "+str(column)) + @cog_ext.cog_subcommand(**params["connectFourSurrender"]) + async def connectFourSurrender(self, ctx): + await self.bot.games.connectFour.surrender(ctx) class HangmanCog(commands.Cog): diff --git a/cogs/ReactionCog.py b/cogs/ReactionCog.py index 14b4cc0..741d66a 100644 --- a/cogs/ReactionCog.py +++ b/cogs/ReactionCog.py @@ -21,8 +21,8 @@ class ReactionCog(commands.Cog): bedreNetflixMessage, addMovie, imdbIds = self.bot.databaseFuncs.bedreNetflixReactionTest(channel, message) if connectFourTheirTurn: - place = emojiToCommand(reaction.emoji) - await self.bot.games.gameLoops.connectFour(message,"place "+str(piece)+" "+str(place),user.id, str(message.channel.id)) + column = emojiToCommand(reaction.emoji) + await self.bot.games.connectFour.placePiece(message, f"#{user.id}", column-1) elif bedreNetflixMessage and addMovie: moviePick = emojiToCommand(reaction.emoji) await message.delete() @@ -42,5 +42,6 @@ class ReactionCog(commands.Cog): elif self.bot.databaseFuncs.hangmanReactionTest(channel,message) and ord(reaction.emoji) in range(127462,127488): guess = chr(ord(reaction.emoji)-127397) await self.bot.games.gameLoops.runHangman(channel,"#"+str(user.id),command="guess "+guess) + def setup(bot): bot.add_cog(ReactionCog(bot)) diff --git a/funcs/games/connectFour.py b/funcs/games/connectFour.py index d655c62..365ebf2 100644 --- a/funcs/games/connectFour.py +++ b/funcs/games/connectFour.py @@ -1,10 +1,11 @@ import random import copy import math +import discord from .connectFourDraw import drawConnectFour -AIScores = { +AISCORES = { "middle": 3, "two in a row": 10, "three in a row": 50, @@ -15,9 +16,8 @@ AIScores = { "avoid losing": 100 } -rowCount = 6 -columnCount = 7 -easy = True +ROWCOUNT = 6 +COLUMNCOUNT = 7 class connectFour(): def __init__(self,bot): @@ -25,65 +25,106 @@ class connectFour(): self.draw = drawConnectFour(bot) # Starts the game - def connectFourStart(self, channel, user, opponent): + async def start(self, ctx, opponent): + try: + await ctx.defer() + except: + self.bot.log("Defer failed") + user = f"#{ctx.author.id}" + channel = str(ctx.channel_id) game = self.bot.database["connect 4 games"].find_one({"_id":channel}) - if game == None: + startedGame = False + canStart = True - if opponent in ["1","2","3","4","5"]: - difficulty = int(opponent) - diffText = " with difficulty "+opponent - opponent = "Gwendolyn" - elif opponent.lower() == "gwendolyn": - difficulty = 3 - diffText = " with difficulty 3" - opponent = "Gwendolyn" - else: - try: - int(opponent) - return "That difficulty doesn't exist", False, False, False, False - except: - # Opponent is another player - opponent = self.bot.databaseFuncs.getID(opponent) - if opponent != None: - difficulty = 5 - diffText = "" - else: - return "I can't find that user", False, False, False, False + if game != None: + sendMessage = "There's already a connect 4 game going on in this channel" + logMessage = "There was already a game going on" + canStart = False + else: + if type(opponent) == int: + # Opponent is Gwendolyn + if opponent in range(1, 6): + difficulty = int(opponent) + diffText = f" with difficulty {difficulty}" + opponent = f"#{self.bot.user.id}" + else: + sendMessage = "Difficulty doesn't exist" + logMessage = "They tried to play against a difficulty that doesn't exist" + canStart = False - if user == opponent: - return "You can't play against yourself", False, False, False, False + elif type(opponent) == discord.user: + # Opponent is another player + if ctx.author != opponent: + opponent = f"#{opponent.id}" + difficulty = 5 + diffText = "" + else: + sendMessage = "You can't play against yourself" + logMessage = "They tried to play against themself" + canStart = False - board = [ [ 0 for i in range(columnCount) ] for j in range(rowCount) ] - players = [user,opponent] + if canStart: + board = [[0 for _ in range(COLUMNCOUNT)] for _ in range(ROWCOUNT)] + players = [user, opponent] random.shuffle(players) - newGame = {"_id":channel,"board": board,"winner":0,"win direction":"", - "win coordinates":[0,0],"players":players,"turn":0,"difficulty":difficulty} + newGame = {"_id":channel, "board": board, "winner":0, + "win direction":"", "win coordinates":[0, 0], + "players":players, "turn":0, "difficulty":difficulty} self.bot.database["connect 4 games"].insert_one(newGame) self.draw.drawImage(channel) - gwendoTurn = False + gwendoTurn = (players[0] == f"#{self.bot.user.id}") + startedGame = True - if players[0] == "Gwendolyn": - gwendoTurn = True + opponentName = self.bot.databaseFuncs.getName(opponent) + turnName = self.bot.databaseFuncs.getName(players[0]) - 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 + startedText = f"Started game against {opponentName}{diffText}." + turnText = f"It's {turnName}'s turn" + sendMessage = f"{startedText} {turnText}" + logMessage = "They started a game" + + self.bot.log(logMessage) + await ctx.send(sendMessage) + + # Sets the whole game in motion + if startedGame: + filePath = f"resources/games/connect4Boards/board{ctx.channel_id}.png" + oldImage = await ctx.channel.send(file = discord.File(filePath)) + + with open(f"resources/games/oldImages/connectFour{ctx.channel_id}", "w") as f: + f.write(str(oldImage.id)) + + if gwendoTurn: + await self.connectFourAI(ctx) + else: + reactions = ["1️⃣","2️⃣","3️⃣","4️⃣","5️⃣","6️⃣","7️⃣"] + for reaction in reactions: + await oldImage.add_reaction(reaction) # Places a piece at the lowest available point in a specific column - def placePiece(self, channel : str,player : int,column : int): + async def placePiece(self, ctx, user, column): + channel = str(ctx.channel.id) game = self.bot.database["connect 4 games"].find_one({"_id":channel}) + playerNumber = game["players"].index(user)+1 + userName = self.bot.databaseFuncs.getName(user) + placedPiece = False - if game != None: + if game is None: + sendMessage = "There's no game in this channel" + logMessage = "There was no game in the channel" + else: board = game["board"] + board = self.placeOnBoard(board, playerNumber, column) - board = self.placeOnBoard(board,player,column) - - if board != None: + if board is None: + sendMessage = "There isn't any room in that column" + logMessage = "There wasn't any room in the column" + else: self.bot.database["connect 4 games"].update_one({"_id":channel},{"$set":{"board":board}}) turn = (game["turn"]+1)%2 self.bot.database["connect 4 games"].update_one({"_id":channel},{"$set":{"turn":turn}}) @@ -98,82 +139,115 @@ class connectFour(): self.bot.database["connect 4 games"].update_one({"_id":channel}, {"$set":{"win coordinates":winCoordinates}}) - message = self.bot.databaseFuncs.getName(game["players"][won-1])+" placed a piece in column "+str(column+1)+" and won." + sendMessage = f"{userName} placed a piece in column {column+1} and won." + logMessage = f"{userName} won" winAmount = int(game["difficulty"])**2+5 - if game["players"][won-1] != "Gwendolyn": - message += " Adding "+str(winAmount)+" GwendoBucks to their account." + if game["players"][won-1] != f"#{self.bot.user.id}": + sendMessage += " Adding "+str(winAmount)+" GwendoBucks to their account" elif 0 not in board[0]: gameWon = True - message = "It's a draw!" + sendMessage = "It's a draw!" + logMessage = "The game ended in a draw" else: gameWon = False - 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." + otherUserName = self.bot.databaseFuncs.getName(game["players"][turn]) + sendMessage = f"{userName} placed a piece in column {column+1}. It's now {otherUserName}'s turn" + logMessage = "They placed the piece" - gwendoTurn = False + gwendoTurn = (game["players"][turn] == f"#{self.bot.user.id}") - if game["players"][turn] == "Gwendolyn": - self.bot.log("It's Gwendolyn's turn") - gwendoTurn = True + placedPiece = True - self.draw.drawImage(channel) - return message, True, True, gameWon, gwendoTurn + await ctx.channel.send(sendMessage) + self.bot.log(logMessage) + + if placedPiece: + self.draw.drawImage(channel) + + with open(f"resources/games/oldImages/connectFour{channel}", "r") as f: + oldImage = await ctx.channel.fetch_message(int(f.read())) + + if oldImage is not None: + await oldImage.delete() else: - return "There isn't any room in that column", True, True, False, False - else: - return "There's no game in this channel", False, False, False, False + self.bot.log("The old image was already deleted") + + filePath = f"resources/games/connect4Boards/board{channel}.png" + oldImage = await ctx.channel.send(file = discord.File(filePath)) + + if gameWon: + self.endGame(channel) + else: + with open(f"resources/games/oldImages/connectFour{channel}", "w") as f: + f.write(str(oldImage.id)) + if gwendoTurn: + await self.connectFourAI(ctx) + else: + reactions = ["1️⃣","2️⃣","3️⃣","4️⃣","5️⃣","6️⃣","7️⃣"] + for reaction in reactions: + await oldImage.add_reaction(reaction) # Returns a board where a piece has been placed in the column - def placeOnBoard(self,board,player,column): - placementx, placementy = -1, column + def placeOnBoard(self, board, player, column): + placementX, placementY = -1, column for x, line in enumerate(board): if line[column] == 0: - placementx = x + placementX = x - board[placementx][placementy] = player + board[placementX][placementY] = player - if placementx == -1: + if placementX == -1: return None else: return board + def endGame(self, channel): + game = self.bot.database["connect 4 games"].find_one({"_id":channel}) + + winner = game["winner"] + if winner != 0: + if game["players"][winner-1] != f"#{self.bot.user.id}": + difficulty = int(game["difficulty"]) + reward = difficulty**2 + 5 + self.bot.money.addMoney(game["players"][winner-1], reward) + + self.bot.databaseFuncs.deleteGame("connect 4 games", channel) + # Parses command - def parseconnectFour(self, command, channel, user): - commands = command.split() - if command == "" or command == " ": - 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 "/connectFour start", the opponent is Gwendolyn - commands.append("3") - return self.connectFourStart(channel,user,commands[1]) # commands[1] is the opponent + async def surrender(self, ctx): + try: + await ctx.defer() + except: + self.bot.log("Defer failed") + channel = str(ctx.channel_id) + game = self.bot.database["connect 4 games"].find_one({"_id":channel}) - # Stopping the game - elif commands[0] == "stop": - game = self.bot.database["connect 4 games"].find_one({"_id":channel}) + if f"#{ctx.author.id}" in game["players"]: + loserIndex = game["players"].index(f"#{ctx.author.id}") + winnerIndex = (loserIndex+1)%2 + winnerID = game["players"][winnerIndex] + winnerName = self.bot.databaseFuncs.getName(winnerID) - if user in game["players"]: - return "Ending game.", False, False, True, False + sendMessage = f"{ctx.author.display_name} surrenders." + sendMessage += f" This means {winnerName} is the winner." + if winnerID != f"#{self.bot.user.id}": + difficulty = int(game["difficulty"]) + reward = difficulty**2 + 5 + sendMessage += f" Adding {reward} to their account" + + await ctx.send(sendMessage) + with open(f"resources/games/oldImages/connectFour{channel}", "r") as f: + oldImage = await ctx.channel.fetch_message(int(f.read())) + + if oldImage is not None: + await oldImage.delete() else: - return "You can't end a game where you're not a player.", False, False, False, False + self.bot.log("The old image was already deleted") - # Placing manually - elif commands[0] == "place": - 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: - self.bot.log("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) + self.endGame(channel) else: - 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 + await ctx.send("You can't surrender when you're not a player") # Checks if someone has won the game and returns the winner def isWon(self, board): @@ -181,13 +255,13 @@ class connectFour(): winDirection = "" winCoordinates = [0,0] - for row in range(rowCount): - for place in range(columnCount): + for row in range(ROWCOUNT): + for place in range(COLUMNCOUNT): if won == 0: piecePlayer = board[row][place] if piecePlayer != 0: # Checks horizontal - if place <= columnCount-4: + if place <= COLUMNCOUNT-4: pieces = [board[row][place+1],board[row][place+2],board[row][place+3]] else: pieces = [0] @@ -198,7 +272,7 @@ class connectFour(): winCoordinates = [row,place] # Checks vertical - if row <= rowCount-4: + if row <= ROWCOUNT-4: pieces = [board[row+1][place],board[row+2][place],board[row+3][place]] else: pieces = [0] @@ -209,7 +283,7 @@ class connectFour(): winCoordinates = [row,place] # Checks right diagonal - if row <= rowCount-4 and place <= columnCount-4: + if row <= ROWCOUNT-4 and place <= COLUMNCOUNT-4: pieces = [board[row+1][place+1],board[row+2][place+2],board[row+3][place+3]] else: pieces = [0] @@ -220,7 +294,7 @@ class connectFour(): winCoordinates = [row,place] # Checks left diagonal - if row <= rowCount-4 and place >= 3: + if row <= ROWCOUNT-4 and place >= 3: pieces = [board[row+1][place-1],board[row+2][place-2],board[row+3][place-3]] else: pieces = [0] @@ -234,21 +308,23 @@ class connectFour(): return won, winDirection, winCoordinates # Plays as the AI - async def connectFourAI(self, channel): + async def connectFourAI(self, ctx): + channel = str(ctx.channel.id) + self.bot.log("Figuring out best move") game = self.bot.database["connect 4 games"].find_one({"_id":channel}) board = game["board"] - player = game["players"].index("Gwendolyn")+1 + player = game["players"].index(f"#{self.bot.user.id}")+1 difficulty = game["difficulty"] - scores = [-math.inf,-math.inf,-math.inf,-math.inf,-math.inf,-math.inf,-math.inf] - for column in range(0,columnCount): + scores = [-math.inf for _ in range(COLUMNCOUNT)] + for column in range(COLUMNCOUNT): testBoard = copy.deepcopy(board) 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) - self.bot.log("Best score for column "+str(column)+" is "+str(scores[column])) + self.bot.log(f"Best score for column {column} is {scores[column]}") possibleScores = scores.copy() @@ -257,9 +333,10 @@ class connectFour(): highest_score = random.choice(possibleScores) - indices = [i for i, x in enumerate(scores) if x == highest_score] - placement = random.choice(indices) - return self.placePiece(channel,player,placement) + bestColumns = [i for i, x in enumerate(scores) if x == highest_score] + placement = random.choice(bestColumns) + + await self.placePiece(ctx, f"#{self.bot.user.id}", placement) # Calculates points for a board def AICalcPoints(self,board,player): @@ -268,28 +345,28 @@ class connectFour(): # Adds points for middle placement # Checks horizontal - for row in range(rowCount): + for row in range(ROWCOUNT): if board[row][3] == player: - score += AIScores["middle"] + score += AISCORES["middle"] rowArray = [int(i) for i in list(board[row])] - for place in range(columnCount-3): + for place in range(COLUMNCOUNT-3): window = rowArray[place:place+4] score += self.evaluateWindow(window,player,otherPlayer) # Checks Vertical - for column in range(columnCount): + for column in range(COLUMNCOUNT): columnArray = [int(i[column]) for i in list(board)] - for place in range(rowCount-3): + for place in range(ROWCOUNT-3): window = columnArray[place:place+4] score += self.evaluateWindow(window,player,otherPlayer) # Checks right diagonal - for row in range(rowCount-3): - for place in range(columnCount-3): + for row in range(ROWCOUNT-3): + for place in range(COLUMNCOUNT-3): window = [board[row][place],board[row+1][place+1],board[row+2][place+2],board[row+3][place+3]] score += self.evaluateWindow(window,player,otherPlayer) - for place in range(3,columnCount): + for place in range(3,COLUMNCOUNT): window = [board[row][place],board[row+1][place-1],board[row+2][place-2],board[row+3][place-3]] score += self.evaluateWindow(window,player,otherPlayer) @@ -299,20 +376,19 @@ class connectFour(): ## Add points if AI wins #if won == player: - # score += AIScores["win"] + # score += AISCORES["win"] return score - def evaluateWindow(self, window,player,otherPlayer): if window.count(player) == 4: - return AIScores["win"] + return AISCORES["win"] elif window.count(player) == 3 and window.count(0) == 1: - return AIScores["three in a row"] + return AISCORES["three in a row"] elif window.count(player) == 2 and window.count(0) == 2: - return AIScores["two in a row"] + return AISCORES["two in a row"] elif window.count(otherPlayer) == 4: - return AIScores["enemy win"] + return AISCORES["enemy win"] else: return 0 @@ -325,24 +401,24 @@ class connectFour(): return points if maximizingPlayer: value = -math.inf - for column in range(0,columnCount): + for column in range(0,COLUMNCOUNT): testBoard = copy.deepcopy(board) testBoard = self.placeOnBoard(testBoard,player,column) if testBoard != None: evaluation = await self.minimax(testBoard,depth-1,player%2+1,originalPlayer,alpha,beta,False) - if evaluation < -9000: evaluation += AIScores["avoid losing"] + if evaluation < -9000: evaluation += AISCORES["avoid losing"] value = max(value,evaluation) alpha = max(alpha,evaluation) if beta <= alpha: break return value else: value = math.inf - for column in range(0,columnCount): + for column in range(0,COLUMNCOUNT): testBoard = copy.deepcopy(board) testBoard = self.placeOnBoard(testBoard,player,column) if testBoard != None: evaluation = await self.minimax(testBoard,depth-1,player%2+1,originalPlayer,alpha,beta,True) - if evaluation < -9000: evaluation += AIScores["avoid losing"] + if evaluation < -9000: evaluation += AISCORES["avoid losing"] value = min(value,evaluation) beta = min(beta,evaluation) if beta <= alpha: break diff --git a/resources/slashParameters.json b/resources/slashParameters.json index dd7159b..0b38945 100644 --- a/resources/slashParameters.json +++ b/resources/slashParameters.json @@ -140,23 +140,10 @@ } ] }, - "connectFourStop" : { + "connectFourSurrender" : { "base" : "connectFour", - "name" : "stop", - "description" : "Stop the game of connect four" - }, - "connectFourPlace" : { - "base" : "connectFour", - "name" : "place", - "description" : "Place a piece", - "options" : [ - { - "name" : "column", - "description" : "The column to place the piece", - "type" : 4, - "required" : "true" - } - ] + "name" : "surrender", + "description" : "Surrender the game of connect four" }, "downloading" : { "name" : "downloading", diff --git a/utils/eventHandlers.py b/utils/eventHandlers.py index 999e96f..002107d 100644 --- a/utils/eventHandlers.py +++ b/utils/eventHandlers.py @@ -1,4 +1,4 @@ -import discord, traceback, discord_slash +import discord, traceback, discord_slash, sys from discord.ext import commands class EventHandler(): @@ -31,8 +31,6 @@ class ErrorHandler(): elif isinstance(error, commands.errors.MissingRequiredArgument): self.bot.log(f"{error}",str(ctx.channel_id)) await ctx.send("Missing command parameters (error code 002). Try using `!help [command]` to find out how to use the command.") - elif isinstance(error, discord_slash.error.AlreadyResponded): - self.bot.log("Defer failed") else: exception = traceback.format_exception(type(error), error, error.__traceback__) stopAt = "\nThe above exception was the direct cause of the following exception:\n\n" @@ -48,11 +46,15 @@ class ErrorHandler(): await ctx.send("Something went wrong (error code 000)") async def on_error(self, method): - exception = traceback.format_exc() - stopAt = "\nThe above exception was the direct cause of the following exception:\n\n" - if stopAt in exception: - index = exception.index(stopAt) - exception = exception[:index] + errorType = sys.exc_info()[0] + if errorType == discord.errors.NotFound: + self.bot.log("Deleted message before I could add all reactions") + else: + exception = traceback.format_exc() + stopAt = "\nThe above exception was the direct cause of the following exception:\n\n" + if stopAt in exception: + index = exception.index(stopAt) + exception = exception[:index] - exceptionString = "".join(exception) - self.bot.log([f"exception in {method}", f"{exceptionString}"], level = 40) \ No newline at end of file + exceptionString = "".join(exception) + self.bot.log([f"exception in {method}", f"{exceptionString}"], level = 40) \ No newline at end of file diff --git a/utils/helperClasses.py b/utils/helperClasses.py index 07f2f99..56a1aa4 100644 --- a/utils/helperClasses.py +++ b/utils/helperClasses.py @@ -55,10 +55,10 @@ class databaseFuncs(): if user != None: return user["user name"] - elif userID == "Gwendolyn": - return userID + elif userID == f"#{self.bot.user.id}": + return "Gwendolyn" else: - self.bot.log("Couldn't find user "+userID) + self.bot.log(f"Couldn't find user {userID}") return userID def getID(self,userName): @@ -70,7 +70,7 @@ class databaseFuncs(): self.bot.log("Couldn't find user "+userName) return None - def deleteGame(self, gameType,channel): + def deleteGame(self, gameType, channel): self.bot.database[gameType].delete_one({"_id":channel}) def stopServer(self):