Click here to Skip to main content
15,917,174 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
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
Updated 30-Nov-21 19:58pm

1 solution

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.
Share this answer
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)

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