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.

34 lines
1.0 KiB

  1. package edu.stuy.goldfish.rules;
  2. import edu.stuy.goldfish.Grid;
  3. import edu.stuy.goldfish.Patch;
  4. public class Conway implements RuleSet {
  5. states = 2;
  6. @Override
  7. public static Grid run (Grid g) {
  8. Grid newGrid = new Grid(g.getWidth(), g.getHeight());
  9. for (int i = 0; i < g.getWidth(); i++) {
  10. for (int j = 0; j < j.getHeight(); j++) {
  11. Patch[] neighbors = g.getPatch(i, j).get8Neighbors();
  12. int numAlive = 0;
  13. for (Patch p : neighbors)
  14. if (p.getState() == 1) numAlive++;
  15. Patch p = g.getPatch(i,j).clone();
  16. if (numAlive < 2) {
  17. p.setState(0); //Dies by underpopulation
  18. }
  19. if (numAlive > 3) {
  20. p.setState(0); //Dies by overpopulation
  21. }
  22. if (numAlive == 3)
  23. p.setState(1); //Born with 3 neighbors.
  24. newGrid.setPatch(i,j,p);
  25. }
  26. }
  27. return newGrid;
  28. }
  29. }