You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Life.java 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. public class Life implements ILife {
  2. private char[][] world = {
  3. {'.', '.', '.', '.', '.'},
  4. {'.', '.', '.', '.', '.'},
  5. {'.', '.', '.', '.', '.'},
  6. {'.', '.', '.', '.', '.'},
  7. {'.', '.', '.', '.', '.'}
  8. };
  9. private char[][] newWorld = world;
  10. public static void main(String[] args) {
  11. Life l = new Life(new String[] { ".....",
  12. ".....",
  13. ".***.",
  14. ".....",
  15. "....." });
  16. l = (Life) l.nextGeneration();
  17. }
  18. public Life() {
  19. nukeAll();
  20. }
  21. public Life(String[] setup) {
  22. this();
  23. int x = 0;
  24. int y;
  25. for (y = 0; y < setup.length; y++) {
  26. for (x = 0; x < setup[y].length(); x++) {
  27. if (setup[y].charAt(x) != '.') {
  28. world[x][y] = '*';
  29. }
  30. }
  31. }
  32. }
  33. @Override
  34. public void nukeAll() {
  35. for (int y = 0; y < world.length; y++)
  36. for (int x = 0; x < world[y].length; x++) {
  37. setDead(x, y);
  38. }
  39. }
  40. @Override
  41. public void setAlive(int x, int y) {
  42. newWorld [x][y] = '*';
  43. }
  44. @Override
  45. public void setDead(int x, int y) {
  46. newWorld [x][y] = '.';
  47. }
  48. @Override
  49. public boolean isAlive(int x, int y) {
  50. if(world[y][x] == '*'){
  51. return true;
  52. }
  53. else return false;
  54. }
  55. @Override
  56. public ILife nextGeneration() {
  57. String[] s = new String[newWorld.length];
  58. checkNeighbors();
  59. for(int y = 0; y < newWorld.length; y++){
  60. s[y] = new String (newWorld[y]);
  61. System.out.println(s[y]);
  62. }
  63. return new Life(s);
  64. }
  65. private void checkNeighbors(){
  66. for (int y = 0; y < world.length; y++)
  67. for (int x = 0; x < world[y].length; x++) {
  68. if (!isAlive(x, y) && getNeighborCount(x, y) == 3) {
  69. setAlive(x, y);
  70. }
  71. else if (isAlive(x, y) && getNeighborCount(x, y) <= 1){
  72. setDead(x, y);
  73. }
  74. else if (isAlive(x, y) && getNeighborCount(x, y) >= 4){
  75. setDead(x, y);
  76. }
  77. else{
  78. newWorld[x][y] = world[x][y];
  79. }
  80. }
  81. }
  82. private int getNeighborCount(int x, int y){
  83. int aliveNeighborCount = 0;
  84. for(int i = -1; i<=1; i++) {
  85. for (int j = -1; j<=1; j++) {
  86. if(isAlive(x, y))
  87. aliveNeighborCount++;
  88. }
  89. }
  90. return aliveNeighborCount;
  91. }
  92. }