如何确定有效的棋步?

Act*_*nor 5 chess

我试图理解为每个棋子确定有效移动背后的算法。我遇到的具体问题是确定一块何时无法移动通过某个点,因为它被自己颜色的一块挡住了,或者能够占据相反颜色的一块但无法移动通过该点。

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

有效王棋,如果棋子从(X1,Y1)移动到(X2,Y2),当且仅当|X2-X1|<=1且|Y2-Y1|<=1时该棋步有效。

有效的象棋移动,如果棋子从 (X1, Y1) 移动到 (X2, Y2),则移动有效当且仅当 |X2-X1|=|Y2-Y1|。

有效的车子移动,如果棋子从(X1,Y1)移动到(X2,Y2),则当且仅当 X2=X1 或 Y2=Y1 时移动有效。

有效的后移动,如果后移动是有效的象或车移动,则该移动是有效的。

有效的骑士移动,如果棋子从 (X1, Y1) 移动到 (X2, Y2),则移动有效当且仅当 (|X2-X1|=1 and |Y2-Y1|=2) 或 (|X2 -X1|=2 和 |Y2-Y1|=1)。

有效的Pawn移动,如果棋子从(X1,Y1)移动到(X2,Y2),则当且仅当X2=X1且Y2-Y1=1时移动有效(仅适用于白色Pawn)。

任何意见,将不胜感激。

dog*_*ano 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;
    }
Run Code Online (Sandbox Code Playgroud)

界面IBoard只是为了说明这一点。您应该有一个董事会以某种方式公开这些信息。