Refactoring: überprüfe alle acht Nachbarn einer Zelle
This commit is contained in:
parent
b13b551045
commit
72d8e1c320
Binary file not shown.
@ -51,18 +51,46 @@ public class Life implements ILife {
|
||||
public ILife nextGeneration() {
|
||||
Life next = new Life();
|
||||
|
||||
if (countAliveNeighbours() == 3) {
|
||||
if (countAliveNeighbours(1, 1) == 3) {
|
||||
next.setAlive(1,1);
|
||||
}
|
||||
|
||||
return next;
|
||||
}
|
||||
|
||||
private int countAliveNeighbours() {
|
||||
private int countAliveNeighbours(int x, int y) {
|
||||
int count = 0;
|
||||
if (isAlive(0, 0)) count++;
|
||||
if (isAlive(0, 1)) count++;
|
||||
if (isAlive(0, 2)) count++;
|
||||
|
||||
// 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_Y = -1; offset_Y <= 1; offset_Y++) {
|
||||
if (offset_X == 0 && offset_Y == 0) continue; // eigene Zelle überspringen
|
||||
int neighbor_X = x + offset_X;
|
||||
int neighbor_Y = y + offset_Y;
|
||||
|
||||
if (isValid(neighbor_X, neighbor_Y) && isAlive(neighbor_X, neighbor_Y)) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
// soll in countAliveNeighbours() genutzt werden
|
||||
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;
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user