The following is a simple implementation of Conway's Life game. The rule is simple: a life stays alive when it has 2 or 3 neighbors, a new life is born at the place of 3 neighbors.
Another version of GameOfLife stores the arrays value as int instead of boolean, which is easier to be generalized.
public class GameOfLife {
static int countSurrounding(boolean[][] board, int a, int b) {
int count = 0;
int[][] surroundings = { { a - 1, b - 1 }, { a - 1, b },
{ a - 1, b + 1 }, { a, b - 1 }, { a, b + 1 }, { a + 1, b - 1 },
{ a + 1, b }, { a + 1, b + 1 } };
for (int surrounding[] : surroundings) {
try {
if (board[surrounding[0]][surrounding[1]]) {
count++;
}
} catch (ArrayIndexOutOfBoundsException e) {
}
}
return count;
}
static void visualizeBoard(boolean[][] board) {
for (boolean row[] : board) {
for (boolean cell : row) {
System.out.print(cell ? "#" : ".");
}
System.out.println();
}
System.out.println();
}
private static boolean nextCellState(boolean[][] board, int i, int j) {
int count = countSurrounding(board, i, j);
if (board[i][j] && (count == 2 || count == 3)) { // stay alive rule
return true;
}
if (!board[i][j] && count == 3) { // birth new rule
return true;
}
return false;
}
public static boolean[][] nextGeneration(boolean[][] board) {
boolean next[][] = new boolean[board.length][board[0].length];
int rows = board.length;
int cols = board[0].length;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
next[i][j] = nextCellState(board, i, j);
}
}
return next;
}
static final boolean[][] initialBoard = new boolean[10][10]; //default false
public static void main(String[] args) {
initialBoard[0][1] = initialBoard[0][2] = initialBoard[0][3] = initialBoard[0][4] = true; //seeds
boolean[][] board = new boolean[initialBoard.length][initialBoard[0].length];
// copy over the initial board
for (int i = 0; i < initialBoard.length; i++) {
for (int j = 0; j < initialBoard[i].length; j++) {
board[i][j] = initialBoard[i][j];
}
}
// loop over 25 generations
visualizeBoard(board);
for (int gen = 0; gen < 25; gen++) {
System.out.println("\nGeneration " + gen);
board = nextGeneration(board);
visualizeBoard(board);
}
}
}