451 lines
20 KiB
Python
451 lines
20 KiB
Python
import random
|
|
import copy
|
|
import math
|
|
import discord
|
|
|
|
from .hexDraw import DrawHex
|
|
|
|
BOARDWIDTH = 11
|
|
ALL_POSITIONS = [(i,j) for i in range(11) for j in range(11)]
|
|
ALL_SET = set(ALL_POSITIONS)
|
|
EMPTY_DIJKSTRA = {}
|
|
for position in ALL_POSITIONS:
|
|
EMPTY_DIJKSTRA[position] = math.inf # an impossibly high number
|
|
HEX_DIRECTIONS = [(0,1),(-1,1),(-1,0),(0,-1),(1,-1),(1,0)]
|
|
|
|
class HexGame():
|
|
def __init__(self, bot):
|
|
self.bot = bot
|
|
self.draw = DrawHex(bot)
|
|
|
|
async def surrender(self, ctx):
|
|
channel = str(ctx.channel_id)
|
|
game = self.bot.database["hex games"].find_one({"_id":channel})
|
|
user = f"#{ctx.author.id}"
|
|
players = game["players"]
|
|
|
|
if user not in players:
|
|
await ctx.send("You can't surrender when you're not a player.")
|
|
else:
|
|
opponent = (players.index(user) + 1) % 2
|
|
opponentName = self.bot.databaseFuncs.getName(players[opponent])
|
|
self.bot.database["hex games"].update_one({"_id":channel},{"$set":{"winner":opponent + 1}})
|
|
await ctx.send(f"{ctx.author.display_name} surrendered. That means {opponentName} won! Adding 30 Gwendobucks to their account")
|
|
|
|
with open(f"resources/games/oldImages/hex{channel}", "r") as f:
|
|
oldImage = await ctx.channel.fetch_message(int(f.read()))
|
|
|
|
if oldImage is not None:
|
|
await oldImage.delete()
|
|
else:
|
|
self.bot.log("The old image was already deleted")
|
|
|
|
self.bot.log("Sending the image")
|
|
filePath = f"resources/games/hexBoards/board{channel}.png"
|
|
oldImage = await ctx.channel.send(file = discord.File(filePath))
|
|
|
|
with open(f"resources/games/oldImages/hex{channel}", "w") as f:
|
|
f.write(str(oldImage.id))
|
|
|
|
# Swap
|
|
async def swap(self, ctx):
|
|
channel = str(ctx.channel_id)
|
|
game = self.bot.database["hex games"].find_one({"_id":channel})
|
|
user = f"#{ctx.author.id}"
|
|
|
|
if game is None:
|
|
await ctx.send("You can't swap nothing")
|
|
elif user not in game["players"]:
|
|
await ctx.send("You're not in the game")
|
|
elif len(game["gameHistory"]) != 1: # Only after the first move
|
|
await ctx.send("You can only swap as the second player after the very first move.")
|
|
elif user != game["players"][game["turn"]-1]:
|
|
await ctx.send("You can only swap after your opponent has placed their piece")
|
|
else:
|
|
self.bot.database["hex games"].update_one({"_id":channel},
|
|
{"$set":{"players":game["players"][::-1]}}) # Swaps their player-number
|
|
|
|
# Swaps the color of the hexes on the board drawing:
|
|
self.draw.drawSwap(channel)
|
|
|
|
opponent = game["players"][::-1][game["turn"]-1]
|
|
gwendoTurn = (opponent == f"#{self.bot.user.id}")
|
|
opponentName = self.bot.databaseFuncs.getName(opponent)
|
|
await ctx.send(f"The color of the players were swapped. It is now {opponentName}'s turn")
|
|
|
|
with open(f"resources/games/oldImages/hex{channel}", "r") as f:
|
|
oldImage = await ctx.channel.fetch_message(int(f.read()))
|
|
|
|
if oldImage is not None:
|
|
await oldImage.delete()
|
|
else:
|
|
self.bot.log("The old image was already deleted")
|
|
|
|
self.bot.log("Sending the image")
|
|
filePath = f"resources/games/hexBoards/board{channel}.png"
|
|
oldImage = await ctx.channel.send(file = discord.File(filePath))
|
|
|
|
with open(f"resources/games/oldImages/hex{channel}", "w") as f:
|
|
f.write(str(oldImage.id))
|
|
|
|
if gwendoTurn:
|
|
await self.hexAI(ctx)
|
|
|
|
# Starts the game
|
|
async def start(self, ctx, opponent):
|
|
await self.bot.defer(ctx)
|
|
user = f"#{ctx.author.id}"
|
|
channel = str(ctx.channel_id)
|
|
game = self.bot.database["hex games"].find_one({"_id":channel})
|
|
|
|
startedGame = False
|
|
canStart = True
|
|
|
|
if game != None:
|
|
sendMessage = "There's already a hex 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):
|
|
opponentName = "Gwendolyn"
|
|
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
|
|
|
|
elif type(opponent) == discord.member.Member:
|
|
if opponent.bot:
|
|
# User has challenged a bot
|
|
if opponent == self.bot.user:
|
|
# It was Gwendolyn
|
|
opponentName = "Gwendolyn"
|
|
difficulty = 2
|
|
diffText = f" with difficulty {difficulty}"
|
|
opponent = f"#{self.bot.user.id}"
|
|
else:
|
|
sendMessage = "You can't challenge a bot!"
|
|
logMessage = "They tried to challenge a bot"
|
|
canStart = False
|
|
else:
|
|
# Opponent is another player
|
|
if ctx.author != opponent:
|
|
opponentName = opponent.display_name
|
|
opponent = f"#{opponent.id}"
|
|
difficulty = 5
|
|
diffText = ""
|
|
else:
|
|
sendMessage = "You can't play against yourself"
|
|
logMessage = "They tried to play against themself"
|
|
canStart = False
|
|
else:
|
|
canStart = False
|
|
logMessage = f"Opponent was neither int or member. It was {type(opponent)}"
|
|
sendMessage = "Something went wrong"
|
|
|
|
if canStart:
|
|
# board is 11x11
|
|
board = [[0 for i in range(BOARDWIDTH)] for j in range(BOARDWIDTH)]
|
|
players = [user, opponent]
|
|
random.shuffle(players) # random starting player
|
|
gameHistory = []
|
|
|
|
newGame = {"_id":channel,"board":board, "winner":0,
|
|
"players":players, "turn":1, "difficulty":difficulty, "gameHistory":gameHistory}
|
|
|
|
self.bot.database["hex games"].insert_one(newGame)
|
|
|
|
# draw the board
|
|
self.draw.drawBoard(channel)
|
|
|
|
gwendoTurn = (players[0] == f"#{self.bot.user.id}")
|
|
startedGame = True
|
|
|
|
turnName = self.bot.databaseFuncs.getName(players[0])
|
|
sendMessage = f"Started Hex game against {opponentName}{diffText}. It's {turnName}'s turn"
|
|
logMessage = "Game started"
|
|
|
|
await ctx.send(sendMessage)
|
|
self.bot.log(logMessage)
|
|
|
|
if startedGame:
|
|
filePath = f"resources/games/hexBoards/board{ctx.channel_id}.png"
|
|
newImage = await ctx.channel.send(file = discord.File(filePath))
|
|
|
|
with open(f"resources/games/oldImages/hex{ctx.channel_id}", "w") as f:
|
|
f.write(str(newImage.id))
|
|
|
|
if gwendoTurn:
|
|
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
|
|
|
|
if game == None:
|
|
sendMessage = "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."
|
|
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.databaseFuncs.getName(game['players'][0])} and {self.bot.databaseFuncs.getName(game['players'][1])}."
|
|
self.bot.log("They aren't in the game")
|
|
elif players[game["turn"]-1] != user:
|
|
sendMessage = "It's not your turn"
|
|
self.bot.log("It wasn't their turn")
|
|
else:
|
|
player = game["turn"]
|
|
turn = game["turn"]
|
|
board = game["board"]
|
|
|
|
self.bot.log("Placing a piece on the board with placeHex()")
|
|
# Places on board
|
|
board = self.placeOnHexBoard(board,player,position)
|
|
|
|
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.")
|
|
else:
|
|
# If the move is valid:
|
|
self.bot.database["hex games"].update_one({"_id":channel},{"$set":{"board":board}})
|
|
turn = (turn % 2) + 1
|
|
self.bot.database["hex games"].update_one({"_id":channel},{"$set":{"turn":turn}})
|
|
|
|
# Checking for a win
|
|
self.bot.log("Checking for win")
|
|
winner = self.evaluateBoard(game["board"])[1]
|
|
|
|
if winner == 0: # Continue with the game.
|
|
gameWon = False
|
|
sendMessage = 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}})
|
|
sendMessage = self.bot.databaseFuncs.getName(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."
|
|
|
|
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
|
|
if game["players"][turn-1] == f"#{self.bot.user.id}":
|
|
self.bot.log("It's Gwendolyn's turn")
|
|
gwendoTurn = True
|
|
|
|
placedPiece = True
|
|
|
|
if user == f"#{self.bot.user.id}":
|
|
await ctx.channel.send(sendMessage)
|
|
else:
|
|
await ctx.send(sendMessage)
|
|
|
|
if placedPiece:
|
|
# Update the board
|
|
self.draw.drawHexPlacement(channel,player, position)
|
|
|
|
with open(f"resources/games/oldImages/hex{channel}", "r") as f:
|
|
oldImage = await ctx.channel.fetch_message(int(f.read()))
|
|
|
|
if oldImage is not None:
|
|
await oldImage.delete()
|
|
else:
|
|
self.bot.log("The old image was already deleted")
|
|
|
|
self.bot.log("Sending the image")
|
|
filePath = f"resources/games/hexBoards/board{channel}.png"
|
|
oldImage = await ctx.channel.send(file = discord.File(filePath))
|
|
|
|
if gameWon:
|
|
self.bot.log("Dealing with the winning player")
|
|
game = self.bot.database["hex games"].find_one({"_id":channel})
|
|
|
|
winner = game["winner"]
|
|
if game["players"][winner-1] != f"#{self.bot.user.id}":
|
|
winnings = game["difficulty"]*10
|
|
self.bot.money.addMoney(game["players"][winner-1].lower(),winnings)
|
|
else:
|
|
with open(f"resources/games/oldImages/hex{channel}", "w") as f:
|
|
f.write(str(oldImage.id))
|
|
|
|
if gwendoTurn:
|
|
await self.hexAI(ctx)
|
|
|
|
# Returns a board where the placement has ocurred
|
|
def placeOnHexBoard(self, board,player,position):
|
|
# Translates the position
|
|
position = position.lower()
|
|
# Error handling
|
|
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):
|
|
self.bot.log("Position out of bounds")
|
|
return None
|
|
# Place at the position
|
|
if board[row][column] == 0:
|
|
board[row][column] = player
|
|
return board
|
|
else:
|
|
self.bot.log("Cannot place on existing piece (error code 1532)")
|
|
return None
|
|
|
|
# After your move, you have the option to undo get your turn back #TimeTravel
|
|
async def undo(self, ctx):
|
|
channel = str(ctx.channel_id)
|
|
user = f"#{ctx.author.id}"
|
|
undid = False
|
|
|
|
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"
|
|
elif len(game["gameHistory"]) == 0:
|
|
sendMessage = "You can't undo nothing"
|
|
elif user != game["players"][(game["turn"] % 2)]: # If it's not your turn
|
|
sendMessage = "It's not your turn"
|
|
else:
|
|
turn = game["turn"]
|
|
self.bot.log("Undoing {}'s last move".format(self.bot.databaseFuncs.getName(user)))
|
|
|
|
lastMove = game["gameHistory"].pop()
|
|
game["board"][lastMove[0]][lastMove[1]] = 0
|
|
self.bot.database["hex games"].update_one({"_id":channel},
|
|
{"$set":{"board":game["board"]}})
|
|
self.bot.database["hex games"].update_one({"_id":channel},
|
|
{"$set":{"turn":turn%2 + 1}})
|
|
|
|
# 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}"
|
|
undid = True
|
|
|
|
await ctx.send(sendMessage)
|
|
if undid:
|
|
with open(f"resources/games/oldImages/hex{channel}", "r") as f:
|
|
oldImage = await ctx.channel.fetch_message(int(f.read()))
|
|
|
|
if oldImage is not None:
|
|
await oldImage.delete()
|
|
else:
|
|
self.bot.log("The old image was already deleted")
|
|
|
|
self.bot.log("Sending the image")
|
|
filePath = f"resources/games/hexBoards/board{channel}.png"
|
|
oldImage = await ctx.channel.send(file = discord.File(filePath))
|
|
|
|
with open(f"resources/games/oldImages/hex{channel}", "w") as f:
|
|
f.write(str(oldImage.id))
|
|
|
|
|
|
# Plays as the AI
|
|
async def hexAI(self, ctx):
|
|
channel = str(ctx.channel_id)
|
|
self.bot.log("Figuring out best move")
|
|
game = self.bot.database["hex games"].find_one({"_id":channel})
|
|
board = game["board"]
|
|
|
|
if len(game["gameHistory"]):
|
|
lastMove = game["gameHistory"][-1]
|
|
else:
|
|
lastMove = (5,5)
|
|
|
|
# These moves are the last move +- 2.
|
|
moves = [[(lastMove[0]+j-2,lastMove[1]+i-2) for i in range(5) if lastMove[1]+i-2 in range(11)] for j in range(5) if lastMove[0]+j-2 in range(11)]
|
|
moves = sum(moves,[])
|
|
movesCopy = moves.copy()
|
|
for move in movesCopy:
|
|
if board[move[0]][move[1]] != 0:
|
|
moves.remove(move)
|
|
chosenMove = random.choice(moves)
|
|
|
|
placement = "abcdefghijk"[chosenMove[1]]+str(chosenMove[0]+1)
|
|
self.bot.log(f"ChosenMove is {chosenMove} at {placement}")
|
|
|
|
await self.placeHex(ctx, placement, f"#{self.bot.user.id}")
|
|
|
|
|
|
def evaluateBoard(self, board):
|
|
scores = {1:0, 2:0}
|
|
winner = 0
|
|
# Here, I use Dijkstra's algorithm to evaluate the board, as proposed by this article: https://towardsdatascience.com/hex-creating-intelligent-adversaries-part-2-heuristics-dijkstras-algorithm-597e4dcacf93
|
|
for player in [1,2]:
|
|
Distance = copy.deepcopy(EMPTY_DIJKSTRA)
|
|
# Initialize the starting hexes. For the blue player, this is the leftmost column. For the red player, this is the tom row.
|
|
for start in (ALL_POSITIONS[::11] if player == 2 else ALL_POSITIONS[:11]):
|
|
# An empty hex adds a of distance of 1. A hex of own color add distance 0. Opposite color adds infinite distance.
|
|
Distance[start] = 1 if (board[start[0]][start[1]] == 0) else 0 if (board[start[0]][start[1]] == player) else math.inf
|
|
visited = set() # Also called sptSet, short for "shortest path tree Set"
|
|
for _ in range(BOARDWIDTH**2): # We can at most check every 121 hexes
|
|
# Find the next un-visited hex, that has the lowest distance
|
|
remainingHexes = ALL_SET.difference(visited)
|
|
A = [Distance[k] for k in remainingHexes] # Find the distance to each un-visited hex
|
|
u = list(remainingHexes)[A.index(min(A))] # Chooses the one with the lowest distance
|
|
|
|
# Find neighbors of the hex u
|
|
for di in HEX_DIRECTIONS:
|
|
v = (u[0] + di[0] , u[1] + di[1]) # v is a neighbor of u
|
|
if v[0] in range(11) and v[1] in range(11) and v not in visited:
|
|
new_dist = Distance[u] + (1 if (board[v[0]][v[1]] == 0) else 0 if (board[v[0]][v[1]] == player) else math.inf)
|
|
Distance[v] = min(Distance[v], new_dist)
|
|
# After a hex has been visited, this is noted
|
|
visited.add(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:
|
|
self.bot.log("For some reason, no path to the goal was found. ")
|
|
if scores[player] == 0:
|
|
winner = player
|
|
break # We don't need to check the other player's score, if player1 won.
|
|
return scores[2]-scores[1], winner
|
|
|
|
|
|
def minimaxHex(self, board, depth, alpha, beta, maximizingPlayer):
|
|
# 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
|
|
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 // BOARDWIDTH][i % BOARDWIDTH] = 1 # because maximizingPlayer is Red which is number 1
|
|
evaluation = self.minimaxHex(testBoard,depth-1,alpha,beta,False)
|
|
maxEval = max(maxEval, evaluation)
|
|
alpha = max(alpha, evaluation)
|
|
if beta <= alpha:
|
|
#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]
|
|
#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
|
|
evaluation = self.minimaxHex(testBoard,depth-1,alpha,beta,True)
|
|
minEval = min(minEval, evaluation)
|
|
beta = min(beta, evaluation)
|
|
if beta <= alpha:
|
|
#self.bot.log("Just pruned something!")
|
|
break
|
|
return minEval
|
|
|