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.

68 lines
1.4 KiB

  1. package edu.stuy.goldfish;
  2. public class Grid {
  3. private Patch[][] _grid;
  4. public Grid() {
  5. _grid = new Patch[1][1];
  6. _grid[0][0] = new Patch(this, 0, 0);
  7. }
  8. public Grid(int x, int y) {
  9. _grid = new Patch[x][y];
  10. for (int i = 0; i < x; i++) {
  11. for (int j = 0; j < y; j++) {
  12. _grid[i][j] = new Patch(this, i, j);
  13. }
  14. }
  15. }
  16. private int normalizeX(int x) {
  17. while (x >= getWidth())
  18. x -= getWidth();
  19. while (x < 0)
  20. x += getWidth();
  21. return x;
  22. }
  23. private int normalizeY(int y) {
  24. while (y >= getHeight())
  25. y -= getHeight();
  26. while (y < 0)
  27. y += getHeight();
  28. return y;
  29. }
  30. public int getWidth() {
  31. return _grid.length;
  32. }
  33. public int getHeight() {
  34. return _grid[0].length;
  35. }
  36. public Patch getPatch(int x, int y) {
  37. x = normalizeX(x);
  38. y = normalizeY(y);
  39. return _grid[x][y];
  40. }
  41. public void setPatch(int x, int y, Patch p) {
  42. x = normalizeX(x);
  43. y = normalizeY(y);
  44. _grid[x][y] = p;
  45. }
  46. public String toString() {
  47. String ans = "";
  48. for (int i = 0; i < _grid.length; i++) {
  49. for (int j = 0; j < _grid[i].length; j++) {
  50. ans += _grid[i][j];
  51. }
  52. ans += "\n";
  53. }
  54. return ans;
  55. }
  56. }