A simple Game of Life implementation in Java
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

80 lignes
1.9 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, 0);
  7. }
  8. public Grid(int x, int y, boolean fill) {
  9. _grid = new Patch[y][x];
  10. if (fill) {
  11. for (int i = 0; i < x; i++) {
  12. for (int j = 0; j < y; j++) {
  13. _grid[j][i] = new Patch(this, i, j, 0);
  14. }
  15. }
  16. }
  17. }
  18. public Grid(int x, int y) {
  19. this(x, y, true);
  20. }
  21. /* Take an x coordinate, and return x′ such that 0 <= x′ < width. */
  22. private int normalizeX(int x) {
  23. while (x >= getWidth())
  24. x -= getWidth();
  25. while (x < 0)
  26. x += getWidth();
  27. return x;
  28. }
  29. /* Take a y coordinate, and return y′ such that 0 <= y′ < height. */
  30. private int normalizeY(int y) {
  31. while (y >= getHeight())
  32. y -= getHeight();
  33. while (y < 0)
  34. y += getHeight();
  35. return y;
  36. }
  37. /* Return the width of the grid. */
  38. public int getWidth() {
  39. return _grid[0].length;
  40. }
  41. /* Return the height of the grid. */
  42. public int getHeight() {
  43. return _grid.length;
  44. }
  45. /* Return the patch at (x, y). x and y need not be within range of the
  46. grid. */
  47. public Patch getPatch(int x, int y) {
  48. x = normalizeX(x);
  49. y = normalizeY(y);
  50. return _grid[y][x];
  51. }
  52. /* Set the patch at (x, y) to p. */
  53. public void setPatch(int x, int y, Patch p) {
  54. x = normalizeX(x);
  55. y = normalizeY(y);
  56. _grid[y][x] = p;
  57. }
  58. public String toString() {
  59. String ans = "";
  60. for (int i = 0; i < _grid.length; i++) {
  61. for (int j = 0; j < _grid[i].length; j++) {
  62. ans += _grid[i][j];
  63. }
  64. ans += "\n";
  65. }
  66. return ans;
  67. }
  68. }