Merge branch 'master' of github.com:NikolajDanger/Gwendolyn
This commit is contained in:
@ -2,6 +2,7 @@ import json
|
|||||||
import random
|
import random
|
||||||
import copy
|
import copy
|
||||||
import math
|
import math
|
||||||
|
import asyncio
|
||||||
|
|
||||||
from . import fourInARowDraw
|
from . import fourInARowDraw
|
||||||
from funcs import logThis, getName, getID
|
from funcs import logThis, getName, getID
|
||||||
@ -13,7 +14,7 @@ AIScores = {
|
|||||||
"enemy two in a row": -35,
|
"enemy two in a row": -35,
|
||||||
"enemy three in a row": -200,
|
"enemy three in a row": -200,
|
||||||
"enemy win": -10000,
|
"enemy win": -10000,
|
||||||
"win": 1000,
|
"win": 10000,
|
||||||
"avoid losing": 100
|
"avoid losing": 100
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -232,7 +233,7 @@ def isWon(board):
|
|||||||
return won, winDirection, winCoordinates
|
return won, winDirection, winCoordinates
|
||||||
|
|
||||||
# Plays as the AI
|
# Plays as the AI
|
||||||
def fourInARowAI(channel):
|
async def fourInARowAI(channel):
|
||||||
logThis("Figuring out best move")
|
logThis("Figuring out best move")
|
||||||
with open("resources/games/games.json", "r") as f:
|
with open("resources/games/games.json", "r") as f:
|
||||||
data = json.load(f)
|
data = json.load(f)
|
||||||
@ -246,7 +247,7 @@ def fourInARowAI(channel):
|
|||||||
testBoard = copy.deepcopy(board)
|
testBoard = copy.deepcopy(board)
|
||||||
testBoard = placeOnBoard(testBoard,player,column)
|
testBoard = placeOnBoard(testBoard,player,column)
|
||||||
if testBoard != None:
|
if testBoard != None:
|
||||||
scores[column] = minimax(testBoard,difficulty,player%2+1,player,-math.inf,math.inf,False)
|
scores[column] = await minimax(testBoard,difficulty,player%2+1,player,-math.inf,math.inf,False)
|
||||||
logThis("Best score for column "+str(column)+" is "+str(scores[column]))
|
logThis("Best score for column "+str(column)+" is "+str(scores[column]))
|
||||||
|
|
||||||
possibleScores = scores.copy()
|
possibleScores = scores.copy()
|
||||||
@ -266,12 +267,10 @@ def AICalcPoints(board,player):
|
|||||||
otherPlayer = player%2+1
|
otherPlayer = player%2+1
|
||||||
|
|
||||||
# Adds points for middle placement
|
# Adds points for middle placement
|
||||||
for row in range(len(board)):
|
|
||||||
if board[row][3] == player:
|
|
||||||
score += AIScores["middle"]
|
|
||||||
|
|
||||||
# Checks horizontal
|
# Checks horizontal
|
||||||
for row in range(rowCount):
|
for row in range(rowCount):
|
||||||
|
if board[row][3] == player:
|
||||||
|
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]
|
||||||
@ -290,8 +289,6 @@ def AICalcPoints(board,player):
|
|||||||
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 += evaluateWindow(window,player,otherPlayer)
|
score += evaluateWindow(window,player,otherPlayer)
|
||||||
|
|
||||||
# Checks left diagonal
|
|
||||||
for row in range(rowCount-3):
|
|
||||||
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 += evaluateWindow(window,player,otherPlayer)
|
score += evaluateWindow(window,player,otherPlayer)
|
||||||
@ -319,11 +316,12 @@ def evaluateWindow(window,player,otherPlayer):
|
|||||||
else:
|
else:
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
def minimax(board, depth, player , originalPlayer, alpha, beta, maximizingPlayer):
|
async def minimax(board, depth, player , originalPlayer, alpha, beta, maximizingPlayer):
|
||||||
terminal = ((isWon(board)[0] != 0) or (0 not in board[0]))
|
#terminal = ((0 not in board[0]) or (isWon(board)[0] != 0))
|
||||||
|
terminal = 0 not in board[0]
|
||||||
|
points = AICalcPoints(board,originalPlayer)
|
||||||
# The depth is how many moves ahead the computer checks. This value is the difficulty.
|
# The depth is how many moves ahead the computer checks. This value is the difficulty.
|
||||||
if depth == 0 or terminal:
|
if depth == 0 or terminal or (points > 5000 or points < -6000):
|
||||||
points = AICalcPoints(board,originalPlayer)
|
|
||||||
return points
|
return points
|
||||||
if maximizingPlayer:
|
if maximizingPlayer:
|
||||||
value = -math.inf
|
value = -math.inf
|
||||||
@ -331,12 +329,11 @@ def minimax(board, depth, player , originalPlayer, alpha, beta, maximizingPlayer
|
|||||||
testBoard = copy.deepcopy(board)
|
testBoard = copy.deepcopy(board)
|
||||||
testBoard = placeOnBoard(testBoard,player,column)
|
testBoard = placeOnBoard(testBoard,player,column)
|
||||||
if testBoard != None:
|
if testBoard != None:
|
||||||
evaluation = minimax(testBoard,depth-1,player%2+1,originalPlayer,alpha,beta,False)
|
evaluation = await 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:
|
if beta <= alpha: break
|
||||||
break
|
|
||||||
return value
|
return value
|
||||||
else:
|
else:
|
||||||
value = math.inf
|
value = math.inf
|
||||||
@ -344,10 +341,9 @@ def minimax(board, depth, player , originalPlayer, alpha, beta, maximizingPlayer
|
|||||||
testBoard = copy.deepcopy(board)
|
testBoard = copy.deepcopy(board)
|
||||||
testBoard = placeOnBoard(testBoard,player,column)
|
testBoard = placeOnBoard(testBoard,player,column)
|
||||||
if testBoard != None:
|
if testBoard != None:
|
||||||
evaluation = minimax(testBoard,depth-1,player%2+1,originalPlayer,alpha,beta,True)
|
evaluation = await 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:
|
if beta <= alpha: break
|
||||||
break
|
|
||||||
return value
|
return value
|
||||||
|
@ -45,6 +45,7 @@ async def runHex(channel,command,user):
|
|||||||
try:
|
try:
|
||||||
response, showImage, deleteImage, gameDone, gwendoTurn = hexAI(str(channel.id))
|
response, showImage, deleteImage, gameDone, gwendoTurn = hexAI(str(channel.id))
|
||||||
except:
|
except:
|
||||||
|
response, showImage, deleteImage, gameDone, gwendoTurn = "An AI error occured",False,False,False,False
|
||||||
logThis("AI error (error code 1520)")
|
logThis("AI error (error code 1520)")
|
||||||
await channel.send(response)
|
await channel.send(response)
|
||||||
logThis(response,str(channel.id))
|
logThis(response,str(channel.id))
|
||||||
@ -61,8 +62,9 @@ async def runHex(channel,command,user):
|
|||||||
with open("resources/games/hexGames.json", "r") as f:
|
with open("resources/games/hexGames.json", "r") as f:
|
||||||
data = json.load(f)
|
data = json.load(f)
|
||||||
winner = data[str(channel.id)]["winner"]
|
winner = data[str(channel.id)]["winner"]
|
||||||
if winner != 0:
|
if winner != 0 and data[channel]["players"][0] != data[channel]["players"][1]: # player1 != player2
|
||||||
addMoney(data[str(channel.id)]["players"][winner-1].lower(),50)
|
winnings = data[str(channel.id)]["difficulty"]*10
|
||||||
|
addMoney(data[str(channel.id)]["players"][winner-1].lower(),winnings)
|
||||||
|
|
||||||
#deleteGame("hex games",str(channel.id))
|
#deleteGame("hex games",str(channel.id))
|
||||||
with open("resources/games/hexGames.json", "r") as f:
|
with open("resources/games/hexGames.json", "r") as f:
|
||||||
@ -92,7 +94,7 @@ async def fiar(channel,command,user):
|
|||||||
if gameDone == False:
|
if gameDone == False:
|
||||||
if gwendoTurn:
|
if gwendoTurn:
|
||||||
try:
|
try:
|
||||||
response, showImage, deleteImage, gameDone, gwendoTurn = fourInARowAI(str(channel.id))
|
response, showImage, deleteImage, gameDone, gwendoTurn = await fourInARowAI(str(channel.id))
|
||||||
except:
|
except:
|
||||||
logThis("AI error (error code 1420)")
|
logThis("AI error (error code 1420)")
|
||||||
await channel.send(response)
|
await channel.send(response)
|
||||||
|
@ -6,15 +6,6 @@ import math
|
|||||||
from . import hexDraw
|
from . import hexDraw
|
||||||
from funcs import logThis, getName, getID
|
from funcs import logThis, getName, getID
|
||||||
|
|
||||||
# This is totally copied from the four in a row game. Just modified
|
|
||||||
|
|
||||||
AIScoresHex = {
|
|
||||||
"lol, dunno": 3,
|
|
||||||
"enemy win": -10000,
|
|
||||||
"win": 1000,
|
|
||||||
"avoid losing": 100
|
|
||||||
}
|
|
||||||
|
|
||||||
BOARDWIDTH = 11
|
BOARDWIDTH = 11
|
||||||
ALL_POSITIONS = [(i,j) for i in range(11) for j in range(11)]
|
ALL_POSITIONS = [(i,j) for i in range(11) for j in range(11)]
|
||||||
ALL_SET = set(ALL_POSITIONS)
|
ALL_SET = set(ALL_POSITIONS)
|
||||||
@ -23,10 +14,12 @@ for position in ALL_POSITIONS:
|
|||||||
EMPTY_DIJKSTRA[position] = math.inf # an impossibly high number
|
EMPTY_DIJKSTRA[position] = math.inf # an impossibly high number
|
||||||
HEX_DIRECTIONS = [(0,1),(-1,1),(-1,0),(0,-1),(1,-1),(1,0)]
|
HEX_DIRECTIONS = [(0,1),(-1,1),(-1,0),(0,-1),(1,-1),(1,0)]
|
||||||
|
|
||||||
|
|
||||||
# Parses command
|
# Parses command
|
||||||
def parseHex(command, channel, user):
|
def parseHex(command, channel, user):
|
||||||
commands = command.lower().split()
|
commands = command.lower().split()
|
||||||
|
with open("resources/games/hexGames.json", "r") as f:
|
||||||
|
data = json.load(f)
|
||||||
|
|
||||||
if command == "" or command == " ":
|
if command == "" or command == " ":
|
||||||
return "I didn't get that. Use \"!hex start [opponent]\" to start a game.", False, False, False, False
|
return "I didn't get that. Use \"!hex start [opponent]\" to start a game.", False, False, False, False
|
||||||
|
|
||||||
@ -37,11 +30,12 @@ def parseHex(command, channel, user):
|
|||||||
logThis("Starting a hex game with hexStart(). "+str(user)+" challenged "+commands[1])
|
logThis("Starting a hex game with hexStart(). "+str(user)+" challenged "+commands[1])
|
||||||
return hexStart(channel,user,commands[1]) # commands[1] is the opponent
|
return hexStart(channel,user,commands[1]) # commands[1] is the opponent
|
||||||
|
|
||||||
|
# If using a command with no game, return error
|
||||||
|
elif channel not in data:
|
||||||
|
return "There's no game in this channel", False, False, False, False
|
||||||
|
|
||||||
# Stopping the game
|
# Stopping the game
|
||||||
elif commands[0] == "stop":
|
elif commands[0] == "stop":
|
||||||
with open("resources/games/hexGames.json", "r") as f:
|
|
||||||
data = json.load(f)
|
|
||||||
|
|
||||||
if user in data[channel]["players"]:
|
if user in data[channel]["players"]:
|
||||||
return "Ending game.", False, False, True, False
|
return "Ending game.", False, False, True, False
|
||||||
else:
|
else:
|
||||||
@ -60,16 +54,28 @@ def parseHex(command, channel, user):
|
|||||||
|
|
||||||
# Surrender
|
# Surrender
|
||||||
elif commands[0] == "surrender":
|
elif commands[0] == "surrender":
|
||||||
with open("resources/games/hexGames.json", "r") as f:
|
|
||||||
data = json.load(f)
|
|
||||||
players = data[channel]["players"]
|
players = data[channel]["players"]
|
||||||
if user in players:
|
if user in players:
|
||||||
opponent = (players.index(user) + 1) % 2
|
opponent = (players.index(user) + 1) % 2
|
||||||
data[channel]["winner"] = opponent
|
data[channel]["winner"] = opponent + 1
|
||||||
return "{} surrendered. Ending game.".format(getName(user)), False, False, True, False
|
return "{} surrendered. That means {} won! Adding 30 Gwendobucks to their account.".format(getName(user),getName(players[opponent])), False, False, True, False
|
||||||
else:
|
else:
|
||||||
return "You can't surrender when you're not a player.", False, False, False, False
|
return "You can't surrender when you're not a player.", False, False, False, False
|
||||||
|
|
||||||
|
# Swap
|
||||||
|
elif commands[0] == "swap":
|
||||||
|
if len(data[channel]["gameHistory"]) == 1: # Only after the first move
|
||||||
|
data[channel]["players"] = data[channel]["players"][::-1] # Swaps their player-number
|
||||||
|
with open("resources/games/hexGames.json", "w") as f:
|
||||||
|
json.dump(data,f,indent=4)
|
||||||
|
# Swaps the color of the hexes on the board drawing:
|
||||||
|
hexDraw.drawSwap(channel)
|
||||||
|
player2 = data[channel]["players"][1]
|
||||||
|
gwendoTurn = (player2 == "Gwendolyn")
|
||||||
|
return "The color of both players were swapped. It is now {}'s turn".format(player2), True, True, False, gwendoTurn
|
||||||
|
else:
|
||||||
|
return "You can only swap as the second player after the very first move.", False, False, False, False
|
||||||
|
|
||||||
else:
|
else:
|
||||||
return "I didn't get that. Use \"!hex start [opponent]\" to start a game, \"!hex place [position]\" to place a piece, \"!hex undo\" to undo your last move or \"!hex stop\" to stop a current game.", False, False, False, False
|
return "I didn't get that. Use \"!hex start [opponent]\" to start a game, \"!hex place [position]\" to place a piece, \"!hex undo\" to undo your last move or \"!hex stop\" to stop a current game.", False, False, False, False
|
||||||
|
|
||||||
@ -94,24 +100,21 @@ def hexStart(channel, user, opponent):
|
|||||||
return "That difficulty doesn't exist", False, False, False, False
|
return "That difficulty doesn't exist", False, False, False, False
|
||||||
except:
|
except:
|
||||||
opponent = getID(opponent)
|
opponent = getID(opponent)
|
||||||
if opponent == user:
|
if opponent == None:
|
||||||
return "You can't play against yourself", False, False, False, False
|
|
||||||
elif opponent == None:
|
|
||||||
return "I can't find that user", False, False, False, False
|
return "I can't find that user", False, False, False, False
|
||||||
else:
|
else:
|
||||||
# Opponent is another player
|
# Opponent is another player
|
||||||
difficulty = 5
|
difficulty = 3
|
||||||
diffText = ""
|
diffText = ""
|
||||||
|
|
||||||
# board is 11x11
|
# board is 11x11
|
||||||
board = [ [ 0 for i in range(BOARDWIDTH) ] for j in range(BOARDWIDTH) ]
|
board = [ [ 0 for i in range(BOARDWIDTH) ] for j in range(BOARDWIDTH) ]
|
||||||
players = [user,opponent]
|
players = [user,opponent]
|
||||||
random.shuffle(players) # random starting player
|
random.shuffle(players) # random starting player
|
||||||
winningPieces = [[""],[""],[""]] # etc.
|
gameHistory = []
|
||||||
lastMove = (-1,-1)
|
|
||||||
|
|
||||||
data[channel] = {"board":board, "winner":0,
|
data[channel] = {"board":board, "winner":0,
|
||||||
"players":players, "winningPieces":winningPieces, "turn":1, "difficulty":difficulty, "lastMove":lastMove}
|
"players":players, "turn":1, "difficulty":difficulty, "gameHistory":gameHistory}
|
||||||
|
|
||||||
with open("resources/games/hexGames.json", "w") as f:
|
with open("resources/games/hexGames.json", "w") as f:
|
||||||
json.dump(data,f,indent=4)
|
json.dump(data,f,indent=4)
|
||||||
@ -119,7 +122,6 @@ def hexStart(channel, user, opponent):
|
|||||||
# draw the board
|
# draw the board
|
||||||
hexDraw.drawBoard(channel)
|
hexDraw.drawBoard(channel)
|
||||||
|
|
||||||
|
|
||||||
gwendoTurn = True if players[0] == "Gwendolyn" else False
|
gwendoTurn = True if players[0] == "Gwendolyn" else False
|
||||||
showImage = True
|
showImage = True
|
||||||
return "Started Hex game against "+getName(opponent)+ diffText+". It's "+getName(players[0])+"'s turn", showImage, False, False, gwendoTurn
|
return "Started Hex game against "+getName(opponent)+ diffText+". It's "+getName(players[0])+"'s turn", showImage, False, False, gwendoTurn
|
||||||
@ -132,9 +134,14 @@ def placeHex(channel : str,position : str, user):
|
|||||||
data = json.load(f)
|
data = json.load(f)
|
||||||
|
|
||||||
if channel in data:
|
if channel in data:
|
||||||
if user in data[channel]["players"]:
|
players = data[channel]["players"]
|
||||||
|
if user in players:
|
||||||
turn = data[channel]["turn"]
|
turn = data[channel]["turn"]
|
||||||
player = data[channel]["players"].index(user)+1
|
if players[0] == players[1]:
|
||||||
|
player = turn
|
||||||
|
else:
|
||||||
|
player = players.index(user)+1
|
||||||
|
|
||||||
if player == turn:
|
if player == turn:
|
||||||
board = data[channel]["board"]
|
board = data[channel]["board"]
|
||||||
|
|
||||||
@ -149,32 +156,23 @@ def placeHex(channel : str,position : str, user):
|
|||||||
data[channel]["turn"] = turn
|
data[channel]["turn"] = turn
|
||||||
|
|
||||||
|
|
||||||
"""
|
|
||||||
with open("resources/games/hexGames.json", "w") as f:
|
|
||||||
json.dump(data,f,indent=4)
|
|
||||||
|
|
||||||
|
|
||||||
# Checking for a win
|
# Checking for a win
|
||||||
logThis("Checking for win")
|
logThis("Checking for win")
|
||||||
won, winningPieces = isHexWon(data[channel]["board"])
|
score, winner = evaluateBoard(data[channel]["board"])
|
||||||
|
|
||||||
if won != 0:
|
if winner == 0: # Continue with the game.
|
||||||
|
gameWon = False
|
||||||
|
message = getName(data[channel]["players"][player-1])+" placed at "+position.upper()+". It's now "+getName(data[channel]["players"][turn-1])+"'s turn."# The score is "+str(score)
|
||||||
|
|
||||||
|
else: # Congratulations!
|
||||||
gameWon = True
|
gameWon = True
|
||||||
data[channel]["winner"] = won
|
data[channel]["winner"] = winner
|
||||||
data[channel]["winningPieces"] = winningPieces
|
message = getName(data[channel]["players"][player-1])+" placed at "+position.upper()+" and won!"
|
||||||
|
if data[channel]["players"][winner-1] != "Gwendolyn":
|
||||||
|
winAmount = data[channel]["difficulty"]*10
|
||||||
message = data[channel]["players"][won-1]+" won!"
|
|
||||||
if data[channel]["players"][won-1] != "Gwendolyn":
|
|
||||||
winAmount = data[channel]["difficulty"]^2+5
|
|
||||||
message += " Adding "+str(winAmount)+" GwendoBucks to their account."
|
message += " Adding "+str(winAmount)+" GwendoBucks to their account."
|
||||||
else:"""
|
|
||||||
|
|
||||||
gameWon = False
|
data[channel]["gameHistory"].append((int(position[1])-1, ord(position[0])-97))
|
||||||
message = getName(data[channel]["players"][player-1])+" placed at "+position.upper()+". It's now "+getName(data[channel]["players"][turn-1])+"'s turn."
|
|
||||||
data[channel]["lastMove"] = (int(position[1])-1, ord(position[0])-97)
|
|
||||||
with open("resources/games/hexGames.json", "w") as f:
|
|
||||||
json.dump(data,f,indent=4)
|
|
||||||
|
|
||||||
# Is it now Gwendolyn's turn?
|
# Is it now Gwendolyn's turn?
|
||||||
gwendoTurn = False
|
gwendoTurn = False
|
||||||
@ -182,6 +180,10 @@ def placeHex(channel : str,position : str, user):
|
|||||||
logThis("It's Gwendolyn's turn")
|
logThis("It's Gwendolyn's turn")
|
||||||
gwendoTurn = True
|
gwendoTurn = True
|
||||||
|
|
||||||
|
# Save the data
|
||||||
|
with open("resources/games/hexGames.json", "w") as f:
|
||||||
|
json.dump(data,f,indent=4)
|
||||||
|
|
||||||
# Update the board
|
# Update the board
|
||||||
hexDraw.drawHexPlacement(channel,player,position)
|
hexDraw.drawHexPlacement(channel,player,position)
|
||||||
|
|
||||||
@ -205,6 +207,7 @@ def placeHex(channel : str,position : str, user):
|
|||||||
def placeOnHexBoard(board,player,position):
|
def placeOnHexBoard(board,player,position):
|
||||||
# Translates the position
|
# Translates the position
|
||||||
position = position.lower()
|
position = position.lower()
|
||||||
|
# Error handling
|
||||||
try:
|
try:
|
||||||
column = ord(position[0]) - 97 # ord() translates from letter to number
|
column = ord(position[0]) - 97 # ord() translates from letter to number
|
||||||
row = int(position[1:]) - 1
|
row = int(position[1:]) - 1
|
||||||
@ -214,7 +217,6 @@ def placeOnHexBoard(board,player,position):
|
|||||||
except:
|
except:
|
||||||
logThis("Invalid position (error code 1531)")
|
logThis("Invalid position (error code 1531)")
|
||||||
return "Error. The position should be a letter followed by a number, e.g. \"e2\"."
|
return "Error. The position should be a letter followed by a number, e.g. \"e2\"."
|
||||||
|
|
||||||
# Place at the position
|
# Place at the position
|
||||||
if board[row][column] == 0:
|
if board[row][column] == 0:
|
||||||
board[row][column] = player
|
board[row][column] = player
|
||||||
@ -229,19 +231,22 @@ def undoHex(channel, user):
|
|||||||
with open("resources/games/hexGames.json", "r") as f:
|
with open("resources/games/hexGames.json", "r") as f:
|
||||||
data = json.load(f)
|
data = json.load(f)
|
||||||
if user in data[channel]["players"]:
|
if user in data[channel]["players"]:
|
||||||
if data[channel]["lastMove"] != (-1,-1):
|
if len(data[channel]["gameHistory"]):
|
||||||
turn = data[channel]["turn"]
|
turn = data[channel]["turn"]
|
||||||
# You can only undo after your turn, which is the opponent's turn.
|
# You can only undo after your turn, which is the opponent's turn.
|
||||||
if user == data[channel]["players"][(turn % 2)]: # If it's not your turn
|
if user == data[channel]["players"][(turn % 2)]: # If it's not your turn
|
||||||
logThis("Undoing {}'s last move".format(getName(user)))
|
logThis("Undoing {}'s last move".format(getName(user)))
|
||||||
|
|
||||||
lastMove = data[channel]["lastMove"]
|
lastMove = data[channel]["gameHistory"].pop()
|
||||||
data[channel]["board"][lastMove[0]][lastMove[1]] = 0
|
data[channel]["board"][lastMove[0]][lastMove[1]] = 0
|
||||||
data[channel]["turn"] = turn%2 + 1
|
data[channel]["turn"] = turn%2 + 1
|
||||||
|
# Save the data
|
||||||
|
with open("resources/games/hexGames.json", "w") as f:
|
||||||
|
json.dump(data,f,indent=4)
|
||||||
|
|
||||||
# Update the board
|
# Update the board
|
||||||
hexDraw.drawHexPlacement(channel,0,"abcdefghijk"[lastMove[1]]+str(lastMove[0]+1)) # The zero makes the hex disappear
|
hexDraw.drawHexPlacement(channel,0,"abcdefghijk"[lastMove[1]]+str(lastMove[0]+1)) # The zero makes the hex disappear
|
||||||
return "You undid", True, True, False, False
|
return "You undid your last move at {}".format(lastMove), True, True, False, False
|
||||||
else:
|
else:
|
||||||
# Sassy
|
# Sassy
|
||||||
return "Nice try. You can't undo your opponent's move. ", False, False, False, False
|
return "Nice try. You can't undo your opponent's move. ", False, False, False, False
|
||||||
@ -258,61 +263,60 @@ def hexAI(channel):
|
|||||||
logThis("Figuring out best move")
|
logThis("Figuring out best move")
|
||||||
with open("resources/games/hexGames.json", "r") as f:
|
with open("resources/games/hexGames.json", "r") as f:
|
||||||
data = json.load(f)
|
data = json.load(f)
|
||||||
|
|
||||||
board = data[channel]["board"]
|
board = data[channel]["board"]
|
||||||
player = data[channel]["players"].index("Gwendolyn")+1
|
|
||||||
#difficulty = data[channel]["difficulty"]
|
if len(data[channel]["gameHistory"]):
|
||||||
lastMove = data[channel]["lastMove"]
|
lastMove = data[channel]["gameHistory"][-1]
|
||||||
|
else:
|
||||||
|
lastMove = (5,5)
|
||||||
|
|
||||||
# These moves are the last move +- 2.
|
# 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 = [[(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,[])
|
moves = sum(moves,[])
|
||||||
chosenMove = None
|
movesCopy = moves.copy()
|
||||||
safety = 0
|
for move in movesCopy:
|
||||||
while chosenMove == None:
|
if board[move[0]][move[1]] != 0:
|
||||||
safety += 1
|
moves.remove(move)
|
||||||
if safety > 1000:
|
chosenMove = random.choice(moves)
|
||||||
break
|
|
||||||
candidate = random.choice(moves)
|
|
||||||
if board[candidate[0]][candidate[1]] == 0:
|
|
||||||
chosenMove = candidate
|
|
||||||
logThis("Last move was "+str(lastMove))
|
|
||||||
logThis("Chosen move is "+str(chosenMove))
|
|
||||||
"""
|
"""
|
||||||
scores = [-math.inf,-math.inf,-math.inf,-math.inf,-math.inf,-math.inf,-math.inf]
|
GwenColor = data[channel]["players"].index("Gwendolyn") + 1 # either 1 or 2 - red or blue
|
||||||
for column in range(0,BOARDWIDTH):
|
if len(data[channel]["gameHistory"]) == 0:
|
||||||
|
return placeHex(channel,"F6", "Gwendolyn") # If starting, start in the middle
|
||||||
|
board = data[channel]["board"]
|
||||||
|
difficulty = data[channel]["difficulty"]
|
||||||
|
possiblePlaces = [i for i,v in enumerate(sum(board,[])) if v == 0]
|
||||||
|
judgements = [float('nan')]*len(possiblePlaces) # All possible moves are yet to be judged
|
||||||
|
|
||||||
|
current_score = evaluateBoard(board)[0]
|
||||||
|
for i in possiblePlaces:
|
||||||
testBoard = copy.deepcopy(board)
|
testBoard = copy.deepcopy(board)
|
||||||
# Testing a move
|
testBoard[i // BOARDWIDTH][i % BOARDWIDTH] = GwenColor
|
||||||
testBoard = placeOnHexBoard(testBoard,player,column)
|
if evaluateBoard(testBoard)[0] != current_score: # only think about a move if it improves the score (it's impossible to get worse)
|
||||||
# Evaluating that move
|
# Testing a move and evaluating it
|
||||||
if testBoard != None:
|
judgements[i] = minimaxHex(testBoard,difficulty,-math.inf,math.inf,GwenColor==2)
|
||||||
scores[column] = minimaxHex(testBoard,difficulty,player%2+1,player,-math.inf,math.inf,False)
|
logThis("Best score for place {} is {}".format((i // BOARDWIDTH,i % BOARDWIDTH),judgements[i]))
|
||||||
logThis("Best score for column "+str(column)+" is "+str(scores[column]))
|
|
||||||
|
|
||||||
possibleScores = scores.copy()
|
bestScore = max(judgements) if (GwenColor == 1) else min(judgements) # this line has an error
|
||||||
|
indices = [i for i, x in enumerate(judgements) if x == bestScore] # which moves got that score?
|
||||||
while (min(possibleScores) < (max(possibleScores)*0.9)):
|
i = random.choice(indices)
|
||||||
possibleScores.remove(min(possibleScores))
|
chosenMove = (i // BOARDWIDTH , i % BOARDWIDTH)
|
||||||
|
|
||||||
highest_score = random.choice(possibleScores)
|
|
||||||
|
|
||||||
indices = [i for i, x in enumerate(scores) if x == highest_score]
|
|
||||||
"""
|
"""
|
||||||
placement = "abcdefghijk"[chosenMove[1]]+str(chosenMove[0]+1)
|
placement = "abcdefghijk"[chosenMove[1]]+str(chosenMove[0]+1)
|
||||||
|
logThis("ChosenMove is {} at {}".format(chosenMove,placement))
|
||||||
return placeHex(channel,placement, "Gwendolyn")
|
return placeHex(channel,placement, "Gwendolyn")
|
||||||
|
|
||||||
|
|
||||||
def evaluateBoard(board):
|
def evaluateBoard(board):
|
||||||
score = {1:0, 2:0}
|
scores = {1:0, 2:0}
|
||||||
winner = 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
|
# 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]:
|
for player in [1,2]:
|
||||||
logThis("Running Dijkstra for player "+str(player))
|
|
||||||
Distance = copy.deepcopy(EMPTY_DIJKSTRA)
|
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.
|
# 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]):
|
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.
|
# 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[v[0]][v[1]] == 0) else 0 if (board[v[0]][v[1]] == player) else math.inf
|
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"
|
visited = set() # Also called sptSet, short for "shortest path tree Set"
|
||||||
for _ in range(BOARDWIDTH**2): # We can at most check every 121 hexes
|
for _ in range(BOARDWIDTH**2): # We can at most check every 121 hexes
|
||||||
# Find the next un-visited hex, that has the lowest distance
|
# Find the next un-visited hex, that has the lowest distance
|
||||||
@ -326,57 +330,52 @@ def evaluateBoard(board):
|
|||||||
if v[0] in range(11) and v[1] in range(11) and v not in visited:
|
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)
|
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)
|
Distance[v] = min(Distance[v], new_dist)
|
||||||
|
|
||||||
# If at the goal, we've found the shortest distance
|
|
||||||
if v[player-1] == 10: # if the right coordinate of v is 10, it means we're at the goal
|
|
||||||
atGoal = True
|
|
||||||
break
|
|
||||||
if atGoal:
|
|
||||||
score[player] = Distance[v] # 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
|
|
||||||
# After a hex has been visited, this is noted
|
# After a hex has been visited, this is noted
|
||||||
visited.add(u)
|
visited.add(u)
|
||||||
logThis("Distance from player {}'s start to {} is {}".format(player,u,Distance[u]))
|
#logThis("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:
|
else:
|
||||||
logThis("For some reason, no path to the goal was found. ")
|
logThis("For some reason, no path to the goal was found. ")
|
||||||
if score[player] == 0:
|
if scores[player] == 0:
|
||||||
winner = player
|
winner = player
|
||||||
break # We don't need to check the other player's score, if player1 won.
|
break # We don't need to check the other player's score, if player1 won.
|
||||||
|
return scores[2]-scores[1], winner
|
||||||
return score, winner
|
|
||||||
|
|
||||||
|
|
||||||
|
def minimaxHex(board, depth, alpha, beta, maximizingPlayer):
|
||||||
def minimaxHex(board, depth, player , originalPlayer, alpha, beta, maximizingPlayer):
|
|
||||||
# The depth is how many moves ahead the computer checks. This value is the difficulty.
|
# The depth is how many moves ahead the computer checks. This value is the difficulty.
|
||||||
if depth == 0 or 0 not in sum(board,[0]):
|
if depth == 0 or 0 not in sum(board,[]):
|
||||||
score = evaluateBoard(board)
|
score = evaluateBoard(board)[0]
|
||||||
return score
|
return score
|
||||||
# if final depth is not reached, look another move ahead:
|
# if final depth is not reached, look another move ahead:
|
||||||
if maximizingPlayer:
|
if maximizingPlayer: # red player predicts next move
|
||||||
value = -math.inf
|
maxEval = -math.inf
|
||||||
for column in range(0,BOARDWIDTH):
|
possiblePlaces = [i for i,v in enumerate(sum(board,[])) if v == 0]
|
||||||
|
#logThis("Judging a red move at depth {}".format(depth))
|
||||||
|
for i in possiblePlaces:
|
||||||
testBoard = copy.deepcopy(board)
|
testBoard = copy.deepcopy(board)
|
||||||
testBoard = placeOnHexBoard(testBoard,player,column)
|
testBoard[i // BOARDWIDTH][i % BOARDWIDTH] = 1 # because maximizingPlayer is Red which is number 1
|
||||||
if testBoard != None:
|
evaluation = minimaxHex(testBoard,depth-1,alpha,beta,False)
|
||||||
evaluation = minimaxHex(testBoard,depth-1,player%2+1,originalPlayer,alpha,beta,False)
|
maxEval = max(maxEval, evaluation)
|
||||||
if evaluation < -9000: evaluation += AIScoresHex["avoid losing"]
|
alpha = max(alpha, evaluation)
|
||||||
value = max(value,evaluation)
|
if beta <= alpha:
|
||||||
alpha = max(alpha,evaluation)
|
#logThis("Just pruned something!")
|
||||||
if beta <= alpha:
|
break
|
||||||
break
|
return maxEval
|
||||||
return value
|
else: # blue player predicts next move
|
||||||
else:
|
minEval = math.inf
|
||||||
value = math.inf
|
possiblePlaces = [i for i,v in enumerate(sum(board,[])) if v == 0]
|
||||||
for column in range(0,BOARDWIDTH):
|
#logThis("Judging a blue move at depth {}".format(depth))
|
||||||
|
for i in possiblePlaces:
|
||||||
testBoard = copy.deepcopy(board)
|
testBoard = copy.deepcopy(board)
|
||||||
testBoard = placeOnHexBoard(testBoard,player,column)
|
testBoard[i // BOARDWIDTH][i % BOARDWIDTH] = 2 # because minimizingPlayer is Blue which is number 2
|
||||||
if testBoard != None:
|
evaluation = minimaxHex(testBoard,depth-1,alpha,beta,True)
|
||||||
evaluation = minimaxHex(testBoard,depth-1,player%2+1,originalPlayer,alpha,beta,True)
|
minEval = min(minEval, evaluation)
|
||||||
if evaluation < -9000: evaluation += AIScoresHex["avoid losing"]
|
beta = min(beta, evaluation)
|
||||||
value = min(value,evaluation)
|
if beta <= alpha:
|
||||||
beta = min(beta,evaluation)
|
#logThis("Just pruned something!")
|
||||||
if beta <= alpha:
|
break
|
||||||
break
|
return minEval
|
||||||
return value
|
|
||||||
|
|
||||||
|
@ -22,7 +22,7 @@ HEXTHICKNESS = 6 # This is half the width of the background lining between every
|
|||||||
X_THICKNESS = HEXTHICKNESS * math.cos(math.pi/6)
|
X_THICKNESS = HEXTHICKNESS * math.cos(math.pi/6)
|
||||||
Y_THICKNESS = HEXTHICKNESS * math.sin(math.pi/6)
|
Y_THICKNESS = HEXTHICKNESS * math.sin(math.pi/6)
|
||||||
BACKGROUND_COLOR = (230,230,230)
|
BACKGROUND_COLOR = (230,230,230)
|
||||||
BETWEEN_COLOR = BACKGROUND_COLOR
|
BETWEEN_COLOR = (231,231,231)
|
||||||
BLANK_COLOR = "lightgrey"
|
BLANK_COLOR = "lightgrey"
|
||||||
PIECECOLOR = {1:(237,41,57),2:(0,165,255),0:BLANK_COLOR} # player1 is red, player2 is blue
|
PIECECOLOR = {1:(237,41,57),2:(0,165,255),0:BLANK_COLOR} # player1 is red, player2 is blue
|
||||||
BOARDCOORDINATES = [ [(X_OFFSET + HEXAGONWIDTH*(column + row/2),Y_OFFSET + HEXAGONHEIGHT*row) for column in range(11)] for row in range(11)] # These are the coordinates for the upperleft corner of every hex
|
BOARDCOORDINATES = [ [(X_OFFSET + HEXAGONWIDTH*(column + row/2),Y_OFFSET + HEXAGONHEIGHT*row) for column in range(11)] for row in range(11)] # These are the coordinates for the upperleft corner of every hex
|
||||||
@ -41,16 +41,12 @@ SMOL_SIDELENGTH = SIDELENGTH * 0.6
|
|||||||
def drawBoard(channel):
|
def drawBoard(channel):
|
||||||
logThis("Drawing empty Hex board")
|
logThis("Drawing empty Hex board")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# Creates the empty image
|
# Creates the empty image
|
||||||
im = Image.new('RGB', size=(CANVAS_WIDTH, CANVAS_HEIGHT),color = BACKGROUND_COLOR)
|
im = Image.new('RGB', size=(CANVAS_WIDTH, CANVAS_HEIGHT),color = BACKGROUND_COLOR)
|
||||||
# 'd' is a shortcut to drawing on the image
|
# 'd' is a shortcut to drawing on the image
|
||||||
d = ImageDraw.Draw(im,"RGBA")
|
d = ImageDraw.Draw(im,"RGBA")
|
||||||
|
|
||||||
|
# Drawing all the hexagons
|
||||||
|
|
||||||
# The board is indexed with [row][column]
|
|
||||||
for column in BOARDCOORDINATES:
|
for column in BOARDCOORDINATES:
|
||||||
for startingPoint in column:
|
for startingPoint in column:
|
||||||
x = startingPoint[0]
|
x = startingPoint[0]
|
||||||
@ -98,22 +94,6 @@ def drawBoard(channel):
|
|||||||
d.text( (X_OFFSET + HEXAGONWIDTH*(i/2+11) + 30 , Y_OFFSET + 6 + i*HEXAGONHEIGHT) , str(i+1), font=fnt, fill=TEXTCOLOR)
|
d.text( (X_OFFSET + HEXAGONWIDTH*(i/2+11) + 30 , Y_OFFSET + 6 + i*HEXAGONHEIGHT) , str(i+1), font=fnt, fill=TEXTCOLOR)
|
||||||
|
|
||||||
# Write player names and color
|
# Write player names and color
|
||||||
"""
|
|
||||||
with open("resources/games/hexGames.json", "r") as f:
|
|
||||||
data = json.load(f)
|
|
||||||
|
|
||||||
board = data[channel]["board"]
|
|
||||||
# Getting player names
|
|
||||||
players = data[channel]["players"]
|
|
||||||
if players[0] == "Gwendolyn":
|
|
||||||
player1 = "Gwendolyn"
|
|
||||||
else:
|
|
||||||
player1 = getName(players[0])
|
|
||||||
if players[1] == "Gwendolyn":
|
|
||||||
player2 = "Gwendolyn"
|
|
||||||
else:
|
|
||||||
player2 = getName(players[1])
|
|
||||||
"""
|
|
||||||
with open("resources/games/hexGames.json", "r") as f:
|
with open("resources/games/hexGames.json", "r") as f:
|
||||||
data = json.load(f)
|
data = json.load(f)
|
||||||
for p in [1,2]:
|
for p in [1,2]:
|
||||||
@ -141,7 +121,7 @@ def drawBoard(channel):
|
|||||||
|
|
||||||
def drawHexPlacement(channel,player,position):
|
def drawHexPlacement(channel,player,position):
|
||||||
FILEPATH = "resources/games/hexBoards/board"+channel+".png"
|
FILEPATH = "resources/games/hexBoards/board"+channel+".png"
|
||||||
logThis("Drawing a newly placed hex. Filepath:"+FILEPATH)
|
logThis("Drawing a newly placed hex. Filepath: "+FILEPATH)
|
||||||
|
|
||||||
# Translates position
|
# Translates position
|
||||||
# We don't need to error-check, because the position is already checked in placeOnHexBoard()
|
# We don't need to error-check, because the position is already checked in placeOnHexBoard()
|
||||||
@ -170,3 +150,40 @@ def drawHexPlacement(channel,player,position):
|
|||||||
im.save(FILEPATH)
|
im.save(FILEPATH)
|
||||||
except:
|
except:
|
||||||
logThis("Error drawing new hex on board (error code 1541")
|
logThis("Error drawing new hex on board (error code 1541")
|
||||||
|
|
||||||
|
def drawSwap(channel):
|
||||||
|
FILEPATH = "resources/games/hexBoards/board"+channel+".png"
|
||||||
|
with open("resources/games/hexGames.json", "r") as f:
|
||||||
|
data = json.load(f)
|
||||||
|
# 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 = getName(data[channel]["players"][p%2])
|
||||||
|
|
||||||
|
x = X_NAME[p]
|
||||||
|
x -= NAME_fnt.getsize(playername)[0] if p==2 else 0 # player2's name is right-aligned
|
||||||
|
y = Y_NAME[p]
|
||||||
|
|
||||||
|
# Draw a half-size Hexagon to indicate the player's color
|
||||||
|
x -= NAMEHEXPADDING # To the left of both names
|
||||||
|
d.polygon([
|
||||||
|
(x, y),
|
||||||
|
(x+SMOL_WIDTH/2, y-SMOL_SIDELENGTH/2),
|
||||||
|
(x+SMOL_WIDTH, y),
|
||||||
|
(x+SMOL_WIDTH, y+SMOL_SIDELENGTH),
|
||||||
|
(x+SMOL_WIDTH/2, y+SMOL_SIDELENGTH*3/2),
|
||||||
|
(x, y+SMOL_SIDELENGTH),
|
||||||
|
],fill = PIECECOLOR[p % 2 + 1])
|
||||||
|
|
||||||
|
# Save
|
||||||
|
im.save(FILEPATH)
|
||||||
|
except:
|
||||||
|
logThis("Error drawing swap (error code 1542)")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
@ -323,7 +323,7 @@ def getName(userID):
|
|||||||
if userID in data:
|
if userID in data:
|
||||||
return data[userID]["user name"]
|
return data[userID]["user name"]
|
||||||
else:
|
else:
|
||||||
logThis("Couldn't find user")
|
logThis("Couldn't find user "+userID)
|
||||||
return userID
|
return userID
|
||||||
except:
|
except:
|
||||||
logThis("Error getting name")
|
logThis("Error getting name")
|
||||||
|
@ -114,6 +114,7 @@
|
|||||||
1532 - Cannot place on existing piece
|
1532 - Cannot place on existing piece
|
||||||
1533 - Position out of bounds
|
1533 - Position out of bounds
|
||||||
1541 - Error loading board-image
|
1541 - Error loading board-image
|
||||||
|
1542 - Error swapping
|
||||||
|
|
||||||
16 - Monopoly
|
16 - Monopoly
|
||||||
1600 - Unspecified error
|
1600 - Unspecified error
|
||||||
|
Binary file not shown.
Before Width: | Height: | Size: 80 KiB |
Reference in New Issue
Block a user