繁体   English   中英

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

[英]Infinite while loop stopping unexpectedly python threading

我希望你过得愉快:)

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

我现在正在制作 AI,我正在使用 Stockfish 进行测试。

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

我还使用 python-chess 作为我的主要库来处理游戏状态和移动,以及访问 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()

出于某种原因,engine_play() 中的 while 循环停止执行。

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

当它在 while 循环后打印 board.result 值 = "*" 时。

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

它实际上是线程问题吗?

此外,pygame 游戏循环仅更新图形并实现诸如拖放功能之类的功能。

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

我不完全确定循环停止的原因,但我确实找到了解决问题的方法。 代替:

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 似乎也很重要,否则无限循环将阻止程序停止。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM