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.

Simulation.java 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. public class Simulation {
  2. int width;
  3. int height;
  4. int[][] board;
  5. public Simulation(int width, int height) {
  6. this.width = width;
  7. this.height = height;
  8. this.board = new int[width][height];
  9. }
  10. public void printBoard() {
  11. System.out.println("---");
  12. for (int y = 0; y < height; y++) {
  13. String line = "|";
  14. for (int x = 0; x < width; x++) {
  15. if (this.board[x][y] == 0) {
  16. line += ".";
  17. } else {
  18. line += "*";
  19. }
  20. }
  21. line += "|";
  22. System.out.println(line);
  23. }
  24. System.out.println("---\n");
  25. }
  26. public void setAlive(int x, int y) {
  27. this.board[x][y] = 1;
  28. }
  29. public void setDead(int x, int y) {
  30. this.board[x][y] = 0;
  31. }
  32. public int countAliveNeighbours(int x, int y) {
  33. int count = 0;
  34. count += getState(x - 1, y - 1);
  35. count += getState(x, y - 1);
  36. count += getState(x + 1, y - 1);
  37. count += getState(x - 1, y);
  38. count += getState(x + 1, y);
  39. count += getState(x - 1, y + 1);
  40. count += getState(x, y + 1);
  41. count += getState(x + 1, y + 1);
  42. return count;
  43. }
  44. public int getState(int x, int y) {
  45. if (x < 0 || x >= width) {
  46. return 0;
  47. }
  48. if (y < 0 || y >= height) {
  49. return 0;
  50. }
  51. return this.board[x][y];
  52. }
  53. public void step() {
  54. int[][] newBoard = new int[width][height];
  55. for (int y = 0; y < height; y++) {
  56. for (int x = 0; x < width; x++) {
  57. int aliveNeighbours = countAliveNeighbours(x, y);
  58. if (getState(x, y) == 1) {
  59. if (aliveNeighbours < 2) {
  60. newBoard[x][y] = 0;
  61. } else if (aliveNeighbours == 2 || aliveNeighbours == 3) {
  62. newBoard[x][y] = 1;
  63. } else if (aliveNeighbours > 3) {
  64. newBoard[x][y] = 0;
  65. }
  66. } else {
  67. if (aliveNeighbours == 3) {
  68. newBoard[x][y] = 1;
  69. }
  70. }
  71. }
  72. }
  73. this.board = newBoard;
  74. }
  75. public static void main(String[] args) {
  76. Simulation simulation = new Simulation(8, 5);
  77. simulation.setAlive(2, 2);
  78. simulation.setAlive(3, 2);
  79. simulation.setAlive(4, 2);
  80. simulation.printBoard();
  81. simulation.step();
  82. simulation.printBoard();
  83. simulation.step();
  84. simulation.printBoard();
  85. }
  86. }