Skip to content

Instantly share code, notes, and snippets.

@matejker
Created August 31, 2021 19:58
Show Gist options
  • Save matejker/2f4f8b4fdd8b637eba714be5f9ee851b to your computer and use it in GitHub Desktop.
Save matejker/2f4f8b4fdd8b637eba714be5f9ee851b to your computer and use it in GitHub Desktop.
def get_score(board: Ternary, depth: int, player: int = 2) -> Tuple[int, bool]:
winner = whois_winner(board)
if winner == player:
return 10 - depth, True
elif winner < 1:
return 0, winner == 0
else:
return depth - 10, True
def minimax(board: Ternary, depth: int = 0, player: int = 2) -> Tuple[Ternary, int]:
score, ended = get_score(board, depth, player)
if score != 0 or ended:
return board, score
depth += 1
scored_actions: Dict = {}
actions = np.where(np.array(list(board.number)) == "0")[0]
active_player = len(actions) % 2 + 1
for a in actions:
action_board = list(board.number)
action_board[a] = str(active_player)
new_board = "".join(action_board)
_, scored_actions[new_board] = minimax(Ternary(new_board), depth, player)
if player == active_player:
max_value = max(scored_actions.values())
max_boards = [b for b, v in scored_actions.items() if v == max_value]
return Ternary(np.random.choice(max_boards)), max_value
else:
min_value = min(scored_actions.values())
min_boards = [b for b, v in scored_actions.items() if v == min_value]
return Ternary(np.random.choice(min_boards)), min_value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment