🧹 More refactoring
This commit is contained in:
@ -28,7 +28,7 @@ class HexGame():
|
||||
await ctx.send("You can't surrender when you're not a player.")
|
||||
else:
|
||||
opponent = (players.index(user) + 1) % 2
|
||||
opponentName = self.bot.database_funcs.get_name(players[opponent])
|
||||
opponent_name = self.bot.database_funcs.get_name(players[opponent])
|
||||
self.bot.database["hex games"].update_one({"_id":channel},{"$set":{"winner":opponent + 1}})
|
||||
await ctx.send(f"{ctx.author.display_name} surrendered")
|
||||
|
||||
@ -71,9 +71,9 @@ class HexGame():
|
||||
self.draw.drawSwap(channel)
|
||||
|
||||
opponent = game["players"][::-1][game["turn"]-1]
|
||||
gwendoTurn = (opponent == f"#{self.bot.user.id}")
|
||||
opponentName = self.bot.database_funcs.get_name(opponent)
|
||||
await ctx.send(f"The color of the players were swapped. It is now {opponentName}'s turn")
|
||||
gwendolyn_turn = (opponent == f"#{self.bot.user.id}")
|
||||
opponent_name = self.bot.database_funcs.get_name(opponent)
|
||||
await ctx.send(f"The color of the players were swapped. It is now {opponent_name}'s turn")
|
||||
|
||||
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "r") as f:
|
||||
old_image = await ctx.channel.fetch_message(int(f.read()))
|
||||
@ -90,7 +90,7 @@ class HexGame():
|
||||
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "w") as f:
|
||||
f.write(str(old_image.id))
|
||||
|
||||
if gwendoTurn:
|
||||
if gwendolyn_turn:
|
||||
await self.hexAI(ctx)
|
||||
|
||||
# Starts the game
|
||||
@ -100,109 +100,109 @@ class HexGame():
|
||||
channel = str(ctx.channel_id)
|
||||
game = self.bot.database["hex games"].find_one({"_id":channel})
|
||||
|
||||
startedGame = False
|
||||
canStart = True
|
||||
started_game = False
|
||||
can_start = True
|
||||
|
||||
if game != None:
|
||||
sendMessage = "There's already a hex game going on in this channel"
|
||||
send_message = "There's already a hex game going on in this channel"
|
||||
log_message = "There was already a game going on"
|
||||
canStart = False
|
||||
can_start = False
|
||||
else:
|
||||
if type(opponent) == int:
|
||||
# Opponent is Gwendolyn
|
||||
if opponent in range(1, 6):
|
||||
opponentName = "Gwendolyn"
|
||||
opponent_name = "Gwendolyn"
|
||||
difficulty = int(opponent)
|
||||
diffText = f" with difficulty {difficulty}"
|
||||
difficulty_text = f" with difficulty {difficulty}"
|
||||
opponent = f"#{self.bot.user.id}"
|
||||
else:
|
||||
sendMessage = "Difficulty doesn't exist"
|
||||
send_message = "Difficulty doesn't exist"
|
||||
log_message = "They tried to play against a difficulty that doesn't exist"
|
||||
canStart = False
|
||||
can_start = False
|
||||
|
||||
elif type(opponent) == discord.member.Member:
|
||||
if opponent.bot:
|
||||
# User has challenged a bot
|
||||
if opponent == self.bot.user:
|
||||
# It was Gwendolyn
|
||||
opponentName = "Gwendolyn"
|
||||
opponent_name = "Gwendolyn"
|
||||
difficulty = 2
|
||||
diffText = f" with difficulty {difficulty}"
|
||||
difficulty_text = f" with difficulty {difficulty}"
|
||||
opponent = f"#{self.bot.user.id}"
|
||||
else:
|
||||
sendMessage = "You can't challenge a bot!"
|
||||
send_message = "You can't challenge a bot!"
|
||||
log_message = "They tried to challenge a bot"
|
||||
canStart = False
|
||||
can_start = False
|
||||
else:
|
||||
# Opponent is another player
|
||||
if ctx.author != opponent:
|
||||
opponentName = opponent.display_name
|
||||
opponent_name = opponent.display_name
|
||||
opponent = f"#{opponent.id}"
|
||||
difficulty = 5
|
||||
diffText = ""
|
||||
difficulty_text = ""
|
||||
else:
|
||||
sendMessage = "You can't play against yourself"
|
||||
send_message = "You can't play against yourself"
|
||||
log_message = "They tried to play against themself"
|
||||
canStart = False
|
||||
can_start = False
|
||||
else:
|
||||
canStart = False
|
||||
can_start = False
|
||||
log_message = f"Opponent was neither int or member. It was {type(opponent)}"
|
||||
sendMessage = "Something went wrong"
|
||||
send_message = "Something went wrong"
|
||||
|
||||
if canStart:
|
||||
if can_start:
|
||||
# board is 11x11
|
||||
board = [[0 for i in range(self.BOARDWIDTH)] for j in range(self.BOARDWIDTH)]
|
||||
players = [user, opponent]
|
||||
random.shuffle(players) # random starting player
|
||||
gameHistory = []
|
||||
|
||||
newGame = {"_id":channel,"board":board, "winner":0,
|
||||
new_game = {"_id":channel,"board":board, "winner":0,
|
||||
"players":players, "turn":1, "difficulty":difficulty, "gameHistory":gameHistory}
|
||||
|
||||
self.bot.database["hex games"].insert_one(newGame)
|
||||
self.bot.database["hex games"].insert_one(new_game)
|
||||
|
||||
# draw the board
|
||||
self.draw.drawBoard(channel)
|
||||
|
||||
gwendoTurn = (players[0] == f"#{self.bot.user.id}")
|
||||
startedGame = True
|
||||
gwendolyn_turn = (players[0] == f"#{self.bot.user.id}")
|
||||
started_game = True
|
||||
|
||||
turnName = self.bot.database_funcs.get_name(players[0])
|
||||
sendMessage = f"Started Hex game against {opponentName}{diffText}. It's {turnName}'s turn"
|
||||
turn_name = self.bot.database_funcs.get_name(players[0])
|
||||
send_message = f"Started Hex game against {opponent_name}{difficulty_text}. It's {turn_name}'s turn"
|
||||
log_message = "Game started"
|
||||
|
||||
await ctx.send(sendMessage)
|
||||
await ctx.send(send_message)
|
||||
self.bot.log(log_message)
|
||||
|
||||
if startedGame:
|
||||
if started_game:
|
||||
file_path = f"gwendolyn/resources/games/hex_boards/board{ctx.channel_id}.png"
|
||||
newImage = await ctx.channel.send(file = discord.File(file_path))
|
||||
new_image = await ctx.channel.send(file = discord.File(file_path))
|
||||
|
||||
with open(f"gwendolyn/resources/games/old_images/hex{ctx.channel_id}", "w") as f:
|
||||
f.write(str(newImage.id))
|
||||
f.write(str(new_image.id))
|
||||
|
||||
if gwendoTurn:
|
||||
if gwendolyn_turn:
|
||||
await self.hexAI(ctx)
|
||||
|
||||
# Places a piece at the given location and checks things afterwards
|
||||
async def placeHex(self, ctx, position : str, user):
|
||||
channel = str(ctx.channel_id)
|
||||
game = self.bot.database["hex games"].find_one({"_id":channel})
|
||||
placedPiece = False
|
||||
placed_piece = False
|
||||
|
||||
if game == None:
|
||||
sendMessage = "There's no game in this channel"
|
||||
send_message = "There's no game in this channel"
|
||||
self.bot.log("There was no game going on")
|
||||
elif not (position[0].isalpha() and position[1:].isnumeric() and len(position) in [2, 3]):
|
||||
sendMessage = "The position must be a letter followed by a number."
|
||||
send_message = "The position must be a letter followed by a number."
|
||||
self.bot.log(f"The position was not valid, {position}")
|
||||
else:
|
||||
players = game["players"]
|
||||
if user not in players:
|
||||
sendMessage = f"You can't place when you're not in the game. The game's players are: {self.bot.database_funcs.get_name(game['players'][0])} and {self.bot.database_funcs.get_name(game['players'][1])}."
|
||||
send_message = f"You can't place when you're not in the game. The game's players are: {self.bot.database_funcs.get_name(game['players'][0])} and {self.bot.database_funcs.get_name(game['players'][1])}."
|
||||
self.bot.log("They aren't in the game")
|
||||
elif players[game["turn"]-1] != user:
|
||||
sendMessage = "It's not your turn"
|
||||
send_message = "It's not your turn"
|
||||
self.bot.log("It wasn't their turn")
|
||||
else:
|
||||
player = game["turn"]
|
||||
@ -215,7 +215,7 @@ class HexGame():
|
||||
|
||||
if board is None:
|
||||
self.bot.log("It was an invalid position")
|
||||
sendMessage = ("That's an invalid position. You must place your piece on an empty field.")
|
||||
send_message = ("That's an invalid position. You must place your piece on an empty field.")
|
||||
else:
|
||||
# If the move is valid:
|
||||
self.bot.database["hex games"].update_one({"_id":channel},{"$set":{"board":board}})
|
||||
@ -227,34 +227,34 @@ class HexGame():
|
||||
winner = self.evaluateBoard(game["board"])[1]
|
||||
|
||||
if winner == 0: # Continue with the game.
|
||||
gameWon = False
|
||||
sendMessage = self.bot.database_funcs.get_name(game["players"][player-1])+" placed at "+position.upper()+". It's now "+self.bot.database_funcs.get_name(game["players"][turn-1])+"'s turn."# The score is "+str(score)
|
||||
game_won = False
|
||||
send_message = self.bot.database_funcs.get_name(game["players"][player-1])+" placed at "+position.upper()+". It's now "+self.bot.database_funcs.get_name(game["players"][turn-1])+"'s turn."# The score is "+str(score)
|
||||
|
||||
else: # Congratulations!
|
||||
gameWon = True
|
||||
game_won = True
|
||||
self.bot.database["hex games"].update_one({"_id":channel},{"$set":{"winner":winner}})
|
||||
sendMessage = self.bot.database_funcs.get_name(game["players"][player-1])+" placed at "+position.upper()+" and won!"
|
||||
send_message = self.bot.database_funcs.get_name(game["players"][player-1])+" placed at "+position.upper()+" and won!"
|
||||
if game["players"][winner-1] != f"#{self.bot.user.id}":
|
||||
winAmount = game["difficulty"]*10
|
||||
sendMessage += " Adding "+str(winAmount)+" GwendoBucks to their account."
|
||||
win_amount = game["difficulty"]*10
|
||||
send_message += " Adding "+str(win_amount)+" GwendoBucks to their account."
|
||||
|
||||
self.bot.database["hex games"].update_one({"_id":channel},
|
||||
{"$push":{"gameHistory":(int(position[1])-1, ord(position[0])-97)}})
|
||||
|
||||
# Is it now Gwendolyn's turn?
|
||||
gwendoTurn = False
|
||||
gwendolyn_turn = False
|
||||
if game["players"][turn-1] == f"#{self.bot.user.id}":
|
||||
self.bot.log("It's Gwendolyn's turn")
|
||||
gwendoTurn = True
|
||||
gwendolyn_turn = True
|
||||
|
||||
placedPiece = True
|
||||
placed_piece = True
|
||||
|
||||
if user == f"#{self.bot.user.id}":
|
||||
await ctx.channel.send(sendMessage)
|
||||
await ctx.channel.send(send_message)
|
||||
else:
|
||||
await ctx.send(sendMessage)
|
||||
await ctx.send(send_message)
|
||||
|
||||
if placedPiece:
|
||||
if placed_piece:
|
||||
# Update the board
|
||||
self.draw.drawHexPlacement(channel,player, position)
|
||||
|
||||
@ -270,7 +270,7 @@ class HexGame():
|
||||
file_path = f"gwendolyn/resources/games/hex_boards/board{channel}.png"
|
||||
old_image = await ctx.channel.send(file = discord.File(file_path))
|
||||
|
||||
if gameWon:
|
||||
if game_won:
|
||||
self.bot.log("Dealing with the winning player")
|
||||
game = self.bot.database["hex games"].find_one({"_id":channel})
|
||||
|
||||
@ -284,7 +284,7 @@ class HexGame():
|
||||
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "w") as f:
|
||||
f.write(str(old_image.id))
|
||||
|
||||
if gwendoTurn:
|
||||
if gwendolyn_turn:
|
||||
await self.hexAI(ctx)
|
||||
|
||||
# Returns a board where the placement has ocurred
|
||||
@ -314,11 +314,11 @@ class HexGame():
|
||||
game = self.bot.database["hex games"].find_one({"_id":channel})
|
||||
|
||||
if user not in game["players"]:
|
||||
sendMessage = "You're not a player in the game"
|
||||
send_message = "You're not a player in the game"
|
||||
elif len(game["gameHistory"]) == 0:
|
||||
sendMessage = "You can't undo nothing"
|
||||
send_message = "You can't undo nothing"
|
||||
elif user != game["players"][(game["turn"] % 2)]: # If it's not your turn
|
||||
sendMessage = "It's not your turn"
|
||||
send_message = "It's not your turn"
|
||||
else:
|
||||
turn = game["turn"]
|
||||
self.bot.log("Undoing {}'s last move".format(self.bot.database_funcs.get_name(user)))
|
||||
@ -332,10 +332,10 @@ class HexGame():
|
||||
|
||||
# Update the board
|
||||
self.draw.drawHexPlacement(channel,0,"abcdefghijk"[lastMove[1]]+str(lastMove[0]+1)) # The zero makes the hex disappear
|
||||
sendMessage = f"You undid your last move at {lastMove}"
|
||||
send_message = f"You undid your last move at {lastMove}"
|
||||
undid = True
|
||||
|
||||
await ctx.send(sendMessage)
|
||||
await ctx.send(send_message)
|
||||
if undid:
|
||||
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "r") as f:
|
||||
old_image = await ctx.channel.fetch_message(int(f.read()))
|
||||
@ -417,20 +417,20 @@ class HexGame():
|
||||
return scores[2]-scores[1], winner
|
||||
|
||||
|
||||
def minimaxHex(self, board, depth, alpha, beta, maximizingPlayer):
|
||||
def minimaxHex(self, board, depth, alpha, beta, maximizing_player):
|
||||
# The depth is how many moves ahead the computer checks. This value is the difficulty.
|
||||
if depth == 0 or 0 not in sum(board,[]):
|
||||
score = self.evaluateBoard(board)[0]
|
||||
return score
|
||||
# if final depth is not reached, look another move ahead:
|
||||
if maximizingPlayer: # red player predicts next move
|
||||
if maximizing_player: # red player predicts next move
|
||||
maxEval = -math.inf
|
||||
possiblePlaces = [i for i,v in enumerate(sum(board,[])) if v == 0]
|
||||
#self.bot.log("Judging a red move at depth {}".format(depth))
|
||||
for i in possiblePlaces:
|
||||
testBoard = copy.deepcopy(board)
|
||||
testBoard[i // self.BOARDWIDTH][i % self.BOARDWIDTH] = 1 # because maximizingPlayer is Red which is number 1
|
||||
evaluation = self.minimaxHex(testBoard,depth-1,alpha,beta,False)
|
||||
test_board = copy.deepcopy(board)
|
||||
test_board[i // self.BOARDWIDTH][i % self.BOARDWIDTH] = 1 # because maximizing_player is Red which is number 1
|
||||
evaluation = self.minimaxHex(test_board,depth-1,alpha,beta,False)
|
||||
maxEval = max(maxEval, evaluation)
|
||||
alpha = max(alpha, evaluation)
|
||||
if beta <= alpha:
|
||||
@ -442,9 +442,9 @@ class HexGame():
|
||||
possiblePlaces = [i for i,v in enumerate(sum(board,[])) if v == 0]
|
||||
#self.bot.log("Judging a blue move at depth {}".format(depth))
|
||||
for i in possiblePlaces:
|
||||
testBoard = copy.deepcopy(board)
|
||||
testBoard[i // self.BOARDWIDTH][i % self.BOARDWIDTH] = 2 # because minimizingPlayer is Blue which is number 2
|
||||
evaluation = self.minimaxHex(testBoard,depth-1,alpha,beta,True)
|
||||
test_board = copy.deepcopy(board)
|
||||
test_board[i // self.BOARDWIDTH][i % self.BOARDWIDTH] = 2 # because minimizingPlayer is Blue which is number 2
|
||||
evaluation = self.minimaxHex(test_board,depth-1,alpha,beta,True)
|
||||
minEval = min(minEval, evaluation)
|
||||
beta = min(beta, evaluation)
|
||||
if beta <= alpha:
|
||||
|
Reference in New Issue
Block a user