import java.util.Arrays; public class Life implements ILife { Life nextworld; String[] board; 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 board = new String[]{" ", " ", " ", " ", " "}; } @Override public void setAlive(int x, int y) { // TODO Auto-generated method stub String line = ""; for (int i = 0; i < board[y].length(); i++) { if (i == x) line += '*'; else line += board[y].charAt(i); } board[y] = line; } @Override public void setDead(int x, int y) { // TODO Auto-generated method stub String line = ""; for (int i = 0; i < board[y].length(); i++) { if (i == x) line += ' '; else line += board[y].charAt(i); } board[y] = line; } @Override public boolean isAlive(int x, int y) { // TODO Auto-generated method stub if (board[y].charAt(x) == '*') return true; else return false; } @Override public ILife nextGeneration() { // TODO Auto-generated method stub Life nextWorld = new Life(); for (int y = 0; y < board.length; y++) { for (int x = 0; x < board[y].length(); x++) { int neighbourCells = CountNeighbourCells(x, y); if (isAlive(x, y)) if (neighbourCells == 3 || neighbourCells == 2) nextWorld.setAlive(x, y); if (neighbourCells < 2 || neighbourCells > 3) nextWorld.setDead(x, y); if (!isAlive(x, y)) if (neighbourCells == 3) nextWorld.setAlive(x, y); else nextWorld.setDead(x, y); } } nextWorld.drawWorld(); return nextWorld; } public int CountNeighbourCells(int x, int y) { int pre_y = y - 1; int pre_x = x - 1; int after_y = y + 1; int after_x = x + 1; int counter = 0; //UpperSide if (pre_y >= 0) { for (int i = pre_x; i <= after_x; i++) { if (i >= 0 && i < board[pre_y].length()&& isAlive(i,pre_y)){ counter++; } } } //DownSide if (after_y < board.length) { for (int i = pre_x; i <= after_x; i++) { if (i >= 0 && i < board[after_y].length()&&isAlive(i,after_y)) { counter++; } } } //leftSide if (pre_x >= 0&& isAlive(pre_x,y)) { counter++; } //rightSide if (after_x < board[y].length()&&isAlive(after_x,y)) { counter++; } return counter; } public void drawWorld() { for (int i = 0; i < board.length; i++) { System.out.println(Arrays.toString(new String[]{ board[i] })); } } }