87 lines
2.0 KiB
Java

public class Life implements ILife {
private boolean[][] grid = new boolean[5][5]; // vorläufig 5x5 Raster
public static void main(String[] args) {
Life l = new Life(new String[] { " ",
" ",
" *** ",
" ",
" " });
l = (Life) l.nextGeneration();
}
public Life() {
nukeAll();
}
public Life(String[] setup) {
this();
for (int y = 0; y < setup.length; y++)
for (int x = 0; x < setup[y].length(); x++)
if (setup[y].charAt(x) != ' ')
setAlive(x, y);
}
@Override
public void nukeAll() {
// TODO Auto-generated method stub
}
@Override
public void setAlive(int x, int y) {
grid[x][y] = true;
}
@Override
public void setDead(int x, int y) {
grid[x][y] = false;
}
@Override
public boolean isAlive(int x, int y) {
return grid[x][y];
}
@Override
public ILife nextGeneration() {
Life next = new Life();
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);
} else if (countAliveNeighbours(x, y) < 2 || countAliveNeighbours(x, y) > 3) {
next.setDead(x, y);
}
}
}
return next;
}
private int countAliveNeighbours(int x, int y) {
int count = 0;
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;
}
private boolean isValid(int x, int y) {
return x >= 0 && x < grid.length && y >= 0 && y < grid[x].length;
}
}