无限while循环意外停止python线程

2024-05-14 03:47:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望你今天过得愉快:)

最近我一直在做一个国际象棋程序

我现在正在制作人工智能,我正在使用Stockfish进行测试

因为我需要计算机有时间在不暂停pygame游戏循环的情况下进行评估,所以我使用线程库

我还使用python国际象棋作为我的主库来处理游戏状态和移动,以及访问Stockfish

以下是我的线程代码:

def engine_play():
    global player_color
    global board
    while board.result() == "*":
        if board.turn is not player_color:
            result = engine.play(board, chess.engine.Limit(time=3.0))
            board.push(result.move)
            print(result.move)
    print(board.result())

engine_thread = threading.Thread(target=engine_play)
engine_thread.setDaemon(True)
engine_thread.start()

由于某种原因,引擎_play()中的while循环停止执行

它不会一直停止,只是随机停止

当它在while循环后打印board.result时,值为=“*”

当条件(board.result()==“*”)仍然满足时,while循环如何停止

这实际上是一个线程问题吗

此外,pygame游戏循环只是更新图形并实现拖放功能

没有显示错误,我只有一个线程


Tags: board游戏playmoveresult线程globalthread
1条回答
网友
1楼 · 发布于 2024-05-14 03:47:20

我不完全确定为什么循环会停止,但我确实找到了解决问题的方法。 而不是:

while board.result() == "*":
    if board.turn is not player_color:
        result = engine.play(board, chess.engine.Limit(time=3.0))
        board.push(result.move)
        print(result.move)
print(board.result())

我放置了一个无限循环,每次都检查board.result()

while True:
    if board.result() == "*":
        if board.turn is not player_color:
            result = engine.play(board, chess.engine.Limit(time=3.0))
            board.push(result.move)
            print(result.move)
print(board.result())

将Daemon设置为True似乎也很重要,否则无限循环将阻止程序停止

相关问题 更多 >