Bueno hago este hilo de parte del maquina de Overxfl0w13 que no se acoradaba de la pass y cuando recupero la pass el captcha no le funcionaba xDDD, este post esta tal como el lo queria poner.

Overxfl0w13:
Buenas idt :). Hoy vengo a hablaros de algo que muchos igual ya conocéis, se trata del juego de la vida (Game of Life). El juego de la vida fue concebido por J.H. Conway y debido al interés de la comunidad ha sido un referente para los estudios de simulación de sistemas dinámicos y la observación de fenónemos en la evolución de éstos. Se desarrolla con autómatas celulares extremadamente simples con valores 0 (célula muerta) y 1 (célula viva) en un espacio celular bidimensional infinito en ambas direcciones regidos por las siguientes reglas (las originales de Conway, hay muchas otras):

· Si la célula está viva y tiene dos o tres celdillas circundantes* vivas, entonces continúa viva en la siguiente etapa, en otro caso muere.
· Si la célula está muerta y tiene exactamente tres celdilas circundantes vivas, entonces la célula vive en la siguiente etapa.
* Con circundantes se refiere al vecindario de moore([Enlace externo eliminado para invitados])


El juego arranca de una configuración inicial con un número N de celdas vivas a partir de la cual el sistema evoluciona a través de la correspondiente secuencia de configuraciones, una por etapa.

Estas configuraciones vienen dadas por un conjunto de células vivas que pueden formar patrones, algunos de los más conocidos son (hay muchos más,usaremos * para representar una célula viva y 0 para una muerta):

· Invariante:

Código: Seleccionar todo

0 0 0 0
0 * * 0  (Esta configuración pertenece invariable con el paso de las etapas.)
0 * * 0
0 0 0 0
· Osciladores:

Código: Seleccionar todo

0 0 0 0 0
0 * * * 0  (Esta configuración presenta un comportamiento cíclico permanente.)
0 0 0 0 0
· Gliders:

Código: Seleccionar todo

0 0 0 0 0 0 0
0 0 0 * 0 0 0
0 0 0 0 * 0 0
0 0 * * * 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0  (Esta configuración oscila con desplazamiento a través de una coulmna, fila o diagonal)
Computacionalmente, el juego de la vida es equivalente a la máquina de turing ([Enlace externo eliminado para invitados]) (Turing-completo) ya que es posible construir un estructura que actúe como una máquina de estados finitos ([Enlace externo eliminado para invitados]) conectada a dos contadores (para manejar el flujo de ejecución de la máquina).

Podéis probar un proyecto más cuidado para realizar pruebas sobre un tablero que SI cumple las especificaciones: [Enlace externo eliminado para invitados]


Ahora os dejo mi código, las configuraciones del tablero iniciales son: ancho de la matriz = 75 casillas, alto de la matriz = 20 casillas, periodo T = 350ms, número de células vivas mínimo para continuar viva = 2, número de células vivas máximo para continuar viva = 3, número de células vivas para revivir una célula = 3. Se pueden simular otras formas de vida diferentes cambiando estos parámetros, para ello cambiar los valores desde Configuration.java


El uso está explicado en el banner pero dejo un gif del funcionamiento para un oscilador simple en la configuración inicial:

Imagen


[Board.java]
public class Board
{
    private byte[][] board;
    
    public Board(){
        this.board = new byte[Configuration.height][Configuration.width];
    }
    
    public void set_coords(int x,int y,byte value){ 
        try{this.board[x][y] = value; }
        catch(ArrayIndexOutOfBoundsException e){ System.out.println("Not valid coords");}
    }
    public byte get_coords(int x,int y){ return this.board[x][y]; }
           
    // Receives coords of interested point
    public int surrounders_alive(int x,int y){
        int count = 0;
        try{ if(this.board[x-1][y-1]==1) count++; }
        catch(Exception e){}
        try{ if(this.board[x+1][y-1]==1) count++; }
        catch(Exception e){}
        try{ if(this.board[x-1][y]==1) count++; }
        catch(Exception e){}
        try{ if(this.board[x+1][y]==1) count++; }
        catch(Exception e){}
        try{ if(this.board[x][y-1]==1) count++; }
        catch(Exception e){}
        try{ if(this.board[x][y+1]==1) count++; }
        catch(Exception e){}
        try{ if(this.board[x+1][y+1]==1) count++; }
        catch(Exception e){}
        try{ if(this.board[x-1][y+1]==1) count++; }
        catch(Exception e){}
        return count;
    }
    
