public class Life implements ILife { private int width; private int height; private boolean[][] grid; public static void main(String[] args) { Life l = new Life(new String[]{ " ", " ", " *** ", " ", " " }); l = (Life) l.nextGeneration(); } public Life() { this.width = 5; this.height = 5; this.grid = new boolean[width][height]; nukeAll(); } public Life(String[] setup) { this.height = setup.length; this.width = setup[0].length(); this.grid = new boolean[width][height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (setup[y].charAt(x) == '*') { setAlive(x, y); } } } } @Override public void nukeAll() { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { grid[x][y] = false; } } } @Override public void setAlive(int x, int y) { if (isInBounds(x, y)) { grid[x][y] = true; } } @Override public void setDead(int x, int y) { } @Override public boolean isAlive(int x, int y) { return isInBounds(x, y) && grid[x][y]; } @Override public ILife nextGeneration() { Life newLife = new Life(); newLife.width = this.width; newLife.height = this.height; newLife.grid = new boolean[width][height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int neighbors = countAliveNeighbors(x, y); if (isAlive(x, y)) { if (neighbors < 2 || neighbors > 3) { newLife.setDead(x, y); } else { newLife.setAlive(x, y); } } else { if (neighbors == 3) { newLife.setAlive(x, y); } } } } return newLife; } private int countAliveNeighbors(int x, int y) { int count = 0; for (int dy = -1; dy <= 1; dy++) { for (int dx = -1; dx <= 1; dx++) { if (dx == 0 && dy == 0) continue; if (isAlive(x + dx, y + dy)) count++; } } return count; } private boolean isInBounds(int x, int y) { return x >= 0 && x < width && y >= 0 && y < height; } }