Skip to content

Instantly share code, notes, and snippets.

@mahdyadi
Created March 9, 2020 00:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahdyadi/d8da3adbd3d40d0c81abff61a040cd09 to your computer and use it in GitHub Desktop.
Save mahdyadi/d8da3adbd3d40d0c81abff61a040cd09 to your computer and use it in GitHub Desktop.
...
public Game nextTick() {
HashMap<Cell, Integer> updateMap = new HashMap<Cell, Integer>();
for (Cell livingCell : this.cells) {
for (Cell neighbouringCell : livingCell.neighbours()) {
int currentCount = updateMap.getOrDefault(neighbouringCell, 0);
currentCount++;
updateMap.put(neighbouringCell, currentCount);
}
}
HashSet<Cell> nextCells = new HashSet<>();
for (HashMap.Entry<Cell, Integer> entry : updateMap.entrySet()) {
Cell currentCell = entry.getKey();
int previousNeighbourCount = entry.getValue();
if (previousNeighbourCount == 2 && this.cells.contains(currentCell)) {
nextCells.add(currentCell);
}
if (previousNeighbourCount == 3) {
nextCells.add(currentCell);
}
}
boolean needToExpandDown = false;
for (int col = this.colLowerBound; col <= this.colUpperBound; col++) {
Cell outsideLowerBoundCell = new Cell(this.rowUpperBound + 1, col);
if (nextCells.contains(outsideLowerBoundCell)) {
needToExpandDown = true;
}
}
boolean needToExpandRight = false;
for (int row = this.rowLowerBound; row <= this.rowUpperBound; row++) {
Cell outsideRightBoundCell = new Cell(row, colUpperBound + 1);
if (nextCells.contains(outsideRightBoundCell)) {
needToExpandRight = true;
}
}
boolean needToExpandUp = false;
for (int col = this.colLowerBound; col <= this.colUpperBound; col++) {
Cell outsideUpBoundCell = new Cell(this.rowLowerBound - 1, col);
if (nextCells.contains(outsideUpBoundCell)) {
needToExpandUp = true;
}
}
boolean needToExpandLeft = false;
for (int row = this.rowLowerBound; row <= this.rowUpperBound; row++) {
Cell outsideLeftBoundCell = new Cell(row, colLowerBound - 1);
if (nextCells.contains(outsideLeftBoundCell)) {
needToExpandLeft = true;
}
}
Game updatedGame = new Game(this.rowUpperBound + 1, this.colUpperBound + 1);
if (needToExpandDown) {
updatedGame.expandDown();
}
if (needToExpandRight) {
updatedGame.expandRight();
}
if (needToExpandUp) {
updatedGame.expandUp();
}
if (needToExpandLeft){
updatedGame.expandLeft();
}
for (Cell cell : nextCells) {
updatedGame.setCellAlive(cell);
}
return updatedGame;
}
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment