module Gamefic::Node
Parent/child relationships for objects.
Attributes
The object’s parent.
@return [Node, nil]
Public Instance Methods
Source
# File lib/gamefic/node.rb, line 88 def accessible children end
Get an array of children that are accessible to external entities.
A child is considered accessible if external entities can interact with it. For Example, an author can designate that the contents of a bowl are accessible, while the contents of a locked safe are not. All of an entity’s children are accessible by default. Authors should override this method if they need custom behavior.
@return [Array<Entity>]
Source
# File lib/gamefic/node.rb, line 102 def adjacent?(other) other.parent == parent end
True if this node and the other node have the same parent.
@param other [Node]
Source
# File lib/gamefic/node.rb, line 21 def children child_set.to_a.freeze end
An array of the object’s children.
@return [Array<Node>]
Source
# File lib/gamefic/node.rb, line 28 def flatten children.flat_map { |child| [child] + child.flatten } end
Get a flat array of all descendants.
@return [Array<Node>]
Source
# File lib/gamefic/node.rb, line 95 def include?(other) other.parent == self end
True if this node is the other’s parent.
@param other [Node]
Source
# File lib/gamefic/node.rb, line 35 def parent=(node) return if node == parent validate_parent node parent&.rem_child self @parent = node @relation = nil parent&.add_child self end
Set the object’s parent.
@param node [Node, nil]
Source
# File lib/gamefic/node.rb, line 73 def put(parent, relation = nil) self.parent = parent @relation = relation end
Source
# File lib/gamefic/node.rb, line 52 def relation @relation ||= (parent ? :in : nil) end
The node’s relation to its parent.
The inherently supported relations are ‘:in` and `:on`, but authors are free to define their own.
@return [Symbol, nil]
Source
# File lib/gamefic/node.rb, line 57 def relation=(symbol) raise NodeError, "Invalid relation #{symbol.inspect} on #{inspect} without parent" unless parent || !symbol @relation = symbol end
@param symbol [Symbol, nil]
Source
# File lib/gamefic/node.rb, line 68 def take *children, relation: nil children.flatten.each { |child| child.put self, relation } children end
Add children to the node. Return all the node’s children.
@param children [Array<Node, Array
<Node>>] @param relation [Symbol, nil] @return [Array<Node>]
Protected Instance Methods
Source
# File lib/gamefic/node.rb, line 108 def add_child(node) child_set.add node end
Source
# File lib/gamefic/node.rb, line 112 def rem_child(node) child_set.delete node end
Private Instance Methods
Source
# File lib/gamefic/node.rb, line 122 def validate_parent(node) raise NodeError, "Parent of #{inspect} must be a Node, received #{node.inspect}" unless node.is_a?(Node) || node.nil? raise NodeError, "#{inspect} cannot be its own parent" if node == self raise NodeError, "#{inspect} cannot be a child of descendant #{node.inspect}" if flatten.include?(node) end