终极井字棋Alpha-Beta搜索算法优化求助:搜索深度受限性能差
终极井字棋Alpha-Beta搜索算法优化求助
我正在完成学校项目,为终极井字棋(由3x3个普通井字棋组成的棋盘,每一步落子会指定对手下一步的落子棋盘)编写Alpha-Beta搜索算法。当前算法因分支因子过大,为避免性能问题不得不限制搜索深度——搜索深度超过4时基本无法使用,这导致AI效果很差:仅能战胜随机落子的Bot,对阵其他AI Bot时几乎全败。我正在实现启发式函数对落子进行排序,但不确定能否解决问题。
以下是代码核心片段:
# choose a move to play - this is called everytime its the bots move def play(max_rec_depth=4): n = execute_alp_bta(max_rec_depth) place(curr, n, 1) return n # Call to execute def execute_alp_bta(max_rec_depth) -> int: global curr max_pos = -1 max_val = float('-inf') moves = get_heuristic_ordered_moves(curr) # Iterate over possible moves on the current board for i in range(1, 10): if boards[curr][i] == 0: boards[curr][i] = 1 # Simulate place Maximiser (us) # Recurse starting from opponents view score = minimax(max_rec_depth, float('-inf'), float('inf'), is_maximising_player=False, curr_val=i) boards[curr][i] = 0 # Undo the simulated move # Update the best score and position if the current score is better if score > max_val: max_val = score max_pos = i # Return the position that gives the maximum value as per minimax if max_pos == -1: raise ValueError("Error with Minimax recursion") # print(f"found max val of {max_val} for pos {max_pos}") return max_pos # MAXIMISING PLAYER - should be the US the computer def minimax(depth, alpha, beta, is_maximising_player, curr_val) -> int: eval = evaluate() # returns win loss draw or none if depth == 0 or abs(eval) == 1: # Terminal condition return eval if is_maximising_player: max_val = float('-inf') for i in range(1, 10): if boards[curr_val][i] == 0: boards[curr_val][i] = 1 # Maximisers move # print(f"placed at board: {curr_val} with index {i}") score = minimax(depth-1, alpha, beta, False, curr_val=i) # print(f"exited back out of recursion. Undid board: {curr_val} with index {i}") boards[curr_val][i] = 0 # Undo move max_val = max(max_val, score) alpha = max(alpha, score) if beta <= alpha: break return max_val else: min_val = float('inf') for i in range(1, 10): if boards[curr_val][i] == 0: boards[curr_val][i] = -1 # minimizers move # print(f"placed at board: {curr_val} with index {i}") score = minimax(depth-1, alpha, beta, True, curr_val=i) # print(f"exited back out of recursion. Undid board: {curr_val} with index {i}") boards[curr_val][i] = 0 # undo move min_val = min(min_val, score) beta = min(beta, score) if beta <= alpha: break return min_val

现寻求该算法的优化方案或改进建议,我是AI算法领域新手,恳请帮助。
内容的提问来源于stack exchange,提问作者Alex
相关产品推荐
相关产品推荐

