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.

40 lines
1.3 KiB

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