samedi 27 novembre 2021

Python: How can I reduce the number of 'if' statements down to a reasonable amount for my game?

Im making a chess game in python and was trying to generate the legal moves of each piece using 'if' statements to see if the space the player wants to move to is free and if the move is actually within the borders of the board. The problem is that there are too many 'if' statements as well as nested 'if' statements. This really makes my file look like spaghetti code and over-complicates the process.

Here is an example:

def valid_moves(self, board):
    i = self.row
    j = self.col

    moves = []

    if i > 0:
        # TOP LEFT
        if j > 0:
            p = board[i - 1][j - 1]
            if p == 0: # checks if space empty
                moves.append((j - 1, i - 1,))
            elif p.color != self.color:
                moves.append((j - 1, i - 1,))

        # TOP MIDDLE
        p = board[i - 1][j]
        if p == 0: # checks if space empty
            moves.append((j, i - 1))
        elif p.color != self.color:
            moves.append((j, i - 1))

        # TOP RIGHT
        if j < 7:
            p = board[i - 1][j + 1]
            if p == 0: # checks if space empty
                moves.append((j + 1, i - 1,))
            elif p.color != self.color:
                moves.append((j + 1, i - 1,))

    if i < 7:
        # BOTTOM LEFT
        if j > 0:
            p = board[i + 1][j - 1]
            if p == 0: # checks if space empty
                moves.append((j - 1, i + 1,))
            elif p.color != self.color:
                moves.append((j - 1, i + 1,))

        # BOTTOM MIDDLE
        p = board[i + 1][j]
        if p == 0: # checks if space empty
            moves.append((j, i + 1))
        elif p.color != self.color:
            moves.append((j, i + 1))

        # BOTTOM RIGHT
        if j < 7:
            p = board[i + 1][j + 1]
            if p == 0: # checks if space empty
                moves.append((j + 1, i + 1))
            elif p.color != self.color:
                moves.append((j + 1, i + 1))

    # MIDDLE LEFT
    if j > 0:
        p = board[i][j - 1]
        if p == 0: # checks if space empty
            moves.append((j - 1, i))
        elif p.color != self.color:
            moves.append((j - 1, i))

    # MIDDLE RIGHT
    if j < 7:
        p = board[i][j + 1]
        if p == 0: # checks if space empty
            moves.append((j + 1, i))
        elif p.color != self.color:
            moves.append((j + 1, i))

    return moves

This example is for just 1 piece out of 6 and so there is a lot of occurring 'if' statements. How can I refractor this to where I don't need to use as many 'if' statements?

Aucun commentaire:

Enregistrer un commentaire