Search code examples
pythonchess

How to model Bishop movement on a chessboard


I have a board, and I want to model a bishop's possible moves on it. I attempted this code:

for c1, c2 in [(1, -1), (1, 1), (-1, -1), (-1, 1)]:
    for x, y in [range(x+c1, board_size), range(y+c2, board_size)]:
        moves.append(x, y)

But it doesn't work to find all the moves. Yet, I don't understand why. Doesn't it check all four directions?


Solution

  • Your logic is sound, but your execution is not.

    1. Half of your calculations must go from x or y to 0 (the other half go from x or y to board_size
    2. Ranges don't work from larger to smaller values with the default step, so you'll need to introduce a step of -1 to count from x or y to 0
    3. You should use zip() to create an iterable collection of tuples.

    This will work:

    right_up = zip(range(x + 1, board_size), range(y - 1, -1, -1))
    right_down = zip(range(x + 1, board_size), range(y + 1, board_size)) 
    
    left_up = zip(range(x - 1, -1, -1), range(y - 1, -1, -1))
    left_down = zip(range(x - 1, -1, -1), range(y + 1, board_size))
    
    for r in (right_up, right_down, left_up, left_down):
        for new_x, new_y in r:  # add coordinates to move list