Home > other >  Diagonal bishop moves on chess board with python
Diagonal bishop moves on chess board with python

Time:10-20

I have the following problem

In chess, the bishop moves diagonally, any number of squares. Given two different squares of the chessboard, determine whether a bishop can go from the first to the second in one move.

The program receives as input four numbers from 1 to 8, specifying the column and row numbers of the starting square and the column and row numbers of the ending square. The program should output YES if a Bishop can go from the first square to the second in one move, or NO otherwise.

For example:

Input: 2 3 5 6

Output:

YES

It is assumed that the cells are numbered from left to right and from bottom to top, i.e., the bottom left cell has column number 1 and row number 1 while the bottom-right cell has column number 8 and row number 1.

How far did I get?

I have managed to get to check if the bishop moved diagonally, but it can move any diagonal, so it is not correct. Can someone give me some hints?

my code


initial_coord_x=int (input('enter the initial x'))
initial_coord_y=int (input('enter the initial y'))
final_coord_x=int (input('enter the final x'))
final_coord_y=int (input('enter the final y'))
if final_coord_x<=8 and final_coord_y<=8:
  if final_coord_x < initial_coord_x and final_coord_y > initial_coord_y:
    print ('you moved legally')
  elif final_coord_x < initial_coord_x and final_coord_y < initial_coord_y:
    print ('you moved legally')
  elif final_coord_x > initial_coord_x and final_coord_y > initial_coord_y:
    print ('you moved legally')
  elif final_coord_x > initial_coord_x and final_coord_y < initial_coord_y:
    print ('you moved legally')
  else:
    print ('no!')


else:
  print ('illegal move, you moved outside the chessboard')

CodePudding user response:

To check the possibility of bishop moving (at existing cells) it is enough to check whether the absolute value of horizontal displacement is equal to the absolute value of vertical displacement (so both positions lie in the same diagonal)

dx = abs(final_coord_x - initial_coord_x)
dy = abs(final_coord_y - initial_coord_y)
if (dx == dy) and (dx > 0):
     legal move 
  • Related