View Javadoc
1   package org.woehlke.simulation.cyclic.cellular.automaton.model;
2   
3   import java.util.Date;
4   import java.util.Random;
5   
6   /**
7    * Created with IntelliJ IDEA.
8    * User: Fert
9    * Date: 28.08.13
10   * Time: 12:39
11   * To change this template use File | Settings | File Templates.
12   */
13  public class CyclicCellularAutomaton {
14      public final static int MAX_STATUS = 13;
15      private Point worldDimensions;
16      private Random random;
17  
18      private int[][][] lattice;
19      private int source;
20      private int target;
21  
22  
23      public CyclicCellularAutomaton(Point worldDimensions) {
24          this.worldDimensions = worldDimensions;
25          random = new Random(new Date().getTime());
26          lattice = new int[2][worldDimensions.getX()][worldDimensions.getY()];
27          source = 0;
28          target = 1;
29          for(int y=0;y<worldDimensions.getY();y++){
30              for(int x=0;x<worldDimensions.getX();x++){
31                  lattice[source][x][y] = random.nextInt(MAX_STATUS);
32              }
33          }
34      }
35  
36      public void step(){
37          //System.out.print(".");
38          for(int y=0;y<worldDimensions.getY();y++){
39              for(int x=0;x<worldDimensions.getX();x++){
40                  lattice[target][x][y] = lattice[source][x][y];
41                  int nextState = (lattice[source][x][y] + 1) % MAX_STATUS;
42                  if(nextState == lattice[source][x][(y-1+worldDimensions.getY())%worldDimensions.getY()]){
43                      lattice[target][x][y] = nextState;
44                      continue;
45                  }
46                  if(nextState == lattice[source][(x+1+worldDimensions.getX())%worldDimensions.getX()][y]){
47                      lattice[target][x][y] = nextState;
48                      continue;
49                  }
50                  if(nextState == lattice[source][x][(y+1+worldDimensions.getY())%worldDimensions.getY()]){
51                      lattice[target][x][y] = nextState;
52                      continue;
53                  }
54                  if(nextState == lattice[source][(x-1+worldDimensions.getX())%worldDimensions.getX()][y]){
55                      lattice[target][x][y] = nextState;
56                  }
57              }
58          }
59          source++;
60          target++;
61          source%=2;
62          target%=2;
63      }
64  
65      public int getCellStatusFor(int x,int y){
66          return lattice[source][x][y];
67      }
68  }