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.

54 lines
1.9 KiB

  1. package edu.stuy.goldfish.rules;
  2. import edu.stuy.goldfish.Grid;
  3. import edu.stuy.goldfish.Patch;
  4. // An implementation of conway using von Neumann Neighborhoods.
  5. public class Conway4 extends RuleSet {
  6. public static int states = 2;
  7. public static Grid run(Grid g) {
  8. Grid newGrid = new Grid(g.getWidth(), g.getHeight(), false);
  9. for (int i = 0; i < g.getWidth(); i++) {
  10. for (int j = 0; j < g.getHeight(); j++) {
  11. Patch orig = g.getPatch(i, j);
  12. int numAlive = orig.get4Neighbors(1);
  13. Patch p = orig.clone(newGrid);
  14. if (numAlive < 2)
  15. p.setState(0); // Dies by underpopulation
  16. else if (numAlive > 3)
  17. p.setState(0); // Dies by overpopulation
  18. else if (numAlive == 3)
  19. p.setState(1); // Born with 3 neighbors
  20. newGrid.setPatch(i, j, p);
  21. }
  22. }
  23. return newGrid;
  24. }
  25. public static void setup(Grid g) {
  26. int[][] pattern = {
  27. {1,1,1,1,1,1,1,1,1,1,1,1,0,1},
  28. {1,0,0,0,0,0,0,0,0,0,0,1,0,1},
  29. {1,0,1,1,1,1,1,1,1,1,0,1,0,1},
  30. {1,0,1,0,0,0,0,0,0,1,0,1,0,1},
  31. {1,0,1,0,1,1,1,1,0,1,0,1,0,1},
  32. {1,0,1,0,1,0,0,1,0,1,0,1,0,1},
  33. {1,0,1,0,1,0,0,1,0,1,0,1,0,1},
  34. {1,0,1,0,1,0,1,1,0,1,0,1,0,1},
  35. {1,0,1,0,1,0,0,0,0,1,0,1,0,1},
  36. {1,0,1,0,1,1,1,1,1,1,0,1,0,1},
  37. {1,0,1,0,0,0,0,0,0,0,0,1,0,1},
  38. {1,0,1,1,1,1,1,1,1,1,1,1,0,1},
  39. {1,0,0,0,0,0,0,0,0,0,0,0,0,1},
  40. {1,1,1,1,1,1,1,1,1,1,1,1,1,1}
  41. };
  42. for (int i = 0; i < 14; i++) {
  43. for (int j = 0; j < 14; j++) {
  44. g.getPatch(i + ((g.getWidth() - 14) / 2),
  45. j + ((g.getHeight() - 14) / 2)).setState(pattern[j][i]);
  46. }
  47. }
  48. }
  49. }