-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.go
More file actions
118 lines (100 loc) · 2.14 KB
/
node.go
File metadata and controls
118 lines (100 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package engine
import (
"slices"
"github.com/google/uuid"
"github.com/hajimehoshi/ebiten/v2"
)
// Node is the interface all nodes, i.e., objects in the game
// must implement.
type Node interface {
Name() string
UUID() uuid.UUID
Update() error
Draw(screen *ebiten.Image)
SetParent(Node)
GetParent() Node
AddChild(Node)
GetChildren() []Node
AddTag(string)
RemoveTag(string)
HasTag(string) bool
}
// BaseNode is the default implementation of the Node interface,
// and helps to reduce the amount of boilerplate code needed
type BaseNode struct {
name string
uuid uuid.UUID
tags []string
parent Node
children []Node
}
func NewNode(name string) *BaseNode {
return &BaseNode{
name: name,
uuid: uuid.New(),
tags: []string{},
children: []Node{},
}
}
func (n *BaseNode) Name() string {
return n.name
}
func (n *BaseNode) UUID() uuid.UUID {
return n.uuid
}
func (n *BaseNode) Update() error {
for _, child := range n.children {
if err := child.Update(); err != nil {
return err
}
}
return nil
}
func (n *BaseNode) Draw(screen *ebiten.Image) {
for _, child := range n.children {
child.Draw(screen)
}
}
func (n *BaseNode) SetParent(parent Node) {
n.parent = parent
}
func (n *BaseNode) GetParent() Node {
return n.parent
}
// AddChild adds a child node to the current node, which is made its parent.
func (n *BaseNode) AddChild(child Node) {
child.SetParent(n)
n.children = append(n.children, child)
}
func (n *BaseNode) GetChildren() []Node {
return n.children
}
func (n *BaseNode) AddTag(tag string) {
n.tags = append(n.tags, tag)
}
func (n *BaseNode) RemoveTag(tag string) {
for i, t := range n.tags {
if t == tag {
n.tags = slices.Delete(n.tags, i, i+1)
return
}
}
}
func (n *BaseNode) HasTag(tag string) bool {
return slices.Contains(n.tags, tag)
}
func VisitAllNodes(node Node, visitor func(Node)) {
visitor(node)
for _, child := range node.GetChildren() {
VisitAllNodes(child, visitor)
}
}
func GetAllNodesWithTag(node Node, tag string) []Node {
nodes := []Node{}
VisitAllNodes(node, func(node Node) {
if node.HasTag(tag) {
nodes = append(nodes, node)
}
})
return nodes
}