I am doing a chess project in C++. I am trying to check for a valid knight move in a 2D array.
I've got the old position of the player this->getLocX(),this->getLocY()
variables (where the player was) and I have x,y
(this is where the player wants to move his knight into).
How can you check validity in the best way? Here's my solution but I want to know if theres a better way.
if (x == this->getLocX() + 1 && y == this->getLocY() + 2 || x == this->getLocX() - 1 && y == this->getLocY() + 2 || y == this->getLocY() + 1 && x == this->getLocX() + 2 || y == this->getLocY() + 1 && x == this->getLocX() - 2 || x == this->getLocX() - 1 && y == this->getLocY() + 2 || x == this->getLocX() + 1 && y == this->getLocY() - 2 || y == this->getLocY() - 1 && x == this->getLocX() - 2 || y == this->getLocY() - 1 && x == this->getLocX() + 2 || x == this->getLocX() - 1 && y == this->getLocY() - 2)
{
//Move is vaid
}
My try:
abs((X0 - X1) * (Y0 - Y1)) == 2
For efficiency, the absolute value can be computed branchless.