当只有一个合法的移动可用时,python 中的国际象棋模块出现问题[关闭]

问题描述 投票:0回答:1

我在测试我编写的这个机器人时遇到问题,如果只有一个合法的动作,它就无法采取行动,有人可以向我解释这个问题吗?

import random
import chess
import time
import sys
import os

Board = chess.Board()

Turn = 0

YourTurn = True

while True:
    Turn += 1
    BotMove = ""
    os.system("clear")
    print(Board)
    if YourTurn == True:
        Move = input("Enter Move: ")
        LegalMoves = str(Board.legal_moves)[37:-1]
        LegalMoves = LegalMoves.replace(", ", "', '")
        LegalMoves = LegalMoves.replace("(", "('")
        LegalMoves = LegalMoves.replace(")", "')")
        LegalMoves = eval(LegalMoves)
        Moves = []
        for i in LegalMoves:
            Moves.append(i)
        if Move in LegalMoves:
            Board.push_san(Move)
            YourTurn = False
        else:
            print("Invalid Move!")
            time.sleep(2)

    else:
        LegalMoves = str(Board.legal_moves)[37:-1]
        LegalMoves = LegalMoves.replace(", ", "', '")
        LegalMoves = LegalMoves.replace("(", "('")
        LegalMoves = LegalMoves.replace(")", "')")
        LegalMoves = eval(LegalMoves)
        Moves = []
        for i in LegalMoves:
            Moves.append(i)

        time.sleep(2)
        counter = 0
        for i in range(len(LegalMoves)):
            if "ax" in LegalMoves[counter] or "bx" in LegalMoves[counter] or "cx" in LegalMoves[counter] or "dx" in LegalMoves[counter] or "ex" in LegalMoves[counter] or "fx" in LegalMoves[counter] or "gx" in LegalMoves[counter] or "hx" in LegalMoves[counter]:
                BotMove = LegalMoves[counter]
                break
            elif "Nx" in LegalMoves[counter]:
                BotMove = LegalMoves[counter]
                break
            elif "Bx" in LegalMoves[counter]:
                BotMove = LegalMoves[counter]
                break
            elif "Rx" in LegalMoves[counter]:
                BotMove = LegalMoves[counter]
                break
            elif "Qx" in LegalMoves[counter]:
                BotMove = LegalMoves[counter]
                break
            elif "x" in LegalMoves[counter]:
                BotMove = LegalMoves[counter]
                break
            elif "Kx" in LegalMoves[counter]:
                BotMove = LegalMoves[counter]
                break
            else:
                counter += 1
    
        if BotMove == "":
            BotMove = random.choice(LegalMoves)
        Board.push_san(BotMove)
        print(BotMove)
        time.sleep(2)
        YourTurn = True


我什么都没试过请帮助我

python chess
1个回答
0
投票

问题出在轮到机器人时采取行动的代码逻辑上。当只有一个合法的移动可用时,检查各种移动符号是否存在的循环不会执行,因为 len(LegalMoves) 是 1。因此,BotMove 永远不会被分配一个值,并且机器人最终会做出无效的移动,因为它试图推动一个空字符串作为移动。

要解决这个问题,你可以简单地检查是否只有一个合法的移动可用,如果是,直接移动而不通过循环。

© www.soinside.com 2019 - 2024. All rights reserved.