首页 > 解决方案 > 无法为可能的棋子移动构建树

问题描述

我正在构建一个国际象棋游戏,它采用开始坐标和结束坐标并使用 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

标签: rubybinarybinary-treechess

解决方案


推荐阅读