Sha256: 407af812a50c876056ca9139395ccc28a528e65fe2c41f884743b45402857a0c

Contents?: true

Size: 1.55 KB

Versions: 10

Compression:

Stored size: 1.55 KB

Contents

#   Pathfinders provide the shortest route between two locations. The
#   destination needs to be accessible from the origin through portals. Note
#   that Pathfinders do not take into account portals that characters should
#   not be able to traverse, such as locked doors.
class Pathfinder
  # @return [Room]
  attr_reader :origin

  # @return [Room]
  attr_reader :destination

  def initialize origin, destination
    @origin = origin
    @destination = destination
    @path = nil
    @paths = [[@origin]]
    @visited = []
    if @origin == @destination
      @path = []
    else
      embark while @path.nil? && @paths.length > 0
    end
  end

  # @return [Array<Room>]
  def path
    # @path is nil if the path is invalid, but #path should return an empty
    # array instead.
    @path || []
  end

  # @return [Boolean]
  def valid?
    path.length > 0 || origin == destination
  end

  private

  def embark
    new_paths = []
    @paths.each { |path|
      last = path.last
      portals = last.children.that_are(Portal)
      portals.each { |portal|
        new_path = path.clone
        if !@visited.include?(portal.destination)
          new_path.push portal.destination
          @visited.push portal.destination
          if portal.destination == @destination
            @path = new_path
            @path.shift
            break
          end
          new_paths.push new_path
        end
      }
      path.push nil
    }
    @paths += new_paths
    @paths.delete_if{|path| path.last.nil?}
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
gamefic-standard-3.2.4 lib/gamefic-standard/pathfinder.rb
gamefic-standard-3.2.3 lib/gamefic-standard/pathfinder.rb
gamefic-standard-3.2.2 lib/gamefic-standard/pathfinder.rb
gamefic-standard-3.2.1 lib/gamefic-standard/pathfinder.rb
gamefic-standard-3.2.0 lib/gamefic-standard/pathfinder.rb
gamefic-standard-3.1.0 lib/gamefic-standard/pathfinder.rb
gamefic-standard-3.0.0 lib/gamefic-standard/pathfinder.rb
gamefic-standard-2.4.0 lib/gamefic-standard/pathfinder.rb
gamefic-standard-2.3.1 lib/gamefic-standard/pathfinder.rb
gamefic-standard-2.3.0 lib/gamefic-standard/pathfinder.rb