-
Notifications
You must be signed in to change notification settings - Fork 1
/
conway.ino
120 lines (105 loc) · 2.56 KB
/
conway.ino
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
119
120
bool states[nStrips][ledsPerStrip];
float fade[nStrips][ledsPerStrip];
int neighbors[nStrips][ledsPerStrip];
boolean isAlive(int row, int col) {
return states[row][col];
}
void setState(int row, int col, bool state) {
states[row][col] = state;
}
int numNeighborsHelper(int row, int col) {
int totalCount = 0;
for (int r = -1; r <= 1; r++) {
for (int c = -1; c <= 1; c++) {
if (row + r >= 0 && row + r < nStrips &&
isAlive(wrap(row + r, nStrips),
wrap(col + c, ledsPerStrip))) {
totalCount += 1;
}
}
}
if (isAlive(row,col)) {
return totalCount-1;
} else {
return totalCount;
}
}
void countNeighbors() {
for (int row=0; row < nStrips; row++) {
for (int col = 0; col < ledsPerStrip; col++) {
neighbors[row][col] = numNeighborsHelper(row,col);
}
}
}
int numAlive() {
int total = 0;
for (int row=0; row < nStrips; row++) {
for (int col = 0; col < ledsPerStrip; col++) {
states[row][col] && total++;
}
}
return total;
}
int numNeighbors(int row, int col) {
return neighbors[row][col];
}
void evolveCell(int row, int col) {
int n = numNeighbors(row, col);
setState(row, col, isAlive(row,col) ? (n == 2 || n == 3) : n == 3);
}
void evolve () {
for (int row=0; row < nStrips; row++) {
for (int col = 0; col < ledsPerStrip; col++) {
evolveCell(row, col);
}
}
}
int simpleShip[][5] = {
{0, 1, 0, 0, 1},
{1, 0, 0, 0, 0},
{1, 0, 0, 0, 1},
{1, 1, 1, 1, 0}
};
void initShip(int x, int y) {
for (int row = 0; row < 4; row++) {
for (int col = 0; col < 5; col++) {
setState(y + row, x + col, simpleShip[row][col] == 1);
}
}
}
void randomSetup(int color) {
for (int row = 0; row < nStrips; row++) {
for (int col = 0; col < ledsPerStrip; col++) {
if (random(2) == 1) {
setState(row, col, true);
}
}
}
}
void draw(int color, float fadeSpeed) {
for (int row=0; row < nStrips; row++) {
for (int col = 0; col < ledsPerStrip; col++) {
pixel(row, col, interpolateRGB(color, BLACK, fade[row][col]));
if (!isAlive(row, col)) {
fade[row][col] = max(fade[row][col] - fadeSpeed, 0);
} else {
fade[row][col] = min(fade[row][col] + fadeSpeed, 1);
}
}
}
}
void conway(int nSteps, int color) {
randomSetup(color);
for (int i = 0; i< nSteps; i++) {
if (i % 50 == 0) {
countNeighbors();
evolve();
}
if (i % 1000 == 0) {
initShip(random(ledsPerStrip), random(1));
}
draw(color, 0.03);
leds.show();
delayMicroseconds(500);
}
}