I made a chess game GUI with pygame and now I want to add a computer player that will be stockfish in this case. github repo: https://github.com/Dark-Leader/Chess
sorry I can't show the code here.. it's multiple files. at the moment the game works perfectly for player vs player. have a look at main.py file:
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()
and this is 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())
have a look at the commented lines. I tried to create the engine instance and communicate with it. but the engine just freezes the program and thus the GUI is frozen. I have looked at these posts too and couldn't solve it: Stockfish and Python
How to Communicate with a Chess engine in Python?
Basically what I want to achieve is, when I give a command to the engine I want to get the response and close it immidiately so the GUI can continue (or if there's a way to run both at the same time with threading / multiprocessing) thanks