import random
import copy
import math
import discord

from PIL import Image, ImageDraw, ImageFont

class HexGame():
  def __init__(self, bot):
    self.bot = bot
    self.draw = DrawHex(bot)
    self.BOARDWIDTH = 11
    self.ALLPOSITIONS = [(i,j) for i in range(11) for j in range(11)]
    self.ALLSET = set(self.ALLPOSITIONS)
    self.EMPTYDIJKSTRA = {}
    for position in self.ALLPOSITIONS:
      self.EMPTYDIJKSTRA[position] = math.inf # an impossibly high number
    self.HEXDIRECTIONS = [(0,1),(-1,1),(-1,0),(0,-1),(1,-1),(1,0)]

  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
      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")

      with open(f"gwendolyn/resources/games/old_images/hex{channel}", "r") as f:
        old_image = await ctx.channel.fetch_message(int(f.read()))

      if old_image is not None:
        await old_image.delete()
      else:
        self.bot.log("The old image was already deleted")

      self.bot.log("Sending the image")
      file_path = f"gwendolyn/resources/games/hex_boards/board{channel}.png"
      old_image = await ctx.channel.send(file = discord.File(file_path))

      with open(f"gwendolyn/resources/games/old_images/hex{channel}", "w") as f:
        f.write(str(old_image.id))

      self.bot.database["hex games"].delete_one({"_id":channel})

  # 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]
      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()))

      if old_image is not None:
        await old_image.delete()
      else:
        self.bot.log("The old image was already deleted")

      self.bot.log("Sending the image")
      file_path = f"gwendolyn/resources/games/hex_boards/board{channel}.png"
      old_image = await ctx.channel.send(file = discord.File(file_path))

      with open(f"gwendolyn/resources/games/old_images/hex{channel}", "w") as f:
        f.write(str(old_image.id))

      if gwendolyn_turn:
        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})

    started_game = False
    can_start = True

    if game != None:
      send_message = "There's already a hex game going on in this channel"
      log_message = "There was already a game going on"
      can_start = False
    else:
      if type(opponent) == int:
        # Opponent is Gwendolyn
        if opponent in range(1, 6):
          opponent_name = "Gwendolyn"
          difficulty = int(opponent)
          difficulty_text = f" with difficulty {difficulty}"
          opponent = f"#{self.bot.user.id}"
        else:
          send_message = "Difficulty doesn't exist"
          log_message = "They tried to play against a difficulty that doesn't exist"
          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
            opponent_name = "Gwendolyn"
            difficulty = 2
            difficulty_text = f" with difficulty {difficulty}"
            opponent = f"#{self.bot.user.id}"
          else:
            send_message = "You can't challenge a bot!"
            log_message = "They tried to challenge a bot"
            can_start = False
        else:
          # Opponent is another player
          if ctx.author != opponent:
            opponent_name = opponent.display_name
            opponent = f"#{opponent.id}"
            difficulty = 5
            difficulty_text = ""
          else:
            send_message = "You can't play against yourself"
            log_message = "They tried to play against themself"
            can_start = False
      else:
        can_start = False
        log_message = f"Opponent was neither int or member. It was {type(opponent)}"
        send_message = "Something went wrong"

    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 = []

      new_game = {"_id":channel,"board":board, "winner":0,
        "players":players, "turn":1, "difficulty":difficulty, "gameHistory":gameHistory}

      self.bot.database["hex games"].insert_one(new_game)

      # draw the board
      self.draw.drawBoard(channel)

      gwendolyn_turn = (players[0] == f"#{self.bot.user.id}")
      started_game = True

      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(send_message)
    self.bot.log(log_message)

    if started_game:
      file_path = f"gwendolyn/resources/games/hex_boards/board{ctx.channel_id}.png"
      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(new_image.id))

      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})
    placed_piece = False

    if game == None:
      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]):
      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:
        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:
        send_message = "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")
          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}})
          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.
            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!
            game_won = True
            self.bot.database["hex games"].update_one({"_id":channel},{"$set":{"winner":winner}})
            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}":
              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?
          gwendolyn_turn = False
          if game["players"][turn-1] == f"#{self.bot.user.id}":
            self.bot.log("It's Gwendolyn's turn")
            gwendolyn_turn = True

          placed_piece = True

    if user == f"#{self.bot.user.id}":
      await ctx.channel.send(send_message)
    else:
      await ctx.send(send_message)

    if placed_piece:
      # Update the board
      self.draw.drawHexPlacement(channel,player, position)

      with open(f"gwendolyn/resources/games/old_images/hex{channel}", "r") as f:
        old_image = await ctx.channel.fetch_message(int(f.read()))

      if old_image is not None:
        await old_image.delete()
      else:
        self.bot.log("The old image was already deleted")

      self.bot.log("Sending the image")
      file_path = f"gwendolyn/resources/games/hex_boards/board{channel}.png"
      old_image = await ctx.channel.send(file = discord.File(file_path))

      if game_won:
        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)

        self.bot.database["hex games"].delete_one({"_id":channel})
      else:
        with open(f"gwendolyn/resources/games/old_images/hex{channel}", "w") as f:
          f.write(str(old_image.id))

        if gwendolyn_turn:
          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(self.BOARDWIDTH) or row not in range(self.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")
      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"]:
      send_message = "You're not a player in the game"
    elif len(game["gameHistory"]) == 0:
      send_message = "You can't undo nothing"
    elif user != game["players"][(game["turn"] % 2)]: # If 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)))

      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
      send_message = f"You undid your last move at {lastMove}"
      undid = True

    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()))

      if old_image is not None:
        await old_image.delete()
      else:
        self.bot.log("The old image was already deleted")

      self.bot.log("Sending the image")
      file_path = f"gwendolyn/resources/games/hex_boards/board{channel}.png"
      old_image = await ctx.channel.send(file = discord.File(file_path))

      with open(f"gwendolyn/resources/games/old_images/hex{channel}", "w") as f:
        f.write(str(old_image.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(self.EMPTYDIJKSTRA)
      # 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 (self.ALLPOSITIONS[::11] if player == 2 else self.ALLPOSITIONS[: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(self.BOARDWIDTH**2): # We can at most check every 121 hexes
        # Find the next un-visited hex, that has the lowest distance
        remainingHexes = self.ALLSET.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 self.HEXDIRECTIONS:
          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, 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 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:
        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:
          #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:
        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:
          #self.bot.log("Just pruned something!")
          break
      return minEval

class DrawHex():
  def __init__(self,bot):
    self.bot = bot
    # Defining all the variables
    self.CANVASWIDTH  = 2400
    self.CANVASHEIGHT = 1800
    self.SIDELENGTH = 75

    # The offsets centers the board in the picture
    self.XOFFSET = self.CANVASWIDTH/2 - 8*math.sqrt(3)*self.SIDELENGTH

    # The offsets are the coordinates of the upperleft point in the
    # upperleftmost hexagon
    self.YOFFSET = self.CANVASHEIGHT/2 - 8*self.SIDELENGTH

    # The whole width of one hexagon
    self.HEXAGONWIDTH = math.sqrt(3) * self.SIDELENGTH

    # The height difference between two layers
    self.HEXAGONHEIGHT = 1.5 * self.SIDELENGTH
    self.FONTSIZE = 45
    self.TEXTCOLOR = (0,0,0)
    self.FONT = ImageFont.truetype('gwendolyn/resources/fonts/futura-bold.ttf', self.FONTSIZE)

    self.LINETHICKNESS = 15
    self.HEXTHICKNESS = 6 # This is half the width of the background lining between every hex
    self.XTHICKNESS = self.HEXTHICKNESS * math.cos(math.pi/6)
    self.YTHICKNESS = self.HEXTHICKNESS * math.sin(math.pi/6)
    self.BACKGROUNDCOLOR = (230,230,230)
    self.BETWEENCOLOR = (231,231,231)
    self.BLANKCOLOR = "lightgrey"
    self.PIECECOLOR = {1:(237,41,57),2:(0,165,255),0:self.BLANKCOLOR} # player1 is red, player2 is blue
    self.BOARDCOORDINATES = [ [(self.XOFFSET + self.HEXAGONWIDTH*(column + row/2),self.YOFFSET + self.HEXAGONHEIGHT*row) for column in range(11)] for row in range(11)] # These are the coordinates for the upperleft corner of every hex
    self.COLHEXTHICKNESS = 4 # When placing a hex, it is a little bigger than the underlying hex in the background (4 < 6)
    self.COLXTHICKNESS = self.COLHEXTHICKNESS * math.cos(math.pi/6)
    self.COLYTHICKNESS = self.COLHEXTHICKNESS * math.sin(math.pi/6)
    # The Name display things:
    self.NAMESIZE = 60
    self.NAMEFONT = ImageFont.truetype('gwendolyn/resources/fonts/futura-bold.ttf', self.NAMESIZE)
    self.XNAME = {1:175, 2:self.CANVASWIDTH-100}
    self.YNAME = {1:self.CANVASHEIGHT-150, 2:150}
    self.NAMEHEXPADDING = 90
    self.SMALLWIDTH = self.HEXAGONWIDTH * 0.6
    self.SMALLSIDELENGTH = self.SIDELENGTH * 0.6

  def drawBoard(self, channel):
    self.bot.log("Drawing empty Hex board")

    # Creates the empty image
    im = Image.new('RGB', size=(self.CANVASWIDTH, self.CANVASHEIGHT),color = self.BACKGROUNDCOLOR)
    # 'd' is a shortcut to drawing on the image
    d = ImageDraw.Draw(im,"RGBA")

    # Drawing all the hexagons
    for column in self.BOARDCOORDINATES:
      for startingPoint in column:
        x = startingPoint[0]
        y = startingPoint[1]
        d.polygon([
          (x,          y),
          (x+self.HEXAGONWIDTH/2,   y-0.5*self.SIDELENGTH),
          (x+self.HEXAGONWIDTH,   y),
          (x+self.HEXAGONWIDTH,   y+self.SIDELENGTH),
          (x+self.HEXAGONWIDTH/2,   y+1.5*self.SIDELENGTH),
          (x,          y+self.SIDELENGTH),
        ],fill = self.BETWEENCOLOR)
        d.polygon([
          (x+self.XTHICKNESS,        y + self.YTHICKNESS),
          (x+self.HEXAGONWIDTH/2,       y-0.5*self.SIDELENGTH + self.HEXTHICKNESS),
          (x+self.HEXAGONWIDTH-self.XTHICKNESS,   y + self.YTHICKNESS),
          (x+self.HEXAGONWIDTH-self.XTHICKNESS,   y+self.SIDELENGTH - self.YTHICKNESS),
          (x+self.HEXAGONWIDTH/2,       y+1.5*self.SIDELENGTH - self.HEXTHICKNESS),
          (x+self.XTHICKNESS,        y+self.SIDELENGTH - self.YTHICKNESS),
        ],fill = self.BLANKCOLOR)

    # Draw color on the outside of the board
    # Top line, red
    d.line(sum((sum([(point[0],point[1],point[0]+self.HEXAGONWIDTH/2,point[1]-self.HEXAGONHEIGHT+self.SIDELENGTH) for point in self.BOARDCOORDINATES[0]],()),(self.BOARDCOORDINATES[0][10][0]+self.HEXAGONWIDTH*3/4,self.BOARDCOORDINATES[0][10][1]-self.SIDELENGTH/4)),()),
        fill = self.PIECECOLOR[1],width = self.LINETHICKNESS)
    # Bottom line, red
    d.line(sum(((self.BOARDCOORDINATES[10][0][0]+self.HEXAGONWIDTH/4,self.BOARDCOORDINATES[10][0][1]+self.SIDELENGTH*5/4),sum([(point[0]+self.HEXAGONWIDTH/2,point[1]+self.HEXAGONHEIGHT,point[0]+self.HEXAGONWIDTH,point[1]+self.SIDELENGTH) for point in self.BOARDCOORDINATES[10]],())),()),
        fill = self.PIECECOLOR[1],width = self.LINETHICKNESS)
    # Left line, blue
    d.line(sum((sum([(row[0][0],row[0][1],row[0][0],row[0][1]+self.SIDELENGTH) for row in self.BOARDCOORDINATES],()),(self.BOARDCOORDINATES[10][0][0]+self.HEXAGONWIDTH/4,self.BOARDCOORDINATES[10][0][1]+self.SIDELENGTH*5/4)),()),
        fill = self.PIECECOLOR[2],width = self.LINETHICKNESS)
    # Right line, blue
    d.line(sum(((self.BOARDCOORDINATES[0][10][0]+self.HEXAGONWIDTH*3/4,self.BOARDCOORDINATES[0][10][1]-self.SIDELENGTH/4),sum([(row[10][0]+self.HEXAGONWIDTH,row[10][1],row[10][0]+self.HEXAGONWIDTH,row[10][1]+self.SIDELENGTH) for row in self.BOARDCOORDINATES],())),()),
        fill = self.PIECECOLOR[2],width = self.LINETHICKNESS)

    # Writes "abc..", "123.." on the columns and rows
    for i in range(11):
      # Top letters
      d.text( (self.XOFFSET + self.HEXAGONWIDTH*i, self.YOFFSET-66) , "ABCDEFGHIJK"[i], font=self.FONT, fill=self.TEXTCOLOR)
      # Bottom letters
      d.text( (self.XOFFSET + self.HEXAGONWIDTH*(i+11.5/2), self.YOFFSET - 15 + 11*self.HEXAGONHEIGHT) , "ABCDEFGHIJK"[i], font=self.FONT, fill=self.TEXTCOLOR)
      # Left numbers
      d.multiline_text( (self.XOFFSET + self.HEXAGONWIDTH*i/2 - 72 -4*(i>8), self.YOFFSET + 18 + i*self.HEXAGONHEIGHT) , str(i+1), font=self.FONT, fill=self.TEXTCOLOR, align="right")
      # Right numbers
      d.text( (self.XOFFSET + self.HEXAGONWIDTH*(i/2+11) + 30 , self.YOFFSET + 6 + i*self.HEXAGONHEIGHT) , str(i+1), font=self.FONT, fill=self.TEXTCOLOR)

    # Write player names and color
    game = self.bot.database["hex games"].find_one({"_id":channel})

    for p in [1,2]:
      playername = self.bot.database_funcs.get_name(game["players"][p-1])
      # Draw name
      x = self.XNAME[p]
      x -= self.NAMEFONT.getsize(playername)[0] if p==2 else 0 # player2's name is right-aligned
      y = self.YNAME[p]
      d.text((x,y),playername, font=self.NAMEFONT, fill = self.TEXTCOLOR)
      # Draw a half-size Hexagon to indicate the player's color
      x -= self.NAMEHEXPADDING # To the left of both names
      d.polygon([
        (x,          y),
        (x+self.SMALLWIDTH/2,   y-self.SMALLSIDELENGTH/2),
        (x+self.SMALLWIDTH,     y),
        (x+self.SMALLWIDTH,     y+self.SMALLSIDELENGTH),
        (x+self.SMALLWIDTH/2,   y+self.SMALLSIDELENGTH*3/2),
        (x,          y+self.SMALLSIDELENGTH),
      ],fill = self.PIECECOLOR[p])

    im.save("gwendolyn/resources/games/hex_boards/board"+channel+".png")




  def drawHexPlacement(self, channel,player,position):
    FILEPATH = "gwendolyn/resources/games/hex_boards/board"+channel+".png"
    self.bot.log(f"Drawing a newly placed hex. Filename: board{channel}.png")

    # Translates position
    # We don't need to error-check, because the position is already checked in placeOnHexBoard()
    position = position.lower()
    column = ord(position[0])-97   # ord() translates from letter to number
    row = int(position[1:])-1

    # Find the coordinates for the filled hex drawing
    hex_coords = [
      (self.BOARDCOORDINATES[row][column][0]+self.COLXTHICKNESS,        self.BOARDCOORDINATES[row][column][1] + self.COLYTHICKNESS),
      (self.BOARDCOORDINATES[row][column][0]+self.HEXAGONWIDTH/2,        self.BOARDCOORDINATES[row][column][1]-0.5*self.SIDELENGTH + self.COLHEXTHICKNESS),
      (self.BOARDCOORDINATES[row][column][0]+self.HEXAGONWIDTH-self.COLXTHICKNESS, self.BOARDCOORDINATES[row][column][1] + self.COLYTHICKNESS),
      (self.BOARDCOORDINATES[row][column][0]+self.HEXAGONWIDTH-self.COLXTHICKNESS, self.BOARDCOORDINATES[row][column][1]+self.SIDELENGTH - self.COLYTHICKNESS),
      (self.BOARDCOORDINATES[row][column][0]+self.HEXAGONWIDTH/2,        self.BOARDCOORDINATES[row][column][1]+1.5*self.SIDELENGTH - self.COLHEXTHICKNESS),
      (self.BOARDCOORDINATES[row][column][0]+self.COLXTHICKNESS,        self.BOARDCOORDINATES[row][column][1]+self.SIDELENGTH - self.COLYTHICKNESS),
      ]

    # Opens the image
    try:
      with Image.open(FILEPATH) as im:
        d = ImageDraw.Draw(im,"RGBA")
        # Draws the hex piece
        d.polygon(hex_coords,fill = self.PIECECOLOR[player], outline = self.BETWEENCOLOR)

        # Save
        im.save(FILEPATH)
    except:
      self.bot.log("Error drawing new hex on board")

  def drawSwap(self, channel):
    FILEPATH = "gwendolyn/resources/games/hex_boards/board"+channel+".png"
    game = self.bot.database["hex games"].find_one({"_id":channel})
    # Opens the image
    try:
      with Image.open(FILEPATH) as im:
        d = ImageDraw.Draw(im,"RGBA")

        # Write player names and color
        for p in [1,2]:
          playername = self.bot.database_funcs.get_name(game["players"][p%2])

          x = self.XNAME[p]
          x -= self.NAMEFONT.getsize(playername)[0] if p==2 else 0 # player2's name is right-aligned
          y = self.YNAME[p]

          # Draw a half-size Hexagon to indicate the player's color
          x -= self.NAMEHEXPADDING # To the left of both names
          d.polygon([
            (x,          y),
            (x+self.SMALLWIDTH/2,   y-self.SMALLSIDELENGTH/2),
            (x+self.SMALLWIDTH,     y),
            (x+self.SMALLWIDTH,     y+self.SMALLSIDELENGTH),
            (x+self.SMALLWIDTH/2,   y+self.SMALLSIDELENGTH*3/2),
            (x,          y+self.SMALLSIDELENGTH),
          ],fill = self.PIECECOLOR[p % 2 + 1])

        # Save
        im.save(FILEPATH)
    except:
      self.bot.log("Error drawing swap")
