首页 > 解决方案 > 用python与stockfish交流

问题描述

我用 pygame 制作了一个国际象棋游戏 GUI,现在我想添加一个电脑玩家,在这种情况下将是鱼。github 仓库:https ://github.com/Dark-Leader/Chess

对不起,我不能在这里显示代码.. 它是多个文件。目前这款游戏非常适合玩家对玩家。看看 main.py 文件:

import pygame
from chess.constants import WIDTH, HEIGHT, FPS, BOARD_EDGE
from chess.game import Game
from chess.engine import Engine
pygame.init()
window = pygame.display.set_mode((WIDTH + BOARD_EDGE * 2, HEIGHT + BOARD_EDGE * 2))
pygame.display.set_caption("Chess")
clock = pygame.time.Clock()
game = Game(window)
# engine = Engine()
# engine.get_response()
# engine.put_command("uci")
# engine.get_response()
# engine.put_command('quit')

running = True
while running:
    clock.tick(FPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        if event.type == pygame.MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()
            game.select(pos)

    game.update()
    result = game.get_winner()
    if result:
        print(result)
        running = False
    pygame.display.flip()

pygame.quit()

这是engine.py:

import subprocess


class Engine:

    def __init__(self):
        self.engine = subprocess.Popen("chess/stockfish.exe", stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                   universal_newlines=True)

    def put_command(self, command):
        self.engine.stdin.write(command + "\n")

    def get_response(self):
        for line in self.engine.stdout:
            print(line.strip())

看看注释行。我试图创建引擎实例并与之通信。但引擎只是冻结程序,因此 GUI 被冻结。我也看过这些帖子但无法解决: Stockfish and Python

如何在 Python 中与国际象棋引擎通信?

基本上我想要实现的是,当我向引擎发出命令时,我想获得响应并立即关闭它,以便 GUI 可以继续(或者如果有办法通过线程/多处理同时运行两者)谢谢

标签: pythonchess

解决方案


推荐阅读