chess - 如何确定有效的国际象棋走法?
问题描述
我试图了解确定每个棋子的有效移动背后的算法。我遇到的具体问题是确定一块不能移动超过某个点的时间,因为它被自己颜色的一块挡住了,或者能够拿一块相反颜色的但不能移动过去。
我对每件作品的简单算法是:
有效的王棋步,如果棋子从 (X1, Y1) 移动到 (X2, Y2),当且仅当 |X2-X1|<=1 且 |Y2-Y1|<=1 时,该步才有效。
有效的主教移动,如果棋子从 (X1, Y1) 移动到 (X2, Y2),则移动有效当且仅当 |X2-X1|=|Y2-Y1|。
有效的 Rook 移动,如果棋子从 (X1, Y1) 移动到 (X2, Y2),当且仅当 X2=X1 或 Y2=Y1 时移动有效。
有效的皇后移动,如果皇后的移动是有效的主教或车移动,则它是有效的。
有效的骑士移动,如果棋子从 (X1, Y1) 移动到 (X2, Y2),当且仅当 (|X2-X1|=1 和 |Y2-Y1|=2) 或 (|X2) 时,该移动才有效-X1|=2 和 |Y2-Y1|=1)。
有效的典当移动,如果棋子从 (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
界面只是为了说明这一点。您应该有一个以某种方式公开这些信息的董事会状态。
推荐阅读
- c# - 如何卸载特定版本的 NuGet 包?
- c++builder - 检查 AnsiString 末尾的字符(如果找到),删除它
- html - 制作相同的长度并出现在列中
- java - hdfs namenode 和 datanode 未根据 dfs.replication 值启动
- laravel - laravel 没有 index.php 的所有 url 404
- javascript - 使用 javascript 从桌面播放音频
- php - 带有弹性搜索的 Laravel scout - 响应缓慢
- php - Yii2 Kartik 日期范围选择器。
- validation - 自动完成与地理编码器 API - 不同的结果
- python - 带有自定义分隔符的 Python readline