希望你们一切都好。
最近两天我一直在尝试编写象棋引擎的代码,但是我似乎无法解决问题,我下面的代码可以正常工作,在所有2D空间中该块都是对角线的在木板上(请注意,木板是8 * 8 2D阵列),问题是我无法弄清楚如何防止对角线移动时一块跳到其他块上
这是方法:
/**
* 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;
}
感谢您的帮助!
答案 0 :(得分:1)
这里是我曾经编写的一些代码,它可以正常工作,但使用与您的体系结构不同的体系结构。无论如何,它可能会帮助您提出自己的解决方案。
else if((piece == 'B') || (piece == 'b')){
//Check if deltaX and deltaY are equal
if(Math.abs(move.getFromX()-move.getToX()) == Math.abs(move.getFromY() - move.getToY())){
//check the directions
int directionX = 1;
if(move.getToX() < move.getFromX())
directionX = -1;
int directionY = 1;
if(move.getToY() < move.getFromY())
directionY = -1;
// Check if everything is free
int y = move.getFromY();
for(int x = move.getFromX() + directionX; x != move.getToX(); x += directionX){
y += directionY;
if(position.getPieceAt(x, y) != ' ')
//A piece is in the way -> move illegal!
return false;
}
}
else{
return false;
}
}
请注意,我在2009年编写了此代码,它不是很好的代码,它的结构可能更好,并且存在样式问题。但是数学是可靠的。