【发布时间】:2021-08-06 03:57:49
【问题描述】:
我正在使用pygame 在 Python 上实现国际象棋(但不是最佳选择)。为了找到移动,我使用标准的对 minimax + alpha pruning,minimax 是一个递归搜索树,所以程序大部分时间都会做这部分。
def minimax(self, depth, alpha, beta, is_maxing_white):
# recursive tree exit condition
# if board in cache
if self.hash_board(depth, is_maxing_white) in self.board_caches:
return self.board_caches[self.hash_board(depth, is_maxing_white)]
# reached the desired depth
if depth == 0:
#return self.quiesce(alpha, beta)
return self.evaluation()
# if checkmate or stalemate
if not [*self.board.get_all_ligal_moves(self.side)]:
self.board_caches[self.hash_board(
depth, is_maxing_white)] = self.evaluation()
return self.board_caches[self.hash_board(depth, is_maxing_white)]
best_score = -float("inf") if is_maxing_white else float("inf")
for move in self.board.get_all_ligal_moves(self.side):
self.board.push(move, self.side)
local_score = self.minimax(depth - 1, alpha, beta, not is_maxing_white)
self.board_caches[self.hash_board(
depth - 1, not is_maxing_white)] = local_score
if is_maxing_white:
best_score = max(best_score, local_score)
alpha = max(alpha, best_score)
else:
best_score = min(best_score, local_score)
beta = min(beta, best_score)
self.board.pop()
if beta <= alpha:
print ("pruning")
break
return best_score
该脚本返回正确的评估值并且通常可以工作,但在它不回答任何输入的时候可能会导致它崩溃。我应该朝哪个方向思考,是否有可能以某种方式禁止不负责任的行为?
Windows 10、python 3.7、pygame 1.9
【问题讨论】:
-
“[...] 在她不回答任何输入的时候可能会崩溃。” - 这很难理解。
-
什么样的输入会崩溃呢?是否显示任何错误消息?
-
程序对鼠标点击做出反应。现在鼠标输入在搜索过程中不会使程序崩溃,但程序窗口在这部分仍然进入状态(无响应)。工作正常结束,无错误输出
-
使用循环会干扰主循环,所以我猜导致错误的原因是
for loop。你可以试着把它放在不同的线程中,看看会发生什么。
标签: python pygame game-development chess minimax