forked from sausheong/petri
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsim.go
More file actions
103 lines (92 loc) · 2.25 KB
/
sim.go
File metadata and controls
103 lines (92 loc) · 2.25 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
package petri
import (
"flag"
"image/color"
"math/rand"
"time"
)
// Default implementation is Conway's Game of Life
var population *float64
func init() {
population = flag.Float64("pop", 0.1, "percentage initial population")
}
// Sim is the default Simulator struct
type Sim struct {
Units []Cellular
}
// Process runs every simulation day to process the cells
func (s *Sim) Process() {
// test each cell against the rules to determine
// if the cell dies, survives or is born anew
for n := range s.Units {
neighbours := FindNeighboursIndex(n)
ncount := 0
for _, neighbour := range neighbours {
if s.Units[neighbour].RGB() == Deeppink {
ncount++
}
}
if s.Units[n].RGB() == Deeppink {
if ncount < 2 || ncount > 3 {
s.Units[n].Set(White)
}
} else {
if ncount == 3 {
s.Units[n].Set(Deeppink)
}
}
}
// change the color of the cells accordingly
for n := range s.Units {
s.Units[n].SetRGB(s.Units[n].State())
}
}
// Cells returns the cells
func (s *Sim) Cells() []Cellular {
return s.Units
}
// Exit executes when the simulation exits
// It catches the ctrl-c signal and runs this before exiting
func (s *Sim) Exit() {
// execute this on exit
// empty method
}
// Init creates the initial cell population
func (s *Sim) Init() {
rand.Seed(time.Now().UTC().UnixNano())
s.Units = make([]Cellular, *Width*(*Width))
n := 0
for i := 1; i <= *Width; i++ {
for j := 1; j <= *Width; j++ {
p := rand.Float64()
if p < *population {
s.Units[n] = s.CreateCell(i, j, Deeppink, Deeppink)
} else {
s.Units[n] = s.CreateCell(i, j, White, White)
}
n++
}
}
}
// CreateCell creates a cell given the x and y locations
func (s *Sim) CreateCell(x, y, clr, st int) Cellular {
c := Cell{
X: x * *CellSize,
Y: y * *CellSize,
Radius: *CellSize, // radius of cell
Status: st,
Color: color.RGBA{getR(clr), getG(clr), getB(clr), uint8(255)},
}
return &c
}
// CreateCellWithIndex creates a cell from the index of an array
func (s *Sim) CreateCellWithIndex(n, clr, st int) Cellular {
c := Cell{
X: (n % (*Width)) * *CellSize,
Y: (int(n / (*Width))) * *CellSize,
Radius: *CellSize, // radius of cell
Status: st,
Color: color.RGBA{getR(clr), getG(clr), getB(clr), uint8(255)},
}
return &c
}