001package org.woehlke.simulation.cyclic.cellular.automaton.model;
002
003import java.util.Date;
004import java.util.Random;
005
006/**
007 * Created with IntelliJ IDEA.
008 * User: Fert
009 * Date: 28.08.13
010 * Time: 12:39
011 * To change this template use File | Settings | File Templates.
012 */
013public class CyclicCellularAutomaton {
014    public final static int MAX_STATUS = 13;
015    private Point worldDimensions;
016    private Random random;
017
018    private int[][][] lattice;
019    private int source;
020    private int target;
021
022
023    public CyclicCellularAutomaton(Point worldDimensions) {
024        this.worldDimensions = worldDimensions;
025        random = new Random(new Date().getTime());
026        lattice = new int[2][worldDimensions.getX()][worldDimensions.getY()];
027        source = 0;
028        target = 1;
029        for(int y=0;y<worldDimensions.getY();y++){
030            for(int x=0;x<worldDimensions.getX();x++){
031                lattice[source][x][y] = random.nextInt(MAX_STATUS);
032            }
033        }
034    }
035
036    public void step(){
037        //System.out.print(".");
038        for(int y=0;y<worldDimensions.getY();y++){
039            for(int x=0;x<worldDimensions.getX();x++){
040                lattice[target][x][y] = lattice[source][x][y];
041                int nextState = (lattice[source][x][y] + 1) % MAX_STATUS;
042                if(nextState == lattice[source][x][(y-1+worldDimensions.getY())%worldDimensions.getY()]){
043                    lattice[target][x][y] = nextState;
044                    continue;
045                }
046                if(nextState == lattice[source][(x+1+worldDimensions.getX())%worldDimensions.getX()][y]){
047                    lattice[target][x][y] = nextState;
048                    continue;
049                }
050                if(nextState == lattice[source][x][(y+1+worldDimensions.getY())%worldDimensions.getY()]){
051                    lattice[target][x][y] = nextState;
052                    continue;
053                }
054                if(nextState == lattice[source][(x-1+worldDimensions.getX())%worldDimensions.getX()][y]){
055                    lattice[target][x][y] = nextState;
056                }
057            }
058        }
059        source++;
060        target++;
061        source%=2;
062        target%=2;
063    }
064
065    public int getCellStatusFor(int x,int y){
066        return lattice[source][x][y];
067    }
068}