Flutter国际象棋项目:主教棋子合法移动计算函数问题排查
主教(Bishop)合法移动计算的错误修正
你的主教移动逻辑存在两个核心问题:
- 初始
i=0时,计算的是棋子当前所在位置,此时会检测到自身棋子,直接触发break终止该方向的循环,导致所有方向都无法生成有效移动 - 没有跳过当前位置,错误地将原地判定为候选移动位置
修正后的代码
List<List> checkValideMoves(int row, int col, ChessPiece? piece) { List<List> candidateMoves = []; // 此处direction变量未被主教逻辑使用,可考虑移除 int direction = piece!.isWhite ? -1 : 1; switch (piece.type) { case ChessPieceType.knight: // 骑士逻辑保持不变 var knightMoves = [ [-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1] ]; for (var move in knightMoves) { var newRow = row + move[0]; var newCol = col + move[1]; if (!isInBoard(newRow, newCol)) { continue; } if (board[newRow][newCol] != null) { if (board[newRow][newCol]!.isWhite != piece.isWhite) { candidateMoves.add([newRow, newCol]); } continue; } candidateMoves.add([newRow, newCol]); } break; case ChessPieceType.bishop: var directions = [ [-1, -1], [-1, 1], [1, -1], [1, 1] ]; for (var dir in directions) { // 从1开始,跳过当前位置 var i = 1; while (true) { var newRow = row + i * dir[0]; var newCol = col + i * dir[1]; // 超出棋盘则终止该方向搜索 if (!isInBoard(newRow, newCol)) { break; } if (board[newRow][newCol] != null) { // 敌方棋子可捕获,加入列表后终止该方向 if (board[newRow][newCol]!.isWhite != piece.isWhite) { candidateMoves.add([newRow, newCol]); } // 碰到任何棋子都停止该方向延伸 break; } // 空位置加入候选列表 candidateMoves.add([newRow, newCol]); i++; } } break; } return candidateMoves; }
关键修正说明
- 将
i的初始值从0改为1,直接跳过棋子当前位置,避免检测到自身导致循环提前终止 - 重命名变量
direction为dir,避免和上方冗余变量重名,提升代码可读性 - 优化逻辑判断,确保每个方向的搜索会持续到碰到棋子或超出棋盘为止
内容的提问来源于stack exchange,提问作者Mouaad Ouajib
相关产品推荐
相关产品推荐

