【问题标题】:C++ check if there are players on the way in Chess gameC ++检查国际象棋游戏中是否有玩家在路上
【发布时间】:2018-12-15 14:45:41
【问题描述】:

我正在尝试检查是否有棋手正在下棋。 为此,我有以下变量 this->getLocX(),this->getLocY()(玩家所在的位置),x,y(玩家想去的地方)

我有一个函数 boardP->hasPiece(x, y) 如果在给定的点中有玩家,则返回我 true(1)(x ,y)

我正在为主教做这个,所以它可以并且需要在诊断中检查玩家(我已经检查过移动是否无效

这里我试过了,但是不管用,即使有玩家,玩家仍然可以移动,我可以知道,因为程序是本地主机到代表玩家的 c# 程序。

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;

【问题讨论】:

  • “这不起作用”本身并不是一个有用的问题描述。即使伴随着代码的一些随机部分。在 stackoverflow.com 上,“这不起作用”形式的所有问题都必须包含 minimal reproducible example,任何人都可以尝试自己编译和执行,以便重现问题,否则无法回答。当然,这并不意味着“发布所有代码”,因为这将无法满足minimal reproducible example 的“最低”要求。您还应该去 stackoverflow.com help center,并学习 How to Ask 问题。

标签: c++ algorithm chess


【解决方案1】:

你真的需要一个解决方案,假设位置是 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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 2016-04-04
    相关资源
    最近更新 更多