【发布时间】:2020-08-07 15:47:48
【问题描述】:
希望你们一切都好。
过去两天我一直在尝试编写一个国际象棋引擎,我遇到了我似乎无法解决的问题,我在下面的这段代码运行良好,该棋子在所有有限的 2D 空间中对角线在棋盘中(注意棋盘是一个 8*8 的二维数组),问题是我不知道如何防止一个棋子在对角线时跳过其他棋子
方法如下:
/**
* y = abs(x)
* y = -abs(x)
* programming these 2 functions will let the piece go diagonally in all directions.
*@param pieceX: current X coordinates of the piece
* @param pieceY : current Y Coordinates of the piece
* @param board: Board instance to get the locations of all the pieces
* @return legal movements
*/
protected int[][] diagonalMove(int pieceX, int pieceY, Board board)
{
ArrayList<Integer> legalXMovements = new ArrayList<>();
ArrayList<Integer> legalYMovements = new ArrayList<>();
//cartesian plane with a size of 8*8.
for (int x = 7; x > -8; x--)
{
for (int y = 7; y > -8; y--)
{
//function 1: y = abs(x) and y > 0: Math.abs(x) == Math.abs(y)
//function 2: y = -abs(x) : y == -Math.abs(x)
if (Math.abs(x) == Math.abs(y) || y == -Math.abs(x))
{
//prevent OutOfBounds at any case.
if (pieceX + x >= 0 && pieceX + x < 8)
{
if (pieceY + y >= 0 && pieceY + y < 8)
{
//make sure that the piece doesn't eat his allies
//if Tile is empty.
if (board.getTile(pieceX + x, pieceY + y).checkIsEmpty())
{
legalXMovements.add(pieceX + x);
legalYMovements.add(pieceY + y);
}
else
{
//if enemy.
if (color != board.getTile(pieceX + x, pieceY + y).getPiece().getColor())
{
legalXMovements.add(pieceX + x);
legalYMovements.add(pieceY + y);
}
}
}
}
}
}
}
//Chess, preventing a piece from jumping over pieces when going diagonally
int[][] finalLegalMovements = new int[legalXMovements.size()][2];
for (int x = 0; x < legalXMovements.size(); x++)
{
finalLegalMovements[x][0] = legalXMovements.get(x);
finalLegalMovements[x][1] = legalYMovements.get(x);
}
return finalLegalMovements;
}
感谢您的帮助!
【问题讨论】:
-
您必须检查路径中的每个图块是否为空。就这么简单。
-
感谢您的回复!,我知道我需要检查每个图块,但是,问题是如何在上面的代码中实现解决方案?再次感谢
-
构建一个从起始空间到目标空间的循环,忽略这两个,并检查所有空间是否为空。但是我会以不同的方式对整个事情进行编码(事实上,我以前也这样做过)。