【问题标题】:Program won't end程序不会结束
【发布时间】:2022-01-18 02:16:14
【问题描述】:

我试图制作一个可以随机对 Stockfish 下棋的程序。运行程序时,它会播放整个游戏并给出结果,但执行此操作后程序不会停止运行。有谁知道问题出在哪里以及如何解决?

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

【问题讨论】:

  • 它是打印print(board.result()) 行,还是卡在循环中?
  • 这条线print(board.result())运行了吗?
  • 运行 print(board.result()) 行。
  • 那么问题不在于您向我们展示的行。底部random_play()之后还有什么写的吗?您究竟是如何运行该程序的?
  • 如果最后的打印显示,那么它不可能是代码的问题,你如何运行代码?到底发生了什么让你说程序不会结束?

标签: python chess


【解决方案1】:

您可以使用engine.quit() 退出引擎。您还可以在函数内部定义板和引擎。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多