Assignment 5
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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. public class Life implements ILife {
  2. boolean[][] cells = new boolean[15][15];
  3. public static void main(String[] args) {
  4. Life l = new Life(new String[] { " ",
  5. " ",
  6. " *** ",
  7. " ",
  8. " " });
  9. l = (Life) l.nextGeneration();
  10. }
  11. public Life() {
  12. nukeAll();
  13. }
  14. public Life(String[] setup) {
  15. this();
  16. for (int y = 0; y < setup.length; y++)
  17. for (int x = 0; x < setup[y].length(); x++)
  18. if (setup[y].charAt(x) != ' ')
  19. setAlive(x, y);
  20. }
  21. @Override
  22. public void nukeAll() {
  23. // TODO Auto-generated method stub
  24. for (int i = 0; i < 15; i++) {
  25. for (int j = 0; j < 15; j++) {
  26. cells[i][j] = false;
  27. }
  28. }
  29. }
  30. @Override
  31. public void setAlive(int x, int y) {
  32. // TODO Auto-generated method stub
  33. cells[x][y] = true;
  34. }
  35. @Override
  36. public void setDead(int x, int y) {
  37. // TODO Auto-generated method stub
  38. cells[x][y] = false;
  39. }
  40. @Override
  41. public boolean isAlive(int x, int y) {
  42. // TODO Auto-generated method stub
  43. return cells[x][y];
  44. }
  45. @Override
  46. public ILife nextGeneration() {
  47. // TODO Auto-generated method stub
  48. boolean[][] nextGen = new boolean[15][15];
  49. for (int y = 0; y < 15; y++) {
  50. for (int x = 0; x < 15; x++) {
  51. int aliveNeighbours = countNeighbourCells(x, y);
  52. if (isAlive(x, y)) {
  53. if (aliveNeighbours == 2 || aliveNeighbours == 3) {
  54. nextGen[x][y] = true;
  55. } else {
  56. nextGen[x][y] = false;
  57. }
  58. } else {
  59. if (aliveNeighbours == 3) {
  60. nextGen[x][y] = true;
  61. } else {
  62. nextGen[x][y] = false;
  63. }
  64. }
  65. }
  66. }
  67. cells = nextGen;
  68. return this;
  69. }
  70. public int countNeighbourCells(int x , int y){
  71. int counter = 0;
  72. if((x-1) >=0 && (y-1) >=0 && isAlive(x-1,y-1)) counter++;
  73. if((y-1) >=0 && isAlive(x,y-1)) counter++;
  74. if((x+1) < 15 && (y-1) >=0 && isAlive(x+1,y-1)) counter++;
  75. if((x-1) >=0&& isAlive(x-1,y)) counter++;
  76. if((x+1) < 15 && isAlive(x+1,y)) counter++;
  77. if((x-1) >=0 && (y+1) < 15 && isAlive(x-1,y+1)) counter++;
  78. if((y+1) <15 && isAlive(x,y+1)) counter++;
  79. if((x+1) <15 && (y+1) <15 && isAlive(x+1,y+1)) counter++;
  80. return counter;
  81. }
  82. }