forked from ebarlas/game-of-life-csp
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Cell.java
41 lines (34 loc) · 1.33 KB
/
Cell.java
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
package gameoflife;
import java.util.List;
public class Cell {
private boolean alive;
private final Channel<Boolean> tickChannel;
private final Channel<Boolean> resultChannel;
private final List<Channel<Boolean>> inChannels;
private final List<Channel<Boolean>> outChannels;
Cell(CellOptions options) {
this.alive = options.alive();
this.tickChannel = options.tickChannel();
this.resultChannel = options.resultChannel();
this.inChannels = options.inChannels();
this.outChannels = options.outChannels();
}
void start() {
Thread.startVirtualThread(this::run);
}
private void run() {
while (true) {
tickChannel.take(); // wait for tick stimulus
outChannels.forEach(ch -> ch.put(alive)); // announce liveness to neighbors
int neighbors = inChannels.stream().map(Channel::take).mapToInt(b -> b ? 1 : 0).sum(); // receive liveness from neighbors
alive = nextState(alive, neighbors); // calculate next state based on game of life rules
resultChannel.put(alive); // announce resulting next state
}
}
private static boolean nextState(boolean alive, int neighbors) {
if (alive) {
return neighbors == 2 || neighbors == 3;
}
return neighbors == 3;
}
}