Created
August 13, 2022 19:38
-
-
Save ronzhin-dmitry/c6cce08a4c169085167ab8496318cca8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def minimax(self, last_moves, d, min_val, max_val, only_closest = True, children = None): #recursive minimax with alpha-beta that performs evaluation in every node, not only in leafs (thus evaluation should be very cheap) | |
if d == 0: | |
cur_evalutaion = self.evaluate(last_moves) | |
return cur_evalutaion, d | |
last_move = last_moves[-1] | |
turn = (self.board[last_move] + 1) % 2 | |
if children == None: | |
children = set(self.getChildren(only_closest)) | |
d1 = d | |
if turn == 0: #we are in max node - user move | |
v = min_val | |
for coord in children: | |
if self.board[coord] != -1: | |
continue | |
self.board[coord] = turn | |
children = children.difference([coord]) | |
buf = self.get_all_neigh_possible_moves(coord) | |
children = children.union(buf) | |
last_moves.append(coord) | |
v1, d1 = self.minimax(last_moves, d-1, v, max_val, only_closest, children) | |
last_moves.pop() | |
children = children.difference(buf) | |
children = children.union([coord]) | |
self.board[coord] = -1 | |
if v1 > v: | |
v = v1 | |
if v >= max_val: | |
return max_val, d1 | |
return v, d1 | |
if turn == 1: #we are in min node - AI move | |
v = max_val | |
for coord in children: | |
if self.board[coord] != -1: | |
continue | |
self.board[coord] = turn | |
children = children.difference([coord]) | |
buf = self.get_all_neigh_possible_moves(coord) | |
children = children.union(buf) | |
last_moves.append(coord) | |
v1, d1 = self.minimax(last_moves, d-1, min_val, v, only_closest, children) | |
last_moves.pop() | |
children = children.difference(buf) | |
children = children.union([coord]) | |
self.board[coord] = -1 | |
if v1 < v: | |
v = v1 | |
if v <= min_val: | |
return min_val, d1 | |
return v, d1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment