Sha256: 73f872243b97dc21add9e88cd9513f78a4866ad36018aa971670bf14a0e8bef9

Contents?: true

Size: 1.61 KB

Versions: 2

Compression:

Stored size: 1.61 KB

Contents

require_relative 'writer'

class SGF::Gametree
  include Enumerable

  SGF::Gametree::PROPERTIES.each do |human_readable_method, sgf_identity|
    define_method(human_readable_method.to_sym) do
      @root[sgf_identity] || raise(SGF::NoIdentityError, "This gametree does not have '#{human_readable_method}' available")
    end
  end

  attr_reader :root

  attr_accessor :current_node

  # Takes a SGF::Node as an argument. It will be a problem if that node isn't
  # really the first node of of a game (ie: no FF property)
  def initialize node
    raise ArgumentError, "Expected SGF::Node argument but received #{node.class}" unless node.instance_of? SGF::Node
    @root = node
    @current_node = node
  end

  # A simple way to go to the next node in the same branch of the tree
  def next_node
    @current_node = @current_node.children[0]
  end

  # Iterate through all the nodes in preorder fashion
  def each &block
    @root.each(&block)
  end

  def inspect
    "<SGF::Gametree:#{object_id}>"
  end

  def to_s
    SGF::Writer.new.stringify_tree_from @root
  end

  def slice range
    new_root = nil
    each do |node|
      if node.depth == range.begin
        new_root = node.dup
        break
      end
    end

    new_root ||= @root.dup
    new_root.depth = 0
    new_root.parent = nil
    SGF::Gametree.new new_root
  end

  private

  def method_missing method_name, *args
    human_readable_method = method_name.to_s.downcase
    sgf_identity = SGF::Gametree::PROPERTIES[human_readable_method]
    return @root[sgf_identity] || raise(SGF::NoIdentityError, "This gametree does not have '#{human_readable_method}' available")
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
SgfParser-3.0.1 lib/sgf/gametree.rb
SgfParser-3.0.0 lib/sgf/gametree.rb