    public void print_status(){
        for(int x=0;x<Configuration.height;x++){
            for(int y=0;y<Configuration.width;y++){
                if(this.board[x][y]==1) System.out.print("*");
                else System.out.print("0");
            }
            System.out.println();
        }
    }    
}
[GOLife.java]
import java.util.Scanner;
public class GOLife
{
   private Board board;
   private byte[][] aux_board;
   private Scanner sc_key;
   
   public GOLife(){
       this.board       = new Board();
       this.aux_board   = new byte[Configuration.height][Configuration.width];
       this.sc_key      = new Scanner(System.in);
       this.print_banner();
       this.set_board_user();
       this.game_process();
   }
   
   private void print_banner(){
       System.out.println("******************** Game of life ********************\n");
       System.out.println("· The size of matrix is specified in Configuration.java, please refer it to change this options");
       System.out.println("· Now, set initial configuration of automata, to put ON a cell (value 1), input cell coords by this way:");
       System.out.println("\t\tValid Examples:\n\t\t2 3\n\t\t0 0\n");
       System.out.println("When you finish configuration,please insert an invalid coords like: -1 -1 :)");
       System.out.println("Please enter a key...");
       this.sc_key.nextLine();
       this.clear_window();
    }  
   
   private void set_board_user(){
       int x,y = 0;
       boolean flag = false;
       do{
           System.out.println("Current configuration: "); this.board.print_status();
           System.out.println("\n\nCoords:\t");
           x = this.sc_key.nextInt();
           y = this.sc_key.nextInt();
           flag = x>=0 && x<=Configuration.height && y>=0 && y<=Configuration.width;
           if(flag) this.board.set_coords(x,y,(byte)1);
       }while(flag);
   }
       
   private void game_process(){
       int surrounders_alive = 0;
       this.board.print_status();
       while(true){
           try{ Thread.sleep(Configuration.tCycle); }
           catch(InterruptedException e){}
           finally{
               for(int x=0;x<Configuration.height;x++){
                   for(int y=0;y<Configuration.width;y++){
                       surrounders_alive = board.surrounders_alive(x,y);
                       if(this.board.get_coords(x,y)==1){
                           if(surrounders_alive>=Configuration.celLives0 && surrounders_alive<=Configuration.celLives1){ aux_board[x][y] = (byte)1;}
                           else if(surrounders_alive<Configuration.celLives0 || surrounders_alive>Configuration.celLives1){ aux_board[x][y] = (byte)0;}
                           }
                   else if(surrounders_alive==Configuration.celLives2){ aux_board[x][y] = (byte)1;} 
                   }             
               }
           }
           if(this.check_break_flag()) break;
           this.copy_boards();
           this.clear_window();
           this.board.print_status();                  
       }
    }
    
   private boolean check_break_flag(){
       for(int i=0;i<Configuration.height;i++) for(int j=0;j<Configuration.width;j++) if(this.aux_board[i][j]!=this.board.get_coords(i,j)) return false;
       return true;
   }
   
   private void copy_boards(){ for(int i=0;i<Configuration.height;i++) for(int j=0;j<Configuration.width;j++) this.board.set_coords(i,j,this.aux_board[i][j]); }
   
   private void clear_window(){for(int i=0;i<50;++i,System.out.println());}
   public static void main(String args[]){
       GOLife gol = new GOLife();
   }

}
[Configuration.java]
public class Configuration
{
    public static int height    = 20;
    public static int width     = 75;
    public static int tCycle    = 350;
    public static int celLives0 = 2;  // Specifies the minimum number of living celds to maintain with life a celule
    public static int celLives1 = 3;  // Specifies the minimum number of living celds to maintain with life a celule
    public static int celLives2 = 3; // Specifies the minimum number of living celds to realive a celule
    /** ... **/
}
Eso es todo, espero que os interese el tema, si queréis saber más [Enlace externo eliminado para invitados], no es muy complicado.

Un saludo :D
Abolición para el torneo del toro de la vega. Death to the murderers of bulls.
Responder

Volver a “Fuentes”