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,
^^ 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)
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