15,917,174 members
1.00/5 (1 vote)
See more:
```Complete the following function to validate the move of a given chess piece and return True (boolean) if the move is valid or False(boolean) if the move is invalid. The chessboard is given below for your reference.

Function takes 3 arguments

piece can be a "Knight" or "Bishop"

currentpos(a string) is a combination of row and column it be anything between "a1" to "h8". currentpos represents the cell on the chessboard where the piece is currently located

nextpos(a string) is also a combination of row and column and can also be between from "a1" to "h8". nextpos represents the cell to which the piece is intended to be moved

I have a hard time understanding this question. Can anyone tell me the correct approach for this problem implementing bishop and knight?```

What I have tried:

```def valid_move_or_not(piece,currentpos,nextpos):
if currentpos == nextpos:
return False
if piece == 'Rook':
return (currentpos[0] == nextpos[0]) or (currentpos[1] == nextpos[1])

if __name__=='__main__':
#you can run your tests here
print(valid_move_or_not("Knight","a1","a2"))```
Posted
Updated 30-Nov-21 19:58pm

## Solution 1

Simple: from the current location of the piece, generate every valid move: each time to create a valid position, check it against the desired position (bearing in mind that it's only valid if the destination isn't occupied by a piece of the same colour, and for a bishop if there are no pieces in the way en route). If you find it is a valid move, retun so.
If you get to the end of the "possible moves" from the current position without finding it, it's invalid.

Naveen Kollu 1-Dec-21 2:04am
@OriginalGriff Can you help write the logic for the bishop? That will be appreciated.
OriginalGriff 1-Dec-21 2:16am
Oh come on! You *know* how a bishop moves! Diagonally from current position to the edge of the board ...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Top Experts
Last 24hrsThis month
 Richard Deeming 75 OriginalGriff 50 Ralf Meier 10 Pete O'Hanlon 10 Dave Kreskowiak 10
 Pete O'Hanlon 700 OriginalGriff 458 Dave Kreskowiak 380 Richard MacCutchan 310 merano99 215

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900