import java.util.Arrays; public class Life implements ILife { static String[] board = new String[]{ "* ", "* ", "* ", " ", " " }; public static void main(String[] args) { Life l = new Life(board); 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); } } } printTable(board); } private void printTable(String[] board) { for(int i = 0; i < board.length; i++) System.out.println(Arrays.toString(new String[]{board[i]})); System.out.println("________"); } @Override public void nukeAll() { //works // TODO Auto-generated method stub for (int y = 0; y < board.length; y++){ for (int x = 0; x < board[y].length(); x++) { setDead(x, y); } } } @Override public void setAlive(int x, int y) { // TODO Auto-generated method stub board[y] = board[y].substring(0, x) + '*' + board[y].substring(x+1); } @Override public void setDead(int x, int y) { // TODO Auto-generated method stub board[y] = board[y].substring(0, x) + ' ' + board[y].substring(x+1); } @Override public boolean isAlive(int x, int y) { if(board[y].charAt(x) == '*'){ return true; } else{ return false; } } @Override public ILife nextGeneration() { int alive; String[] nextBoard = new String[]{ " ", " ", " ", " ", " " }; for (int y = 0; y < board.length; y++){ for (int x = 0; x < board[y].length(); x++){ alive=aliveNeighbours(x,y); //A new Cell is born if(!isAlive(x,y) && alive == 3) { nextBoard[y] = nextBoard[y].substring(0, x) + '*' + nextBoard[y].substring(x+1); } //Cell is lonely and dies or cell is overpopulated and dies else if((isAlive(x,y) && (alive < 2)) || (alive > 3)){ nextBoard[y] = nextBoard[y].substring(0, x) + ' ' + nextBoard[y].substring(x+1); } //Cell with two or three living neighbours lives on else if(isAlive(x,y) && (alive == 2 || alive == 3)){ nextBoard[y] = nextBoard[y].substring(0, x) + board[y].charAt(x) + nextBoard[y].substring(x+1); } } } board = nextBoard; System.out.println("next Generation"); printTable(board); return null; } private int aliveNeighbours(int x, int y) { int neighbours = 0; if(x>0 && y>0){ if(board[y-1].charAt(x-1) == '*'){ neighbours++; } } if(x>0){ if(board[y].charAt(x-1) == '*'){ neighbours++; } if(y<4 ){ if(board[y+1].charAt(x-1) == '*'){ neighbours++; } } } if(y>0){ if(board[y-1].charAt(x) == '*'){ neighbours++; } if(x<4){ if(board[y-1].charAt(x+1) == '*'){ neighbours++; } } } if(x<4){ if(board[y].charAt(x+1) == '*'){ neighbours++; } } if(y<4){ if(board[y+1].charAt(x) == '*'){ neighbours++; } } if(x<4 && y<4){ if(board[y+1].charAt(x+1) == '*'){ neighbours++; } } return neighbours; } }