简体   繁体   中英

Program won't end

I have tried to make a program which can play random chess moves against Stockfish. When running the program, it will play the entire game and give the result, but the program won't stop running after doing this. Does anybody know what is wrong and how to fix it?

import random
import chess.engine
import pydirectory

board = chess.Board()

engine = chess.engine.SimpleEngine.popen_uci(r"C:\Users\qenij\stockfish\stockfish_14.1_win_x64_avx2")

def random_play():
    while not board.is_game_over():
        if board.turn == chess.WHITE:
            m1 = random.choice([move for move in board.legal_moves])
            uci = m1.uci()
            print("Play:", uci)
            board.push_uci(uci)
            print(board)
        else: 
            result = engine.play(board, chess.engine.Limit(time=0.05))
            board.push(result.move)
            
        
    print(board.result())

random_play()

You can quit the engine with engine.quit() . Also you can define board and engine inside the function.

import random
import chess.engine
import pydirectory


def random_play():
    board = chess.Board()
    engine = chess.engine.SimpleEngine.popen_uci(r"C:\Users\qenij\stockfish\stockfish_14.1_win_x64_avx2")
    
    while not board.is_game_over():
        if board.turn == chess.WHITE:
            m1 = random.choice([move for move in board.legal_moves])
            uci = m1.uci()
            print("Play:", uci)
            board.push_uci(uci)
            print(board)
        else: 
            result = engine.play(board, chess.engine.Limit(time=0.05))
            board.push(result.move)
            
    engine.quit()           
    print(board.result())    
    

random_play()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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