Home > Software engineering >  How do I check if the move is valid or not made by Knight and Bishop
How do I check if the move is valid or not made by Knight and Bishop

Time:12-03

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

enter image description here

I have a hard time understanding this question. Can anyone tell me the correct approach for this problem?

def valid_move_or_not(piece,currentpos,nextpos):
    #Write your code here
    return True

if __name__=='__main__':
    #you can run your tests here
    print(valid_move_or_not("Knight","a1","a2"))

CodePudding user response:

It asks you to code the move rule of chess pieces. You can google if you are not familiar with chess.

As a simple example, you can check the validity of a Rook move like below

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])

CodePudding user response:

if piece == "Bishop":
    return (currentpos[0] != nextpos[0] or currentpos[1]   2 == nextpos[1])

This logic failing one of seven testcases.

  • Related