lib/sgf/parser/tree.rb in SgfParser-0.9.0 vs lib/sgf/parser/tree.rb in SgfParser-0.9.1

- old
+ new

@@ -1,21 +1,12 @@ module SgfParser - # This is a placeholder for the root of the gametree(s). It's an abstraction, - # but it allows an easy way to save, iterate over, and compare other trees. - # Accessors: tree.root class Tree include Enumerable attr_accessor :root - # Create a new tree. Can also be used to load a tree from either a file or - # a string. Raises an error if both are provided. - # options: \n - # :filename => filename \n - # !!! OR !!! \n - # :string => string \n def initialize args={} @root = Node.new @sgf = "" raise ArgumentError, "Both file and string provided" if args[:filename] && args[:string] if args[:filename] @@ -25,14 +16,13 @@ end parse unless @sgf.empty? end - # Iterates over the tree, node by node, in preorder fashion. - # Does not support other types of iteration, but may in the future. - # tree.each { |node| puts "I am node. Hear me #{node.properties} !"} def each order=:preorder, &block + # I know, I know. SGF is only preorder. Well, it's implemented, ain't it? + # Stop complaining. case order when :preorder preorder @root, &block end end @@ -49,14 +39,12 @@ # Saves the tree as an SGF file. raises an error if a filename is not given. # tree.save :filename => file_name def save args={} raise ArgumentError, "No file name provided" if args[:filename].nil? - # SGF files are trees stored in pre-order traversal. @savable_sgf = "(" @root.children.each { |child| write_node child } - # write_node @root @savable_sgf << ")" File.open(args[:filename], 'w') { |f| f << @savable_sgf } end @@ -65,15 +53,16 @@ # Adds a stringified node to the variable @savable_sgf. def write_node node=@root @savable_sgf << ";" unless node.properties.empty? properties = "" - node.properties.each do |k, v| - v_escaped = v.gsub("]", "\\]") - properties += "#{k.to_s}[#{v_escaped}]" + node.properties.each do |identity, property| + new_property = property[1...-1] + new_property.gsub!("]", "\\]") if identity == "C" + properties += "#{identity.to_s}[#{new_property}]" end - @savable_sgf << "#{properties}" + @savable_sgf << properties end case node.children.size when 0 @savable_sgf << ")" @@ -102,16 +91,16 @@ if yield node then node.each_child do |child| preorder(child, &block) end end - end # preorder + end def method_missing method_name, *args output = @root.children[0].properties[method_name] super(method_name, args) if output.nil? output - end # method_missing + end end end