Reputation: 19
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?
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"))
Upvotes: 0
Views: 2209
Reputation: 11
Calculate the displacement in the X and Y axes. You'll find the pattern.
def valid_move_or_not(piece, currentpos, nextpos):
coord = lambda x: (ord(x[0]) - ord('a'), int(x[1]))
xdiff = abs(coord(currentpos)[0] - coord(nextpos)[0])
ydiff = abs(coord(currentpos)[1] - coord(nextpos)[1])
if piece == "Bishop":
return xdiff == ydiff
elif piece == "Knight":
return xdiff == 2 and ydiff == 1 or xdiff == 1 and ydiff == 2
Upvotes: 1
Reputation: 7351
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])
Upvotes: 0