🔴 Converted all of connectFour to slash commands
This commit is contained in:
@ -78,27 +78,21 @@ class ConnectFourCog(commands.Cog):
|
|||||||
def __init__(self,bot):
|
def __init__(self,bot):
|
||||||
"""Runs game stuff."""
|
"""Runs game stuff."""
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
|
|
||||||
# Start a game of connect four against a user
|
# Start a game of connect four against a user
|
||||||
@cog_ext.cog_subcommand(**params["connectFourStartUser"])
|
@cog_ext.cog_subcommand(**params["connectFourStartUser"])
|
||||||
async def connectFourStartUser(self, ctx, user):
|
async def connectFourStartUser(self, ctx, user):
|
||||||
await ctx.defer()
|
await self.bot.games.connectFour.start(ctx, user)
|
||||||
await self.bot.games.gameLoops.connectFour(ctx, "start "+user.display_name)
|
|
||||||
|
|
||||||
# Start a game of connect four against gwendolyn
|
# Start a game of connect four against gwendolyn
|
||||||
@cog_ext.cog_subcommand(**params["connectFourStartGwendolyn"])
|
@cog_ext.cog_subcommand(**params["connectFourStartGwendolyn"])
|
||||||
async def connectFourStartGwendolyn(self, ctx, difficulty = 3):
|
async def connectFourStartGwendolyn(self, ctx, difficulty = 3):
|
||||||
await ctx.defer()
|
await self.bot.games.connectFour.start(ctx, difficulty)
|
||||||
await self.bot.games.gameLoops.connectFour(ctx, "start "+str(difficulty))
|
|
||||||
|
|
||||||
# Stop the current game of connect four
|
# Stop the current game of connect four
|
||||||
@cog_ext.cog_subcommand(**params["connectFourStop"])
|
@cog_ext.cog_subcommand(**params["connectFourSurrender"])
|
||||||
async def connectFourStop(self, ctx):
|
async def connectFourSurrender(self, ctx):
|
||||||
await self.bot.games.gameLoops.connectFour(ctx, "stop")
|
await self.bot.games.connectFour.surrender(ctx)
|
||||||
|
|
||||||
# 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))
|
|
||||||
|
|
||||||
|
|
||||||
class HangmanCog(commands.Cog):
|
class HangmanCog(commands.Cog):
|
||||||
|
@ -21,8 +21,8 @@ class ReactionCog(commands.Cog):
|
|||||||
bedreNetflixMessage, addMovie, imdbIds = self.bot.databaseFuncs.bedreNetflixReactionTest(channel, message)
|
bedreNetflixMessage, addMovie, imdbIds = self.bot.databaseFuncs.bedreNetflixReactionTest(channel, message)
|
||||||
|
|
||||||
if connectFourTheirTurn:
|
if connectFourTheirTurn:
|
||||||
place = emojiToCommand(reaction.emoji)
|
column = emojiToCommand(reaction.emoji)
|
||||||
await self.bot.games.gameLoops.connectFour(message,"place "+str(piece)+" "+str(place),user.id, str(message.channel.id))
|
await self.bot.games.connectFour.placePiece(message, f"#{user.id}", column-1)
|
||||||
elif bedreNetflixMessage and addMovie:
|
elif bedreNetflixMessage and addMovie:
|
||||||
moviePick = emojiToCommand(reaction.emoji)
|
moviePick = emojiToCommand(reaction.emoji)
|
||||||
await message.delete()
|
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):
|
elif self.bot.databaseFuncs.hangmanReactionTest(channel,message) and ord(reaction.emoji) in range(127462,127488):
|
||||||
guess = chr(ord(reaction.emoji)-127397)
|
guess = chr(ord(reaction.emoji)-127397)
|
||||||
await self.bot.games.gameLoops.runHangman(channel,"#"+str(user.id),command="guess "+guess)
|
await self.bot.games.gameLoops.runHangman(channel,"#"+str(user.id),command="guess "+guess)
|
||||||
|
|
||||||
def setup(bot):
|
def setup(bot):
|
||||||
bot.add_cog(ReactionCog(bot))
|
bot.add_cog(ReactionCog(bot))
|
||||||
|
@ -1,10 +1,11 @@
|
|||||||
import random
|
import random
|
||||||
import copy
|
import copy
|
||||||
import math
|
import math
|
||||||
|
import discord
|
||||||
|
|
||||||
from .connectFourDraw import drawConnectFour
|
from .connectFourDraw import drawConnectFour
|
||||||
|
|
||||||
AIScores = {
|
AISCORES = {
|
||||||
"middle": 3,
|
"middle": 3,
|
||||||
"two in a row": 10,
|
"two in a row": 10,
|
||||||
"three in a row": 50,
|
"three in a row": 50,
|
||||||
@ -15,9 +16,8 @@ AIScores = {
|
|||||||
"avoid losing": 100
|
"avoid losing": 100
|
||||||
}
|
}
|
||||||
|
|
||||||
rowCount = 6
|
ROWCOUNT = 6
|
||||||
columnCount = 7
|
COLUMNCOUNT = 7
|
||||||
easy = True
|
|
||||||
|
|
||||||
class connectFour():
|
class connectFour():
|
||||||
def __init__(self,bot):
|
def __init__(self,bot):
|
||||||
@ -25,65 +25,106 @@ class connectFour():
|
|||||||
self.draw = drawConnectFour(bot)
|
self.draw = drawConnectFour(bot)
|
||||||
|
|
||||||
# Starts the game
|
# 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})
|
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"]:
|
if game != None:
|
||||||
difficulty = int(opponent)
|
sendMessage = "There's already a connect 4 game going on in this channel"
|
||||||
diffText = " with difficulty "+opponent
|
logMessage = "There was already a game going on"
|
||||||
opponent = "Gwendolyn"
|
canStart = False
|
||||||
elif opponent.lower() == "gwendolyn":
|
else:
|
||||||
difficulty = 3
|
if type(opponent) == int:
|
||||||
diffText = " with difficulty 3"
|
# Opponent is Gwendolyn
|
||||||
opponent = "Gwendolyn"
|
if opponent in range(1, 6):
|
||||||
else:
|
difficulty = int(opponent)
|
||||||
try:
|
diffText = f" with difficulty {difficulty}"
|
||||||
int(opponent)
|
opponent = f"#{self.bot.user.id}"
|
||||||
return "That difficulty doesn't exist", False, False, False, False
|
else:
|
||||||
except:
|
sendMessage = "Difficulty doesn't exist"
|
||||||
# Opponent is another player
|
logMessage = "They tried to play against a difficulty that doesn't exist"
|
||||||
opponent = self.bot.databaseFuncs.getID(opponent)
|
canStart = False
|
||||||
if opponent != None:
|
|
||||||
difficulty = 5
|
|
||||||
diffText = ""
|
|
||||||
else:
|
|
||||||
return "I can't find that user", False, False, False, False
|
|
||||||
|
|
||||||
if user == opponent:
|
elif type(opponent) == discord.user:
|
||||||
return "You can't play against yourself", False, False, False, False
|
# 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) ]
|
if canStart:
|
||||||
players = [user,opponent]
|
board = [[0 for _ in range(COLUMNCOUNT)] for _ in range(ROWCOUNT)]
|
||||||
|
players = [user, opponent]
|
||||||
random.shuffle(players)
|
random.shuffle(players)
|
||||||
|
|
||||||
newGame = {"_id":channel,"board": board,"winner":0,"win direction":"",
|
newGame = {"_id":channel, "board": board, "winner":0,
|
||||||
"win coordinates":[0,0],"players":players,"turn":0,"difficulty":difficulty}
|
"win direction":"", "win coordinates":[0, 0],
|
||||||
|
"players":players, "turn":0, "difficulty":difficulty}
|
||||||
|
|
||||||
self.bot.database["connect 4 games"].insert_one(newGame)
|
self.bot.database["connect 4 games"].insert_one(newGame)
|
||||||
|
|
||||||
self.draw.drawImage(channel)
|
self.draw.drawImage(channel)
|
||||||
|
|
||||||
gwendoTurn = False
|
gwendoTurn = (players[0] == f"#{self.bot.user.id}")
|
||||||
|
startedGame = True
|
||||||
|
|
||||||
if players[0] == "Gwendolyn":
|
opponentName = self.bot.databaseFuncs.getName(opponent)
|
||||||
gwendoTurn = True
|
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
|
startedText = f"Started game against {opponentName}{diffText}."
|
||||||
else:
|
turnText = f"It's {turnName}'s turn"
|
||||||
return "There's already a connect 4 game going on in this channel", False, False, False, False
|
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
|
# 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})
|
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 = game["board"]
|
||||||
|
board = self.placeOnBoard(board, playerNumber, column)
|
||||||
|
|
||||||
board = self.placeOnBoard(board,player,column)
|
if board is None:
|
||||||
|
sendMessage = "There isn't any room in that column"
|
||||||
if board != None:
|
logMessage = "There wasn't any room in the column"
|
||||||
|
else:
|
||||||
self.bot.database["connect 4 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
|
turn = (game["turn"]+1)%2
|
||||||
self.bot.database["connect 4 games"].update_one({"_id":channel},{"$set":{"turn":turn}})
|
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},
|
self.bot.database["connect 4 games"].update_one({"_id":channel},
|
||||||
{"$set":{"win coordinates":winCoordinates}})
|
{"$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
|
winAmount = int(game["difficulty"])**2+5
|
||||||
if game["players"][won-1] != "Gwendolyn":
|
if game["players"][won-1] != f"#{self.bot.user.id}":
|
||||||
message += " Adding "+str(winAmount)+" GwendoBucks to their account."
|
sendMessage += " Adding "+str(winAmount)+" GwendoBucks to their account"
|
||||||
elif 0 not in board[0]:
|
elif 0 not in board[0]:
|
||||||
gameWon = True
|
gameWon = True
|
||||||
message = "It's a draw!"
|
sendMessage = "It's a draw!"
|
||||||
|
logMessage = "The game ended in a draw"
|
||||||
else:
|
else:
|
||||||
gameWon = False
|
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":
|
placedPiece = True
|
||||||
self.bot.log("It's Gwendolyn's turn")
|
|
||||||
gwendoTurn = True
|
|
||||||
|
|
||||||
self.draw.drawImage(channel)
|
await ctx.channel.send(sendMessage)
|
||||||
return message, True, True, gameWon, gwendoTurn
|
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:
|
else:
|
||||||
return "There isn't any room in that column", True, True, False, False
|
self.bot.log("The old image was already deleted")
|
||||||
else:
|
|
||||||
return "There's no game in this channel", False, False, False, False
|
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
|
# Returns a board where a piece has been placed in the column
|
||||||
def placeOnBoard(self,board,player,column):
|
def placeOnBoard(self, board, player, column):
|
||||||
placementx, placementy = -1, column
|
placementX, placementY = -1, column
|
||||||
|
|
||||||
for x, line in enumerate(board):
|
for x, line in enumerate(board):
|
||||||
if line[column] == 0:
|
if line[column] == 0:
|
||||||
placementx = x
|
placementX = x
|
||||||
|
|
||||||
board[placementx][placementy] = player
|
board[placementX][placementY] = player
|
||||||
|
|
||||||
if placementx == -1:
|
if placementX == -1:
|
||||||
return None
|
return None
|
||||||
else:
|
else:
|
||||||
return board
|
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
|
# Parses command
|
||||||
def parseconnectFour(self, command, channel, user):
|
async def surrender(self, ctx):
|
||||||
commands = command.split()
|
try:
|
||||||
if command == "" or command == " ":
|
await ctx.defer()
|
||||||
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
|
except:
|
||||||
elif commands[0] == "start":
|
self.bot.log("Defer failed")
|
||||||
# Starting a game
|
channel = str(ctx.channel_id)
|
||||||
if len(commands) == 1: # if the commands is "/connectFour start", the opponent is Gwendolyn
|
game = self.bot.database["connect 4 games"].find_one({"_id":channel})
|
||||||
commands.append("3")
|
|
||||||
return self.connectFourStart(channel,user,commands[1]) # commands[1] is the opponent
|
|
||||||
|
|
||||||
# Stopping the game
|
if f"#{ctx.author.id}" in game["players"]:
|
||||||
elif commands[0] == "stop":
|
loserIndex = game["players"].index(f"#{ctx.author.id}")
|
||||||
game = self.bot.database["connect 4 games"].find_one({"_id":channel})
|
winnerIndex = (loserIndex+1)%2
|
||||||
|
winnerID = game["players"][winnerIndex]
|
||||||
|
winnerName = self.bot.databaseFuncs.getName(winnerID)
|
||||||
|
|
||||||
if user in game["players"]:
|
sendMessage = f"{ctx.author.display_name} surrenders."
|
||||||
return "Ending game.", False, False, True, False
|
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:
|
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
|
self.endGame(channel)
|
||||||
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)
|
|
||||||
else:
|
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
|
# Checks if someone has won the game and returns the winner
|
||||||
def isWon(self, board):
|
def isWon(self, board):
|
||||||
@ -181,13 +255,13 @@ class connectFour():
|
|||||||
winDirection = ""
|
winDirection = ""
|
||||||
winCoordinates = [0,0]
|
winCoordinates = [0,0]
|
||||||
|
|
||||||
for row in range(rowCount):
|
for row in range(ROWCOUNT):
|
||||||
for place in range(columnCount):
|
for place in range(COLUMNCOUNT):
|
||||||
if won == 0:
|
if won == 0:
|
||||||
piecePlayer = board[row][place]
|
piecePlayer = board[row][place]
|
||||||
if piecePlayer != 0:
|
if piecePlayer != 0:
|
||||||
# Checks horizontal
|
# Checks horizontal
|
||||||
if place <= columnCount-4:
|
if place <= COLUMNCOUNT-4:
|
||||||
pieces = [board[row][place+1],board[row][place+2],board[row][place+3]]
|
pieces = [board[row][place+1],board[row][place+2],board[row][place+3]]
|
||||||
else:
|
else:
|
||||||
pieces = [0]
|
pieces = [0]
|
||||||
@ -198,7 +272,7 @@ class connectFour():
|
|||||||
winCoordinates = [row,place]
|
winCoordinates = [row,place]
|
||||||
|
|
||||||
# Checks vertical
|
# Checks vertical
|
||||||
if row <= rowCount-4:
|
if row <= ROWCOUNT-4:
|
||||||
pieces = [board[row+1][place],board[row+2][place],board[row+3][place]]
|
pieces = [board[row+1][place],board[row+2][place],board[row+3][place]]
|
||||||
else:
|
else:
|
||||||
pieces = [0]
|
pieces = [0]
|
||||||
@ -209,7 +283,7 @@ class connectFour():
|
|||||||
winCoordinates = [row,place]
|
winCoordinates = [row,place]
|
||||||
|
|
||||||
# Checks right diagonal
|
# 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]]
|
pieces = [board[row+1][place+1],board[row+2][place+2],board[row+3][place+3]]
|
||||||
else:
|
else:
|
||||||
pieces = [0]
|
pieces = [0]
|
||||||
@ -220,7 +294,7 @@ class connectFour():
|
|||||||
winCoordinates = [row,place]
|
winCoordinates = [row,place]
|
||||||
|
|
||||||
# Checks left diagonal
|
# 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]]
|
pieces = [board[row+1][place-1],board[row+2][place-2],board[row+3][place-3]]
|
||||||
else:
|
else:
|
||||||
pieces = [0]
|
pieces = [0]
|
||||||
@ -234,21 +308,23 @@ class connectFour():
|
|||||||
return won, winDirection, winCoordinates
|
return won, winDirection, winCoordinates
|
||||||
|
|
||||||
# Plays as the AI
|
# 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")
|
self.bot.log("Figuring out best move")
|
||||||
game = self.bot.database["connect 4 games"].find_one({"_id":channel})
|
game = self.bot.database["connect 4 games"].find_one({"_id":channel})
|
||||||
|
|
||||||
board = game["board"]
|
board = game["board"]
|
||||||
player = game["players"].index("Gwendolyn")+1
|
player = game["players"].index(f"#{self.bot.user.id}")+1
|
||||||
difficulty = game["difficulty"]
|
difficulty = game["difficulty"]
|
||||||
|
|
||||||
scores = [-math.inf,-math.inf,-math.inf,-math.inf,-math.inf,-math.inf,-math.inf]
|
scores = [-math.inf for _ in range(COLUMNCOUNT)]
|
||||||
for column in range(0,columnCount):
|
for column in range(COLUMNCOUNT):
|
||||||
testBoard = copy.deepcopy(board)
|
testBoard = copy.deepcopy(board)
|
||||||
testBoard = self.placeOnBoard(testBoard,player,column)
|
testBoard = self.placeOnBoard(testBoard,player,column)
|
||||||
if testBoard != None:
|
if testBoard != None:
|
||||||
scores[column] = await self.minimax(testBoard,difficulty,player%2+1,player,-math.inf,math.inf,False)
|
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()
|
possibleScores = scores.copy()
|
||||||
|
|
||||||
@ -257,9 +333,10 @@ class connectFour():
|
|||||||
|
|
||||||
highest_score = random.choice(possibleScores)
|
highest_score = random.choice(possibleScores)
|
||||||
|
|
||||||
indices = [i for i, x in enumerate(scores) if x == highest_score]
|
bestColumns = [i for i, x in enumerate(scores) if x == highest_score]
|
||||||
placement = random.choice(indices)
|
placement = random.choice(bestColumns)
|
||||||
return self.placePiece(channel,player,placement)
|
|
||||||
|
await self.placePiece(ctx, f"#{self.bot.user.id}", placement)
|
||||||
|
|
||||||
# Calculates points for a board
|
# Calculates points for a board
|
||||||
def AICalcPoints(self,board,player):
|
def AICalcPoints(self,board,player):
|
||||||
@ -268,28 +345,28 @@ class connectFour():
|
|||||||
|
|
||||||
# Adds points for middle placement
|
# Adds points for middle placement
|
||||||
# Checks horizontal
|
# Checks horizontal
|
||||||
for row in range(rowCount):
|
for row in range(ROWCOUNT):
|
||||||
if board[row][3] == player:
|
if board[row][3] == player:
|
||||||
score += AIScores["middle"]
|
score += AISCORES["middle"]
|
||||||
rowArray = [int(i) for i in list(board[row])]
|
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]
|
window = rowArray[place:place+4]
|
||||||
score += self.evaluateWindow(window,player,otherPlayer)
|
score += self.evaluateWindow(window,player,otherPlayer)
|
||||||
|
|
||||||
# Checks Vertical
|
# Checks Vertical
|
||||||
for column in range(columnCount):
|
for column in range(COLUMNCOUNT):
|
||||||
columnArray = [int(i[column]) for i in list(board)]
|
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]
|
window = columnArray[place:place+4]
|
||||||
score += self.evaluateWindow(window,player,otherPlayer)
|
score += self.evaluateWindow(window,player,otherPlayer)
|
||||||
|
|
||||||
# Checks right diagonal
|
# Checks right diagonal
|
||||||
for row in range(rowCount-3):
|
for row in range(ROWCOUNT-3):
|
||||||
for place in range(columnCount-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]]
|
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)
|
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]]
|
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)
|
score += self.evaluateWindow(window,player,otherPlayer)
|
||||||
|
|
||||||
@ -299,20 +376,19 @@ class connectFour():
|
|||||||
|
|
||||||
## Add points if AI wins
|
## Add points if AI wins
|
||||||
#if won == player:
|
#if won == player:
|
||||||
# score += AIScores["win"]
|
# score += AISCORES["win"]
|
||||||
|
|
||||||
return score
|
return score
|
||||||
|
|
||||||
|
|
||||||
def evaluateWindow(self, window,player,otherPlayer):
|
def evaluateWindow(self, window,player,otherPlayer):
|
||||||
if window.count(player) == 4:
|
if window.count(player) == 4:
|
||||||
return AIScores["win"]
|
return AISCORES["win"]
|
||||||
elif window.count(player) == 3 and window.count(0) == 1:
|
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:
|
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:
|
elif window.count(otherPlayer) == 4:
|
||||||
return AIScores["enemy win"]
|
return AISCORES["enemy win"]
|
||||||
else:
|
else:
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
@ -325,24 +401,24 @@ class connectFour():
|
|||||||
return points
|
return points
|
||||||
if maximizingPlayer:
|
if maximizingPlayer:
|
||||||
value = -math.inf
|
value = -math.inf
|
||||||
for column in range(0,columnCount):
|
for column in range(0,COLUMNCOUNT):
|
||||||
testBoard = copy.deepcopy(board)
|
testBoard = copy.deepcopy(board)
|
||||||
testBoard = self.placeOnBoard(testBoard,player,column)
|
testBoard = self.placeOnBoard(testBoard,player,column)
|
||||||
if testBoard != None:
|
if testBoard != None:
|
||||||
evaluation = await self.minimax(testBoard,depth-1,player%2+1,originalPlayer,alpha,beta,False)
|
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)
|
value = max(value,evaluation)
|
||||||
alpha = max(alpha,evaluation)
|
alpha = max(alpha,evaluation)
|
||||||
if beta <= alpha: break
|
if beta <= alpha: break
|
||||||
return value
|
return value
|
||||||
else:
|
else:
|
||||||
value = math.inf
|
value = math.inf
|
||||||
for column in range(0,columnCount):
|
for column in range(0,COLUMNCOUNT):
|
||||||
testBoard = copy.deepcopy(board)
|
testBoard = copy.deepcopy(board)
|
||||||
testBoard = self.placeOnBoard(testBoard,player,column)
|
testBoard = self.placeOnBoard(testBoard,player,column)
|
||||||
if testBoard != None:
|
if testBoard != None:
|
||||||
evaluation = await self.minimax(testBoard,depth-1,player%2+1,originalPlayer,alpha,beta,True)
|
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)
|
value = min(value,evaluation)
|
||||||
beta = min(beta,evaluation)
|
beta = min(beta,evaluation)
|
||||||
if beta <= alpha: break
|
if beta <= alpha: break
|
||||||
|
@ -140,23 +140,10 @@
|
|||||||
}
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"connectFourStop" : {
|
"connectFourSurrender" : {
|
||||||
"base" : "connectFour",
|
"base" : "connectFour",
|
||||||
"name" : "stop",
|
"name" : "surrender",
|
||||||
"description" : "Stop the game of connect four"
|
"description" : "Surrender 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"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
},
|
||||||
"downloading" : {
|
"downloading" : {
|
||||||
"name" : "downloading",
|
"name" : "downloading",
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import discord, traceback, discord_slash
|
import discord, traceback, discord_slash, sys
|
||||||
from discord.ext import commands
|
from discord.ext import commands
|
||||||
|
|
||||||
class EventHandler():
|
class EventHandler():
|
||||||
@ -31,8 +31,6 @@ class ErrorHandler():
|
|||||||
elif isinstance(error, commands.errors.MissingRequiredArgument):
|
elif isinstance(error, commands.errors.MissingRequiredArgument):
|
||||||
self.bot.log(f"{error}",str(ctx.channel_id))
|
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.")
|
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:
|
else:
|
||||||
exception = traceback.format_exception(type(error), error, error.__traceback__)
|
exception = traceback.format_exception(type(error), error, error.__traceback__)
|
||||||
stopAt = "\nThe above exception was the direct cause of the following exception:\n\n"
|
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)")
|
await ctx.send("Something went wrong (error code 000)")
|
||||||
|
|
||||||
async def on_error(self, method):
|
async def on_error(self, method):
|
||||||
exception = traceback.format_exc()
|
errorType = sys.exc_info()[0]
|
||||||
stopAt = "\nThe above exception was the direct cause of the following exception:\n\n"
|
if errorType == discord.errors.NotFound:
|
||||||
if stopAt in exception:
|
self.bot.log("Deleted message before I could add all reactions")
|
||||||
index = exception.index(stopAt)
|
else:
|
||||||
exception = exception[:index]
|
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)
|
exceptionString = "".join(exception)
|
||||||
self.bot.log([f"exception in {method}", f"{exceptionString}"], level = 40)
|
self.bot.log([f"exception in {method}", f"{exceptionString}"], level = 40)
|
@ -55,10 +55,10 @@ class databaseFuncs():
|
|||||||
|
|
||||||
if user != None:
|
if user != None:
|
||||||
return user["user name"]
|
return user["user name"]
|
||||||
elif userID == "Gwendolyn":
|
elif userID == f"#{self.bot.user.id}":
|
||||||
return userID
|
return "Gwendolyn"
|
||||||
else:
|
else:
|
||||||
self.bot.log("Couldn't find user "+userID)
|
self.bot.log(f"Couldn't find user {userID}")
|
||||||
return userID
|
return userID
|
||||||
|
|
||||||
def getID(self,userName):
|
def getID(self,userName):
|
||||||
@ -70,7 +70,7 @@ class databaseFuncs():
|
|||||||
self.bot.log("Couldn't find user "+userName)
|
self.bot.log("Couldn't find user "+userName)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
def deleteGame(self, gameType,channel):
|
def deleteGame(self, gameType, channel):
|
||||||
self.bot.database[gameType].delete_one({"_id":channel})
|
self.bot.database[gameType].delete_one({"_id":channel})
|
||||||
|
|
||||||
def stopServer(self):
|
def stopServer(self):
|
||||||
|
Reference in New Issue
Block a user