/*
 * AutomateCellulaire.java
 *
 * Created on 24 mai 2005, 20:15
 */

package examples;

import java.awt.Color;
import java.awt.image.BufferedImage;
import sema.Element;
import sema.World;

/**
 *
 * @author Boris
 */
public class AutomateCellulaire extends Element {
    
    /** Creates a new instance of AutomateCellulaire */
    public AutomateCellulaire(World world) {
        super(world,new RectangularArea2(world.map,0,0,0,0),new BufferedImage(1,1,1));
        for (int i=0; i<world.map.xLength; i++){
            for (int j=0; j<world.map.yLength; j++){
                new Cellule(world,i,j);
            }
        }
        
    }
    
}

class Cellule extends Element {
    public Cellule(World world, int x, int y){
        super(world, new DefinitiveRectangularArea2(world.map,(x+.5f)*world.map.boxLength,(y+.5f)*world.map.boxLength,world.map.boxLength,world.map.boxLength),new BufferedImage(1,1,1));
        new Evolve();
        new Synchrone(1.5);
        this.x = x;
        this.y = y;
    }
    protected int x,y;
    int état = (int)(Math.random()*2);
    int previousétat = 0;
    
    class Evolve extends ElementEvent  {
        public Evolve(){
            super(1);
        }
        public void whatToDo(){
            int compteur = 0;
            for (int i=-1; i<2; i++){
                for (int j=-1; j<2; j++){
                    int xx = (x+i+world.map.xBoxes)%world.map.xBoxes;
                    int yy = (y+j+world.map.yBoxes)%world.map.yBoxes;
                    try {
                        Cellule e = (Cellule) world.map.boxes[xx][yy].getContents().first();
                        if (e.état>0 && e!=Cellule.this) compteur++;
                    } catch (Exception ex) {}
                }
            }
            if (compteur ==3) previousétat =1;
            else if (compteur!=2) previousétat=0; else previousétat=état;
            new Evolve();
        }
    }
    class Synchrone extends ElementEvent  {
        public Synchrone(double d){
            super(d);
        }
        public void whatToDo(){
            état = previousétat;
            new Synchrone(1);
        }
    }
    
public void highlight(){
    super.highlight();
    previousétat= 1-previousétat;
    état = 1-état;
}
    
    public void draw(){
        if (état==0) getArea().fill(world.drawing,(Color.BLUE));
        if (état==1) getArea().fill(world.drawing,Color.RED);
        if (état==2) getArea().fill(world.drawing,Color.GREEN);
        if (état==3) getArea().fill(world.drawing,Color.YELLOW);
    }
}