ruby - 无法为可能的棋子移动构建树
问题描述
我正在构建一个国际象棋游戏,它采用开始坐标和结束坐标并使用 BFS 构建一棵树。我有两种方法可以找到可能的动作。
#find_possible_positions_from_origin 方法记录棋子最终可能出现的每个可能的方格(例如,车可以结束,北最多 7 个空格,南最多 7 个空格,左最多 7 个空格,右最多 7 个空格。如果结束坐标最终成为来自#find_possible_positions_from_origin 的这些坐标之一,则它直接在其下运行另一个方法#find_possible_incremental_moves,该方法一次仅遍历这些空间中的每一个空间 - 原因是它可以检查是否每个空间都是空的,而不仅仅是跳过另一块。它在每个空间上创建一个“单元”,以便它可以记录到目的地的路径。每个单元都会记住从起始坐标到它的路径。
我无法让第二个变量 #find_possible_incremental_moves 在 #find_possible_positions_from_origin 方法下顺利运行。应该在棋盘的目标坐标处创建一个“单元格”,这样我就可以获得通往它的路径,并检查路径是否被任何其他部分占用。但是当我调用目标坐标时,我得到nil。
有人纠正了我之前的一个问题,即我不应该发布我的整个生产代码,这是有道理的,所以我包含了我遇到问题的单个#build_tree,我希望这就足够了。
这是我在本节中的代码。
def build_tree
@start_coor = convert_input_to_coor(@start)
@destination_coor = convert_input_to_coor(@destination)
@selected_piece = @gameboard[@start_coor[0]][@start_coor[1]]
starting_cell = Cell.new(@start_coor[0], @start_coor[1])
queue = []
queue.unshift(starting_cell)
until queue.empty?
current = queue.shift
possible_positions = find_possible_positions_from_origin([current.x, current.y])
next if possible_positions.nil?
if possible_positions.include?(@destination_coor)
@selected_piece.possible_positions = find_possible_incremental_moves(([current.x, current.y]))
@selected_piece.possible_positions.each do |move|
next unless !@dummyboard.board[move[0]][move[1]].instance_of? Cell
linked_cell = Cell.new(move[0], move[1])
current.edges << linked_cell
linked_cell.path = current.path + linked_cell.path
@dummyboard.board[move[0]][move[1]] = linked_cell
queue.push(linked_cell)
end
end
end
starting_cell
end
解决方案
推荐阅读
- azure - 用于重构模板值的 ARM 模板链接
- python-3.x - python中用户定义的基类
- swift - 使用 SwiftUI Navigation View 和 Sorted FetchRequest 在详细视图中重新排列列表项时出现问题
- solr - Solr Suggester 需要很长时间才能提供响应
- flutter - 如何在颤动中解析格式为“MM/dd/YY”的日期时间
- html - 引导程序 - 同一行
和按钮 - rust - Rust:如何将 BytesMut 转换/读取为文件?
- rust - 如何使用 Substrate API Client 写入 Substrate 的存储?
- c++ - 为什么要在这里计算余数?
- laravel - 在 Laravel 中使用 imagejpeg()