A simple Game of Life implementation in Java
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.

106 lines
2.7 KiB

  1. package edu.stuy.goldfish;
  2. public class Patch {
  3. private int _xcor, _ycor, _state;
  4. private Grid _grid;
  5. public Patch(Grid grid, int xcor, int ycor, int state) {
  6. _grid = grid;
  7. _xcor = xcor;
  8. _ycor = ycor;
  9. _state = state;
  10. }
  11. public Patch() {
  12. this(new Grid(), 0, 0, 0);
  13. }
  14. public Grid getGrid() {
  15. return _grid;
  16. }
  17. public int getX() {
  18. return _xcor;
  19. }
  20. public int getY() {
  21. return _ycor;
  22. }
  23. public int getState() {
  24. return _state;
  25. }
  26. public void setState(int state) {
  27. _state = state;
  28. }
  29. public String toString() {
  30. return "" + ((_state == 0) ? "." : _state);
  31. }
  32. public int get4Neighbors(int state, int max) {
  33. int neighbors = 0;
  34. for (int i = 0; i < 4; i++) {
  35. Patch p;
  36. switch(i) {
  37. case 0:
  38. p = _grid.getPatch(_xcor + 1, _ycor); break;
  39. case 1:
  40. p = _grid.getPatch(_xcor - 1, _ycor); break;
  41. case 2:
  42. p = _grid.getPatch(_xcor, _ycor + 1); break;
  43. default:
  44. p = _grid.getPatch(_xcor, _ycor - 1); break;
  45. }
  46. if (p.getState() == state)
  47. neighbors++;
  48. if (neighbors == max)
  49. break;
  50. }
  51. return neighbors;
  52. }
  53. public int get8Neighbors(int state, int max) {
  54. int neighbors = 0;
  55. for (int i = 0; i < 8; i++) {
  56. Patch p;
  57. switch(i) {
  58. case 0:
  59. p = _grid.getPatch(_xcor + 1, _ycor); break;
  60. case 1:
  61. p = _grid.getPatch(_xcor - 1, _ycor); break;
  62. case 2:
  63. p = _grid.getPatch(_xcor, _ycor + 1); break;
  64. case 3:
  65. p = _grid.getPatch(_xcor, _ycor - 1); break;
  66. case 4:
  67. p = _grid.getPatch(_xcor + 1, _ycor + 1); break;
  68. case 5:
  69. p = _grid.getPatch(_xcor + 1, _ycor - 1); break;
  70. case 6:
  71. p = _grid.getPatch(_xcor - 1, _ycor + 1); break;
  72. default:
  73. p = _grid.getPatch(_xcor - 1, _ycor - 1); break;
  74. }
  75. if (p.getState() == state)
  76. neighbors++;
  77. if (neighbors == max)
  78. break;
  79. }
  80. return neighbors;
  81. }
  82. public int get4Neighbors(int state) {
  83. return get4Neighbors(state, 4);
  84. }
  85. public int get8Neighbors(int state) {
  86. return get8Neighbors(state, 8);
  87. }
  88. public Patch clone(Grid grid) {
  89. return new Patch(grid, _xcor, _ycor, _state);
  90. }
  91. }