-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode.go
71 lines (62 loc) · 1.36 KB
/
node.go
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
package main
import (
"image/color"
"math/rand"
)
type Node struct {
Position Vector
Ch chan *Node
Peers []*Node
Canvas *Canvas
Power uint8
Group int
}
func NewNode(peers int, canvas *Canvas) *Node {
node := new(Node)
node.Peers = make([]*Node, 0, peers)
size := canvas.Bounds().Size()
x := float64(size.X) * rand.Float64()
y := float64(size.Y) * rand.Float64()
node.Position = Vector{x, y}
node.Canvas = canvas
node.Ch = make(chan *Node)
node.Power = 0
go node.Listen()
return node
}
func (n *Node) Listen() {
// Listen for incoming connection on node's channel
for {
peer := <-n.Ch
peer.Power -= 5
n.Power = peer.Power
n.Canvas.DrawLine(color.RGBA{255, n.Power, 0, 255}, n.Position, peer.Position)
// Retransmit to random node
if n.Power > 0 {
go n.Send()
}
}
}
func (n *Node) Send() {
for _, target := range n.Peers {
if target.Power == 0 {
target.Ch <- n
break
}
}
}
type NodeSorter struct {
data []*Node
target *Node
}
func (sorter NodeSorter) Len() int {
return len(sorter.data)
}
func (sorter NodeSorter) Less(i, j int) bool {
iDelta := sorter.data[i].Position.Sub(sorter.target.Position)
jDelta := sorter.data[j].Position.Sub(sorter.target.Position)
return iDelta.Length() < jDelta.Length()
}
func (sorter NodeSorter) Swap(i, j int) {
sorter.data[i], sorter.data[j] = sorter.data[j], sorter.data[i]
}