- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
关闭。这个问题需要更多focused .它目前不接受答案。
想改善这个问题吗?更新问题,使其仅关注一个问题 editing this post .
2年前关闭。
Improve this question
我试图理解为每个棋子确定有效移动背后的算法。我遇到的具体问题是确定一块何时无法移动通过某个点,因为它被自己颜色的一块挡住了,或者能够占据相反颜色的一块但无法移动通过该点。
我对每件作品的简单算法是:
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
界面只是为了表明这一点。你应该有一个董事会状态以某种方式公开这些信息。
关于chess - 如何确定有效的棋步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54972474/
我是一名优秀的程序员,十分优秀!