def stripList(lst):
return [x for x in lst if not x is None]
def endState():
for x, col in enumerate(board):
for y, space in enumerate(col):
if space != 0:
if (x + 3 < len(board) and space == board[x+1][y] == board[x+2][y] == board[x+3][y]):
return space
if (y + 3 < len(board[0]) and space == board[x][y+1] == board[x][y+2] == board[x][y+3]):
return space
if (x + 3 < len(board) and y + 3 < len(board[0]) and space == board[x+1][y+1] == board[x+2][y+2] == board[x+3][y+3]):
return space
if (x + 3 < len(board) and y - 3 >= 0 and space == board[x+1][y-1] == board[x+2][y-2] == board[x+3][y-3]):
return space
return 0
def updateBoard(move, player):
moveStack.append(move)
if player == max:
board[move][board[move].index(0)] = 1
else:
board[move][board[move].index(0)] = -1
def undo():
move = moveStack.pop()
if 0 in board[move]:
board[move][board[move].index(0) - 1] = 0
else:
board[move][-1] = 0
def check(arr):
return 0 in arr and ((1 in arr) ^ (-1 in arr))
def evaluate4(arr):
if 1 in arr:
return 10 ** (arr.count(1) - 1)
return -(10 ** (arr.count(-1) - 1))
def evaluateBoard():
if (winner := endState()) != 0:
return winner * 100000
total = 0
for x, col in enumerate(board):
for y, space in enumerate(col):
if (x + 3 < len(board)):
right = [space, board[x+1][y], board[x+2][y], board[x+3][y]]
if check(right):
total += evaluate4(right)
if (y + 3 < len(board[0])):
up = [space, board[x][y+1], board[x][y+2], board[x][y+3]]
if check(up):
total += evaluate4(up)
if (x + 3 < len(board) and y + 3 < len(board[0])):
upright = [space, board[x+1][y+1], board[x+2][y+2], board[x+3][y+3]]
if check(upright):
total += evaluate4(upright)
if (x + 3 < len(board) and y - 3 >= 0):
downright = [space, board[x+1][y-1], board[x+2][y-2], board[x+3][y-3]]
if check(downright):
total += evaluate4(downright)
return total
def evaluateMove(move, player, depth = 0):
global board
if not 0 in board[move]:
return None
updateBoard(move, min if player == max else max)
if (winner := endState()) != 0:
returnVal = winner * 100000
elif depth > 4: #tune this if it takes to long/short
returnVal = evaluateBoard()
else:
moves = [evaluateMove(x, min if player == max else max, depth+1) for x in range(7)]
if all(move is None for move in moves):
returnVal = None
else:
returnVal = player(stripList(moves))
undo()
return returnVal
def move(player):
moves = [evaluateMove(x, min if player == max else max) for x in range(7)]
choosenMove = moves.index(player(stripList(moves)))
updateBoard(choosenMove, player)
return choosenMove
board = [[0 for _ in range(6)] for _ in range(7)]
moveStack = []
side = input()
player = max
if side == "f":
player = min
print(move(player) + 1)
while endState() == 0:
updateBoard(int(input()) - 1, min if player == max else max)
print(move(player) + 1)
post a comment