123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- public class Life implements ILife {
-
- boolean[][] cells = new boolean[15][15];
-
- public static void main(String[] args) {
- Life l = new Life(new String[] { " ",
- " ",
- " *** ",
- " ",
- " " });
- l = (Life) l.nextGeneration();
- }
-
-
- public Life() {
- nukeAll();
- }
-
- public Life(String[] setup) {
- this();
- for (int y = 0; y < setup.length; y++)
- for (int x = 0; x < setup[y].length(); x++)
- if (setup[y].charAt(x) != ' ')
- setAlive(x, y);
- }
-
-
- @Override
- public void nukeAll() {
- // TODO Auto-generated method stub
- for (int i = 0; i < 15; i++) {
- for (int j = 0; j < 15; j++) {
- cells[i][j] = false;
- }
- }
- }
-
- @Override
- public void setAlive(int x, int y) {
- // TODO Auto-generated method stub
- cells[x][y] = true;
- }
-
- @Override
- public void setDead(int x, int y) {
- // TODO Auto-generated method stub
- cells[x][y] = false;
- }
-
- @Override
- public boolean isAlive(int x, int y) {
- // TODO Auto-generated method stub
- return cells[x][y];
- }
-
- @Override
- public ILife nextGeneration() {
- // TODO Auto-generated method stub
- boolean[][] nextGen = new boolean[15][15];
-
- for (int y = 0; y < 15; y++) {
-
- for (int x = 0; x < 15; x++) {
-
- int aliveNeighbours = countNeighbourCells(x, y);
- if (isAlive(x, y)) {
-
- if (aliveNeighbours == 2 || aliveNeighbours == 3) {
- nextGen[x][y] = true;
- } else {
- nextGen[x][y] = false;
- }
- } else {
- if (aliveNeighbours == 3) {
- nextGen[x][y] = true;
- } else {
- nextGen[x][y] = false;
- }
- }
- }
- }
- cells = nextGen;
- return this;
- }
-
- public int countNeighbourCells(int x , int y){
- int counter = 0;
-
- if((x-1) >=0 && (y-1) >=0 && isAlive(x-1,y-1)) counter++;
- if((y-1) >=0 && isAlive(x,y-1)) counter++;
- if((x+1) < 15 && (y-1) >=0 && isAlive(x+1,y-1)) counter++;
- if((x-1) >=0&& isAlive(x-1,y)) counter++;
- if((x+1) < 15 && isAlive(x+1,y)) counter++;
- if((x-1) >=0 && (y+1) < 15 && isAlive(x-1,y+1)) counter++;
-
- if((y+1) <15 && isAlive(x,y+1)) counter++;
-
- if((x+1) <15 && (y+1) <15 && isAlive(x+1,y+1)) counter++;
-
- return counter;
- }
- }
|