123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- public class Life implements ILife {
-
- private char[][] world = {
- {'.', '.', '.', '.', '.'},
- {'.', '.', '.', '.', '.'},
- {'.', '.', '.', '.', '.'},
- {'.', '.', '.', '.', '.'},
- {'.', '.', '.', '.', '.'}
- };
- private char[][] newWorld = world;
-
- public static void main(String[] args) {
- Life l = new Life(new String[] { ".....",
- ".....",
- ".***.",
- ".....",
- "....." });
- l = (Life) l.nextGeneration();
- }
-
-
- public Life() {
- nukeAll();
- }
-
- public Life(String[] setup) {
- this();
-
- int x = 0;
- int y;
-
-
- for (y = 0; y < setup.length; y++) {
- for (x = 0; x < setup[y].length(); x++) {
- if (setup[y].charAt(x) != '.') {
- world[x][y] = '*';
- }
- }
- }
- }
-
-
- @Override
- public void nukeAll() {
- for (int y = 0; y < world.length; y++)
- for (int x = 0; x < world[y].length; x++) {
- setDead(x, y);
- }
-
- }
-
- @Override
- public void setAlive(int x, int y) {
- newWorld [x][y] = '*';
-
- }
-
- @Override
- public void setDead(int x, int y) {
- newWorld [x][y] = '.';
-
- }
-
- @Override
- public boolean isAlive(int x, int y) {
- if(world[y][x] == '*'){
- return true;
- }
- else return false;
- }
-
- @Override
- public ILife nextGeneration() {
- String[] s = new String[newWorld.length];
- checkNeighbors();
- for(int y = 0; y < newWorld.length; y++){
- s[y] = new String (newWorld[y]);
- System.out.println(s[y]);
- }
- return new Life(s);
- }
-
- private void checkNeighbors(){
- for (int y = 0; y < world.length; y++)
- for (int x = 0; x < world[y].length; x++) {
- if (!isAlive(x, y) && getNeighborCount(x, y) == 3) {
- setAlive(x, y);
- }
- else if (isAlive(x, y) && getNeighborCount(x, y) <= 1){
- setDead(x, y);
- }
- else if (isAlive(x, y) && getNeighborCount(x, y) >= 4){
- setDead(x, y);
- }
- else{
- newWorld[x][y] = world[x][y];
- }
- }
- }
-
- private int getNeighborCount(int x, int y){
- int aliveNeighborCount = 0;
- for(int i = -1; i<=1; i++) {
- for (int j = -1; j<=1; j++) {
- if(isAlive(x, y))
- aliveNeighborCount++;
- }
- }
- return aliveNeighborCount;
- }
- }
|