How to find a valid knight move in Python?

720 Views Asked by At

Chess knight can move to a square that is two squares away horizontally and one square vertically, or two squares vertically and one square horizontally. Given two different squares of the chessboard, determine whether a knight can go from the first square to the second one in a single move. The input is four characters: letters from a to h and numbers from 1 to 8, each specifying the column and the row number. First two are for the first square, and the last two for the second square. The program should print True if a knight can go from the first square to the second one in one move. Or print False otherwise.

Example 1 Can the knight go from d4 to c6? Yes! input d 4 c 6 output True Example 2 input d 4 e 2 output True Example 3 There’s no move from f6 to g5 for the chess knight

input f 6 g 5 output False

1

There are 1 best solutions below

2
Raphael Frei On BEST ANSWER

What have you tried so far?

You can make calculations between the current position and the next one... Considering that knight can only move [1, 2] or [2, 1].

Based on that I recommend you to work with values intead of letters on the board.

def IsMovePossible(player, currentPos, nextPos):

    # You need to replace the currentPos and nextpos for the way you're working on the tiles
    xDif = abs(currentPos[0] - nextPos[0])
    yDif = abs(currentPos[1] - nextPos[1])

    if player == "Knight":
        return (xDif == 2 and yDif == 1) or (xDif == 1 and yDif == 2)

# Considering the chess tiles as array
print(IsMovePossible("Knight", currentPos, nextPos))