簡體   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