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.

79 lines
2.5 KiB

  1. package edu.stuy.goldfish;
  2. import edu.stuy.goldfish.rules.*;
  3. public class Goldfish {
  4. private static final String[] RULES = {"Conway", "Conway4", "Life Without Death", "Brian's Brain"};
  5. private Grid _grid;
  6. private Render _render;
  7. public Goldfish() {
  8. int width = 128;
  9. int height = 128;
  10. _grid = new Grid(width, height);
  11. _render = new Render(width, height, _grid, RULES);
  12. }
  13. /* Main method for running the simulator. */
  14. public void run() {
  15. setup(_render.rule);
  16. while (true) {
  17. if (_render.reset) {
  18. setup(_render.rule);
  19. _render.reset = false;
  20. }
  21. if (!_render.paused) {
  22. _render.acquireLock(0);
  23. doLogic(_render.rule);
  24. _render.releaseLock(0);
  25. }
  26. _render.setGrid(_grid);
  27. _render.run();
  28. _render.sleep();
  29. }
  30. }
  31. /* Advance the grid one step using the given algorithm. */
  32. private void doLogic(String rule) {
  33. if (rule.equals("Conway"))
  34. _grid = Conway.run(_grid);
  35. else if (rule.equals("Conway4"))
  36. _grid = Conway4.run(_grid);
  37. else if (rule.equals("Life Without Death"))
  38. _grid = LifeWithoutDeath.run(_grid);
  39. else if (rule.equals("Brian's Brain"))
  40. _grid = BriansBrain.run(_grid);
  41. }
  42. /* Return the max number of states a patch can be in for the given rule. */
  43. public static int getMaxStates(String rule) {
  44. if (rule.equals("Conway"))
  45. return Conway.states;
  46. else if (rule.equals("Conway4"))
  47. return Conway4.states;
  48. else if (rule.equals("Life Without Death"))
  49. return LifeWithoutDeath.states;
  50. else if (rule.equals("Brian's Brain"))
  51. return BriansBrain.states;
  52. return 2;
  53. }
  54. /* Generate a default shape for the grid based on the given rule. */
  55. private void setup(String rule) {
  56. if (rule.equals("Conway"))
  57. Conway.setup(_grid);
  58. else if (rule.equals("Conway4"))
  59. Conway4.setup(_grid);
  60. else if (rule.equals("Life Without Death"))
  61. LifeWithoutDeath.setup(_grid);
  62. else if (rule.equals("Brian's Brain"))
  63. BriansBrain.setup(_grid);
  64. }
  65. public static void main(String[] args) {
  66. Goldfish g = new Goldfish();
  67. g.run();
  68. }
  69. }