如何确定有效的国际象棋走法?

How to determine valid chess moves?

我正在尝试了解确定每个棋子的有效移动背后的算法。我遇到的具体问题是确定一块何时不能移动超过某个点,因为它被一块自己颜色的块阻挡,或者能够采用相反颜色的一块但不能移动超过该点。

我对每件作品的简单算法是:

Valid King move, if the piece moves from (X1, Y1) to (X2, Y2), the move is valid if and only if |X2-X1|<=1 and |Y2-Y1|<=1.

Valid Bishop move, if the piece moves from (X1, Y1) to (X2, Y2), the move is valid if and only if |X2-X1|=|Y2-Y1|.

Valid Rook move, if the piece moves from (X1, Y1) to (X2, Y2), the move is valid if and only if X2=X1 or Y2=Y1.

Valid Queen move, a queen's move is valid if it is either a valid bishop or rook move.

Valid Knight move, if the piece moves from (X1, Y1) to (X2, Y2), the move is valid if and only if (|X2-X1|=1 and |Y2-Y1|=2) or (|X2-X1|=2 and |Y2-Y1|=1).

Valid Pawn move, if the piece moves from (X1, Y1) to (X2, Y2), the move is valid if and only if X2=X1 and Y2-Y1=1 (only for a white pawn).

如有任何建议,我们将不胜感激。

为此,您需要考虑棋盘状态。 我认为常见的做法是检查路径上的每个单元格是否为空。

    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 界面只是为了说明这一点。你应该有一个董事会状态以某种方式公开这些信息。