简体   繁体   中英

Issue with python skipping code in simple chess program

I am creating a simple program for chess, and I ran to an issue of supposedly python skipping code. Program entry is: find_side()

Console output:

Enter your team(1-black 2-white):1
<PlayResult at 0x3ec1dc0 (move=e2e4, ponder=d7d5, info={}, draw_offered=False, resigned=False)>
Enter your enemies move:

According to the console output, engine randomly generated move for the White player and made a counter-response in ponder. But I have input for that, looks like, that python is executing result_engine sooner than user input. Also, there's one more problem. Engine completely ignores the chess.engine.turn = turn line. I am using stockfish 11 as an engine and import chess as an link between python code and engine with universal chess engine Code:

import chess
import chess.engine
import time
import os

def logic_white():
    engine = chess.engine.SimpleEngine.popen_uci("C:\\Users\\Admin\\Desktop\\sf.exe")
    board = chess.Board()

    turn = True  # True - white False - black
    while True:
        chess.engine.turn = turn # This isn't working
        result_engine = engine.play(board,chess.engine.Limit(time=0.1))
        print(result_engine)

        res = input("Enter your enemie's move: ")
        move = chess.Move.from_uci(res)

        board.push(move)
        turn = not turn
        time.sleep(0.5)

def logic_black():
    engine = chess.engine.SimpleEngine.popen_uci("C:\\Users\\Admin\\Desktop\\sf.exe")
    board = chess.Board()

    turn = True # True - white False - black
    while True:
        chess.engine.turn = turn # This isn't working

        res = input("Enter your enemie's move: ")
        move = chess.Move.from_uci(res) #Inputting the enemy move and putting in on the virtual board
        board.push(move)

        result_engine = engine.play(board,chess.engine.Limit(time=0.1)) #Calculating best move to respond
        print(result_engine)
        board.push(result_engine) #Push the engine's move to the virtual board

        turn = not turn # Inverting turn, so turns can change from black to white, etc.
        time.sleep(0.5)       

def find_side():
    if(input("Enter your team(1-black 2-white):")) == 1:
        logic_black()
    else:
        logic_white()

Python's input function returns a string, so it will never be equal to the integer 1. As such, the code will always go into the else block. To fix this, either convert the input to an integer or compare it to '1'.

def find_side():
    if int(input("Enter your team(1-black 2-white):")) == 1:
        logic_black()
    else:
        logic_white()

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