Created
January 10, 2015 22:18
-
-
Save keshavsaharia/09bc0a9e54cdb726b2a5 to your computer and use it in GitHub Desktop.
Conway's game of life utility functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void step() { | |
boolean[][] newGrid = new boolean[50][50]; | |
for (int x = 0 ; x < 50 ; x++) { | |
for (int y = 0 ; y < 50 ; y++) { | |
// Get how many neighbors this cell has. | |
int count = neighbors(x, y); | |
// 1. If the square is alive, but has less than two neighbors, it dies. | |
if (grid[x][y] == true && count < 2) { | |
newGrid[x][y] = false; | |
} | |
// 2. If the square is alive and has two or three neighbors, it lives. | |
if (grid[x][y] == true && (count == 2 || count == 3)) { | |
newGrid[x][y] = true; | |
} | |
// 3. If the square is alive and has more than three neighbors, it dies. | |
if (grid[x][y] == true && count > 3) { | |
newGrid[x][y] = false; | |
} | |
// 4. If a square is dead, and it has exactly three live neighbors, it becomes alive. | |
if (grid[x][y] == false && count == 3) { | |
newGrid[x][y] = true; | |
} | |
} | |
} | |
grid = newGrid; | |
} | |
public static int neighbors(int x, int y) { | |
int count = 0; | |
if (x > 0 && y > 0 && grid[x - 1][y - 1] == true) { | |
count++; | |
} | |
if (y > 0 && grid[x][y - 1] == true) { | |
count++; | |
} | |
if (x < 49 && y > 0 && grid[x + 1][y - 1] == true) { | |
count++; | |
} | |
if (x > 0 && grid[x - 1][y] == true) { | |
count++; | |
} | |
if (x < 49 && grid[x + 1][y] == true) { | |
count++; | |
} | |
if (x > 0 && y < 49 && grid[x - 1][y + 1] == true) { | |
count++; | |
} | |
if (y < 49 && grid[x][y + 1] == true) { | |
count++; | |
} | |
if (x < 49 && y < 49 && grid[x + 1][y + 1] == true) { | |
count++; | |
} | |
return count; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment