Created
March 6, 2017 21:49
-
-
Save jeresuikkila/b6ad963db0ffebfc17e6c7e758673326 to your computer and use it in GitHub Desktop.
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
// Jere Suikkila kehittänyt metodit: | |
// elossaOleviaNaapureita ja kehity | |
import java.util.Random; | |
public class GameOfLife { | |
private int[][] taulukko; | |
public GameOfLife(int leveys, int korkeus) { | |
this.taulukko = new int[leveys][korkeus]; | |
} | |
public void alustaSatunnaisesti() { | |
Random satunnaistaja = new Random(); | |
int x = 0; | |
while (x < taulukko.length) { | |
int y = 0; | |
while (y < taulukko[x].length) { | |
if (satunnaistaja.nextDouble() < 0.2) { | |
taulukko[x][y] = 1; | |
} | |
y++; | |
} | |
x++; | |
} | |
} | |
public void kehity() { | |
int[][] kopio = new int[this.taulukko.length][this.taulukko[0].length]; | |
for (int i = 0; i < this.taulukko.length; i++) { | |
for (int j = 0; j < this.taulukko[0].length; j++) { | |
// Elossa | |
if (this.taulukko[i][j] == 1) { | |
if (elossaOleviaNaapureita(this.taulukko, i, j) == 2 || | |
elossaOleviaNaapureita(this.taulukko, i, j) == 3) { | |
kopio[i][j] = 1; | |
} else { | |
kopio[i][j] = 0; | |
} | |
// Kuollut | |
} else { | |
if (elossaOleviaNaapureita(this.taulukko, i, j) == 3) { | |
kopio[i][j] = 1; | |
} | |
} | |
} | |
} | |
this.taulukko = kopio; | |
} | |
public int[][] getTaulukko() { | |
return taulukko; | |
} | |
public void setTaulukko(int[][] taulukko) { | |
this.taulukko = taulukko; | |
} | |
public int elossaOleviaNaapureita(int[][] taulukko, int x, int y) { | |
int naapurit = 0; | |
int leveys = taulukko.length -1 ; | |
int korkeus = taulukko[0].length -1; | |
int xMin = 0; | |
int xMax = leveys; | |
int yMin = 0; | |
int yMax = korkeus; | |
if (x-1 > 0) { | |
xMin = x-1; | |
} | |
if (x+1 < leveys) { | |
xMax = x+1; | |
} | |
if (y-1 > 0) { | |
yMin = y-1; | |
} | |
if (y+1 < korkeus) { | |
yMax = y+1; | |
} | |
for (int i = xMin; i <= xMax; i++) { | |
for (int j = yMin; j <= yMax; j++) { | |
if (i == x && j == y) { | |
continue; | |
} else if (taulukko[i][j] == 1) { | |
naapurit++; | |
} | |
} | |
} | |
return naapurit; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Game of Life implementation in Java.
Can be tested with
`GameOfLife gol = new GameOfLife(3, 3);
int[][] taulukko = new int[3][3];
taulukko[0][0] = 1;
taulukko[0][1] = 1;
taulukko[1][1] = 1;
taulukko[2][2] = 1;
System.out.println(gol.elossaOleviaNaapureita(taulukko, 0, 0));
System.out.println(gol.elossaOleviaNaapureita(taulukko, 1, 0));
System.out.println(gol.elossaOleviaNaapureita(taulukko, 1, 1));
System.out.println(gol.elossaOleviaNaapureita(taulukko, 2, 2));`