Infinite while loop stopping unexpectedly python threading

261 views Asked by At

I hope you're having a good day :)

Recently I have been making a chess program.

I'm now at the point of making the AI and I'm using Stockfish for testing purposes.

Since I need the computer to have time to evaluate without pausing the pygame game loop, I'm using the threading library.

I'm also using python-chess as my main library for handling the game state and making moves, as well as accessing Stockfish.

Here is my code for threading:

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()

For some reason, the while loop in engine_play() stops executing.

It doesn't stop consistently, it just stops at random.

When it prints board.result after the while loop the value = "*".

How is this while loop stopping when the condition (board.result() == "*") is still met?

Is it actually a threading problem?

Also, the pygame game loop just updates the graphics and implements things like drag 'n drop functionality.

There are no errors displayed and I only have this one thread.

1

There are 1 answers

0
KNN On BEST ANSWER

I'm not entirely sure why the loop stops, but I did figure out a way to fix my problem. Instead of:

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())

I put an infinite loop and checked for board.result() every time.

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())

It also seems pretty important to set Daemon to True, otherwise the infinite loop will prevent the program from stopping.