我试图理解为每个棋子确定有效移动背后的算法。我所遇到的具体问题是确定一件作品何时不能移动超过某一点,因为它被一块自己的颜色挡住,或者能够拍摄一段相反的颜色但是不能移过那一点。
我对每件作品的简单算法是:
有效King移动,如果片段从(X1,Y1)移动到(X2,Y2),则当且仅当| X2-X1 | <= 1且| Y2-Y1 | <= 1时,移动才有效。
有效的Bishop移动,如果片段从(X1,Y1)移动到(X2,Y2),则当且仅当| X2-X1 | = | Y2-Y1 |时,移动才有效。
有效的车移动,如果棋子从(X1,Y1)移动到(X2,Y2),当且仅当X2 = X1或Y2 = Y1时,移动才有效。
有效的女王移动,女王的移动是有效的,如果它是一个有效的主教或车移动。
有效骑士移动,如果棋子从(X1,Y1)移动到(X2,Y2),当且仅当(| X2-X1 | = 1且| Y2-Y1 | = 2)或(| X2)时,移动才有效-X1 | = 2且| Y2-Y1 | = 1)。
有效的Pawn移动,如果棋子从(X1,Y1)移动到(X2,Y2),当且仅当X2 = X1且Y2-Y1 = 1(仅适用于白色棋子)时,移动才有效。
任何意见,将不胜感激。
你需要考虑董事会的状态。我认为这样做的常用方法是检查路径上的每个单元格是否为空。
public enum PieceColor { Black, White }
public interface IBoard
{
bool IsEmpty(int x, int y);
PieceColor GetPieceColor(int x, int y);
}
IBoard board;
bool BishopCanMove(PieceColor bishopColor, int fromX, int fromY, int toX, int toY)
{
int pathLength = Mathf.Abs(toX - fromX);
if (pathLength != Mathf.Abs(toY - fromY)) return false; // Not diagonal
// Also validate if the coordinates are in the 0-7 range
// Check all cells before the target
for (int i = 1; i < pathLength; i++)
{
int x = fromX + i;
int y = fromY + i;
if(board.IsEmpty(x, y)) continue; // No obstacles here: keep going
else return false; // Obstacle found before reaching target: the move is invalid
}
// Check target cell
if (board.IsEmpty(toX, toY)) return true; // No piece: move is valid
// There's a piece here: the move is valid only if we can capture
return board.GetPieceColor(toX, toY) == bishopColor;
}
IBoard
界面只是为了表明这一点。您应该有一个董事会状态以某种方式暴露这些信息。