Created
March 9, 2016 06:37
-
-
Save bzdgn/39dc015b37cb2d79ec9f to your computer and use it in GitHub Desktop.
A Very Simple Game Of Life Implementation for Java
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 class SimpleGOL { | |
private static final int HEIGHT = 80; | |
private static final int CLEAR_SPACE = 2; | |
public static void main(String[] args) throws InterruptedException { | |
boolean [][] matrix = new boolean[HEIGHT][HEIGHT]; | |
boolean [][] tempMatrix = new boolean[HEIGHT][HEIGHT]; | |
for(int i = 0; i < matrix.length; i++) | |
for(int j = 0; j < matrix[i].length; j++) { | |
matrix[i][j] = false; | |
tempMatrix[i][j] = false; | |
} | |
generateRandom(matrix); | |
while(true) { | |
Thread.sleep(120); | |
printMatrix(matrix); | |
processLife(matrix, tempMatrix); | |
clear(); | |
System.out.println("-----------------------------------------------------"); | |
} | |
} | |
private static void processLife(boolean[][] matrix, boolean[][] tempMatrix) { | |
copyMatrix(matrix, tempMatrix); | |
for(int i = 0; i < HEIGHT; i++) { | |
for(int j = 0; j < HEIGHT; j++) { | |
int countAlive = 0; | |
for(int k = i-1; k <= i+1; k++) { | |
for(int t = j-1; t <= j+1; t++) { | |
if(t < 0 || t >= HEIGHT || k < 0 || k >= HEIGHT) | |
continue; | |
else { | |
if(matrix[k][t]) { | |
countAlive++; | |
} | |
} | |
} | |
} | |
if(matrix[i][j]) | |
countAlive--; // decrement for self | |
if(matrix[i][j]) { | |
if(countAlive > 3 || countAlive < 2) { | |
tempMatrix[i][j] = false; | |
} | |
} else if(countAlive == 3) { | |
tempMatrix[i][j] = true; | |
} | |
} | |
} | |
copyMatrix(tempMatrix, matrix); | |
} | |
private static void copyMatrix(boolean[][] src, boolean[][] dst) { | |
for(int i = 0; i < HEIGHT; i++) | |
System.arraycopy(src[i], 0, dst[i], 0, HEIGHT); | |
} | |
private static void printMatrix(boolean[][] matrix) { | |
for(int i = 0; i < matrix.length; i++) { | |
for(int j = 0; j < matrix[i].length; j++) { | |
if(matrix[i][j] == true) { | |
System.out.print('X'); | |
} else { | |
System.out.print(' '); | |
} | |
} | |
System.out.println(); | |
} | |
} | |
private static void clear() { | |
for(int i = 0; i < CLEAR_SPACE; i++) | |
System.out.println(); | |
} | |
private static void generateRandom(boolean[][] matrix) { | |
for(int i = 0; i < HEIGHT; i++) | |
for(int j = 0; j < HEIGHT; j++) | |
matrix[i][j] = Math.random() < 0.5; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment