You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#棋盘车合法移动遍历:循环逻辑修正技术问询

修复国际象棋车的合法移动位置标记代码

你当前的代码逻辑存在问题:每个循环里都只修改了与当前单元格相邻的单个位置,循环Size次也只是重复设置同一个格子的LegalNextMove为true,并没有遍历同一行或列的所有格子,自然无法标记所有合法移动位置。

基础版重构代码(不考虑棋子阻挡)

这段代码会标记当前车所在行和列的所有棋盘范围内的位置:

// 标记同一列上方的所有合法位置
for (int row = currentCell.RowNumber - 1; row >= 0; row--)
{
    theGrid[row, currentCell.ColumnNumber].LegalNextMove = true;
}

// 标记同一列下方的所有合法位置
for (int row = currentCell.RowNumber + 1; row < Size; row++)
{
    theGrid[row, currentCell.ColumnNumber].LegalNextMove = true;
}

// 标记同一行左侧的所有合法位置
for (int col = currentCell.ColumnNumber - 1; col >= 0; col--)
{
    theGrid[currentCell.RowNumber, col].LegalNextMove = true;
}

// 标记同一行右侧的所有合法位置
for (int col = currentCell.ColumnNumber + 1; col < Size; col++)
{
    theGrid[currentCell.RowNumber, col].LegalNextMove = true;
}

逻辑说明:

  • 每个循环从当前单元格的相邻位置出发,沿着对应方向遍历,直到触及棋盘边界(行/列号小于0或大于等于Size)。
  • 这样就能一次性覆盖同一行或列的所有合法移动位置,而非重复修改同一个相邻格子。

进阶版重构代码(考虑棋子阻挡规则)

国际象棋中车不能穿过己方棋子,遇到敌方棋子时可以吃掉但无法继续前进,加入阻挡判断的代码如下:

// 向上遍历(遇己方棋子停止,遇敌方棋子标记后停止)
for (int row = currentCell.RowNumber - 1; row >= 0; row--)
{
    if (theGrid[row, currentCell.ColumnNumber].HasOwnPiece)
        break;
    theGrid[row, currentCell.ColumnNumber].LegalNextMove = true;
    if (theGrid[row, currentCell.ColumnNumber].HasEnemyPiece)
        break;
}

// 向下遍历
for (int row = currentCell.RowNumber + 1; row < Size; row++)
{
    if (theGrid[row, currentCell.ColumnNumber].HasOwnPiece)
        break;
    theGrid[row, currentCell.ColumnNumber].LegalNextMove = true;
    if (theGrid[row, currentCell.ColumnNumber].HasEnemyPiece)
        break;
}

// 向左遍历
for (int col = currentCell.ColumnNumber - 1; col >= 0; col--)
{
    if (theGrid[currentCell.RowNumber, col].HasOwnPiece)
        break;
    theGrid[currentCell.RowNumber, col].LegalNextMove = true;
    if (theGrid[currentCell.RowNumber, col].HasEnemyPiece)
        break;
}

// 向右遍历
for (int col = currentCell.ColumnNumber + 1; col < Size; col++)
{
    if (theGrid[currentCell.RowNumber, col].HasOwnPiece)
        break;
    theGrid[currentCell.RowNumber, col].LegalNextMove = true;
    if (theGrid[currentCell.RowNumber, col].HasEnemyPiece)
        break;
}

注意:这里假设你的棋盘单元格对象包含HasOwnPiece(是否有己方棋子)和HasEnemyPiece(是否有敌方棋子)两个布尔属性,可根据实际代码结构调整判断条件。

内容的提问来源于stack exchange,提问作者Liza Sarah G

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 07:55:20