-7

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;
TheGameZ
  • 1
  • 1
  • 4
    "This doesn't work" is not a useful problem description by itself. Even if accompanying by some random part of your code. On stackoverflow.com, all questions of the form "this doesn't work" must include a [mcve] that anyone can try to compile and execute themselves, in order to reproduce the issue, otherwise it cannot be answered. This doesn't mean "post all of your code", of course, because this would fail to meet the "minimal" requirement of a [mcve]. You should also go to stackoverflow.com [help], and learn [ask] questions. – Sam Varshavchik Dec 15 '18 at 14:48

1 Answers1

0

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
}
bruno
  • 32,421
  • 7
  • 25
  • 37