1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] How can I make this code for finding legal chess moves more efficient?

Discussão em 'Python' iniciado por Stack, Novembro 30, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to make a chess engine without use of the python chess libraries, so I can learn more about chess programming. Have generated a set of pseudo legal moves (- castling and en passant) and have made a function to generate only the legal moves from the list. my code for this function is here:

    def generateLegalMoves(currentPos, colourToMove):
    kingNumber = 1 if colourToMove == "b" else 9
    opponentColour = "w" if colourToMove == "b" else "b"
    legalMoves = []
    myKingSquare = currentPos.index(kingNumber)
    pseudoLegalList = GeneratePsuedoLegalMoves(currentPos, colourToMove)
    for pseudoMove in pseudoLegalList:
    newPos = makeMove(currentPos, pseudoMove[0], pseudoMove[1])
    newPosPsuedoLegalMoves = GeneratePsuedoLegalMoves(newPos, opponentColour)
    isLegal = True
    for j in newPosPsuedoLegalMoves:
    if j[1] == myKingSquare:
    isLegal = False
    if isLegal:
    legalMoves.append(pseudoMove)
    return legalMoves


    How can I code a more efficient version?

    Continue reading...

Compartilhe esta Página