我正在尝试用Python编写一个国际象棋引擎,我可以找到给定位置的最佳走法,但我在从该位置收集主要变着方面遇到了困难,以下是我目前尝试过的方法:
def alphabeta(board, alpha, beta, depth, pvtable): if depth == 0: return evaluate.eval(board) for move in board.legal_moves: board.push(move) score = -alphabeta(board, -beta, -alpha, depth - 1, pvtable) board.pop() if score >= beta: return beta if score > alpha: alpha = score pvtable[depth-1] = str(move) return alpha
我使用pvtable[depth - 1] = str(move)
来添加走法,但最后发现pvtable
包含了随机且不一致的走法,例如对于起始位置,得到的是['g1h3', 'g8h6', 'h3g5', 'd8g5']
这样的结果。
我知道类似的问题已经被问过,但我仍然没有弄清楚如何解决这个问题。
回答:
我认为当搜索再次达到相同深度时(在游戏树的不同分支中),你的走法会被覆盖。
这个网站很好地解释了如何检索主要变着:https://web.archive.org/web/20071031100114/http://www.brucemo.com:80/compchess/programming/pv.htm
应用到你的代码示例中,应该是这样的(我没有测试过):
def alphabeta(board, alpha, beta, depth, pline): line = [] if depth == 0: return evaluate.eval(board) for move in board.legal_moves: board.push(move) score = -alphabeta(board, -beta, -alpha, depth - 1, line) board.pop() if score >= beta: return beta if score > alpha: alpha = score pline[:] = [str(move)] + line return alpha