Legend of the Gold Box... A game written for the LOWREZJAM 2018 game jam
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.0KB

  1. NODETYPE_NODE = "NODE"
  2. class NodeError(Exception):
  3. pass
  4. class Node:
  5. def __init__(self, name="Node", parent=None):
  6. self._children = []
  7. self.name = name
  8. @property
  9. def parent(self):
  10. return self._parent
  11. @parent.setter
  12. def parent(self, value):
  13. try:
  14. self.parent_to_node(value)
  15. except NodeError as e:
  16. raise e
  17. @property
  18. def name(self):
  19. return self._name
  20. @name.setter
  21. def name(self, value):
  22. self._name = value
  23. def parent_to_node(self, parent, allow_reparenting=False):
  24. if not isinstance(value, Node):
  25. raise NodeError("Node may only parent to another Node instance.")
  26. if self._parent is None:
  27. self._parent = value
  28. elif self._parent != value:
  29. if allow_Reparenting == False:
  30. raise NodeError("Node already assigned a parent Node.")
  31. if self._parent.remove_node(self) != self:
  32. raise NodeError("Failed to remove self from current parent.")
  33. parent.attach_node(self)
  34. def attach_node(self, node, reparent=False, index=-1):
  35. if node.parent is not None:
  36. if node.parent == self:
  37. return # Nothing to do. Given node already parented to this node.
  38. if reparent = False:
  39. raise NodeError("Node already parented.")
  40. if node.parent.remove_node(node) != node:
  41. raise NodeError("Failed to remove given node from it's current parent.")
  42. node._parent = self
  43. if index < 0 or index >= len(self._children):
  44. self._children.append(node)
  45. else:
  46. self._children.insert(index, node)
  47. def remove_node(self, node):
  48. if node.parent != self:
  49. if node.parent == None:
  50. raise NodeError("Cannot remove an unparented node.")
  51. return node.parent.remove_node(node)
  52. if node in self._children:
  53. self._children.remove(node)
  54. node._parent = None
  55. return node