You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.4 KiB

package de.hsfulda.pmuw.oop;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
public class CgolCell {
private final StateChangeListener<CgolCell> listener;
private CgolCell[] neighbors;
private boolean isAlive, nextState;
final int row, column;
public CgolCell(int row, int column, boolean isAlive, StateChangeListener<CgolCell> listener) {
super();
this.row = row;
this.column = column;
this.isAlive = this.nextState = isAlive;
this.listener = listener;
}
public boolean isAlive() {
return isAlive;
}
public void setNeighbors(Set<CgolCell> neighbors) {
this.neighbors = neighbors.toArray(new CgolCell[0]);
// System.out.print(neighbors.stream().map(n -> String.format("(r%d-c%d %s)", n.row, n.column ,n.isAlive?"*":"-"))
// .collect(Collectors.joining("", String.format("cell r%d-c%d:\n ", row, column), "\n")));
}
void calculateNextGeneration() {
int alifeNeigborsCount =0;
for (CgolCell cgolCell : neighbors) {
alifeNeigborsCount+= cgolCell.isAlive?1:0;
}
nextState = 3 == alifeNeigborsCount || (isAlive && (2 == alifeNeigborsCount));
}
void switchState() {
if (isAlive || nextState) {
for (CgolCell cgolCell : neighbors) {
listener.addActiveCell(cgolCell);
}
listener.addActiveCell(this);
}
isAlive = nextState;
}
}