El Juego de la Vida

En este ejemplo vamos a ver cómo crear un sistema complejo de una manera muy sencilla. Construiremos un tablero de dos dimensiones cuyas casillas sólo pueden estar activas o inactivas, es decir que cada casilla se puede codificar digitalmente como uno o cero. A las casillas las llamaremos células y la codificación será el estado de la célula. Esta pequeña estructura nos servirá para entender el funcionamiento básico de los sistemas complejos.

Un autómata celular será un conjunto de células, de las que algunas estarán activas y otras inactivas.

BLA BLA BLA http://natureofcode.com/book/chapter-7-cellular-automata

We used a one-dimensional array to store the list of cell states before, and for the Game of Life, we can use a two-dimensional array. We’ll begin by initializing each cell of the board with a random state: 0 or 1.

Código para poder ejecutar el lenguaje "Processing" en esta página


In [2]:
from metakernel import register_ipython_magics
register_ipython_magics()

Código del Juego de la Vida


In [14]:
%%processing

// Codigo basado en:
// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com

// A basic implementation of John Conway's Game of Life CA
// how could this be improved to use object oriented programming?
// think of it as similar to our particle system, with a "cell" class
// to describe each individual cell and a "cellular automata" class
// to describe a collection of cells

// Configuracion del tablero
int boardWidth = 640; // Anchura del tablero (pixels)
int boardHeight= 320; // Altura del tablero (pixels)
int timeRefresh = 24; // Velocidad de refresco
int colorBackground = 255; // Color de fondo
int colorForeground = 0; // Color frontal

GOL gol;

void setup() {
  size(boardWidth, boardHeight); // drawing size (pixels)
  frameRate(timeRefresh); // refresh time
  //size(640, 320); // drawing size (pixels)
  //frameRate(24); // refresh time
  gol = new GOL();
}

void draw() {
  background(255);
  gol.generate();
  gol.display();
}

// reset board when mouse is pressed
void mousePressed() {
  gol.init();
}

// Class to display the board of the Game of Life 
class GOL {

  int w = 8; // cell width
  int columns, rows;

  // Game of life board
  int[][] board;


  GOL() {
    // Initialize rows, columns and set-up arrays
    columns = width/w;
    rows = height/w;
    board = new int[columns][rows];
    //next = new int[columns][rows];
    // Call function to fill array with random values 0 or 1
    init();
  }

  void init() {
    for (int i =1;i < columns-1;i++) {
      for (int j =1;j < rows-1;j++) {
        board[i][j] = int(random(2));
      }
    }
  }

  // The process of creating the new generation
  void generate() {

    int[][] next = new int[columns][rows];

    // Loop through every spot in our 2D array and check spots neighbors
    for (int x = 1; x < columns-1; x++) {
      for (int y = 1; y < rows-1; y++) {

        // Add up all the states in a 3x3 surrounding grid
        int neighbors = 0;
        for (int i = -1; i <= 1; i++) {
          for (int j = -1; j <= 1; j++) {
            neighbors += board[x+i][y+j];
          }
        }

        // A little trick to subtract the current cell's state since
        // we added it in the above loop
        neighbors -= board[x][y];

        // Rules of Life
        max_neighbors = 3
        min_neighbors = 2
          
        if      ((board[x][y] == 1) && (neighbors <  min_neighbors)) next[x][y] = 0;           // Loneliness
        else if ((board[x][y] == 1) && (neighbors >  max_neighbors)) next[x][y] = 0;           // Overpopulation
        else if ((board[x][y] == 0) && (neighbors == 3)) next[x][y] = 1;           // Reproduction
        else                                            next[x][y] = board[x][y];  // Stasis
      }
    }

    // Next is now our board
    board = next;
  }

  // This is the easy part, just draw the cells, fill 255 for '1', fill 0 for '0'
  void display() {
    for ( int i = 0; i < columns;i++) {
      for ( int j = 0; j < rows;j++) {
        if ((board[i][j] == 1)) fill(0);
        else fill(255); 
        stroke(0);
        rect(i*w, j*w, w, w);
      }
    }
  }
}



In [10]:
import sys
sys.version_info


Out[10]:
sys.version_info(major=3, minor=6, micro=0, releaselevel='final', serial=0)

In [ ]: