Refactoring: nextGeneration() kann nun beliebige Zellen überprüfen, nicht mehr nur 1,1 aus Testfall

This commit is contained in:
Susanne 2025-02-15 23:23:21 +01:00
parent 72d8e1c320
commit 5c79c16b46
2 changed files with 8 additions and 16 deletions

View File

@ -51,8 +51,14 @@ public class Life implements ILife {
public ILife nextGeneration() { public ILife nextGeneration() {
Life next = new Life(); Life next = new Life();
if (countAliveNeighbours(1, 1) == 3) { // Refactoring: erst wurde nur Zelle 1,1 (entsprechend dem Testfall) überprüft,
next.setAlive(1,1); // jetzt auf alle Zellen des grids ausgeweitet
for (int y = 0; y < grid.length; y++) {
for (int x = 0; x < grid[y].length; x++) {
if (countAliveNeighbours(x, y) == 3) {
next.setAlive(x, y);
}
}
} }
return next; return next;
@ -61,18 +67,6 @@ public class Life implements ILife {
private int countAliveNeighbours(int x, int y) { private int countAliveNeighbours(int x, int y) {
int count = 0; int count = 0;
// Eine Zelle hat ja 8 Nachbarn,
// das wäre die Überprüfung für jede einzelne Zelle herum:
// if (isValid(x-1, y-1) && isAlive(x-1, y-1)) count++;
// if (isValid(x, y-1) && isAlive(x, y-1)) count++;
// if (isValid(x+1, y-1) && isAlive(x+1, y-1)) count++;
// if (isValid(x-1, y) && isAlive(x-1, y)) count++;
// if (isValid(x+1, y) && isAlive(x+1, y)) count++;
// if (isValid(x-1, y+1) && isAlive(x-1, y+1)) count++;
// if (isValid(x, y+1) && isAlive(x, y+1)) count++;
// if (isValid(x+1, y+1) && isAlive(x+1, y+1)) count++;
// aber so ist's direkt bisschen "schlanker"
for (int offset_X = -1; offset_X <= 1; offset_X++) { for (int offset_X = -1; offset_X <= 1; offset_X++) {
for (int offset_Y = -1; offset_Y <= 1; offset_Y++) { for (int offset_Y = -1; offset_Y <= 1; offset_Y++) {
if (offset_X == 0 && offset_Y == 0) continue; // eigene Zelle überspringen if (offset_X == 0 && offset_Y == 0) continue; // eigene Zelle überspringen
@ -88,9 +82,7 @@ public class Life implements ILife {
return count; return count;
} }
// soll in countAliveNeighbours() genutzt werden
private boolean isValid(int x, int y) { private boolean isValid(int x, int y) {
// überprüft einfach nur, ob Zelle innerhalb der grid-Grenzen liegt
return x >= 0 && x < grid.length && y >= 0 && y < grid[x].length; return x >= 0 && x < grid.length && y >= 0 && y < grid[x].length;
} }
} }