0

I have run into problems generating valid pieces for chess pieces in an early work-in-progress chess game in Python... I have run into trouble with the Bishop. Here is a glimpse of my program... the lower right white bishop is selected, and the red squares represent valid moves... it is evident what the main problem is.

If there is a blocking piece, I want my program to stop adding more potential moves,

enter image description here

^^ Not a duplicate; I have consulted other sources

Classes for Bishops:

class Bishop(Piece):
    def __init__(self, x, y, pl, im):
        Piece.__init__(self, x, y, pl, im) 

    def findAvailableMoves(self):
        for i in range(1, 8):
            for (dx, dy) in [(i, i), (i, -i), (-i, i), (-i, -i)]:
                if self.inBoundsPiece(self.cor.x + dx, self.cor.y + dy):
                    if board.board[self.cor.y + dy][self.cor.x + dx] == None:
                    self.potentialMoves.append((self.cor.y + dy, self.cor.x + dx))

class WBishop(Bishop):
    def __init__(self, x, y):
        Bishop.__init__(self, x, y, 1, wBishop)

class BBishop(Bishop):
    def __init__(self, x, y):
        Bishop.__init__(self, x, y, 2, bBishop)
myang0630
  • 111
  • 5
  • If your question needs an image please upload it through the question editor so it gets hosted somewhere reliable. – ChrisGPT was on strike Feb 22 '20 at 21:48
  • Can you clarify what problem you are trying to solve? The code and the image seem to show that this *does* find all the spaces that bishop could move to, if other pieces weren't in the way. There is nothing in your code to stop adding potential moves when a blocking piece is encountered, all it does is not add the blocking piece's own location to the potential moves. – cschatz Feb 22 '20 at 21:56
  • Yes the main problem is that if there was a blocking piece I would want my program to stop adding more potential moves – myang0630 Feb 22 '20 at 21:57

1 Answers1

1

I think the easiest solution is to rearrange the order of the loops, so the outer loop cycles through the four directions, and the inner one loops through the distances. Then stop the inner loop when a blocking piece is encountered. You may as well also stop the inner loop once the search goes out of bounds.

def findAvailableMoves(self):
    for (dx, dy) in [(1, 1), (1, -1), (-1, 1), (-1, -1)]:
        for i in range(1, 8):
            (x, y) = (self.cor.x + i*dx, self.cor.y + i*dy)
            if self.inBoundsPiece(x, y) and board.board[x][y] == None:
                self.potentialMoves.append((x, y))
            else:
                break
cschatz
  • 258
  • 1
  • 9