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

  1. package de.hsfulda.pmuw.oop;
  2. import java.util.ArrayList;
  3. import java.util.Collection;
  4. import java.util.HashSet;
  5. import java.util.Set;
  6. import java.util.stream.Collectors;
  7. public class CgolCell {
  8. private final StateChangeListener<CgolCell> listener;
  9. private CgolCell[] neighbors;
  10. private boolean isAlive, nextState;
  11. final int row, column;
  12. public CgolCell(int row, int column, boolean isAlive, StateChangeListener<CgolCell> listener) {
  13. super();
  14. this.row = row;
  15. this.column = column;
  16. this.isAlive = this.nextState = isAlive;
  17. this.listener = listener;
  18. }
  19. public boolean isAlive() {
  20. return isAlive;
  21. }
  22. public void setNeighbors(Set<CgolCell> neighbors) {
  23. this.neighbors = neighbors.toArray(new CgolCell[0]);
  24. // System.out.print(neighbors.stream().map(n -> String.format("(r%d-c%d %s)", n.row, n.column ,n.isAlive?"*":"-"))
  25. // .collect(Collectors.joining("", String.format("cell r%d-c%d:\n ", row, column), "\n")));
  26. }
  27. void calculateNextGeneration() {
  28. int alifeNeigborsCount =0;
  29. for (CgolCell cgolCell : neighbors) {
  30. alifeNeigborsCount+= cgolCell.isAlive?1:0;
  31. }
  32. nextState = 3 == alifeNeigborsCount || (isAlive && (2 == alifeNeigborsCount));
  33. }
  34. void switchState() {
  35. if (isAlive || nextState) {
  36. for (CgolCell cgolCell : neighbors) {
  37. listener.addActiveCell(cgolCell);
  38. }
  39. listener.addActiveCell(this);
  40. }
  41. isAlive = nextState;
  42. }
  43. }