def evaluation(board, maximizing_player, player, last_move): if check_for_player_win(board, last_move[0], last_move[1], player): return SCORE_FOR_WIN elif check_for_player_win(board, last_move[0], last_move[1], get_opposite_player(maximizing_player)): return -SCORE_FOR_WIN else: return get_score_for_board(board, maximizing_player)
def test_for_winner_true(self): board = [ [0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, -1], [0, 0, 0, 0], ] assert check_for_player_win(transform_board_for_game(board), 1, 2, PlayerToken.X)
def test_for_winner_in_diagonal(self): board = [ [0, 0, 0, 0, 0], [0, 0, 1, 1, 0], [1, 1, -1, -1, -1], [1, -1, -1, -1, 1], ] assert check_for_player_win(transform_board_for_game(board), 0, 3, PlayerToken.X)
def test_for_winner_false(self): board = [ [0, 0, 0, 0], [1, 1, 1, 1], [0, 0, 0, -1], [0, 0, 0, 0], ] self.assertFalse( check_for_player_win(transform_board_for_game(board), 1, 2, PlayerToken.O))
def insert(self, column, player_token): """Insert the player in the given column.""" for row in range(len(self.board) - 1, -1, -1): if self.board[row][int(column)] == PlayerToken.NOBODY: self.board[row][int(column)] = player_token self.empty_cells -= 1 if check_for_player_win(board=self.board, chosen_row=row, chosen_column=column, player_token=player_token): self.winner = player_token return True return False
def alpha_beta(board, depth, alpha, beta, maximizing_player, current_player, last_move): moves = get_valid_moves(board) if depth == 0 or not moves \ or check_for_player_win(board, last_move[0], last_move[1], get_opposite_player(current_player)): return evaluation(board, maximizing_player, current_player, last_move) if maximizing_player == current_player: best = -math.inf for row, column in moves: current_board = copy_array(board) current_board[row][column] = current_player value = alpha_beta( current_board, depth - 1, alpha, beta, maximizing_player=maximizing_player, current_player=get_opposite_player(current_player), last_move=(row, column)) best = max(best, value) alpha = max(alpha, best) if beta <= alpha: break return best else: best = math.inf for row, column in moves: current_board = copy_array(board) current_board[row][column] = current_player value = alpha_beta( current_board, depth - 1, alpha, beta, maximizing_player=maximizing_player, current_player=get_opposite_player(current_player), last_move=(row, column)) best = min(best, value) alpha = min(beta, best) if beta <= alpha: break return best