-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathnodeNetwork.go
87 lines (72 loc) · 1.67 KB
/
nodeNetwork.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// Creates a node network
// Reference: http://www.pheelicks.com/2013/11/intro-to-images-in-go-fractals/
package main
// Import packages
import ("image"; "image/color"; "image/png";
"os"
"log"
"math/rand"
"time")
// "coordinate")
type Node struct {
Position Coordinate
Ch chan *Node
Peers []*Node
Canvas *Canvas
Power uint8
}
func (n *Node) Listen() {
// Listen for incoming connection on 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
if n.Power > 0 {
go n.Send()
}
}
func (n *Node) Send() {
for _, target := range n.Peers {
if target.Power == 0 {
target.Ch <- n
break
}
}
}
func NewNode(peers uint32, canvas *Canvas) *Node {
n := new(Node)
size := canvas.Bounds().Size()
n.Position = Coordinate{float64(size.X) * rand.Float64(), float64(size.Y) * rand.Float64()}
n.Ch = make(chan *Node)
n.Peers = make([]*Node, 0, peers)
n.Canvas = canvas
n.Power = 0
go n.Listen()
return n
}
func initialize(totalNodes uint32, peers uint32, canvas *Canvas) {
nodes := make([]*Node, totalNodes)
for i := uint32(0); i < totalNodes; i++ {
nodes[i] = NewNode(peers, canvas)
}
}
func main() {
// Declare image size
width, height := 1024, 1024
// Create a new image
img := image.Rect(0, 0, width, height)
c := NewCanvas(img)
c.DrawRect(color.RGBA{0, 0, 0, 255}, Coordinate{0, 0}, Coordinate{float64(width), float64(height)})
rand.Seed(time.Now().UTC().UnixNano())
initialize(50, 5, c)
fileName := "nodeNetwork.png"
file, err := os.Create(fileName)
if err != nil {
log.Fatal(err)
}
defer file.Close()
png.Encode(file, c)
}