Search code examples
c++algorithmchess

C++ check if there are players on the way in Chess game


i am trying to check if there is a player on the way in the game of chess. to do it i have the following variables this->getLocX(),this->getLocY()(Where the player was), x,y(where the player wants to go)

and I have a function boardP->hasPiece(x, y) that returns me true(1) if there is a player in the points that given(x,y)

I am currectly doing this for the Bishop, So it can and need to check for players in diagnoaly (I already checked if the move is vaid

Here what i triedand it doesnt work, the player can still move even if there is a player, i can know that because the program is localHost to c# program that represent the players.

C++:

if (abs(x - this->getLocX()) == abs(y - this->getLocY())) // THIS WORKS GOOD
{ 
    cout << "\n" << abs(x - this->getLocX()) << abs(y - this->getLocY()) << x << y;
    for (int i = 0; i < abs(x - this->getLocX()); i++)
    {
        cout << "\n" << boardP->hasPiece(this->getLocX() - 1, i-1) << "\n" << boardP->hasPiece(i, y) << "\n" << x << "\n" << y << "\n" << i << "\n";
        if (boardP->hasPiece(this->getLocX() - 1, i-1)) // THIS DOESNT WORK
            return 0; // THERE ARE PLAYERS IN THE WAY
    }
    return 2; // THERE ARE NO PLAYERS IN THE WAY
}
return 0;

Solution

  • And you really need a solution, supposing positions are int :

    if (abs(x - this->getLocX()) == abs(y - this->getLocY()))
    { 
      int cx = this->getLocX();
      int cy = this->getLocY();
      int dx = (x > cx) ? 1 : -1;
      int dy = (y > cy) ? 1 : -1;
    
      while (cx != x)
      {
        cx += dx;
        cy += dy;
        if (boardP->hasPiece(cx, cy))
          return true; // THERE ARE PLAYERS IN THE WAY
      }
      return false; // THERE ARE NO PLAYERS IN THE WAY
    }