如何限制棋盘中的棋子♟️运动?

问题描述

请不要害怕TypeScript。只是带有类型的js。

我正在下棋游戏,并且已经达到验证动作的作用。我的Tile类如下:

class Tile {
  x: number;
  y: number;
  tile: Element;
  team: string;
  piece: string;
  constructor(i: number,j: number,tile: Element,team: string) {
    this.x = i;
    this.y = j;
    this.tile = tile;
    this.piece = "none";
    this.team = team;
  }
}

如您所见,我可以控制2D数组中任何给定图块的x和y位置。

我有以下函数,该函数返回一个数组,该数组包含每个零件在其y和x坐标中进行的总运动。它接收2个Tile对象作为参数。第一个是初始点击,最后一个是最终点击(用户要在其中移动作品)。

function getVectorComponents(start: Tile,end: Tile) {
  return [Math.abs(start.x - end.x),Math.abs(start.y - end.y)];
  //getVectorComponents(start_position,end_position)[0] returns the movement in the y axis
  //getVectorComponents(start_position,end_position)[1] returns the movement in the x axis
}

我设法通过以下方法验证了车ok的运动:

  if (
    (getVectorComponents(start,end)[0] <= 7 &&
      getVectorComponents(start,end)[1] == 0) ||
    (getVectorComponents(start,end)[0] == 0 &&
      getVectorComponents(start,end)[1] <= 7)
  ) {
    //This is an available move for the rook
  }

当我尝试验证棋子♟️的运动时,我的问题来了。由于我的getVectorComponents()返回了运动的绝对值,所以我不知道运动的方向。

对于典当,我具有以下验证算法:

  if (start.x == 6 || start.x == 1) {
    //Check if the pawn hasn't moved,if not: it has 2 available moves
    if (
      getVectorComponents(start,end)[0] <= 2 &&
      getVectorComponents(start,end)[1] == 0
    ) {
      //This is an available move for the pawn
    }
  } else {
    //The pawn only has 1 move available
    if (
      getVectorComponents(start,end)[0] <= 1 &&
      getVectorComponents(start,end)[1] == 0
    ) {
      //This is an available move for the pawn
    }
  }

此算法导致以下问题:

Pawn available moves

在国际象棋游戏中,典当不能向后移动。但是,我使用的算法将该移动返回为有效。

是否有一种很好的方法可以限制棋子的移动,使其只能向前移动?这需要考虑白人和黑人团队。

更多信息:a8 = [0][0] h1 = [7][7]

解决方法

我会在检查中建议有效的动作,如果典当是一种颜色,请检查start.x必须大于end.x,反之亦然。即 白色只能在end.x较大时移动,黑色只能在start.x较大时移动。好像您将注意力集中在矢量分量上。您还可以使用原始值的简单比较!

,

如何?

[90. 45. 30.]

这样可以保留方向,以后可以在移动棋子时检查方向是否为负。如果为负,则表示此举无效。