Files
Gwendolyn/funcs/games/hex.py
2020-08-04 19:48:23 +02:00

366 lines
14 KiB
Python

import json
import random
import copy
import math
from . import hexDraw
from funcs import logThis
# 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
# Parses command
def parseHex(command, channel, user):
commands = command.split()
if command == "" or command == " ":
return "I didn't get that. Use \"!hex start [opponent]\" to start a game.", False, False, False, False
elif commands[0] == "start":
# Starting a game
if len(commands) == 1: # if the commands is "!hex start", the opponent is Gwendolyn
commands.append("2")
return hexStart(channel,user,commands[1]) # commands[1] is the opponent
# Stopping the game
elif commands[0] == "stop":
with open("resources/games/games.json", "r") as f:
data = json.load(f)
if user in data["hex games"][channel]["players"]:
return "Ending game.", False, False, True, False
else:
return "You can't end a game where you're not a player.", False, False, False, False
# Placing a piece
elif commands[0] == "place":
try:
return placeHex(channel,int(commands[1]),commands[2])
except:
return "I didn't get that. To place a piece use \"!hex place [player number] [position]\". A valid position is e.g. \"e2\".", False, False, False, False
else:
return "I didn't get that. Use \"!hex start [opponent]\" to start a game or \"!hex stop\" to stop a current game.", False, False, False, False
# Starts the game
def hexStart(channel, user, opponent):
with open("resources/games/games.json", "r") as f:
data = json.load(f)
if user.lower() != opponent.lower():
if channel not in data["hex games"]:
if opponent in ["1","2","3","4","5"]:
difficulty = int(opponent)
diffText = " with difficulty "+opponent
opponent = "Gwendolyn"
elif opponent.lower() == "gwendolyn":
difficulty = 3
diffText = " with difficulty 3"
opponent = "Gwendolyn"
else:
try:
int(opponent)
return "That difficulty doesn't exist", False, False, False, False
except:
# Opponent is another player
difficulty = 5
diffText = ""
# board is 11x11
board = [ [ 0 for i in range(boardWidth) ] for j in range(boardWidth) ]
players = [user,opponent]
random.shuffle(players)
winningPieces = [[""],[""],[""]] # etc.
data["hex games"][channel] = {"board": board,"winner":0,
"players":players, "winningPieces":winningPieces,"turn":0,"difficulty":difficulty}
with open("resources/games/games.json", "w") as f:
json.dump(data,f,indent=4)
# draw the board
#fourInARowDraw.drawImage(channel)
# hexDraw() # something something
gwendoTurn = False
if players[0] == "Gwendolyn":
# in case she has the first move
gwendoTurn = True
return "Started hex game against "+opponent+". It's "+players[0]+"'s turn", True, False, False, gwendoTurn
else:
return "There's already a hex game going on in this channel", False, False, False, False
else:
return "You can't play against yourself", False, False, False, False
# Places a piece at the given location and checks things afterwards
def placeHex(channel : str,player : int,position : str):
with open("resources/games/games.json", "r") as f:
data = json.load(f)
if channel in data["hex games"]:
board = data["hex games"][channel]["board"]
# Places on board
board = placeOnHexBoard(board,player,position)
if board != None:
# If the move is valid:
data["hex games"][channel]["board"] = board
turn = (data["hex games"][channel]["turn"]+1)%2
data["hex games"][channel]["turn"] = turn
with open("resources/games/games.json", "w") as f:
json.dump(data,f,indent=4)
# Checking for a win
logThis("Checking for win")
won, winningPieces = isHexWon(data["hex games"][channel]["board"])
if won != 0:
gameWon = True
data["hex games"][channel]["winner"] = won
data["hex games"][channel]["winningPieces"] = winningPieces
message = data["hex games"][channel]["players"][won-1]+" won!"
if data["hex games"][channel]["players"][won-1] != "Gwendolyn":
winAmount = data["hex games"][channel]["difficulty"]^2+5
message += " Adding "+str(winAmount)+" GwendoBucks to their account."
else:
gameWon = False
message = data["hex games"][channel]["players"][player-1]+" placed at "+position+". It's now "+data["hex games"][channel]["players"][turn]+"'s turn."
with open("resources/games/games.json", "w") as f:
json.dump(data,f,indent=4)
# Is it Gwendolyn's turn?
gwendoTurn = False
if data["hex games"][channel]["players"][turn] == "Gwendolyn":
logThis("It's Gwendolyn's turn")
gwendoTurn = True
# draw the board
#fourInARowDraw.drawImage(channel)
# hexDraw() # something something
return message, True, True, gameWon, gwendoTurn
else:
# Invalid move
return "That move is invalid. Place only on empty spaces.", True, True, False, False
else:
return "There's no game in this channel", False, False, False, False
# Returns a board where the placement has occured
def placeOnHexBoard(board,player,position):
# Translates the position
position = position.lower()
try:
column = ord(position[0])-97 # ord() translates from letter to number
row = int(position[1])
if column not in range(boardWidth) or row not in range(boardWidth):
logThis("Position out of bounds (error code 1533)")
return "Error. That position is out of bounds."
except:
logThis("Invalid position (error code 1531)")
return "Error. The position should be a letter followed by a number, e.g. \"e2\"."
# Place at the position
if board[row][column] == 0:
board[row][column] = player
return board
else:
logThis("Cannot place on existing piece (error code 1532)")
return "Error. You must place on an empty space."
# Checks if someone has won the game and returns the winner
def isHexWon(board):
won = 0
winDirection = ""
winCoordinates = [0,0]
for row in range(len(board)):
for place in range(len(board[row])):
if won == 0:
piecePlayer = board[row][place]
if piecePlayer != 0:
# Checks horizontal
if place <= boardWidth-4:
pieces = [board[row][place+1],board[row][place+2],board[row][place+3]]
else:
pieces = [0]
if all(x == piecePlayer for x in pieces):
won = piecePlayer
winDirection = "h"
winCoordinates = [row,place]
# Checks vertical
if row <= boardWidth-4:
pieces = [board[row+1][place],board[row+2][place],board[row+3][place]]
else:
pieces = [0]
if all(x == piecePlayer for x in pieces):
won = piecePlayer
winDirection = "v"
winCoordinates = [row,place]
# Checks right diagonal
if row <= boardWidth-4 and place <= boardWidth-4:
pieces = [board[row+1][place+1],board[row+2][place+2],board[row+3][place+3]]
else:
pieces = [0]
if all(x == piecePlayer for x in pieces):
won = piecePlayer
winDirection = "r"
winCoordinates = [row,place]
# Checks left diagonal
if row <= boardWidth-4 and place >= 3:
pieces = [board[row+1][place-1],board[row+2][place-2],board[row+3][place-3]]
else:
pieces = [0]
if all(x == piecePlayer for x in pieces):
won = piecePlayer
winDirection = "l"
winCoordinates = [row,place]
return won, winningPieces
# Plays as the AI
def hexAI(channel):
logThis("Figuring out best move")
with open("resources/games/games.json", "r") as f:
data = json.load(f)
board = data["hex games"][channel]["board"]
player = data["hex games"][channel]["players"].index("Gwendolyn")+1
difficulty = data["hex games"][channel]["difficulty"]
scores = [-math.inf,-math.inf,-math.inf,-math.inf,-math.inf,-math.inf,-math.inf]
for column in range(0,boardWidth):
testBoard = copy.deepcopy(board)
testBoard = placeOnHexBoard(testBoard,player,column)
if testBoard != None:
scores[column] = minimaxHex(testBoard,difficulty,player%2+1,player,-math.inf,math.inf,False)
logThis("Best score for column "+str(column)+" is "+str(scores[column]))
possibleScores = scores.copy()
while (min(possibleScores) <= (max(possibleScores) - max(possibleScores)/10)) and len(possibleScores) != 1:
possibleScores.remove(min(possibleScores))
highest_score = random.choice(possibleScores)
indices = [i for i, x in enumerate(scores) if x == highest_score]
placement = random.choice(indices)
return placeHex(channel,player,placement)
# Calculates points for a board
def AICalcHexPoints(board,player):
score = 0
otherPlayer = player%2+1
# Adds points for middle placement
for row in range(len(board)):
if board[row][3] == player:
score += AIScoresHex["middle"]
# Checks horizontal
for row in range(boardWidth):
rowArray = [int(i) for i in list(board[row])]
for place in range(boardWidth-3):
window = rowArray[place:place+4]
score += evaluateWindow(window,player,otherPlayer)
# Checks Vertical
for column in range(boardWidth):
columnArray = [int(i[column]) for i in list(board)]
for place in range(boardWidth-3):
window = columnArray[place:place+4]
score += evaluateWindow(window,player,otherPlayer)
# Checks right diagonal
for row in range(boardWidth-3):
for place in range(boardWidth-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)
# Checks left diagonal
for row in range(boardWidth-3):
for place in range(3,boardWidth):
window = [board[row][place],board[row+1][place-1],board[row+2][place-2],board[row+3][place-3]]
score += evaluateWindow(window,player,otherPlayer)
## Checks if anyone has won
#won = isHexWon(board)[0]
## Add points if AI wins
#if won == player:
# score += AIScoresHex["win"]
return score
#def evaluateWindow(window,player,otherPlayer):
# if window.count(player) == 4:
# return AIScoresHex["win"]
# elif window.count(player) == 3 and window.count(0) == 1:
# return AIScoresHex["three in a row"]
# elif window.count(player) == 2 and window.count(0) == 2:
# return AIScoresHex["two in a row"]
# elif window.count(otherPlayer) == 4:
# return AIScoresHex["enemy win"]
# else:
# return 0
def minimaxHex(board, depth, player , originalPlayer, alpha, beta, maximizingPlayer):
terminal = ((isHexWon(board)[0] != 0) or (0 not in board[0]))
# The depth is how many moves ahead the computer checks. This value is the difficulty.
if depth == 0 or terminal:
points = AICalcHexPoints(board,originalPlayer)
return points
if maximizingPlayer:
value = -math.inf
for column in range(0,boardWidth):
testBoard = copy.deepcopy(board)
testBoard = placeOnHexBoard(testBoard,player,column)
if testBoard != None:
evaluation = minimaxHex(testBoard,depth-1,player%2+1,originalPlayer,alpha,beta,False)
if evaluation < -9000: evaluation += AIScoresHex["avoid losing"]
value = max(value,evaluation)
alpha = max(alpha,evaluation)
if beta <= alpha:
break
return value
else:
value = math.inf
for column in range(0,boardWidth):
testBoard = copy.deepcopy(board)
testBoard = placeOnHexBoard(testBoard,player,column)
if testBoard != None:
evaluation = minimaxHex(testBoard,depth-1,player%2+1,originalPlayer,alpha,beta,True)
if evaluation < -9000: evaluation += AIScoresHex["avoid losing"]
value = min(value,evaluation)
beta = min(beta,evaluation)
if beta <= alpha:
break
return value