import java.util.Random; import java.awt.Graphics2D; import java.awt.geom.Ellipse2D; import java.awt.Color; import java.awt.Dimension; public class LifeGame { private static Random rand = new Random(); private final int DEAD = 0; private final int GREEN = 1; private final int BLUE = 2; private final Color GREEN_COLOR = Color.green; private final Color BLUE_COLOR = Color.blue; private final Color DEAD_COLOR = Color.white; private final int CELL_SIZE = 10; private int gridHeight; private int gridWidth; private int[][] grid; private int[] colorCounter = new int[2]; private int GREEN_INDEX = 0; private int BLUE_INDEX = 1; public LifeGame(int pixelHeight, int pixelWidth) { gridHeight = pixelHeight / CELL_SIZE; gridWidth = pixelWidth / CELL_SIZE; grid = new int[gridHeight][gridWidth]; //initialize a random grid for(int i = 0; i < gridHeight; i++) { for(int j = 0; j < gridWidth; j++) { grid[i][j] = rand.nextInt(3); } } } public void nextGen() { int[][] temp = new int[gridHeight][gridWidth]; for(int i = 0; i < gridHeight; i++) { for(int j = 0; j < gridWidth; j++) { if(i == 0 || j ==0 || i == gridHeight - 1 || j == gridWidth - 1) { temp[i][j] = 0; } else { calculateNeighbors(i, j); if((colorCounter[GREEN_INDEX] == 3 || colorCounter[GREEN_INDEX] == 4) || (colorCounter[GREEN_INDEX] == 2 && grid[i][j] == GREEN)) temp[i][j] = GREEN; if(colorCounter[BLUE_INDEX] == 3 || (colorCounter[BLUE_INDEX] == 2 && grid[i][j] == BLUE)) temp[i][j] = BLUE; } } } grid = temp; } public void calculateNeighbors(int row, int column) { colorCounter[0] = 0; colorCounter[1] = 0; if(grid[row][column] == GREEN) colorCounter[GREEN_INDEX] = -1; if(grid[row][column] == BLUE) colorCounter[BLUE_INDEX] = -1; for(int i = row - 1; i<= row + 1; i++) { for(int j = column - 1; j <= column + 1; j++) { if(grid[i][j] == GREEN) colorCounter[GREEN_INDEX] += 1; if(grid[i][j] == BLUE) colorCounter[BLUE_INDEX] += 1; } } } public void draw(Graphics2D g2) { for(int i = 0; i < gridHeight; i++) { for(int j = 0; j < gridWidth; j++) { if(grid[i][j] != DEAD) { if(grid[i][j] == GREEN) g2.setColor(GREEN_COLOR); if(grid[i][j] == BLUE) g2.setColor(BLUE_COLOR); g2.fill(new Ellipse2D.Double(j * CELL_SIZE, (i + 1) * CELL_SIZE, CELL_SIZE, CELL_SIZE)); } } } } }