【问题标题】:Script becomes unresponsive during work, but continues to work after that and ends correctly脚本在工作期间变得无响应,但之后继续工作并正确结束
【发布时间】: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


【解决方案1】:

当pygame程序长时间调用pygame.event.get()或pygame.event.pump()失败时,操作系统认为程序崩溃了。

有一些重要的事情必须在事件队列内部处理。主窗口可能需要重新绘制或响应系统。如果您长时间未能调用事件队列,系统可能会判断您的程序已锁定。

来自https://www.pygame.org/docs/ref/event.html#pygame.event.pump

如果你确保在 minimax 函数中偶尔调用pygame.event.pump(),操作系统不会认为你的程序已经崩溃。因此,您将能够单击该窗口而不会收到“此窗口没有响应”或任何其他信息。

希望这能解决您的问题,而不是其他问题。

【讨论】:

  • 谢谢,这正是我想要的
  • @Makc22999 很高兴听到!由于这解决了问题,如果您接受它作为正确答案,我将不胜感激。
猜你喜欢
  • 2020-03-05
  • 2022-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-02
  • 1970-01-01
相关资源
最近更新 更多